zone-testing-node-bundle.js 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (factory());
  12. }(this, (function () { 'use strict';
  13. /**
  14. * @license
  15. * Copyright Google Inc. All Rights Reserved.
  16. *
  17. * Use of this source code is governed by an MIT-style license that can be
  18. * found in the LICENSE file at https://angular.io/license
  19. */
  20. var Zone$1 = (function (global) {
  21. var performance = global['performance'];
  22. function mark(name) {
  23. performance && performance['mark'] && performance['mark'](name);
  24. }
  25. function performanceMeasure(name, label) {
  26. performance && performance['measure'] && performance['measure'](name, label);
  27. }
  28. mark('Zone');
  29. var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
  30. if (global['Zone']) {
  31. // if global['Zone'] already exists (maybe zone.js was already loaded or
  32. // some other lib also registered a global object named Zone), we may need
  33. // to throw an error, but sometimes user may not want this error.
  34. // For example,
  35. // we have two web pages, page1 includes zone.js, page2 doesn't.
  36. // and the 1st time user load page1 and page2, everything work fine,
  37. // but when user load page2 again, error occurs because global['Zone'] already exists.
  38. // so we add a flag to let user choose whether to throw this error or not.
  39. // By default, if existing Zone is from zone.js, we will not throw the error.
  40. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  41. throw new Error('Zone already loaded.');
  42. }
  43. else {
  44. return global['Zone'];
  45. }
  46. }
  47. var Zone = /** @class */ (function () {
  48. function Zone(parent, zoneSpec) {
  49. this._parent = parent;
  50. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  51. this._properties = zoneSpec && zoneSpec.properties || {};
  52. this._zoneDelegate =
  53. new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  54. }
  55. Zone.assertZonePatched = function () {
  56. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  57. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  58. 'has been overwritten.\n' +
  59. 'Most likely cause is that a Promise polyfill has been loaded ' +
  60. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  61. 'If you must load one, do so before loading zone.js.)');
  62. }
  63. };
  64. Object.defineProperty(Zone, "root", {
  65. get: function () {
  66. var zone = Zone.current;
  67. while (zone.parent) {
  68. zone = zone.parent;
  69. }
  70. return zone;
  71. },
  72. enumerable: true,
  73. configurable: true
  74. });
  75. Object.defineProperty(Zone, "current", {
  76. get: function () {
  77. return _currentZoneFrame.zone;
  78. },
  79. enumerable: true,
  80. configurable: true
  81. });
  82. Object.defineProperty(Zone, "currentTask", {
  83. get: function () {
  84. return _currentTask;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. Zone.__load_patch = function (name, fn) {
  90. if (patches.hasOwnProperty(name)) {
  91. if (checkDuplicate) {
  92. throw Error('Already loaded patch: ' + name);
  93. }
  94. }
  95. else if (!global['__Zone_disable_' + name]) {
  96. var perfName = 'Zone:' + name;
  97. mark(perfName);
  98. patches[name] = fn(global, Zone, _api);
  99. performanceMeasure(perfName, perfName);
  100. }
  101. };
  102. Object.defineProperty(Zone.prototype, "parent", {
  103. get: function () {
  104. return this._parent;
  105. },
  106. enumerable: true,
  107. configurable: true
  108. });
  109. Object.defineProperty(Zone.prototype, "name", {
  110. get: function () {
  111. return this._name;
  112. },
  113. enumerable: true,
  114. configurable: true
  115. });
  116. Zone.prototype.get = function (key) {
  117. var zone = this.getZoneWith(key);
  118. if (zone)
  119. return zone._properties[key];
  120. };
  121. Zone.prototype.getZoneWith = function (key) {
  122. var current = this;
  123. while (current) {
  124. if (current._properties.hasOwnProperty(key)) {
  125. return current;
  126. }
  127. current = current._parent;
  128. }
  129. return null;
  130. };
  131. Zone.prototype.fork = function (zoneSpec) {
  132. if (!zoneSpec)
  133. throw new Error('ZoneSpec required!');
  134. return this._zoneDelegate.fork(this, zoneSpec);
  135. };
  136. Zone.prototype.wrap = function (callback, source) {
  137. if (typeof callback !== 'function') {
  138. throw new Error('Expecting function got: ' + callback);
  139. }
  140. var _callback = this._zoneDelegate.intercept(this, callback, source);
  141. var zone = this;
  142. return function () {
  143. return zone.runGuarded(_callback, this, arguments, source);
  144. };
  145. };
  146. Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
  147. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  148. try {
  149. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  150. }
  151. finally {
  152. _currentZoneFrame = _currentZoneFrame.parent;
  153. }
  154. };
  155. Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
  156. if (applyThis === void 0) { applyThis = null; }
  157. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  158. try {
  159. try {
  160. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  161. }
  162. catch (error) {
  163. if (this._zoneDelegate.handleError(this, error)) {
  164. throw error;
  165. }
  166. }
  167. }
  168. finally {
  169. _currentZoneFrame = _currentZoneFrame.parent;
  170. }
  171. };
  172. Zone.prototype.runTask = function (task, applyThis, applyArgs) {
  173. if (task.zone != this) {
  174. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  175. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  176. }
  177. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  178. // will run in notScheduled(canceled) state, we should not try to
  179. // run such kind of task but just return
  180. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  181. return;
  182. }
  183. var reEntryGuard = task.state != running;
  184. reEntryGuard && task._transitionTo(running, scheduled);
  185. task.runCount++;
  186. var previousTask = _currentTask;
  187. _currentTask = task;
  188. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  189. try {
  190. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  191. task.cancelFn = undefined;
  192. }
  193. try {
  194. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  195. }
  196. catch (error) {
  197. if (this._zoneDelegate.handleError(this, error)) {
  198. throw error;
  199. }
  200. }
  201. }
  202. finally {
  203. // if the task's state is notScheduled or unknown, then it has already been cancelled
  204. // we should not reset the state to scheduled
  205. if (task.state !== notScheduled && task.state !== unknown) {
  206. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  207. reEntryGuard && task._transitionTo(scheduled, running);
  208. }
  209. else {
  210. task.runCount = 0;
  211. this._updateTaskCount(task, -1);
  212. reEntryGuard &&
  213. task._transitionTo(notScheduled, running, notScheduled);
  214. }
  215. }
  216. _currentZoneFrame = _currentZoneFrame.parent;
  217. _currentTask = previousTask;
  218. }
  219. };
  220. Zone.prototype.scheduleTask = function (task) {
  221. if (task.zone && task.zone !== this) {
  222. // check if the task was rescheduled, the newZone
  223. // should not be the children of the original zone
  224. var newZone = this;
  225. while (newZone) {
  226. if (newZone === task.zone) {
  227. throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
  228. }
  229. newZone = newZone.parent;
  230. }
  231. }
  232. task._transitionTo(scheduling, notScheduled);
  233. var zoneDelegates = [];
  234. task._zoneDelegates = zoneDelegates;
  235. task._zone = this;
  236. try {
  237. task = this._zoneDelegate.scheduleTask(this, task);
  238. }
  239. catch (err) {
  240. // should set task's state to unknown when scheduleTask throw error
  241. // because the err may from reschedule, so the fromState maybe notScheduled
  242. task._transitionTo(unknown, scheduling, notScheduled);
  243. // TODO: @JiaLiPassion, should we check the result from handleError?
  244. this._zoneDelegate.handleError(this, err);
  245. throw err;
  246. }
  247. if (task._zoneDelegates === zoneDelegates) {
  248. // we have to check because internally the delegate can reschedule the task.
  249. this._updateTaskCount(task, 1);
  250. }
  251. if (task.state == scheduling) {
  252. task._transitionTo(scheduled, scheduling);
  253. }
  254. return task;
  255. };
  256. Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
  257. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  258. };
  259. Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
  260. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  261. };
  262. Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
  263. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  264. };
  265. Zone.prototype.cancelTask = function (task) {
  266. if (task.zone != this)
  267. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  268. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  269. task._transitionTo(canceling, scheduled, running);
  270. try {
  271. this._zoneDelegate.cancelTask(this, task);
  272. }
  273. catch (err) {
  274. // if error occurs when cancelTask, transit the state to unknown
  275. task._transitionTo(unknown, canceling);
  276. this._zoneDelegate.handleError(this, err);
  277. throw err;
  278. }
  279. this._updateTaskCount(task, -1);
  280. task._transitionTo(notScheduled, canceling);
  281. task.runCount = 0;
  282. return task;
  283. };
  284. Zone.prototype._updateTaskCount = function (task, count) {
  285. var zoneDelegates = task._zoneDelegates;
  286. if (count == -1) {
  287. task._zoneDelegates = null;
  288. }
  289. for (var i = 0; i < zoneDelegates.length; i++) {
  290. zoneDelegates[i]._updateTaskCount(task.type, count);
  291. }
  292. };
  293. Zone.__symbol__ = __symbol__;
  294. return Zone;
  295. }());
  296. var DELEGATE_ZS = {
  297. name: '',
  298. onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
  299. onScheduleTask: function (delegate, _, target, task) {
  300. return delegate.scheduleTask(target, task);
  301. },
  302. onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
  303. return delegate.invokeTask(target, task, applyThis, applyArgs);
  304. },
  305. onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
  306. };
  307. var ZoneDelegate = /** @class */ (function () {
  308. function ZoneDelegate(zone, parentDelegate, zoneSpec) {
  309. this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
  310. this.zone = zone;
  311. this._parentDelegate = parentDelegate;
  312. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  313. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  314. this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);
  315. this._interceptZS =
  316. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  317. this._interceptDlgt =
  318. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  319. this._interceptCurrZone =
  320. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);
  321. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  322. this._invokeDlgt =
  323. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  324. this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);
  325. this._handleErrorZS =
  326. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  327. this._handleErrorDlgt =
  328. zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  329. this._handleErrorCurrZone =
  330. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
  331. this._scheduleTaskZS =
  332. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  333. this._scheduleTaskDlgt = zoneSpec &&
  334. (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  335. this._scheduleTaskCurrZone =
  336. zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
  337. this._invokeTaskZS =
  338. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  339. this._invokeTaskDlgt =
  340. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  341. this._invokeTaskCurrZone =
  342. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);
  343. this._cancelTaskZS =
  344. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  345. this._cancelTaskDlgt =
  346. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  347. this._cancelTaskCurrZone =
  348. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);
  349. this._hasTaskZS = null;
  350. this._hasTaskDlgt = null;
  351. this._hasTaskDlgtOwner = null;
  352. this._hasTaskCurrZone = null;
  353. var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  354. var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  355. if (zoneSpecHasTask || parentHasTask) {
  356. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  357. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  358. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  359. this._hasTaskDlgt = parentDelegate;
  360. this._hasTaskDlgtOwner = this;
  361. this._hasTaskCurrZone = zone;
  362. if (!zoneSpec.onScheduleTask) {
  363. this._scheduleTaskZS = DELEGATE_ZS;
  364. this._scheduleTaskDlgt = parentDelegate;
  365. this._scheduleTaskCurrZone = this.zone;
  366. }
  367. if (!zoneSpec.onInvokeTask) {
  368. this._invokeTaskZS = DELEGATE_ZS;
  369. this._invokeTaskDlgt = parentDelegate;
  370. this._invokeTaskCurrZone = this.zone;
  371. }
  372. if (!zoneSpec.onCancelTask) {
  373. this._cancelTaskZS = DELEGATE_ZS;
  374. this._cancelTaskDlgt = parentDelegate;
  375. this._cancelTaskCurrZone = this.zone;
  376. }
  377. }
  378. }
  379. ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
  380. return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  381. new Zone(targetZone, zoneSpec);
  382. };
  383. ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
  384. return this._interceptZS ?
  385. this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  386. callback;
  387. };
  388. ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
  389. return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
  390. callback.apply(applyThis, applyArgs);
  391. };
  392. ZoneDelegate.prototype.handleError = function (targetZone, error) {
  393. return this._handleErrorZS ?
  394. this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  395. true;
  396. };
  397. ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
  398. var returnTask = task;
  399. if (this._scheduleTaskZS) {
  400. if (this._hasTaskZS) {
  401. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  402. }
  403. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  404. if (!returnTask)
  405. returnTask = task;
  406. }
  407. else {
  408. if (task.scheduleFn) {
  409. task.scheduleFn(task);
  410. }
  411. else if (task.type == microTask) {
  412. scheduleMicroTask(task);
  413. }
  414. else {
  415. throw new Error('Task is missing scheduleFn.');
  416. }
  417. }
  418. return returnTask;
  419. };
  420. ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
  421. return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
  422. task.callback.apply(applyThis, applyArgs);
  423. };
  424. ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
  425. var value;
  426. if (this._cancelTaskZS) {
  427. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  428. }
  429. else {
  430. if (!task.cancelFn) {
  431. throw Error('Task is not cancelable');
  432. }
  433. value = task.cancelFn(task);
  434. }
  435. return value;
  436. };
  437. ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
  438. // hasTask should not throw error so other ZoneDelegate
  439. // can still trigger hasTask callback
  440. try {
  441. this._hasTaskZS &&
  442. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  443. }
  444. catch (err) {
  445. this.handleError(targetZone, err);
  446. }
  447. };
  448. ZoneDelegate.prototype._updateTaskCount = function (type, count) {
  449. var counts = this._taskCounts;
  450. var prev = counts[type];
  451. var next = counts[type] = prev + count;
  452. if (next < 0) {
  453. throw new Error('More tasks executed then were scheduled.');
  454. }
  455. if (prev == 0 || next == 0) {
  456. var isEmpty = {
  457. microTask: counts['microTask'] > 0,
  458. macroTask: counts['macroTask'] > 0,
  459. eventTask: counts['eventTask'] > 0,
  460. change: type
  461. };
  462. this.hasTask(this.zone, isEmpty);
  463. }
  464. };
  465. return ZoneDelegate;
  466. }());
  467. var ZoneTask = /** @class */ (function () {
  468. function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
  469. this._zone = null;
  470. this.runCount = 0;
  471. this._zoneDelegates = null;
  472. this._state = 'notScheduled';
  473. this.type = type;
  474. this.source = source;
  475. this.data = options;
  476. this.scheduleFn = scheduleFn;
  477. this.cancelFn = cancelFn;
  478. this.callback = callback;
  479. var self = this;
  480. // TODO: @JiaLiPassion options should have interface
  481. if (type === eventTask && options && options.useG) {
  482. this.invoke = ZoneTask.invokeTask;
  483. }
  484. else {
  485. this.invoke = function () {
  486. return ZoneTask.invokeTask.call(global, self, this, arguments);
  487. };
  488. }
  489. }
  490. ZoneTask.invokeTask = function (task, target, args) {
  491. if (!task) {
  492. task = this;
  493. }
  494. _numberOfNestedTaskFrames++;
  495. try {
  496. task.runCount++;
  497. return task.zone.runTask(task, target, args);
  498. }
  499. finally {
  500. if (_numberOfNestedTaskFrames == 1) {
  501. drainMicroTaskQueue();
  502. }
  503. _numberOfNestedTaskFrames--;
  504. }
  505. };
  506. Object.defineProperty(ZoneTask.prototype, "zone", {
  507. get: function () {
  508. return this._zone;
  509. },
  510. enumerable: true,
  511. configurable: true
  512. });
  513. Object.defineProperty(ZoneTask.prototype, "state", {
  514. get: function () {
  515. return this._state;
  516. },
  517. enumerable: true,
  518. configurable: true
  519. });
  520. ZoneTask.prototype.cancelScheduleRequest = function () {
  521. this._transitionTo(notScheduled, scheduling);
  522. };
  523. ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
  524. if (this._state === fromState1 || this._state === fromState2) {
  525. this._state = toState;
  526. if (toState == notScheduled) {
  527. this._zoneDelegates = null;
  528. }
  529. }
  530. else {
  531. throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
  532. }
  533. };
  534. ZoneTask.prototype.toString = function () {
  535. if (this.data && typeof this.data.handleId !== 'undefined') {
  536. return this.data.handleId.toString();
  537. }
  538. else {
  539. return Object.prototype.toString.call(this);
  540. }
  541. };
  542. // add toJSON method to prevent cyclic error when
  543. // call JSON.stringify(zoneTask)
  544. ZoneTask.prototype.toJSON = function () {
  545. return {
  546. type: this.type,
  547. state: this.state,
  548. source: this.source,
  549. zone: this.zone.name,
  550. runCount: this.runCount
  551. };
  552. };
  553. return ZoneTask;
  554. }());
  555. //////////////////////////////////////////////////////
  556. //////////////////////////////////////////////////////
  557. /// MICROTASK QUEUE
  558. //////////////////////////////////////////////////////
  559. //////////////////////////////////////////////////////
  560. var symbolSetTimeout = __symbol__('setTimeout');
  561. var symbolPromise = __symbol__('Promise');
  562. var symbolThen = __symbol__('then');
  563. var _microTaskQueue = [];
  564. var _isDrainingMicrotaskQueue = false;
  565. var nativeMicroTaskQueuePromise;
  566. function scheduleMicroTask(task) {
  567. // if we are not running in any task, and there has not been anything scheduled
  568. // we must bootstrap the initial task creation by manually scheduling the drain
  569. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  570. // We are not running in Task, so we need to kickstart the microtask queue.
  571. if (!nativeMicroTaskQueuePromise) {
  572. if (global[symbolPromise]) {
  573. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  574. }
  575. }
  576. if (nativeMicroTaskQueuePromise) {
  577. var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  578. if (!nativeThen) {
  579. // native Promise is not patchable, we need to use `then` directly
  580. // issue 1078
  581. nativeThen = nativeMicroTaskQueuePromise['then'];
  582. }
  583. nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
  584. }
  585. else {
  586. global[symbolSetTimeout](drainMicroTaskQueue, 0);
  587. }
  588. }
  589. task && _microTaskQueue.push(task);
  590. }
  591. function drainMicroTaskQueue() {
  592. if (!_isDrainingMicrotaskQueue) {
  593. _isDrainingMicrotaskQueue = true;
  594. while (_microTaskQueue.length) {
  595. var queue = _microTaskQueue;
  596. _microTaskQueue = [];
  597. for (var i = 0; i < queue.length; i++) {
  598. var task = queue[i];
  599. try {
  600. task.zone.runTask(task, null, null);
  601. }
  602. catch (error) {
  603. _api.onUnhandledError(error);
  604. }
  605. }
  606. }
  607. _api.microtaskDrainDone();
  608. _isDrainingMicrotaskQueue = false;
  609. }
  610. }
  611. //////////////////////////////////////////////////////
  612. //////////////////////////////////////////////////////
  613. /// BOOTSTRAP
  614. //////////////////////////////////////////////////////
  615. //////////////////////////////////////////////////////
  616. var NO_ZONE = { name: 'NO ZONE' };
  617. var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  618. var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  619. var patches = {};
  620. var _api = {
  621. symbol: __symbol__,
  622. currentZoneFrame: function () { return _currentZoneFrame; },
  623. onUnhandledError: noop,
  624. microtaskDrainDone: noop,
  625. scheduleMicroTask: scheduleMicroTask,
  626. showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
  627. patchEventTarget: function () { return []; },
  628. patchOnProperties: noop,
  629. patchMethod: function () { return noop; },
  630. bindArguments: function () { return []; },
  631. patchThen: function () { return noop; },
  632. patchMacroTask: function () { return noop; },
  633. setNativePromise: function (NativePromise) {
  634. // sometimes NativePromise.resolve static function
  635. // is not ready yet, (such as core-js/es6.promise)
  636. // so we need to check here.
  637. if (NativePromise && typeof NativePromise.resolve === 'function') {
  638. nativeMicroTaskQueuePromise = NativePromise.resolve(0);
  639. }
  640. },
  641. patchEventPrototype: function () { return noop; },
  642. isIEOrEdge: function () { return false; },
  643. getGlobalObjects: function () { return undefined; },
  644. ObjectDefineProperty: function () { return noop; },
  645. ObjectGetOwnPropertyDescriptor: function () { return undefined; },
  646. ObjectCreate: function () { return undefined; },
  647. ArraySlice: function () { return []; },
  648. patchClass: function () { return noop; },
  649. wrapWithCurrentZone: function () { return noop; },
  650. filterProperties: function () { return []; },
  651. attachOriginToPatched: function () { return noop; },
  652. _redefineProperty: function () { return noop; },
  653. patchCallbacks: function () { return noop; }
  654. };
  655. var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
  656. var _currentTask = null;
  657. var _numberOfNestedTaskFrames = 0;
  658. function noop() { }
  659. function __symbol__(name) {
  660. return '__zone_symbol__' + name;
  661. }
  662. performanceMeasure('Zone', 'Zone');
  663. return global['Zone'] = Zone;
  664. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  665. var __values = (undefined && undefined.__values) || function (o) {
  666. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  667. if (m) return m.call(o);
  668. return {
  669. next: function () {
  670. if (o && i >= o.length) o = void 0;
  671. return { value: o && o[i++], done: !o };
  672. }
  673. };
  674. };
  675. /**
  676. * @license
  677. * Copyright Google Inc. All Rights Reserved.
  678. *
  679. * Use of this source code is governed by an MIT-style license that can be
  680. * found in the LICENSE file at https://angular.io/license
  681. */
  682. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  683. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  684. var ObjectDefineProperty = Object.defineProperty;
  685. function readableObjectToString(obj) {
  686. if (obj && obj.toString === Object.prototype.toString) {
  687. var className = obj.constructor && obj.constructor.name;
  688. return (className ? className : '') + ': ' + JSON.stringify(obj);
  689. }
  690. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  691. }
  692. var __symbol__ = api.symbol;
  693. var _uncaughtPromiseErrors = [];
  694. var symbolPromise = __symbol__('Promise');
  695. var symbolThen = __symbol__('then');
  696. var creationTrace = '__creationTrace__';
  697. api.onUnhandledError = function (e) {
  698. if (api.showUncaughtError()) {
  699. var rejection = e && e.rejection;
  700. if (rejection) {
  701. console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
  702. }
  703. else {
  704. console.error(e);
  705. }
  706. }
  707. };
  708. api.microtaskDrainDone = function () {
  709. while (_uncaughtPromiseErrors.length) {
  710. var _loop_1 = function () {
  711. var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  712. try {
  713. uncaughtPromiseError.zone.runGuarded(function () {
  714. throw uncaughtPromiseError;
  715. });
  716. }
  717. catch (error) {
  718. handleUnhandledRejection(error);
  719. }
  720. };
  721. while (_uncaughtPromiseErrors.length) {
  722. _loop_1();
  723. }
  724. }
  725. };
  726. var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  727. function handleUnhandledRejection(e) {
  728. api.onUnhandledError(e);
  729. try {
  730. var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  731. if (handler && typeof handler === 'function') {
  732. handler.call(this, e);
  733. }
  734. }
  735. catch (err) {
  736. }
  737. }
  738. function isThenable(value) {
  739. return value && value.then;
  740. }
  741. function forwardResolution(value) {
  742. return value;
  743. }
  744. function forwardRejection(rejection) {
  745. return ZoneAwarePromise.reject(rejection);
  746. }
  747. var symbolState = __symbol__('state');
  748. var symbolValue = __symbol__('value');
  749. var symbolFinally = __symbol__('finally');
  750. var symbolParentPromiseValue = __symbol__('parentPromiseValue');
  751. var symbolParentPromiseState = __symbol__('parentPromiseState');
  752. var source = 'Promise.then';
  753. var UNRESOLVED = null;
  754. var RESOLVED = true;
  755. var REJECTED = false;
  756. var REJECTED_NO_CATCH = 0;
  757. function makeResolver(promise, state) {
  758. return function (v) {
  759. try {
  760. resolvePromise(promise, state, v);
  761. }
  762. catch (err) {
  763. resolvePromise(promise, false, err);
  764. }
  765. // Do not return value or you will break the Promise spec.
  766. };
  767. }
  768. var once = function () {
  769. var wasCalled = false;
  770. return function wrapper(wrappedFunction) {
  771. return function () {
  772. if (wasCalled) {
  773. return;
  774. }
  775. wasCalled = true;
  776. wrappedFunction.apply(null, arguments);
  777. };
  778. };
  779. };
  780. var TYPE_ERROR = 'Promise resolved with itself';
  781. var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  782. // Promise Resolution
  783. function resolvePromise(promise, state, value) {
  784. var onceWrapper = once();
  785. if (promise === value) {
  786. throw new TypeError(TYPE_ERROR);
  787. }
  788. if (promise[symbolState] === UNRESOLVED) {
  789. // should only get value.then once based on promise spec.
  790. var then = null;
  791. try {
  792. if (typeof value === 'object' || typeof value === 'function') {
  793. then = value && value.then;
  794. }
  795. }
  796. catch (err) {
  797. onceWrapper(function () {
  798. resolvePromise(promise, false, err);
  799. })();
  800. return promise;
  801. }
  802. // if (value instanceof ZoneAwarePromise) {
  803. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  804. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  805. value[symbolState] !== UNRESOLVED) {
  806. clearRejectedNoCatch(value);
  807. resolvePromise(promise, value[symbolState], value[symbolValue]);
  808. }
  809. else if (state !== REJECTED && typeof then === 'function') {
  810. try {
  811. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  812. }
  813. catch (err) {
  814. onceWrapper(function () {
  815. resolvePromise(promise, false, err);
  816. })();
  817. }
  818. }
  819. else {
  820. promise[symbolState] = state;
  821. var queue = promise[symbolValue];
  822. promise[symbolValue] = value;
  823. if (promise[symbolFinally] === symbolFinally) {
  824. // the promise is generated by Promise.prototype.finally
  825. if (state === RESOLVED) {
  826. // the state is resolved, should ignore the value
  827. // and use parent promise value
  828. promise[symbolState] = promise[symbolParentPromiseState];
  829. promise[symbolValue] = promise[symbolParentPromiseValue];
  830. }
  831. }
  832. // record task information in value when error occurs, so we can
  833. // do some additional work such as render longStackTrace
  834. if (state === REJECTED && value instanceof Error) {
  835. // check if longStackTraceZone is here
  836. var trace = Zone.currentTask && Zone.currentTask.data &&
  837. Zone.currentTask.data[creationTrace];
  838. if (trace) {
  839. // only keep the long stack trace into error when in longStackTraceZone
  840. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  841. }
  842. }
  843. for (var i = 0; i < queue.length;) {
  844. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  845. }
  846. if (queue.length == 0 && state == REJECTED) {
  847. promise[symbolState] = REJECTED_NO_CATCH;
  848. try {
  849. // try to print more readable error log
  850. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  851. (value && value.stack ? '\n' + value.stack : ''));
  852. }
  853. catch (err) {
  854. var error_1 = err;
  855. error_1.rejection = value;
  856. error_1.promise = promise;
  857. error_1.zone = Zone.current;
  858. error_1.task = Zone.currentTask;
  859. _uncaughtPromiseErrors.push(error_1);
  860. api.scheduleMicroTask(); // to make sure that it is running
  861. }
  862. }
  863. }
  864. }
  865. // Resolving an already resolved promise is a noop.
  866. return promise;
  867. }
  868. var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  869. function clearRejectedNoCatch(promise) {
  870. if (promise[symbolState] === REJECTED_NO_CATCH) {
  871. // if the promise is rejected no catch status
  872. // and queue.length > 0, means there is a error handler
  873. // here to handle the rejected promise, we should trigger
  874. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  875. // eventHandler
  876. try {
  877. var handler = Zone[REJECTION_HANDLED_HANDLER];
  878. if (handler && typeof handler === 'function') {
  879. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  880. }
  881. }
  882. catch (err) {
  883. }
  884. promise[symbolState] = REJECTED;
  885. for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
  886. if (promise === _uncaughtPromiseErrors[i].promise) {
  887. _uncaughtPromiseErrors.splice(i, 1);
  888. }
  889. }
  890. }
  891. }
  892. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  893. clearRejectedNoCatch(promise);
  894. var promiseState = promise[symbolState];
  895. var delegate = promiseState ?
  896. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  897. (typeof onRejected === 'function') ? onRejected : forwardRejection;
  898. zone.scheduleMicroTask(source, function () {
  899. try {
  900. var parentPromiseValue = promise[symbolValue];
  901. var isFinallyPromise = chainPromise && symbolFinally === chainPromise[symbolFinally];
  902. if (isFinallyPromise) {
  903. // if the promise is generated from finally call, keep parent promise's state and value
  904. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  905. chainPromise[symbolParentPromiseState] = promiseState;
  906. }
  907. // should not pass value to finally callback
  908. var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  909. [] :
  910. [parentPromiseValue]);
  911. resolvePromise(chainPromise, true, value);
  912. }
  913. catch (error) {
  914. // if error occurs, should always return this error
  915. resolvePromise(chainPromise, false, error);
  916. }
  917. }, chainPromise);
  918. }
  919. var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  920. var ZoneAwarePromise = /** @class */ (function () {
  921. function ZoneAwarePromise(executor) {
  922. var promise = this;
  923. if (!(promise instanceof ZoneAwarePromise)) {
  924. throw new Error('Must be an instanceof Promise.');
  925. }
  926. promise[symbolState] = UNRESOLVED;
  927. promise[symbolValue] = []; // queue;
  928. try {
  929. executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
  930. }
  931. catch (error) {
  932. resolvePromise(promise, false, error);
  933. }
  934. }
  935. ZoneAwarePromise.toString = function () {
  936. return ZONE_AWARE_PROMISE_TO_STRING;
  937. };
  938. ZoneAwarePromise.resolve = function (value) {
  939. return resolvePromise(new this(null), RESOLVED, value);
  940. };
  941. ZoneAwarePromise.reject = function (error) {
  942. return resolvePromise(new this(null), REJECTED, error);
  943. };
  944. ZoneAwarePromise.race = function (values) {
  945. var e_1, _a;
  946. var resolve;
  947. var reject;
  948. var promise = new this(function (res, rej) {
  949. resolve = res;
  950. reject = rej;
  951. });
  952. function onResolve(value) {
  953. resolve(value);
  954. }
  955. function onReject(error) {
  956. reject(error);
  957. }
  958. try {
  959. for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
  960. var value = values_1_1.value;
  961. if (!isThenable(value)) {
  962. value = this.resolve(value);
  963. }
  964. value.then(onResolve, onReject);
  965. }
  966. }
  967. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  968. finally {
  969. try {
  970. if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
  971. }
  972. finally { if (e_1) throw e_1.error; }
  973. }
  974. return promise;
  975. };
  976. ZoneAwarePromise.all = function (values) {
  977. var e_2, _a;
  978. var resolve;
  979. var reject;
  980. var promise = new this(function (res, rej) {
  981. resolve = res;
  982. reject = rej;
  983. });
  984. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  985. var unresolvedCount = 2;
  986. var valueIndex = 0;
  987. var resolvedValues = [];
  988. var _loop_2 = function (value) {
  989. if (!isThenable(value)) {
  990. value = this_1.resolve(value);
  991. }
  992. var curValueIndex = valueIndex;
  993. value.then(function (value) {
  994. resolvedValues[curValueIndex] = value;
  995. unresolvedCount--;
  996. if (unresolvedCount === 0) {
  997. resolve(resolvedValues);
  998. }
  999. }, reject);
  1000. unresolvedCount++;
  1001. valueIndex++;
  1002. };
  1003. var this_1 = this;
  1004. try {
  1005. for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
  1006. var value = values_2_1.value;
  1007. _loop_2(value);
  1008. }
  1009. }
  1010. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  1011. finally {
  1012. try {
  1013. if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
  1014. }
  1015. finally { if (e_2) throw e_2.error; }
  1016. }
  1017. // Make the unresolvedCount zero-based again.
  1018. unresolvedCount -= 2;
  1019. if (unresolvedCount === 0) {
  1020. resolve(resolvedValues);
  1021. }
  1022. return promise;
  1023. };
  1024. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
  1025. get: function () {
  1026. return 'Promise';
  1027. },
  1028. enumerable: true,
  1029. configurable: true
  1030. });
  1031. ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
  1032. var chainPromise = new this.constructor(null);
  1033. var zone = Zone.current;
  1034. if (this[symbolState] == UNRESOLVED) {
  1035. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1036. }
  1037. else {
  1038. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1039. }
  1040. return chainPromise;
  1041. };
  1042. ZoneAwarePromise.prototype.catch = function (onRejected) {
  1043. return this.then(null, onRejected);
  1044. };
  1045. ZoneAwarePromise.prototype.finally = function (onFinally) {
  1046. var chainPromise = new this.constructor(null);
  1047. chainPromise[symbolFinally] = symbolFinally;
  1048. var zone = Zone.current;
  1049. if (this[symbolState] == UNRESOLVED) {
  1050. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1051. }
  1052. else {
  1053. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1054. }
  1055. return chainPromise;
  1056. };
  1057. return ZoneAwarePromise;
  1058. }());
  1059. // Protect against aggressive optimizers dropping seemingly unused properties.
  1060. // E.g. Closure Compiler in advanced mode.
  1061. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1062. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1063. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1064. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1065. var NativePromise = global[symbolPromise] = global['Promise'];
  1066. var ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
  1067. var desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
  1068. if (!desc || desc.configurable) {
  1069. desc && delete desc.writable;
  1070. desc && delete desc.value;
  1071. if (!desc) {
  1072. desc = { configurable: true, enumerable: true };
  1073. }
  1074. desc.get = function () {
  1075. // if we already set ZoneAwarePromise, use patched one
  1076. // otherwise return native one.
  1077. return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
  1078. };
  1079. desc.set = function (NewNativePromise) {
  1080. if (NewNativePromise === ZoneAwarePromise) {
  1081. // if the NewNativePromise is ZoneAwarePromise
  1082. // save to global
  1083. global[ZONE_AWARE_PROMISE] = NewNativePromise;
  1084. }
  1085. else {
  1086. // if the NewNativePromise is not ZoneAwarePromise
  1087. // for example: after load zone.js, some library just
  1088. // set es6-promise to global, if we set it to global
  1089. // directly, assertZonePatched will fail and angular
  1090. // will not loaded, so we just set the NewNativePromise
  1091. // to global[symbolPromise], so the result is just like
  1092. // we load ES6 Promise before zone.js
  1093. global[symbolPromise] = NewNativePromise;
  1094. if (!NewNativePromise.prototype[symbolThen]) {
  1095. patchThen(NewNativePromise);
  1096. }
  1097. api.setNativePromise(NewNativePromise);
  1098. }
  1099. };
  1100. ObjectDefineProperty(global, 'Promise', desc);
  1101. }
  1102. global['Promise'] = ZoneAwarePromise;
  1103. var symbolThenPatched = __symbol__('thenPatched');
  1104. function patchThen(Ctor) {
  1105. var proto = Ctor.prototype;
  1106. var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1107. if (prop && (prop.writable === false || !prop.configurable)) {
  1108. // check Ctor.prototype.then propertyDescriptor is writable or not
  1109. // in meteor env, writable is false, we should ignore such case
  1110. return;
  1111. }
  1112. var originalThen = proto.then;
  1113. // Keep a reference to the original method.
  1114. proto[symbolThen] = originalThen;
  1115. Ctor.prototype.then = function (onResolve, onReject) {
  1116. var _this = this;
  1117. var wrapped = new ZoneAwarePromise(function (resolve, reject) {
  1118. originalThen.call(_this, resolve, reject);
  1119. });
  1120. return wrapped.then(onResolve, onReject);
  1121. };
  1122. Ctor[symbolThenPatched] = true;
  1123. }
  1124. api.patchThen = patchThen;
  1125. function zoneify(fn) {
  1126. return function () {
  1127. var resultPromise = fn.apply(this, arguments);
  1128. if (resultPromise instanceof ZoneAwarePromise) {
  1129. return resultPromise;
  1130. }
  1131. var ctor = resultPromise.constructor;
  1132. if (!ctor[symbolThenPatched]) {
  1133. patchThen(ctor);
  1134. }
  1135. return resultPromise;
  1136. };
  1137. }
  1138. if (NativePromise) {
  1139. patchThen(NativePromise);
  1140. var fetch_1 = global['fetch'];
  1141. if (typeof fetch_1 == 'function') {
  1142. global[api.symbol('fetch')] = fetch_1;
  1143. global['fetch'] = zoneify(fetch_1);
  1144. }
  1145. }
  1146. // This is not part of public API, but it is useful for tests, so we expose it.
  1147. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1148. return ZoneAwarePromise;
  1149. });
  1150. /**
  1151. * @license
  1152. * Copyright Google Inc. All Rights Reserved.
  1153. *
  1154. * Use of this source code is governed by an MIT-style license that can be
  1155. * found in the LICENSE file at https://angular.io/license
  1156. */
  1157. /**
  1158. * Suppress closure compiler errors about unknown 'Zone' variable
  1159. * @fileoverview
  1160. * @suppress {undefinedVars,globalThis,missingRequire}
  1161. */
  1162. // issue #989, to reduce bundle size, use short name
  1163. /** Object.getOwnPropertyDescriptor */
  1164. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1165. /** Object.defineProperty */
  1166. var ObjectDefineProperty = Object.defineProperty;
  1167. /** Object.getPrototypeOf */
  1168. var ObjectGetPrototypeOf = Object.getPrototypeOf;
  1169. /** Object.create */
  1170. /** Array.prototype.slice */
  1171. var ArraySlice = Array.prototype.slice;
  1172. /** addEventListener string const */
  1173. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  1174. /** removeEventListener string const */
  1175. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  1176. /** zoneSymbol addEventListener */
  1177. var ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  1178. /** zoneSymbol removeEventListener */
  1179. var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  1180. /** true string const */
  1181. var TRUE_STR = 'true';
  1182. /** false string const */
  1183. var FALSE_STR = 'false';
  1184. /** __zone_symbol__ string const */
  1185. var ZONE_SYMBOL_PREFIX = '__zone_symbol__';
  1186. function wrapWithCurrentZone(callback, source) {
  1187. return Zone.current.wrap(callback, source);
  1188. }
  1189. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  1190. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  1191. }
  1192. var zoneSymbol = Zone.__symbol__;
  1193. var isWindowExists = typeof window !== 'undefined';
  1194. var internalWindow = isWindowExists ? window : undefined;
  1195. var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  1196. var REMOVE_ATTRIBUTE = 'removeAttribute';
  1197. var NULL_ON_PROP_VALUE = [null];
  1198. function bindArguments(args, source) {
  1199. for (var i = args.length - 1; i >= 0; i--) {
  1200. if (typeof args[i] === 'function') {
  1201. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  1202. }
  1203. }
  1204. return args;
  1205. }
  1206. function isPropertyWritable(propertyDesc) {
  1207. if (!propertyDesc) {
  1208. return true;
  1209. }
  1210. if (propertyDesc.writable === false) {
  1211. return false;
  1212. }
  1213. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  1214. }
  1215. var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  1216. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  1217. // this code.
  1218. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  1219. {}.toString.call(_global.process) === '[object process]');
  1220. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  1221. // we are in electron of nw, so we are both browser and nodejs
  1222. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  1223. // this code.
  1224. var isMix = typeof _global.process !== 'undefined' &&
  1225. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  1226. !!(isWindowExists && internalWindow['HTMLElement']);
  1227. var zoneSymbolEventNames = {};
  1228. var wrapFn = function (event) {
  1229. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1230. // event will be undefined, so we need to use window.event
  1231. event = event || _global.event;
  1232. if (!event) {
  1233. return;
  1234. }
  1235. var eventNameSymbol = zoneSymbolEventNames[event.type];
  1236. if (!eventNameSymbol) {
  1237. eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  1238. }
  1239. var target = this || event.target || _global;
  1240. var listener = target[eventNameSymbol];
  1241. var result;
  1242. if (isBrowser && target === internalWindow && event.type === 'error') {
  1243. // window.onerror have different signiture
  1244. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  1245. // and onerror callback will prevent default when callback return true
  1246. var errorEvent = event;
  1247. result = listener &&
  1248. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  1249. if (result === true) {
  1250. event.preventDefault();
  1251. }
  1252. }
  1253. else {
  1254. result = listener && listener.apply(this, arguments);
  1255. if (result != undefined && !result) {
  1256. event.preventDefault();
  1257. }
  1258. }
  1259. return result;
  1260. };
  1261. function patchProperty(obj, prop, prototype) {
  1262. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  1263. if (!desc && prototype) {
  1264. // when patch window object, use prototype to check prop exist or not
  1265. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  1266. if (prototypeDesc) {
  1267. desc = { enumerable: true, configurable: true };
  1268. }
  1269. }
  1270. // if the descriptor not exists or is not configurable
  1271. // just return
  1272. if (!desc || !desc.configurable) {
  1273. return;
  1274. }
  1275. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  1276. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  1277. return;
  1278. }
  1279. // A property descriptor cannot have getter/setter and be writable
  1280. // deleting the writable and value properties avoids this error:
  1281. //
  1282. // TypeError: property descriptors must not specify a value or be writable when a
  1283. // getter or setter has been specified
  1284. delete desc.writable;
  1285. delete desc.value;
  1286. var originalDescGet = desc.get;
  1287. var originalDescSet = desc.set;
  1288. // substr(2) cuz 'onclick' -> 'click', etc
  1289. var eventName = prop.substr(2);
  1290. var eventNameSymbol = zoneSymbolEventNames[eventName];
  1291. if (!eventNameSymbol) {
  1292. eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  1293. }
  1294. desc.set = function (newValue) {
  1295. // in some of windows's onproperty callback, this is undefined
  1296. // so we need to check it
  1297. var target = this;
  1298. if (!target && obj === _global) {
  1299. target = _global;
  1300. }
  1301. if (!target) {
  1302. return;
  1303. }
  1304. var previousValue = target[eventNameSymbol];
  1305. if (previousValue) {
  1306. target.removeEventListener(eventName, wrapFn);
  1307. }
  1308. // issue #978, when onload handler was added before loading zone.js
  1309. // we should remove it with originalDescSet
  1310. if (originalDescSet) {
  1311. originalDescSet.apply(target, NULL_ON_PROP_VALUE);
  1312. }
  1313. if (typeof newValue === 'function') {
  1314. target[eventNameSymbol] = newValue;
  1315. target.addEventListener(eventName, wrapFn, false);
  1316. }
  1317. else {
  1318. target[eventNameSymbol] = null;
  1319. }
  1320. };
  1321. // The getter would return undefined for unassigned properties but the default value of an
  1322. // unassigned property is null
  1323. desc.get = function () {
  1324. // in some of windows's onproperty callback, this is undefined
  1325. // so we need to check it
  1326. var target = this;
  1327. if (!target && obj === _global) {
  1328. target = _global;
  1329. }
  1330. if (!target) {
  1331. return null;
  1332. }
  1333. var listener = target[eventNameSymbol];
  1334. if (listener) {
  1335. return listener;
  1336. }
  1337. else if (originalDescGet) {
  1338. // result will be null when use inline event attribute,
  1339. // such as <button onclick="func();">OK</button>
  1340. // because the onclick function is internal raw uncompiled handler
  1341. // the onclick will be evaluated when first time event was triggered or
  1342. // the property is accessed, https://github.com/angular/zone.js/issues/525
  1343. // so we should use original native get to retrieve the handler
  1344. var value = originalDescGet && originalDescGet.call(this);
  1345. if (value) {
  1346. desc.set.call(this, value);
  1347. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  1348. target.removeAttribute(prop);
  1349. }
  1350. return value;
  1351. }
  1352. }
  1353. return null;
  1354. };
  1355. ObjectDefineProperty(obj, prop, desc);
  1356. obj[onPropPatchedSymbol] = true;
  1357. }
  1358. function patchOnProperties(obj, properties, prototype) {
  1359. if (properties) {
  1360. for (var i = 0; i < properties.length; i++) {
  1361. patchProperty(obj, 'on' + properties[i], prototype);
  1362. }
  1363. }
  1364. else {
  1365. var onProperties = [];
  1366. for (var prop in obj) {
  1367. if (prop.substr(0, 2) == 'on') {
  1368. onProperties.push(prop);
  1369. }
  1370. }
  1371. for (var j = 0; j < onProperties.length; j++) {
  1372. patchProperty(obj, onProperties[j], prototype);
  1373. }
  1374. }
  1375. }
  1376. var originalInstanceKey = zoneSymbol('originalInstance');
  1377. // wrap some native API on `window`
  1378. function copySymbolProperties(src, dest) {
  1379. if (typeof Object.getOwnPropertySymbols !== 'function') {
  1380. return;
  1381. }
  1382. var symbols = Object.getOwnPropertySymbols(src);
  1383. symbols.forEach(function (symbol) {
  1384. var desc = Object.getOwnPropertyDescriptor(src, symbol);
  1385. Object.defineProperty(dest, symbol, {
  1386. get: function () {
  1387. return src[symbol];
  1388. },
  1389. set: function (value) {
  1390. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1391. // if src[symbol] is not writable or not have a setter, just return
  1392. return;
  1393. }
  1394. src[symbol] = value;
  1395. },
  1396. enumerable: desc ? desc.enumerable : true,
  1397. configurable: desc ? desc.configurable : true
  1398. });
  1399. });
  1400. }
  1401. var shouldCopySymbolProperties = false;
  1402. function setShouldCopySymbolProperties(flag) {
  1403. shouldCopySymbolProperties = flag;
  1404. }
  1405. function patchMethod(target, name, patchFn) {
  1406. var proto = target;
  1407. while (proto && !proto.hasOwnProperty(name)) {
  1408. proto = ObjectGetPrototypeOf(proto);
  1409. }
  1410. if (!proto && target[name]) {
  1411. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1412. proto = target;
  1413. }
  1414. var delegateName = zoneSymbol(name);
  1415. var delegate = null;
  1416. if (proto && !(delegate = proto[delegateName])) {
  1417. delegate = proto[delegateName] = proto[name];
  1418. // check whether proto[name] is writable
  1419. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1420. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1421. if (isPropertyWritable(desc)) {
  1422. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  1423. proto[name] = function () {
  1424. return patchDelegate_1(this, arguments);
  1425. };
  1426. attachOriginToPatched(proto[name], delegate);
  1427. if (shouldCopySymbolProperties) {
  1428. copySymbolProperties(delegate, proto[name]);
  1429. }
  1430. }
  1431. }
  1432. return delegate;
  1433. }
  1434. // TODO: @JiaLiPassion, support cancel task later if necessary
  1435. function patchMacroTask(obj, funcName, metaCreator) {
  1436. var setNative = null;
  1437. function scheduleTask(task) {
  1438. var data = task.data;
  1439. data.args[data.cbIdx] = function () {
  1440. task.invoke.apply(this, arguments);
  1441. };
  1442. setNative.apply(data.target, data.args);
  1443. return task;
  1444. }
  1445. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1446. var meta = metaCreator(self, args);
  1447. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1448. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1449. }
  1450. else {
  1451. // cause an error by calling it directly.
  1452. return delegate.apply(self, args);
  1453. }
  1454. }; });
  1455. }
  1456. function patchMicroTask(obj, funcName, metaCreator) {
  1457. var setNative = null;
  1458. function scheduleTask(task) {
  1459. var data = task.data;
  1460. data.args[data.cbIdx] = function () {
  1461. task.invoke.apply(this, arguments);
  1462. };
  1463. setNative.apply(data.target, data.args);
  1464. return task;
  1465. }
  1466. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1467. var meta = metaCreator(self, args);
  1468. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1469. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1470. }
  1471. else {
  1472. // cause an error by calling it directly.
  1473. return delegate.apply(self, args);
  1474. }
  1475. }; });
  1476. }
  1477. function attachOriginToPatched(patched, original) {
  1478. patched[zoneSymbol('OriginalDelegate')] = original;
  1479. }
  1480. /**
  1481. * @license
  1482. * Copyright Google Inc. All Rights Reserved.
  1483. *
  1484. * Use of this source code is governed by an MIT-style license that can be
  1485. * found in the LICENSE file at https://angular.io/license
  1486. */
  1487. // override Function.prototype.toString to make zone.js patched function
  1488. // look like native function
  1489. Zone.__load_patch('toString', function (global) {
  1490. // patch Func.prototype.toString to let them look like native
  1491. var originalFunctionToString = Function.prototype.toString;
  1492. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1493. var PROMISE_SYMBOL = zoneSymbol('Promise');
  1494. var ERROR_SYMBOL = zoneSymbol('Error');
  1495. var newFunctionToString = function toString() {
  1496. if (typeof this === 'function') {
  1497. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1498. if (originalDelegate) {
  1499. if (typeof originalDelegate === 'function') {
  1500. return originalFunctionToString.call(originalDelegate);
  1501. }
  1502. else {
  1503. return Object.prototype.toString.call(originalDelegate);
  1504. }
  1505. }
  1506. if (this === Promise) {
  1507. var nativePromise = global[PROMISE_SYMBOL];
  1508. if (nativePromise) {
  1509. return originalFunctionToString.call(nativePromise);
  1510. }
  1511. }
  1512. if (this === Error) {
  1513. var nativeError = global[ERROR_SYMBOL];
  1514. if (nativeError) {
  1515. return originalFunctionToString.call(nativeError);
  1516. }
  1517. }
  1518. }
  1519. return originalFunctionToString.call(this);
  1520. };
  1521. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1522. Function.prototype.toString = newFunctionToString;
  1523. // patch Object.prototype.toString to let them look like native
  1524. var originalObjectToString = Object.prototype.toString;
  1525. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1526. Object.prototype.toString = function () {
  1527. if (this instanceof Promise) {
  1528. return PROMISE_OBJECT_TO_STRING;
  1529. }
  1530. return originalObjectToString.call(this);
  1531. };
  1532. });
  1533. /**
  1534. * @license
  1535. * Copyright Google Inc. All Rights Reserved.
  1536. *
  1537. * Use of this source code is governed by an MIT-style license that can be
  1538. * found in the LICENSE file at https://angular.io/license
  1539. */
  1540. Zone.__load_patch('node_util', function (global, Zone, api) {
  1541. api.patchOnProperties = patchOnProperties;
  1542. api.patchMethod = patchMethod;
  1543. api.bindArguments = bindArguments;
  1544. api.patchMacroTask = patchMacroTask;
  1545. setShouldCopySymbolProperties(true);
  1546. });
  1547. /**
  1548. * @license
  1549. * Copyright Google Inc. All Rights Reserved.
  1550. *
  1551. * Use of this source code is governed by an MIT-style license that can be
  1552. * found in the LICENSE file at https://angular.io/license
  1553. */
  1554. /**
  1555. * @fileoverview
  1556. * @suppress {missingRequire}
  1557. */
  1558. var passiveSupported = false;
  1559. if (typeof window !== 'undefined') {
  1560. try {
  1561. var options = Object.defineProperty({}, 'passive', {
  1562. get: function () {
  1563. passiveSupported = true;
  1564. }
  1565. });
  1566. window.addEventListener('test', options, options);
  1567. window.removeEventListener('test', options, options);
  1568. }
  1569. catch (err) {
  1570. passiveSupported = false;
  1571. }
  1572. }
  1573. // an identifier to tell ZoneTask do not create a new invoke closure
  1574. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1575. useG: true
  1576. };
  1577. var zoneSymbolEventNames$1 = {};
  1578. var globalSources = {};
  1579. var EVENT_NAME_SYMBOL_REGX = /^__zone_symbol__(\w+)(true|false)$/;
  1580. var IMMEDIATE_PROPAGATION_SYMBOL = ('__zone_symbol__propagationStopped');
  1581. function patchEventTarget(_global, apis, patchOptions) {
  1582. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1583. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1584. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1585. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1586. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1587. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1588. var PREPEND_EVENT_LISTENER = 'prependListener';
  1589. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1590. var invokeTask = function (task, target, event) {
  1591. // for better performance, check isRemoved which is set
  1592. // by removeEventListener
  1593. if (task.isRemoved) {
  1594. return;
  1595. }
  1596. var delegate = task.callback;
  1597. if (typeof delegate === 'object' && delegate.handleEvent) {
  1598. // create the bind version of handleEvent when invoke
  1599. task.callback = function (event) { return delegate.handleEvent(event); };
  1600. task.originalDelegate = delegate;
  1601. }
  1602. // invoke static task.invoke
  1603. task.invoke(task, target, [event]);
  1604. var options = task.options;
  1605. if (options && typeof options === 'object' && options.once) {
  1606. // if options.once is true, after invoke once remove listener here
  1607. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1608. // inside EventEmitter.once
  1609. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1610. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1611. }
  1612. };
  1613. // global shared zoneAwareCallback to handle all event callback with capture = false
  1614. var globalZoneAwareCallback = function (event) {
  1615. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1616. // event will be undefined, so we need to use window.event
  1617. event = event || _global.event;
  1618. if (!event) {
  1619. return;
  1620. }
  1621. // event.target is needed for Samsung TV and SourceBuffer
  1622. // || global is needed https://github.com/angular/zone.js/issues/190
  1623. var target = this || event.target || _global;
  1624. var tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
  1625. if (tasks) {
  1626. // invoke all tasks which attached to current target with given event.type and capture = false
  1627. // for performance concern, if task.length === 1, just invoke
  1628. if (tasks.length === 1) {
  1629. invokeTask(tasks[0], target, event);
  1630. }
  1631. else {
  1632. // https://github.com/angular/zone.js/issues/836
  1633. // copy the tasks array before invoke, to avoid
  1634. // the callback will remove itself or other listener
  1635. var copyTasks = tasks.slice();
  1636. for (var i = 0; i < copyTasks.length; i++) {
  1637. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1638. break;
  1639. }
  1640. invokeTask(copyTasks[i], target, event);
  1641. }
  1642. }
  1643. }
  1644. };
  1645. // global shared zoneAwareCallback to handle all event callback with capture = true
  1646. var globalZoneAwareCaptureCallback = function (event) {
  1647. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1648. // event will be undefined, so we need to use window.event
  1649. event = event || _global.event;
  1650. if (!event) {
  1651. return;
  1652. }
  1653. // event.target is needed for Samsung TV and SourceBuffer
  1654. // || global is needed https://github.com/angular/zone.js/issues/190
  1655. var target = this || event.target || _global;
  1656. var tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
  1657. if (tasks) {
  1658. // invoke all tasks which attached to current target with given event.type and capture = false
  1659. // for performance concern, if task.length === 1, just invoke
  1660. if (tasks.length === 1) {
  1661. invokeTask(tasks[0], target, event);
  1662. }
  1663. else {
  1664. // https://github.com/angular/zone.js/issues/836
  1665. // copy the tasks array before invoke, to avoid
  1666. // the callback will remove itself or other listener
  1667. var copyTasks = tasks.slice();
  1668. for (var i = 0; i < copyTasks.length; i++) {
  1669. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1670. break;
  1671. }
  1672. invokeTask(copyTasks[i], target, event);
  1673. }
  1674. }
  1675. }
  1676. };
  1677. function patchEventTargetMethods(obj, patchOptions) {
  1678. if (!obj) {
  1679. return false;
  1680. }
  1681. var useGlobalCallback = true;
  1682. if (patchOptions && patchOptions.useG !== undefined) {
  1683. useGlobalCallback = patchOptions.useG;
  1684. }
  1685. var validateHandler = patchOptions && patchOptions.vh;
  1686. var checkDuplicate = true;
  1687. if (patchOptions && patchOptions.chkDup !== undefined) {
  1688. checkDuplicate = patchOptions.chkDup;
  1689. }
  1690. var returnTarget = false;
  1691. if (patchOptions && patchOptions.rt !== undefined) {
  1692. returnTarget = patchOptions.rt;
  1693. }
  1694. var proto = obj;
  1695. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1696. proto = ObjectGetPrototypeOf(proto);
  1697. }
  1698. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1699. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1700. proto = obj;
  1701. }
  1702. if (!proto) {
  1703. return false;
  1704. }
  1705. if (proto[zoneSymbolAddEventListener]) {
  1706. return false;
  1707. }
  1708. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1709. // a shared global taskData to pass data for scheduleEventTask
  1710. // so we do not need to create a new object just for pass some data
  1711. var taskData = {};
  1712. var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1713. var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1714. proto[REMOVE_EVENT_LISTENER];
  1715. var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1716. proto[LISTENERS_EVENT_LISTENER];
  1717. var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1718. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1719. var nativePrependEventListener;
  1720. if (patchOptions && patchOptions.prepend) {
  1721. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1722. proto[patchOptions.prepend];
  1723. }
  1724. function checkIsPassive(task) {
  1725. if (!passiveSupported && typeof taskData.options !== 'boolean' &&
  1726. typeof taskData.options !== 'undefined' && taskData.options !== null) {
  1727. // options is a non-null non-undefined object
  1728. // passive is not supported
  1729. // don't pass options as object
  1730. // just pass capture as a boolean
  1731. task.options = !!taskData.options.capture;
  1732. taskData.options = task.options;
  1733. }
  1734. }
  1735. var customScheduleGlobal = function (task) {
  1736. // if there is already a task for the eventName + capture,
  1737. // just return, because we use the shared globalZoneAwareCallback here.
  1738. if (taskData.isExisting) {
  1739. return;
  1740. }
  1741. checkIsPassive(task);
  1742. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1743. };
  1744. var customCancelGlobal = function (task) {
  1745. // if task is not marked as isRemoved, this call is directly
  1746. // from Zone.prototype.cancelTask, we should remove the task
  1747. // from tasksList of target first
  1748. if (!task.isRemoved) {
  1749. var symbolEventNames = zoneSymbolEventNames$1[task.eventName];
  1750. var symbolEventName = void 0;
  1751. if (symbolEventNames) {
  1752. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1753. }
  1754. var existingTasks = symbolEventName && task.target[symbolEventName];
  1755. if (existingTasks) {
  1756. for (var i = 0; i < existingTasks.length; i++) {
  1757. var existingTask = existingTasks[i];
  1758. if (existingTask === task) {
  1759. existingTasks.splice(i, 1);
  1760. // set isRemoved to data for faster invokeTask check
  1761. task.isRemoved = true;
  1762. if (existingTasks.length === 0) {
  1763. // all tasks for the eventName + capture have gone,
  1764. // remove globalZoneAwareCallback and remove the task cache from target
  1765. task.allRemoved = true;
  1766. task.target[symbolEventName] = null;
  1767. }
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. }
  1773. // if all tasks for the eventName + capture have gone,
  1774. // we will really remove the global event callback,
  1775. // if not, return
  1776. if (!task.allRemoved) {
  1777. return;
  1778. }
  1779. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1780. };
  1781. var customScheduleNonGlobal = function (task) {
  1782. checkIsPassive(task);
  1783. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1784. };
  1785. var customSchedulePrepend = function (task) {
  1786. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1787. };
  1788. var customCancelNonGlobal = function (task) {
  1789. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1790. };
  1791. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1792. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1793. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1794. var typeOfDelegate = typeof delegate;
  1795. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1796. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1797. };
  1798. var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1799. var blackListedEvents = Zone[Zone.__symbol__('BLACK_LISTED_EVENTS')];
  1800. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1801. if (returnTarget === void 0) { returnTarget = false; }
  1802. if (prepend === void 0) { prepend = false; }
  1803. return function () {
  1804. var target = this || _global;
  1805. var eventName = arguments[0];
  1806. var delegate = arguments[1];
  1807. if (!delegate) {
  1808. return nativeListener.apply(this, arguments);
  1809. }
  1810. if (isNode && eventName === 'uncaughtException') {
  1811. // don't patch uncaughtException of nodejs to prevent endless loop
  1812. return nativeListener.apply(this, arguments);
  1813. }
  1814. // don't create the bind delegate function for handleEvent
  1815. // case here to improve addEventListener performance
  1816. // we will create the bind delegate when invoke
  1817. var isHandleEvent = false;
  1818. if (typeof delegate !== 'function') {
  1819. if (!delegate.handleEvent) {
  1820. return nativeListener.apply(this, arguments);
  1821. }
  1822. isHandleEvent = true;
  1823. }
  1824. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1825. return;
  1826. }
  1827. var options = arguments[2];
  1828. if (blackListedEvents) {
  1829. // check black list
  1830. for (var i = 0; i < blackListedEvents.length; i++) {
  1831. if (eventName === blackListedEvents[i]) {
  1832. return nativeListener.apply(this, arguments);
  1833. }
  1834. }
  1835. }
  1836. var capture;
  1837. var once = false;
  1838. if (options === undefined) {
  1839. capture = false;
  1840. }
  1841. else if (options === true) {
  1842. capture = true;
  1843. }
  1844. else if (options === false) {
  1845. capture = false;
  1846. }
  1847. else {
  1848. capture = options ? !!options.capture : false;
  1849. once = options ? !!options.once : false;
  1850. }
  1851. var zone = Zone.current;
  1852. var symbolEventNames = zoneSymbolEventNames$1[eventName];
  1853. var symbolEventName;
  1854. if (!symbolEventNames) {
  1855. // the code is duplicate, but I just want to get some better performance
  1856. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1857. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1858. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1859. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1860. zoneSymbolEventNames$1[eventName] = {};
  1861. zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
  1862. zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
  1863. symbolEventName = capture ? symbolCapture : symbol;
  1864. }
  1865. else {
  1866. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1867. }
  1868. var existingTasks = target[symbolEventName];
  1869. var isExisting = false;
  1870. if (existingTasks) {
  1871. // already have task registered
  1872. isExisting = true;
  1873. if (checkDuplicate) {
  1874. for (var i = 0; i < existingTasks.length; i++) {
  1875. if (compare(existingTasks[i], delegate)) {
  1876. // same callback, same capture, same event name, just return
  1877. return;
  1878. }
  1879. }
  1880. }
  1881. }
  1882. else {
  1883. existingTasks = target[symbolEventName] = [];
  1884. }
  1885. var source;
  1886. var constructorName = target.constructor['name'];
  1887. var targetSource = globalSources[constructorName];
  1888. if (targetSource) {
  1889. source = targetSource[eventName];
  1890. }
  1891. if (!source) {
  1892. source = constructorName + addSource +
  1893. (eventNameToString ? eventNameToString(eventName) : eventName);
  1894. }
  1895. // do not create a new object as task.data to pass those things
  1896. // just use the global shared one
  1897. taskData.options = options;
  1898. if (once) {
  1899. // if addEventListener with once options, we don't pass it to
  1900. // native addEventListener, instead we keep the once setting
  1901. // and handle ourselves.
  1902. taskData.options.once = false;
  1903. }
  1904. taskData.target = target;
  1905. taskData.capture = capture;
  1906. taskData.eventName = eventName;
  1907. taskData.isExisting = isExisting;
  1908. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1909. // keep taskData into data to allow onScheduleEventTask to access the task information
  1910. if (data) {
  1911. data.taskData = taskData;
  1912. }
  1913. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1914. // should clear taskData.target to avoid memory leak
  1915. // issue, https://github.com/angular/angular/issues/20442
  1916. taskData.target = null;
  1917. // need to clear up taskData because it is a global object
  1918. if (data) {
  1919. data.taskData = null;
  1920. }
  1921. // have to save those information to task in case
  1922. // application may call task.zone.cancelTask() directly
  1923. if (once) {
  1924. options.once = true;
  1925. }
  1926. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1927. // if not support passive, and we pass an option object
  1928. // to addEventListener, we should save the options to task
  1929. task.options = options;
  1930. }
  1931. task.target = target;
  1932. task.capture = capture;
  1933. task.eventName = eventName;
  1934. if (isHandleEvent) {
  1935. // save original delegate for compare to check duplicate
  1936. task.originalDelegate = delegate;
  1937. }
  1938. if (!prepend) {
  1939. existingTasks.push(task);
  1940. }
  1941. else {
  1942. existingTasks.unshift(task);
  1943. }
  1944. if (returnTarget) {
  1945. return target;
  1946. }
  1947. };
  1948. };
  1949. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1950. if (nativePrependEventListener) {
  1951. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1952. }
  1953. proto[REMOVE_EVENT_LISTENER] = function () {
  1954. var target = this || _global;
  1955. var eventName = arguments[0];
  1956. var options = arguments[2];
  1957. var capture;
  1958. if (options === undefined) {
  1959. capture = false;
  1960. }
  1961. else if (options === true) {
  1962. capture = true;
  1963. }
  1964. else if (options === false) {
  1965. capture = false;
  1966. }
  1967. else {
  1968. capture = options ? !!options.capture : false;
  1969. }
  1970. var delegate = arguments[1];
  1971. if (!delegate) {
  1972. return nativeRemoveEventListener.apply(this, arguments);
  1973. }
  1974. if (validateHandler &&
  1975. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  1976. return;
  1977. }
  1978. var symbolEventNames = zoneSymbolEventNames$1[eventName];
  1979. var symbolEventName;
  1980. if (symbolEventNames) {
  1981. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1982. }
  1983. var existingTasks = symbolEventName && target[symbolEventName];
  1984. if (existingTasks) {
  1985. for (var i = 0; i < existingTasks.length; i++) {
  1986. var existingTask = existingTasks[i];
  1987. if (compare(existingTask, delegate)) {
  1988. existingTasks.splice(i, 1);
  1989. // set isRemoved to data for faster invokeTask check
  1990. existingTask.isRemoved = true;
  1991. if (existingTasks.length === 0) {
  1992. // all tasks for the eventName + capture have gone,
  1993. // remove globalZoneAwareCallback and remove the task cache from target
  1994. existingTask.allRemoved = true;
  1995. target[symbolEventName] = null;
  1996. }
  1997. existingTask.zone.cancelTask(existingTask);
  1998. if (returnTarget) {
  1999. return target;
  2000. }
  2001. return;
  2002. }
  2003. }
  2004. }
  2005. // issue 930, didn't find the event name or callback
  2006. // from zone kept existingTasks, the callback maybe
  2007. // added outside of zone, we need to call native removeEventListener
  2008. // to try to remove it.
  2009. return nativeRemoveEventListener.apply(this, arguments);
  2010. };
  2011. proto[LISTENERS_EVENT_LISTENER] = function () {
  2012. var target = this || _global;
  2013. var eventName = arguments[0];
  2014. var listeners = [];
  2015. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2016. for (var i = 0; i < tasks.length; i++) {
  2017. var task = tasks[i];
  2018. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2019. listeners.push(delegate);
  2020. }
  2021. return listeners;
  2022. };
  2023. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2024. var target = this || _global;
  2025. var eventName = arguments[0];
  2026. if (!eventName) {
  2027. var keys = Object.keys(target);
  2028. for (var i = 0; i < keys.length; i++) {
  2029. var prop = keys[i];
  2030. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2031. var evtName = match && match[1];
  2032. // in nodejs EventEmitter, removeListener event is
  2033. // used for monitoring the removeListener call,
  2034. // so just keep removeListener eventListener until
  2035. // all other eventListeners are removed
  2036. if (evtName && evtName !== 'removeListener') {
  2037. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2038. }
  2039. }
  2040. // remove removeListener listener finally
  2041. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2042. }
  2043. else {
  2044. var symbolEventNames = zoneSymbolEventNames$1[eventName];
  2045. if (symbolEventNames) {
  2046. var symbolEventName = symbolEventNames[FALSE_STR];
  2047. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2048. var tasks = target[symbolEventName];
  2049. var captureTasks = target[symbolCaptureEventName];
  2050. if (tasks) {
  2051. var removeTasks = tasks.slice();
  2052. for (var i = 0; i < removeTasks.length; i++) {
  2053. var task = removeTasks[i];
  2054. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2055. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2056. }
  2057. }
  2058. if (captureTasks) {
  2059. var removeTasks = captureTasks.slice();
  2060. for (var i = 0; i < removeTasks.length; i++) {
  2061. var task = removeTasks[i];
  2062. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2063. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2064. }
  2065. }
  2066. }
  2067. }
  2068. if (returnTarget) {
  2069. return this;
  2070. }
  2071. };
  2072. // for native toString patch
  2073. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2074. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2075. if (nativeRemoveAllListeners) {
  2076. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2077. }
  2078. if (nativeListeners) {
  2079. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2080. }
  2081. return true;
  2082. }
  2083. var results = [];
  2084. for (var i = 0; i < apis.length; i++) {
  2085. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2086. }
  2087. return results;
  2088. }
  2089. function findEventTasks(target, eventName) {
  2090. var foundTasks = [];
  2091. for (var prop in target) {
  2092. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2093. var evtName = match && match[1];
  2094. if (evtName && (!eventName || evtName === eventName)) {
  2095. var tasks = target[prop];
  2096. if (tasks) {
  2097. for (var i = 0; i < tasks.length; i++) {
  2098. foundTasks.push(tasks[i]);
  2099. }
  2100. }
  2101. }
  2102. }
  2103. return foundTasks;
  2104. }
  2105. /**
  2106. * @license
  2107. * Copyright Google Inc. All Rights Reserved.
  2108. *
  2109. * Use of this source code is governed by an MIT-style license that can be
  2110. * found in the LICENSE file at https://angular.io/license
  2111. */
  2112. Zone.__load_patch('EventEmitter', function (global) {
  2113. // For EventEmitter
  2114. var EE_ADD_LISTENER = 'addListener';
  2115. var EE_PREPEND_LISTENER = 'prependListener';
  2116. var EE_REMOVE_LISTENER = 'removeListener';
  2117. var EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2118. var EE_LISTENERS = 'listeners';
  2119. var EE_ON = 'on';
  2120. var compareTaskCallbackVsDelegate = function (task, delegate) {
  2121. // same callback, same capture, same event name, just return
  2122. return task.callback === delegate || task.callback.listener === delegate;
  2123. };
  2124. var eventNameToString = function (eventName) {
  2125. if (typeof eventName === 'string') {
  2126. return eventName;
  2127. }
  2128. if (!eventName) {
  2129. return '';
  2130. }
  2131. return eventName.toString().replace('(', '_').replace(')', '_');
  2132. };
  2133. function patchEventEmitterMethods(obj) {
  2134. var result = patchEventTarget(global, [obj], {
  2135. useG: false,
  2136. add: EE_ADD_LISTENER,
  2137. rm: EE_REMOVE_LISTENER,
  2138. prepend: EE_PREPEND_LISTENER,
  2139. rmAll: EE_REMOVE_ALL_LISTENER,
  2140. listeners: EE_LISTENERS,
  2141. chkDup: false,
  2142. rt: true,
  2143. diff: compareTaskCallbackVsDelegate,
  2144. eventNameToString: eventNameToString
  2145. });
  2146. if (result && result[0]) {
  2147. obj[EE_ON] = obj[EE_ADD_LISTENER];
  2148. }
  2149. }
  2150. // EventEmitter
  2151. var events;
  2152. try {
  2153. events = require('events');
  2154. }
  2155. catch (err) {
  2156. }
  2157. if (events && events.EventEmitter) {
  2158. patchEventEmitterMethods(events.EventEmitter.prototype);
  2159. }
  2160. });
  2161. /**
  2162. * @license
  2163. * Copyright Google Inc. All Rights Reserved.
  2164. *
  2165. * Use of this source code is governed by an MIT-style license that can be
  2166. * found in the LICENSE file at https://angular.io/license
  2167. */
  2168. Zone.__load_patch('fs', function () {
  2169. var fs;
  2170. try {
  2171. fs = require('fs');
  2172. }
  2173. catch (err) {
  2174. }
  2175. // watch, watchFile, unwatchFile has been patched
  2176. // because EventEmitter has been patched
  2177. var TO_PATCH_MACROTASK_METHODS = [
  2178. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  2179. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  2180. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  2181. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  2182. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  2183. ];
  2184. if (fs) {
  2185. TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; })
  2186. .forEach(function (name) {
  2187. patchMacroTask(fs, name, function (self, args) {
  2188. return {
  2189. name: 'fs.' + name,
  2190. args: args,
  2191. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2192. target: self
  2193. };
  2194. });
  2195. });
  2196. }
  2197. });
  2198. /**
  2199. * @license
  2200. * Copyright Google Inc. All Rights Reserved.
  2201. *
  2202. * Use of this source code is governed by an MIT-style license that can be
  2203. * found in the LICENSE file at https://angular.io/license
  2204. */
  2205. /**
  2206. * @fileoverview
  2207. * @suppress {missingRequire}
  2208. */
  2209. var taskSymbol = zoneSymbol('zoneTask');
  2210. function patchTimer(window, setName, cancelName, nameSuffix) {
  2211. var setNative = null;
  2212. var clearNative = null;
  2213. setName += nameSuffix;
  2214. cancelName += nameSuffix;
  2215. var tasksByHandleId = {};
  2216. function scheduleTask(task) {
  2217. var data = task.data;
  2218. function timer() {
  2219. try {
  2220. task.invoke.apply(this, arguments);
  2221. }
  2222. finally {
  2223. // issue-934, task will be cancelled
  2224. // even it is a periodic task such as
  2225. // setInterval
  2226. if (!(task.data && task.data.isPeriodic)) {
  2227. if (typeof data.handleId === 'number') {
  2228. // in non-nodejs env, we remove timerId
  2229. // from local cache
  2230. delete tasksByHandleId[data.handleId];
  2231. }
  2232. else if (data.handleId) {
  2233. // Node returns complex objects as handleIds
  2234. // we remove task reference from timer object
  2235. data.handleId[taskSymbol] = null;
  2236. }
  2237. }
  2238. }
  2239. }
  2240. data.args[0] = timer;
  2241. data.handleId = setNative.apply(window, data.args);
  2242. return task;
  2243. }
  2244. function clearTask(task) {
  2245. return clearNative(task.data.handleId);
  2246. }
  2247. setNative =
  2248. patchMethod(window, setName, function (delegate) { return function (self, args) {
  2249. if (typeof args[0] === 'function') {
  2250. var options = {
  2251. isPeriodic: nameSuffix === 'Interval',
  2252. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2253. undefined,
  2254. args: args
  2255. };
  2256. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2257. if (!task) {
  2258. return task;
  2259. }
  2260. // Node.js must additionally support the ref and unref functions.
  2261. var handle = task.data.handleId;
  2262. if (typeof handle === 'number') {
  2263. // for non nodejs env, we save handleId: task
  2264. // mapping in local cache for clearTimeout
  2265. tasksByHandleId[handle] = task;
  2266. }
  2267. else if (handle) {
  2268. // for nodejs env, we save task
  2269. // reference in timerId Object for clearTimeout
  2270. handle[taskSymbol] = task;
  2271. }
  2272. // check whether handle is null, because some polyfill or browser
  2273. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2274. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2275. typeof handle.unref === 'function') {
  2276. task.ref = handle.ref.bind(handle);
  2277. task.unref = handle.unref.bind(handle);
  2278. }
  2279. if (typeof handle === 'number' || handle) {
  2280. return handle;
  2281. }
  2282. return task;
  2283. }
  2284. else {
  2285. // cause an error by calling it directly.
  2286. return delegate.apply(window, args);
  2287. }
  2288. }; });
  2289. clearNative =
  2290. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  2291. var id = args[0];
  2292. var task;
  2293. if (typeof id === 'number') {
  2294. // non nodejs env.
  2295. task = tasksByHandleId[id];
  2296. }
  2297. else {
  2298. // nodejs env.
  2299. task = id && id[taskSymbol];
  2300. // other environments.
  2301. if (!task) {
  2302. task = id;
  2303. }
  2304. }
  2305. if (task && typeof task.type === 'string') {
  2306. if (task.state !== 'notScheduled' &&
  2307. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2308. if (typeof id === 'number') {
  2309. delete tasksByHandleId[id];
  2310. }
  2311. else if (id) {
  2312. id[taskSymbol] = null;
  2313. }
  2314. // Do not cancel already canceled functions
  2315. task.zone.cancelTask(task);
  2316. }
  2317. }
  2318. else {
  2319. // cause an error by calling it directly.
  2320. delegate.apply(window, args);
  2321. }
  2322. }; });
  2323. }
  2324. /**
  2325. * @license
  2326. * Copyright Google Inc. All Rights Reserved.
  2327. *
  2328. * Use of this source code is governed by an MIT-style license that can be
  2329. * found in the LICENSE file at https://angular.io/license
  2330. */
  2331. var set = 'set';
  2332. var clear = 'clear';
  2333. Zone.__load_patch('node_timers', function (global, Zone) {
  2334. // Timers
  2335. var globalUseTimeoutFromTimer = false;
  2336. try {
  2337. var timers = require('timers');
  2338. var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  2339. if (!globalEqualTimersTimeout && !isMix) {
  2340. // 1. if isMix, then we are in mix environment such as Electron
  2341. // we should only patch timers.setTimeout because global.setTimeout
  2342. // have been patched
  2343. // 2. if global.setTimeout not equal timers.setTimeout, check
  2344. // whether global.setTimeout use timers.setTimeout or not
  2345. var originSetTimeout_1 = timers.setTimeout;
  2346. timers.setTimeout = function () {
  2347. globalUseTimeoutFromTimer = true;
  2348. return originSetTimeout_1.apply(this, arguments);
  2349. };
  2350. var detectTimeout = global.setTimeout(function () { }, 100);
  2351. clearTimeout(detectTimeout);
  2352. timers.setTimeout = originSetTimeout_1;
  2353. }
  2354. patchTimer(timers, set, clear, 'Timeout');
  2355. patchTimer(timers, set, clear, 'Interval');
  2356. patchTimer(timers, set, clear, 'Immediate');
  2357. }
  2358. catch (error) {
  2359. // timers module not exists, for example, when we using nativeScript
  2360. // timers is not available
  2361. }
  2362. if (isMix) {
  2363. // if we are in mix environment, such as Electron,
  2364. // the global.setTimeout has already been patched,
  2365. // so we just patch timers.setTimeout
  2366. return;
  2367. }
  2368. if (!globalUseTimeoutFromTimer) {
  2369. // 1. global setTimeout equals timers setTimeout
  2370. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  2371. // 3. or load timers module error happens, we should patch global setTimeout
  2372. patchTimer(global, set, clear, 'Timeout');
  2373. patchTimer(global, set, clear, 'Interval');
  2374. patchTimer(global, set, clear, 'Immediate');
  2375. }
  2376. else {
  2377. // global use timers setTimeout, but not equals
  2378. // this happens when use nodejs v0.10.x, global setTimeout will
  2379. // use a lazy load version of timers setTimeout
  2380. // we should not double patch timer's setTimeout
  2381. // so we only store the __symbol__ for consistency
  2382. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2383. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2384. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2385. }
  2386. });
  2387. // patch process related methods
  2388. Zone.__load_patch('nextTick', function () {
  2389. // patch nextTick as microTask
  2390. patchMicroTask(process, 'nextTick', function (self, args) {
  2391. return {
  2392. name: 'process.nextTick',
  2393. args: args,
  2394. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2395. target: process
  2396. };
  2397. });
  2398. });
  2399. Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) {
  2400. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2401. findProcessPromiseRejectionHandler('unhandledRejection');
  2402. Zone[api.symbol('rejectionHandledHandler')] =
  2403. findProcessPromiseRejectionHandler('rejectionHandled');
  2404. // handle unhandled promise rejection
  2405. function findProcessPromiseRejectionHandler(evtName) {
  2406. return function (e) {
  2407. var eventTasks = findEventTasks(process, evtName);
  2408. eventTasks.forEach(function (eventTask) {
  2409. // process has added unhandledrejection event listener
  2410. // trigger the event listener
  2411. if (evtName === 'unhandledRejection') {
  2412. eventTask.invoke(e.rejection, e.promise);
  2413. }
  2414. else if (evtName === 'rejectionHandled') {
  2415. eventTask.invoke(e.promise);
  2416. }
  2417. });
  2418. };
  2419. }
  2420. });
  2421. // Crypto
  2422. Zone.__load_patch('crypto', function () {
  2423. var crypto;
  2424. try {
  2425. crypto = require('crypto');
  2426. }
  2427. catch (err) {
  2428. }
  2429. // use the generic patchMacroTask to patch crypto
  2430. if (crypto) {
  2431. var methodNames = ['randomBytes', 'pbkdf2'];
  2432. methodNames.forEach(function (name) {
  2433. patchMacroTask(crypto, name, function (self, args) {
  2434. return {
  2435. name: 'crypto.' + name,
  2436. args: args,
  2437. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2438. args.length - 1 :
  2439. -1,
  2440. target: crypto
  2441. };
  2442. });
  2443. });
  2444. }
  2445. });
  2446. Zone.__load_patch('console', function (global, Zone) {
  2447. var consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2448. consoleMethods.forEach(function (m) {
  2449. var originalMethod = console[Zone.__symbol__(m)] = console[m];
  2450. if (originalMethod) {
  2451. console[m] = function () {
  2452. var args = ArraySlice.call(arguments);
  2453. if (Zone.current === Zone.root) {
  2454. return originalMethod.apply(this, args);
  2455. }
  2456. else {
  2457. return Zone.root.run(originalMethod, this, args);
  2458. }
  2459. };
  2460. }
  2461. });
  2462. });
  2463. /**
  2464. * @license
  2465. * Copyright Google Inc. All Rights Reserved.
  2466. *
  2467. * Use of this source code is governed by an MIT-style license that can be
  2468. * found in the LICENSE file at https://angular.io/license
  2469. */
  2470. /**
  2471. * @license
  2472. * Copyright Google Inc. All Rights Reserved.
  2473. *
  2474. * Use of this source code is governed by an MIT-style license that can be
  2475. * found in the LICENSE file at https://angular.io/license
  2476. */
  2477. /**
  2478. * @fileoverview
  2479. * @suppress {globalThis}
  2480. */
  2481. var __assign = (undefined && undefined.__assign) || function () {
  2482. __assign = Object.assign || function(t) {
  2483. for (var s, i = 1, n = arguments.length; i < n; i++) {
  2484. s = arguments[i];
  2485. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  2486. t[p] = s[p];
  2487. }
  2488. return t;
  2489. };
  2490. return __assign.apply(this, arguments);
  2491. };
  2492. var NEWLINE = '\n';
  2493. var IGNORE_FRAMES = {};
  2494. var creationTrace = '__creationTrace__';
  2495. var ERROR_TAG = 'STACKTRACE TRACKING';
  2496. var SEP_TAG = '__SEP_TAG__';
  2497. var sepTemplate = SEP_TAG + '@[native]';
  2498. var LongStackTrace = /** @class */ (function () {
  2499. function LongStackTrace() {
  2500. this.error = getStacktrace();
  2501. this.timestamp = new Date();
  2502. }
  2503. return LongStackTrace;
  2504. }());
  2505. function getStacktraceWithUncaughtError() {
  2506. return new Error(ERROR_TAG);
  2507. }
  2508. function getStacktraceWithCaughtError() {
  2509. try {
  2510. throw getStacktraceWithUncaughtError();
  2511. }
  2512. catch (err) {
  2513. return err;
  2514. }
  2515. }
  2516. // Some implementations of exception handling don't create a stack trace if the exception
  2517. // isn't thrown, however it's faster not to actually throw the exception.
  2518. var error = getStacktraceWithUncaughtError();
  2519. var caughtError = getStacktraceWithCaughtError();
  2520. var getStacktrace = error.stack ?
  2521. getStacktraceWithUncaughtError :
  2522. (caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
  2523. function getFrames(error) {
  2524. return error.stack ? error.stack.split(NEWLINE) : [];
  2525. }
  2526. function addErrorStack(lines, error) {
  2527. var trace = getFrames(error);
  2528. for (var i = 0; i < trace.length; i++) {
  2529. var frame = trace[i];
  2530. // Filter out the Frames which are part of stack capturing.
  2531. if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
  2532. lines.push(trace[i]);
  2533. }
  2534. }
  2535. }
  2536. function renderLongStackTrace(frames, stack) {
  2537. var longTrace = [stack ? stack.trim() : ''];
  2538. if (frames) {
  2539. var timestamp = new Date().getTime();
  2540. for (var i = 0; i < frames.length; i++) {
  2541. var traceFrames = frames[i];
  2542. var lastTime = traceFrames.timestamp;
  2543. var separator = "____________________Elapsed " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime;
  2544. separator = separator.replace(/[^\w\d]/g, '_');
  2545. longTrace.push(sepTemplate.replace(SEP_TAG, separator));
  2546. addErrorStack(longTrace, traceFrames.error);
  2547. timestamp = lastTime.getTime();
  2548. }
  2549. }
  2550. return longTrace.join(NEWLINE);
  2551. }
  2552. Zone['longStackTraceZoneSpec'] = {
  2553. name: 'long-stack-trace',
  2554. longStackTraceLimit: 10,
  2555. // add a getLongStackTrace method in spec to
  2556. // handle handled reject promise error.
  2557. getLongStackTrace: function (error) {
  2558. if (!error) {
  2559. return undefined;
  2560. }
  2561. var trace = error[Zone.__symbol__('currentTaskTrace')];
  2562. if (!trace) {
  2563. return error.stack;
  2564. }
  2565. return renderLongStackTrace(trace, error.stack);
  2566. },
  2567. onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
  2568. if (Error.stackTraceLimit > 0) {
  2569. // if Error.stackTraceLimit is 0, means stack trace
  2570. // is disabled, so we don't need to generate long stack trace
  2571. // this will improve performance in some test(some test will
  2572. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  2573. var currentTask = Zone.currentTask;
  2574. var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
  2575. trace = [new LongStackTrace()].concat(trace);
  2576. if (trace.length > this.longStackTraceLimit) {
  2577. trace.length = this.longStackTraceLimit;
  2578. }
  2579. if (!task.data)
  2580. task.data = {};
  2581. if (task.type === 'eventTask') {
  2582. // Fix issue https://github.com/angular/zone.js/issues/1195,
  2583. // For event task of browser, by default, all task will share a
  2584. // singleton instance of data object, we should create a new one here
  2585. // The cast to `any` is required to workaround a closure bug which wrongly applies
  2586. // URL sanitization rules to .data access.
  2587. task.data = __assign({}, task.data);
  2588. }
  2589. task.data[creationTrace] = trace;
  2590. }
  2591. return parentZoneDelegate.scheduleTask(targetZone, task);
  2592. },
  2593. onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
  2594. if (Error.stackTraceLimit > 0) {
  2595. // if Error.stackTraceLimit is 0, means stack trace
  2596. // is disabled, so we don't need to generate long stack trace
  2597. // this will improve performance in some test(some test will
  2598. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  2599. var parentTask = Zone.currentTask || error.task;
  2600. if (error instanceof Error && parentTask) {
  2601. var longStack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
  2602. try {
  2603. error.stack = error.longStack = longStack;
  2604. }
  2605. catch (err) {
  2606. }
  2607. }
  2608. }
  2609. return parentZoneDelegate.handleError(targetZone, error);
  2610. }
  2611. };
  2612. function captureStackTraces(stackTraces, count) {
  2613. if (count > 0) {
  2614. stackTraces.push(getFrames((new LongStackTrace()).error));
  2615. captureStackTraces(stackTraces, count - 1);
  2616. }
  2617. }
  2618. function computeIgnoreFrames() {
  2619. if (Error.stackTraceLimit <= 0) {
  2620. return;
  2621. }
  2622. var frames = [];
  2623. captureStackTraces(frames, 2);
  2624. var frames1 = frames[0];
  2625. var frames2 = frames[1];
  2626. for (var i = 0; i < frames1.length; i++) {
  2627. var frame1 = frames1[i];
  2628. if (frame1.indexOf(ERROR_TAG) == -1) {
  2629. var match = frame1.match(/^\s*at\s+/);
  2630. if (match) {
  2631. sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
  2632. break;
  2633. }
  2634. }
  2635. }
  2636. for (var i = 0; i < frames1.length; i++) {
  2637. var frame1 = frames1[i];
  2638. var frame2 = frames2[i];
  2639. if (frame1 === frame2) {
  2640. IGNORE_FRAMES[frame1] = true;
  2641. }
  2642. else {
  2643. break;
  2644. }
  2645. }
  2646. }
  2647. computeIgnoreFrames();
  2648. /**
  2649. * @license
  2650. * Copyright Google Inc. All Rights Reserved.
  2651. *
  2652. * Use of this source code is governed by an MIT-style license that can be
  2653. * found in the LICENSE file at https://angular.io/license
  2654. */
  2655. var ProxyZoneSpec = /** @class */ (function () {
  2656. function ProxyZoneSpec(defaultSpecDelegate) {
  2657. if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
  2658. this.defaultSpecDelegate = defaultSpecDelegate;
  2659. this.name = 'ProxyZone';
  2660. this._delegateSpec = null;
  2661. this.properties = { 'ProxyZoneSpec': this };
  2662. this.propertyKeys = null;
  2663. this.lastTaskState = null;
  2664. this.isNeedToTriggerHasTask = false;
  2665. this.tasks = [];
  2666. this.setDelegate(defaultSpecDelegate);
  2667. }
  2668. ProxyZoneSpec.get = function () {
  2669. return Zone.current.get('ProxyZoneSpec');
  2670. };
  2671. ProxyZoneSpec.isLoaded = function () {
  2672. return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
  2673. };
  2674. ProxyZoneSpec.assertPresent = function () {
  2675. if (!ProxyZoneSpec.isLoaded()) {
  2676. throw new Error("Expected to be running in 'ProxyZone', but it was not found.");
  2677. }
  2678. return ProxyZoneSpec.get();
  2679. };
  2680. ProxyZoneSpec.prototype.setDelegate = function (delegateSpec) {
  2681. var _this = this;
  2682. var isNewDelegate = this._delegateSpec !== delegateSpec;
  2683. this._delegateSpec = delegateSpec;
  2684. this.propertyKeys && this.propertyKeys.forEach(function (key) { return delete _this.properties[key]; });
  2685. this.propertyKeys = null;
  2686. if (delegateSpec && delegateSpec.properties) {
  2687. this.propertyKeys = Object.keys(delegateSpec.properties);
  2688. this.propertyKeys.forEach(function (k) { return _this.properties[k] = delegateSpec.properties[k]; });
  2689. }
  2690. // if set a new delegateSpec, shoulde check whether need to
  2691. // trigger hasTask or not
  2692. if (isNewDelegate && this.lastTaskState &&
  2693. (this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
  2694. this.isNeedToTriggerHasTask = true;
  2695. }
  2696. };
  2697. ProxyZoneSpec.prototype.getDelegate = function () {
  2698. return this._delegateSpec;
  2699. };
  2700. ProxyZoneSpec.prototype.resetDelegate = function () {
  2701. var delegateSpec = this.getDelegate();
  2702. this.setDelegate(this.defaultSpecDelegate);
  2703. };
  2704. ProxyZoneSpec.prototype.tryTriggerHasTask = function (parentZoneDelegate, currentZone, targetZone) {
  2705. if (this.isNeedToTriggerHasTask && this.lastTaskState) {
  2706. // last delegateSpec has microTask or macroTask
  2707. // should call onHasTask in current delegateSpec
  2708. this.isNeedToTriggerHasTask = false;
  2709. this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
  2710. }
  2711. };
  2712. ProxyZoneSpec.prototype.removeFromTasks = function (task) {
  2713. if (!this.tasks) {
  2714. return;
  2715. }
  2716. for (var i = 0; i < this.tasks.length; i++) {
  2717. if (this.tasks[i] === task) {
  2718. this.tasks.splice(i, 1);
  2719. return;
  2720. }
  2721. }
  2722. };
  2723. ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function () {
  2724. if (this.tasks.length === 0) {
  2725. return '';
  2726. }
  2727. var taskInfo = this.tasks.map(function (task) {
  2728. var dataInfo = task.data &&
  2729. Object.keys(task.data)
  2730. .map(function (key) {
  2731. return key + ':' + task.data[key];
  2732. })
  2733. .join(',');
  2734. return "type: " + task.type + ", source: " + task.source + ", args: {" + dataInfo + "}";
  2735. });
  2736. var pendingTasksInfo = '--Pendng async tasks are: [' + taskInfo + ']';
  2737. // clear tasks
  2738. this.tasks = [];
  2739. return pendingTasksInfo;
  2740. };
  2741. ProxyZoneSpec.prototype.onFork = function (parentZoneDelegate, currentZone, targetZone, zoneSpec) {
  2742. if (this._delegateSpec && this._delegateSpec.onFork) {
  2743. return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
  2744. }
  2745. else {
  2746. return parentZoneDelegate.fork(targetZone, zoneSpec);
  2747. }
  2748. };
  2749. ProxyZoneSpec.prototype.onIntercept = function (parentZoneDelegate, currentZone, targetZone, delegate, source) {
  2750. if (this._delegateSpec && this._delegateSpec.onIntercept) {
  2751. return this._delegateSpec.onIntercept(parentZoneDelegate, currentZone, targetZone, delegate, source);
  2752. }
  2753. else {
  2754. return parentZoneDelegate.intercept(targetZone, delegate, source);
  2755. }
  2756. };
  2757. ProxyZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  2758. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2759. if (this._delegateSpec && this._delegateSpec.onInvoke) {
  2760. return this._delegateSpec.onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
  2761. }
  2762. else {
  2763. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  2764. }
  2765. };
  2766. ProxyZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  2767. if (this._delegateSpec && this._delegateSpec.onHandleError) {
  2768. return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
  2769. }
  2770. else {
  2771. return parentZoneDelegate.handleError(targetZone, error);
  2772. }
  2773. };
  2774. ProxyZoneSpec.prototype.onScheduleTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  2775. if (task.type !== 'eventTask') {
  2776. this.tasks.push(task);
  2777. }
  2778. if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
  2779. return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
  2780. }
  2781. else {
  2782. return parentZoneDelegate.scheduleTask(targetZone, task);
  2783. }
  2784. };
  2785. ProxyZoneSpec.prototype.onInvokeTask = function (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  2786. if (task.type !== 'eventTask') {
  2787. this.removeFromTasks(task);
  2788. }
  2789. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2790. if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
  2791. return this._delegateSpec.onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
  2792. }
  2793. else {
  2794. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  2795. }
  2796. };
  2797. ProxyZoneSpec.prototype.onCancelTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  2798. if (task.type !== 'eventTask') {
  2799. this.removeFromTasks(task);
  2800. }
  2801. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2802. if (this._delegateSpec && this._delegateSpec.onCancelTask) {
  2803. return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
  2804. }
  2805. else {
  2806. return parentZoneDelegate.cancelTask(targetZone, task);
  2807. }
  2808. };
  2809. ProxyZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  2810. this.lastTaskState = hasTaskState;
  2811. if (this._delegateSpec && this._delegateSpec.onHasTask) {
  2812. this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
  2813. }
  2814. else {
  2815. delegate.hasTask(target, hasTaskState);
  2816. }
  2817. };
  2818. return ProxyZoneSpec;
  2819. }());
  2820. // Export the class so that new instances can be created with proper
  2821. // constructor params.
  2822. Zone['ProxyZoneSpec'] = ProxyZoneSpec;
  2823. /**
  2824. * @license
  2825. * Copyright Google Inc. All Rights Reserved.
  2826. *
  2827. * Use of this source code is governed by an MIT-style license that can be
  2828. * found in the LICENSE file at https://angular.io/license
  2829. */
  2830. var SyncTestZoneSpec = /** @class */ (function () {
  2831. function SyncTestZoneSpec(namePrefix) {
  2832. this.runZone = Zone.current;
  2833. this.name = 'syncTestZone for ' + namePrefix;
  2834. }
  2835. SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  2836. switch (task.type) {
  2837. case 'microTask':
  2838. case 'macroTask':
  2839. throw new Error("Cannot call " + task.source + " from within a sync test.");
  2840. case 'eventTask':
  2841. task = delegate.scheduleTask(target, task);
  2842. break;
  2843. }
  2844. return task;
  2845. };
  2846. return SyncTestZoneSpec;
  2847. }());
  2848. // Export the class so that new instances can be created with proper
  2849. // constructor params.
  2850. Zone['SyncTestZoneSpec'] = SyncTestZoneSpec;
  2851. /**
  2852. * @license
  2853. * Copyright Google Inc. All Rights Reserved.
  2854. *
  2855. * Use of this source code is governed by an MIT-style license that can be
  2856. * found in the LICENSE file at https://angular.io/license
  2857. */
  2858. (function () {
  2859. var __extends = function (d, b) {
  2860. for (var p in b)
  2861. if (b.hasOwnProperty(p))
  2862. d[p] = b[p];
  2863. function __() {
  2864. this.constructor = d;
  2865. }
  2866. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2867. };
  2868. var _global = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  2869. // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
  2870. // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
  2871. if (!Zone)
  2872. throw new Error('Missing: zone.js');
  2873. if (typeof jasmine == 'undefined')
  2874. throw new Error('Missing: jasmine.js');
  2875. if (jasmine['__zone_patch__'])
  2876. throw new Error("'jasmine' has already been patched with 'Zone'.");
  2877. jasmine['__zone_patch__'] = true;
  2878. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  2879. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  2880. if (!SyncTestZoneSpec)
  2881. throw new Error('Missing: SyncTestZoneSpec');
  2882. if (!ProxyZoneSpec)
  2883. throw new Error('Missing: ProxyZoneSpec');
  2884. var ambientZone = Zone.current;
  2885. // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
  2886. // error if any asynchronous operations are attempted inside of a `describe` but outside of
  2887. // a `beforeEach` or `it`.
  2888. var syncZone = ambientZone.fork(new SyncTestZoneSpec('jasmine.describe'));
  2889. var symbol = Zone.__symbol__;
  2890. // whether patch jasmine clock when in fakeAsync
  2891. var disablePatchingJasmineClock = _global[symbol('fakeAsyncDisablePatchingClock')] === true;
  2892. // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
  2893. // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
  2894. // automatically disable the auto jump into fakeAsync feature
  2895. var enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
  2896. ((_global[symbol('fakeAsyncPatchLock')] === true) ||
  2897. (_global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
  2898. var ignoreUnhandledRejection = _global[symbol('ignoreUnhandledRejection')] === true;
  2899. if (!ignoreUnhandledRejection) {
  2900. var globalErrors_1 = jasmine.GlobalErrors;
  2901. if (globalErrors_1 && !jasmine[symbol('GlobalErrors')]) {
  2902. jasmine[symbol('GlobalErrors')] = globalErrors_1;
  2903. jasmine.GlobalErrors = function () {
  2904. var instance = new globalErrors_1();
  2905. var originalInstall = instance.install;
  2906. if (originalInstall && !instance[symbol('install')]) {
  2907. instance[symbol('install')] = originalInstall;
  2908. instance.install = function () {
  2909. var originalHandlers = process.listeners('unhandledRejection');
  2910. var r = originalInstall.apply(this, arguments);
  2911. process.removeAllListeners('unhandledRejection');
  2912. if (originalHandlers) {
  2913. originalHandlers.forEach(function (h) { return process.on('unhandledRejection', h); });
  2914. }
  2915. return r;
  2916. };
  2917. }
  2918. return instance;
  2919. };
  2920. }
  2921. }
  2922. // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
  2923. var jasmineEnv = jasmine.getEnv();
  2924. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  2925. var originalJasmineFn = jasmineEnv[methodName];
  2926. jasmineEnv[methodName] = function (description, specDefinitions) {
  2927. return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
  2928. };
  2929. });
  2930. ['it', 'xit', 'fit'].forEach(function (methodName) {
  2931. var originalJasmineFn = jasmineEnv[methodName];
  2932. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  2933. jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
  2934. arguments[1] = wrapTestInZone(specDefinitions);
  2935. return originalJasmineFn.apply(this, arguments);
  2936. };
  2937. });
  2938. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  2939. var originalJasmineFn = jasmineEnv[methodName];
  2940. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  2941. jasmineEnv[methodName] = function (specDefinitions, timeout) {
  2942. arguments[0] = wrapTestInZone(specDefinitions);
  2943. return originalJasmineFn.apply(this, arguments);
  2944. };
  2945. });
  2946. if (!disablePatchingJasmineClock) {
  2947. // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
  2948. // they can work properly in FakeAsyncTest
  2949. var originalClockFn_1 = (jasmine[symbol('clock')] = jasmine['clock']);
  2950. jasmine['clock'] = function () {
  2951. var clock = originalClockFn_1.apply(this, arguments);
  2952. if (!clock[symbol('patched')]) {
  2953. clock[symbol('patched')] = symbol('patched');
  2954. var originalTick_1 = (clock[symbol('tick')] = clock.tick);
  2955. clock.tick = function () {
  2956. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2957. if (fakeAsyncZoneSpec) {
  2958. return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
  2959. }
  2960. return originalTick_1.apply(this, arguments);
  2961. };
  2962. var originalMockDate_1 = (clock[symbol('mockDate')] = clock.mockDate);
  2963. clock.mockDate = function () {
  2964. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2965. if (fakeAsyncZoneSpec) {
  2966. var dateTime = arguments.length > 0 ? arguments[0] : new Date();
  2967. return fakeAsyncZoneSpec.setCurrentRealTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
  2968. arguments);
  2969. }
  2970. return originalMockDate_1.apply(this, arguments);
  2971. };
  2972. // for auto go into fakeAsync feature, we need the flag to enable it
  2973. if (enableAutoFakeAsyncWhenClockPatched) {
  2974. ['install', 'uninstall'].forEach(function (methodName) {
  2975. var originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
  2976. clock[methodName] = function () {
  2977. var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  2978. if (FakeAsyncTestZoneSpec) {
  2979. jasmine[symbol('clockInstalled')] = 'install' === methodName;
  2980. return;
  2981. }
  2982. return originalClockFn.apply(this, arguments);
  2983. };
  2984. });
  2985. }
  2986. }
  2987. return clock;
  2988. };
  2989. }
  2990. /**
  2991. * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
  2992. * synchronous-only zone.
  2993. */
  2994. function wrapDescribeInZone(describeBody) {
  2995. return function () {
  2996. return syncZone.run(describeBody, this, arguments);
  2997. };
  2998. }
  2999. function runInTestZone(testBody, applyThis, queueRunner, done) {
  3000. var isClockInstalled = !!jasmine[symbol('clockInstalled')];
  3001. var testProxyZoneSpec = queueRunner.testProxyZoneSpec;
  3002. var testProxyZone = queueRunner.testProxyZone;
  3003. if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
  3004. // auto run a fakeAsync
  3005. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  3006. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  3007. testBody = fakeAsyncModule.fakeAsync(testBody);
  3008. }
  3009. }
  3010. if (done) {
  3011. return testProxyZone.run(testBody, applyThis, [done]);
  3012. }
  3013. else {
  3014. return testProxyZone.run(testBody, applyThis);
  3015. }
  3016. }
  3017. /**
  3018. * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
  3019. * execute in a ProxyZone zone.
  3020. * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
  3021. */
  3022. function wrapTestInZone(testBody) {
  3023. // The `done` callback is only passed through if the function expects at least one argument.
  3024. // Note we have to make a function with correct number of arguments, otherwise jasmine will
  3025. // think that all functions are sync or async.
  3026. return (testBody && (testBody.length ? function (done) {
  3027. return runInTestZone(testBody, this, this.queueRunner, done);
  3028. } : function () {
  3029. return runInTestZone(testBody, this, this.queueRunner);
  3030. }));
  3031. }
  3032. var QueueRunner = jasmine.QueueRunner;
  3033. jasmine.QueueRunner = (function (_super) {
  3034. __extends(ZoneQueueRunner, _super);
  3035. function ZoneQueueRunner(attrs) {
  3036. var _this = this;
  3037. attrs.onComplete = (function (fn) { return function () {
  3038. // All functions are done, clear the test zone.
  3039. _this.testProxyZone = null;
  3040. _this.testProxyZoneSpec = null;
  3041. ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
  3042. }; })(attrs.onComplete);
  3043. var nativeSetTimeout = _global['__zone_symbol__setTimeout'];
  3044. var nativeClearTimeout = _global['__zone_symbol__clearTimeout'];
  3045. if (nativeSetTimeout) {
  3046. // should run setTimeout inside jasmine outside of zone
  3047. attrs.timeout = {
  3048. setTimeout: nativeSetTimeout ? nativeSetTimeout : _global.setTimeout,
  3049. clearTimeout: nativeClearTimeout ? nativeClearTimeout : _global.clearTimeout
  3050. };
  3051. }
  3052. // create a userContext to hold the queueRunner itself
  3053. // so we can access the testProxy in it/xit/beforeEach ...
  3054. if (jasmine.UserContext) {
  3055. if (!attrs.userContext) {
  3056. attrs.userContext = new jasmine.UserContext();
  3057. }
  3058. attrs.userContext.queueRunner = this;
  3059. }
  3060. else {
  3061. if (!attrs.userContext) {
  3062. attrs.userContext = {};
  3063. }
  3064. attrs.userContext.queueRunner = this;
  3065. }
  3066. // patch attrs.onException
  3067. var onException = attrs.onException;
  3068. attrs.onException = function (error) {
  3069. if (error &&
  3070. error.message ===
  3071. 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
  3072. // jasmine timeout, we can make the error message more
  3073. // reasonable to tell what tasks are pending
  3074. var proxyZoneSpec = this && this.testProxyZoneSpec;
  3075. if (proxyZoneSpec) {
  3076. var pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
  3077. try {
  3078. // try catch here in case error.message is not writable
  3079. error.message += pendingTasksInfo;
  3080. }
  3081. catch (err) {
  3082. }
  3083. }
  3084. }
  3085. if (onException) {
  3086. onException.call(this, error);
  3087. }
  3088. };
  3089. _super.call(this, attrs);
  3090. }
  3091. ZoneQueueRunner.prototype.execute = function () {
  3092. var _this = this;
  3093. var zone = Zone.current;
  3094. var isChildOfAmbientZone = false;
  3095. while (zone) {
  3096. if (zone === ambientZone) {
  3097. isChildOfAmbientZone = true;
  3098. break;
  3099. }
  3100. zone = zone.parent;
  3101. }
  3102. if (!isChildOfAmbientZone)
  3103. throw new Error('Unexpected Zone: ' + Zone.current.name);
  3104. // This is the zone which will be used for running individual tests.
  3105. // It will be a proxy zone, so that the tests function can retroactively install
  3106. // different zones.
  3107. // Example:
  3108. // - In beforeEach() do childZone = Zone.current.fork(...);
  3109. // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
  3110. // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
  3111. // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
  3112. // fakeAsync behavior to the childZone.
  3113. this.testProxyZoneSpec = new ProxyZoneSpec();
  3114. this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
  3115. if (!Zone.currentTask) {
  3116. // if we are not running in a task then if someone would register a
  3117. // element.addEventListener and then calling element.click() the
  3118. // addEventListener callback would think that it is the top most task and would
  3119. // drain the microtask queue on element.click() which would be incorrect.
  3120. // For this reason we always force a task when running jasmine tests.
  3121. Zone.current.scheduleMicroTask('jasmine.execute().forceTask', function () { return QueueRunner.prototype.execute.call(_this); });
  3122. }
  3123. else {
  3124. _super.prototype.execute.call(this);
  3125. }
  3126. };
  3127. return ZoneQueueRunner;
  3128. })(QueueRunner);
  3129. })();
  3130. /**
  3131. * @license
  3132. * Copyright Google Inc. All Rights Reserved.
  3133. *
  3134. * Use of this source code is governed by an MIT-style license that can be
  3135. * found in the LICENSE file at https://angular.io/license
  3136. */
  3137. var _global$1 = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  3138. var AsyncTestZoneSpec = /** @class */ (function () {
  3139. function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
  3140. this.finishCallback = finishCallback;
  3141. this.failCallback = failCallback;
  3142. this._pendingMicroTasks = false;
  3143. this._pendingMacroTasks = false;
  3144. this._alreadyErrored = false;
  3145. this._isSync = false;
  3146. this.runZone = Zone.current;
  3147. this.unresolvedChainedPromiseCount = 0;
  3148. this.supportWaitUnresolvedChainedPromise = false;
  3149. this.name = 'asyncTestZone for ' + namePrefix;
  3150. this.properties = { 'AsyncTestZoneSpec': this };
  3151. this.supportWaitUnresolvedChainedPromise =
  3152. _global$1[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  3153. }
  3154. AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
  3155. return this.unresolvedChainedPromiseCount > 0;
  3156. };
  3157. AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
  3158. var _this = this;
  3159. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  3160. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  3161. // We do this because we would like to catch unhandled rejected promises.
  3162. this.runZone.run(function () {
  3163. setTimeout(function () {
  3164. if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
  3165. _this.finishCallback();
  3166. }
  3167. }, 0);
  3168. });
  3169. }
  3170. };
  3171. AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
  3172. if (!this.supportWaitUnresolvedChainedPromise) {
  3173. return;
  3174. }
  3175. var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  3176. if (patchPromiseForTest) {
  3177. patchPromiseForTest();
  3178. }
  3179. };
  3180. AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
  3181. if (!this.supportWaitUnresolvedChainedPromise) {
  3182. return;
  3183. }
  3184. var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  3185. if (unPatchPromiseForTest) {
  3186. unPatchPromiseForTest();
  3187. }
  3188. };
  3189. AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3190. if (task.type !== 'eventTask') {
  3191. this._isSync = false;
  3192. }
  3193. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  3194. // check whether the promise is a chained promise
  3195. if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
  3196. // chained promise is being scheduled
  3197. this.unresolvedChainedPromiseCount--;
  3198. }
  3199. }
  3200. return delegate.scheduleTask(target, task);
  3201. };
  3202. AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
  3203. if (task.type !== 'eventTask') {
  3204. this._isSync = false;
  3205. }
  3206. return delegate.invokeTask(target, task, applyThis, applyArgs);
  3207. };
  3208. AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  3209. if (task.type !== 'eventTask') {
  3210. this._isSync = false;
  3211. }
  3212. return delegate.cancelTask(target, task);
  3213. };
  3214. // Note - we need to use onInvoke at the moment to call finish when a test is
  3215. // fully synchronous. TODO(juliemr): remove this when the logic for
  3216. // onHasTask changes and it calls whenever the task queues are dirty.
  3217. // updated by(JiaLiPassion), only call finish callback when no task
  3218. // was scheduled/invoked/canceled.
  3219. AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  3220. try {
  3221. this._isSync = true;
  3222. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  3223. }
  3224. finally {
  3225. var afterTaskCounts = parentZoneDelegate._taskCounts;
  3226. if (this._isSync) {
  3227. this._finishCallbackIfDone();
  3228. }
  3229. }
  3230. };
  3231. AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  3232. // Let the parent try to handle the error.
  3233. var result = parentZoneDelegate.handleError(targetZone, error);
  3234. if (result) {
  3235. this.failCallback(error);
  3236. this._alreadyErrored = true;
  3237. }
  3238. return false;
  3239. };
  3240. AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  3241. delegate.hasTask(target, hasTaskState);
  3242. if (hasTaskState.change == 'microTask') {
  3243. this._pendingMicroTasks = hasTaskState.microTask;
  3244. this._finishCallbackIfDone();
  3245. }
  3246. else if (hasTaskState.change == 'macroTask') {
  3247. this._pendingMacroTasks = hasTaskState.macroTask;
  3248. this._finishCallbackIfDone();
  3249. }
  3250. };
  3251. AsyncTestZoneSpec.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
  3252. return AsyncTestZoneSpec;
  3253. }());
  3254. // Export the class so that new instances can be created with proper
  3255. // constructor params.
  3256. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  3257. /**
  3258. * @license
  3259. * Copyright Google Inc. All Rights Reserved.
  3260. *
  3261. * Use of this source code is governed by an MIT-style license that can be
  3262. * found in the LICENSE file at https://angular.io/license
  3263. */
  3264. Zone.__load_patch('asynctest', function (global, Zone, api) {
  3265. /**
  3266. * Wraps a test function in an asynchronous test zone. The test will automatically
  3267. * complete when all asynchronous calls within this zone are done.
  3268. */
  3269. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  3270. // If we're running using the Jasmine test framework, adapt to call the 'done'
  3271. // function when asynchronous activity is finished.
  3272. if (global.jasmine) {
  3273. // Not using an arrow function to preserve context passed from call site
  3274. return function (done) {
  3275. if (!done) {
  3276. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  3277. // fake it here and assume sync.
  3278. done = function () { };
  3279. done.fail = function (e) {
  3280. throw e;
  3281. };
  3282. }
  3283. runInTestZone(fn, this, done, function (err) {
  3284. if (typeof err === 'string') {
  3285. return done.fail(new Error(err));
  3286. }
  3287. else {
  3288. done.fail(err);
  3289. }
  3290. });
  3291. };
  3292. }
  3293. // Otherwise, return a promise which will resolve when asynchronous activity
  3294. // is finished. This will be correctly consumed by the Mocha framework with
  3295. // it('...', async(myFn)); or can be used in a custom framework.
  3296. // Not using an arrow function to preserve context passed from call site
  3297. return function () {
  3298. var _this = this;
  3299. return new Promise(function (finishCallback, failCallback) {
  3300. runInTestZone(fn, _this, finishCallback, failCallback);
  3301. });
  3302. };
  3303. };
  3304. function runInTestZone(fn, context, finishCallback, failCallback) {
  3305. var currentZone = Zone.current;
  3306. var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  3307. if (AsyncTestZoneSpec === undefined) {
  3308. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  3309. 'Please make sure that your environment includes zone.js/dist/async-test.js');
  3310. }
  3311. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  3312. if (ProxyZoneSpec === undefined) {
  3313. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  3314. 'Please make sure that your environment includes zone.js/dist/proxy.js');
  3315. }
  3316. var proxyZoneSpec = ProxyZoneSpec.get();
  3317. ProxyZoneSpec.assertPresent();
  3318. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  3319. // If we do it in ProxyZone then we will get to infinite recursion.
  3320. var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  3321. var previousDelegate = proxyZoneSpec.getDelegate();
  3322. proxyZone.parent.run(function () {
  3323. var testZoneSpec = new AsyncTestZoneSpec(function () {
  3324. // Need to restore the original zone.
  3325. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3326. // Only reset the zone spec if it's
  3327. // sill this one. Otherwise, assume
  3328. // it's OK.
  3329. proxyZoneSpec.setDelegate(previousDelegate);
  3330. }
  3331. testZoneSpec.unPatchPromiseForTest();
  3332. currentZone.run(function () {
  3333. finishCallback();
  3334. });
  3335. }, function (error) {
  3336. // Need to restore the original zone.
  3337. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3338. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  3339. proxyZoneSpec.setDelegate(previousDelegate);
  3340. }
  3341. testZoneSpec.unPatchPromiseForTest();
  3342. currentZone.run(function () {
  3343. failCallback(error);
  3344. });
  3345. }, 'test');
  3346. proxyZoneSpec.setDelegate(testZoneSpec);
  3347. testZoneSpec.patchPromiseForTest();
  3348. });
  3349. return Zone.current.runGuarded(fn, context);
  3350. }
  3351. });
  3352. /**
  3353. * @license
  3354. * Copyright Google Inc. All Rights Reserved.
  3355. *
  3356. * Use of this source code is governed by an MIT-style license that can be
  3357. * found in the LICENSE file at https://angular.io/license
  3358. */
  3359. var __read = (undefined && undefined.__read) || function (o, n) {
  3360. var m = typeof Symbol === "function" && o[Symbol.iterator];
  3361. if (!m) return o;
  3362. var i = m.call(o), r, ar = [], e;
  3363. try {
  3364. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  3365. }
  3366. catch (error) { e = { error: error }; }
  3367. finally {
  3368. try {
  3369. if (r && !r.done && (m = i["return"])) m.call(i);
  3370. }
  3371. finally { if (e) throw e.error; }
  3372. }
  3373. return ar;
  3374. };
  3375. var __spread = (undefined && undefined.__spread) || function () {
  3376. for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
  3377. return ar;
  3378. };
  3379. (function (global) {
  3380. var OriginalDate = global.Date;
  3381. var FakeDate = /** @class */ (function () {
  3382. function FakeDate() {
  3383. if (arguments.length === 0) {
  3384. var d = new OriginalDate();
  3385. d.setTime(FakeDate.now());
  3386. return d;
  3387. }
  3388. else {
  3389. var args = Array.prototype.slice.call(arguments);
  3390. return new (OriginalDate.bind.apply(OriginalDate, __spread([void 0], args)))();
  3391. }
  3392. }
  3393. FakeDate.now = function () {
  3394. var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3395. if (fakeAsyncTestZoneSpec) {
  3396. return fakeAsyncTestZoneSpec.getCurrentRealTime() + fakeAsyncTestZoneSpec.getCurrentTime();
  3397. }
  3398. return OriginalDate.now.apply(this, arguments);
  3399. };
  3400. return FakeDate;
  3401. }());
  3402. FakeDate.UTC = OriginalDate.UTC;
  3403. FakeDate.parse = OriginalDate.parse;
  3404. // keep a reference for zone patched timer function
  3405. var timers = {
  3406. setTimeout: global.setTimeout,
  3407. setInterval: global.setInterval,
  3408. clearTimeout: global.clearTimeout,
  3409. clearInterval: global.clearInterval
  3410. };
  3411. var Scheduler = /** @class */ (function () {
  3412. function Scheduler() {
  3413. // Scheduler queue with the tuple of end time and callback function - sorted by end time.
  3414. this._schedulerQueue = [];
  3415. // Current simulated time in millis.
  3416. this._currentTime = 0;
  3417. // Current real time in millis.
  3418. this._currentRealTime = OriginalDate.now();
  3419. }
  3420. Scheduler.prototype.getCurrentTime = function () {
  3421. return this._currentTime;
  3422. };
  3423. Scheduler.prototype.getCurrentRealTime = function () {
  3424. return this._currentRealTime;
  3425. };
  3426. Scheduler.prototype.setCurrentRealTime = function (realTime) {
  3427. this._currentRealTime = realTime;
  3428. };
  3429. Scheduler.prototype.scheduleFunction = function (cb, delay, args, isPeriodic, isRequestAnimationFrame, id) {
  3430. if (args === void 0) { args = []; }
  3431. if (isPeriodic === void 0) { isPeriodic = false; }
  3432. if (isRequestAnimationFrame === void 0) { isRequestAnimationFrame = false; }
  3433. if (id === void 0) { id = -1; }
  3434. var currentId = id < 0 ? Scheduler.nextId++ : id;
  3435. var endTime = this._currentTime + delay;
  3436. // Insert so that scheduler queue remains sorted by end time.
  3437. var newEntry = {
  3438. endTime: endTime,
  3439. id: currentId,
  3440. func: cb,
  3441. args: args,
  3442. delay: delay,
  3443. isPeriodic: isPeriodic,
  3444. isRequestAnimationFrame: isRequestAnimationFrame
  3445. };
  3446. var i = 0;
  3447. for (; i < this._schedulerQueue.length; i++) {
  3448. var currentEntry = this._schedulerQueue[i];
  3449. if (newEntry.endTime < currentEntry.endTime) {
  3450. break;
  3451. }
  3452. }
  3453. this._schedulerQueue.splice(i, 0, newEntry);
  3454. return currentId;
  3455. };
  3456. Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
  3457. for (var i = 0; i < this._schedulerQueue.length; i++) {
  3458. if (this._schedulerQueue[i].id == id) {
  3459. this._schedulerQueue.splice(i, 1);
  3460. break;
  3461. }
  3462. }
  3463. };
  3464. Scheduler.prototype.tick = function (millis, doTick) {
  3465. if (millis === void 0) { millis = 0; }
  3466. var finalTime = this._currentTime + millis;
  3467. var lastCurrentTime = 0;
  3468. if (this._schedulerQueue.length === 0 && doTick) {
  3469. doTick(millis);
  3470. return;
  3471. }
  3472. while (this._schedulerQueue.length > 0) {
  3473. var current = this._schedulerQueue[0];
  3474. if (finalTime < current.endTime) {
  3475. // Done processing the queue since it's sorted by endTime.
  3476. break;
  3477. }
  3478. else {
  3479. // Time to run scheduled function. Remove it from the head of queue.
  3480. var current_1 = this._schedulerQueue.shift();
  3481. lastCurrentTime = this._currentTime;
  3482. this._currentTime = current_1.endTime;
  3483. if (doTick) {
  3484. doTick(this._currentTime - lastCurrentTime);
  3485. }
  3486. var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTime] : current_1.args);
  3487. if (!retval) {
  3488. // Uncaught exception in the current scheduled function. Stop processing the queue.
  3489. break;
  3490. }
  3491. }
  3492. }
  3493. lastCurrentTime = this._currentTime;
  3494. this._currentTime = finalTime;
  3495. if (doTick) {
  3496. doTick(this._currentTime - lastCurrentTime);
  3497. }
  3498. };
  3499. Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
  3500. if (limit === void 0) { limit = 20; }
  3501. if (flushPeriodic === void 0) { flushPeriodic = false; }
  3502. if (flushPeriodic) {
  3503. return this.flushPeriodic(doTick);
  3504. }
  3505. else {
  3506. return this.flushNonPeriodic(limit, doTick);
  3507. }
  3508. };
  3509. Scheduler.prototype.flushPeriodic = function (doTick) {
  3510. if (this._schedulerQueue.length === 0) {
  3511. return 0;
  3512. }
  3513. // Find the last task currently queued in the scheduler queue and tick
  3514. // till that time.
  3515. var startTime = this._currentTime;
  3516. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  3517. this.tick(lastTask.endTime - startTime, doTick);
  3518. return this._currentTime - startTime;
  3519. };
  3520. Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
  3521. var startTime = this._currentTime;
  3522. var lastCurrentTime = 0;
  3523. var count = 0;
  3524. while (this._schedulerQueue.length > 0) {
  3525. count++;
  3526. if (count > limit) {
  3527. throw new Error('flush failed after reaching the limit of ' + limit +
  3528. ' tasks. Does your code use a polling timeout?');
  3529. }
  3530. // flush only non-periodic timers.
  3531. // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
  3532. if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
  3533. .length === 0) {
  3534. break;
  3535. }
  3536. var current = this._schedulerQueue.shift();
  3537. lastCurrentTime = this._currentTime;
  3538. this._currentTime = current.endTime;
  3539. if (doTick) {
  3540. // Update any secondary schedulers like Jasmine mock Date.
  3541. doTick(this._currentTime - lastCurrentTime);
  3542. }
  3543. var retval = current.func.apply(global, current.args);
  3544. if (!retval) {
  3545. // Uncaught exception in the current scheduled function. Stop processing the queue.
  3546. break;
  3547. }
  3548. }
  3549. return this._currentTime - startTime;
  3550. };
  3551. // Next scheduler id.
  3552. Scheduler.nextId = 1;
  3553. return Scheduler;
  3554. }());
  3555. var FakeAsyncTestZoneSpec = /** @class */ (function () {
  3556. function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
  3557. if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
  3558. this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
  3559. this.macroTaskOptions = macroTaskOptions;
  3560. this._scheduler = new Scheduler();
  3561. this._microtasks = [];
  3562. this._lastError = null;
  3563. this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
  3564. this.pendingPeriodicTimers = [];
  3565. this.pendingTimers = [];
  3566. this.patchDateLocked = false;
  3567. this.properties = { 'FakeAsyncTestZoneSpec': this };
  3568. this.name = 'fakeAsyncTestZone for ' + namePrefix;
  3569. // in case user can't access the construction of FakeAsyncTestSpec
  3570. // user can also define macroTaskOptions by define a global variable.
  3571. if (!this.macroTaskOptions) {
  3572. this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
  3573. }
  3574. }
  3575. FakeAsyncTestZoneSpec.assertInZone = function () {
  3576. if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
  3577. throw new Error('The code should be running in the fakeAsync zone to call this function');
  3578. }
  3579. };
  3580. FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
  3581. var _this = this;
  3582. return function () {
  3583. var args = [];
  3584. for (var _i = 0; _i < arguments.length; _i++) {
  3585. args[_i] = arguments[_i];
  3586. }
  3587. fn.apply(global, args);
  3588. if (_this._lastError === null) { // Success
  3589. if (completers.onSuccess != null) {
  3590. completers.onSuccess.apply(global);
  3591. }
  3592. // Flush microtasks only on success.
  3593. _this.flushMicrotasks();
  3594. }
  3595. else { // Failure
  3596. if (completers.onError != null) {
  3597. completers.onError.apply(global);
  3598. }
  3599. }
  3600. // Return true if there were no errors, false otherwise.
  3601. return _this._lastError === null;
  3602. };
  3603. };
  3604. FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
  3605. var index = timers.indexOf(id);
  3606. if (index > -1) {
  3607. timers.splice(index, 1);
  3608. }
  3609. };
  3610. FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
  3611. var _this = this;
  3612. return function () {
  3613. FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
  3614. };
  3615. };
  3616. FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
  3617. var _this = this;
  3618. return function () {
  3619. // Requeue the timer callback if it's not been canceled.
  3620. if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
  3621. _this._scheduler.scheduleFunction(fn, interval, args, true, false, id);
  3622. }
  3623. };
  3624. };
  3625. FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
  3626. var _this = this;
  3627. return function () {
  3628. FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
  3629. };
  3630. };
  3631. FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
  3632. if (isTimer === void 0) { isTimer = true; }
  3633. var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
  3634. // Queue the callback and dequeue the timer on success and error.
  3635. var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
  3636. var id = this._scheduler.scheduleFunction(cb, delay, args, false, !isTimer);
  3637. if (isTimer) {
  3638. this.pendingTimers.push(id);
  3639. }
  3640. return id;
  3641. };
  3642. FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
  3643. FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
  3644. this._scheduler.removeScheduledFunctionWithId(id);
  3645. };
  3646. FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
  3647. var id = Scheduler.nextId;
  3648. var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
  3649. var cb = this._fnAndFlush(fn, completers);
  3650. // Use the callback created above to requeue on success.
  3651. completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
  3652. // Queue the callback and dequeue the periodic timer only on error.
  3653. this._scheduler.scheduleFunction(cb, interval, args, true);
  3654. this.pendingPeriodicTimers.push(id);
  3655. return id;
  3656. };
  3657. FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
  3658. FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
  3659. this._scheduler.removeScheduledFunctionWithId(id);
  3660. };
  3661. FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
  3662. var error = this._lastError || this._uncaughtPromiseErrors[0];
  3663. this._uncaughtPromiseErrors.length = 0;
  3664. this._lastError = null;
  3665. throw error;
  3666. };
  3667. FakeAsyncTestZoneSpec.prototype.getCurrentTime = function () {
  3668. return this._scheduler.getCurrentTime();
  3669. };
  3670. FakeAsyncTestZoneSpec.prototype.getCurrentRealTime = function () {
  3671. return this._scheduler.getCurrentRealTime();
  3672. };
  3673. FakeAsyncTestZoneSpec.prototype.setCurrentRealTime = function (realTime) {
  3674. this._scheduler.setCurrentRealTime(realTime);
  3675. };
  3676. FakeAsyncTestZoneSpec.patchDate = function () {
  3677. if (!!global[Zone.__symbol__('disableDatePatching')]) {
  3678. // we don't want to patch global Date
  3679. // because in some case, global Date
  3680. // is already being patched, we need to provide
  3681. // an option to let user still use their
  3682. // own version of Date.
  3683. return;
  3684. }
  3685. if (global['Date'] === FakeDate) {
  3686. // already patched
  3687. return;
  3688. }
  3689. global['Date'] = FakeDate;
  3690. FakeDate.prototype = OriginalDate.prototype;
  3691. // try check and reset timers
  3692. // because jasmine.clock().install() may
  3693. // have replaced the global timer
  3694. FakeAsyncTestZoneSpec.checkTimerPatch();
  3695. };
  3696. FakeAsyncTestZoneSpec.resetDate = function () {
  3697. if (global['Date'] === FakeDate) {
  3698. global['Date'] = OriginalDate;
  3699. }
  3700. };
  3701. FakeAsyncTestZoneSpec.checkTimerPatch = function () {
  3702. if (global.setTimeout !== timers.setTimeout) {
  3703. global.setTimeout = timers.setTimeout;
  3704. global.clearTimeout = timers.clearTimeout;
  3705. }
  3706. if (global.setInterval !== timers.setInterval) {
  3707. global.setInterval = timers.setInterval;
  3708. global.clearInterval = timers.clearInterval;
  3709. }
  3710. };
  3711. FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
  3712. this.patchDateLocked = true;
  3713. FakeAsyncTestZoneSpec.patchDate();
  3714. };
  3715. FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
  3716. this.patchDateLocked = false;
  3717. FakeAsyncTestZoneSpec.resetDate();
  3718. };
  3719. FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick) {
  3720. if (millis === void 0) { millis = 0; }
  3721. FakeAsyncTestZoneSpec.assertInZone();
  3722. this.flushMicrotasks();
  3723. this._scheduler.tick(millis, doTick);
  3724. if (this._lastError !== null) {
  3725. this._resetLastErrorAndThrow();
  3726. }
  3727. };
  3728. FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
  3729. var _this = this;
  3730. FakeAsyncTestZoneSpec.assertInZone();
  3731. var flushErrors = function () {
  3732. if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
  3733. // If there is an error stop processing the microtask queue and rethrow the error.
  3734. _this._resetLastErrorAndThrow();
  3735. }
  3736. };
  3737. while (this._microtasks.length > 0) {
  3738. var microtask = this._microtasks.shift();
  3739. microtask.func.apply(microtask.target, microtask.args);
  3740. }
  3741. flushErrors();
  3742. };
  3743. FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
  3744. FakeAsyncTestZoneSpec.assertInZone();
  3745. this.flushMicrotasks();
  3746. var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
  3747. if (this._lastError !== null) {
  3748. this._resetLastErrorAndThrow();
  3749. }
  3750. return elapsed;
  3751. };
  3752. FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3753. switch (task.type) {
  3754. case 'microTask':
  3755. var args = task.data && task.data.args;
  3756. // should pass additional arguments to callback if have any
  3757. // currently we know process.nextTick will have such additional
  3758. // arguments
  3759. var additionalArgs = void 0;
  3760. if (args) {
  3761. var callbackIndex = task.data.cbIdx;
  3762. if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
  3763. additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
  3764. }
  3765. }
  3766. this._microtasks.push({
  3767. func: task.invoke,
  3768. args: additionalArgs,
  3769. target: task.data && task.data.target
  3770. });
  3771. break;
  3772. case 'macroTask':
  3773. switch (task.source) {
  3774. case 'setTimeout':
  3775. task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  3776. break;
  3777. case 'setImmediate':
  3778. task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
  3779. break;
  3780. case 'setInterval':
  3781. task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  3782. break;
  3783. case 'XMLHttpRequest.send':
  3784. throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
  3785. task.data['url']);
  3786. case 'requestAnimationFrame':
  3787. case 'webkitRequestAnimationFrame':
  3788. case 'mozRequestAnimationFrame':
  3789. // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
  3790. // (60 frames per second)
  3791. task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
  3792. break;
  3793. default:
  3794. // user can define which macroTask they want to support by passing
  3795. // macroTaskOptions
  3796. var macroTaskOption = this.findMacroTaskOption(task);
  3797. if (macroTaskOption) {
  3798. var args_1 = task.data && task.data['args'];
  3799. var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
  3800. var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
  3801. if (!!macroTaskOption.isPeriodic) {
  3802. // periodic macroTask, use setInterval to simulate
  3803. task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
  3804. task.data.isPeriodic = true;
  3805. }
  3806. else {
  3807. // not periodic, use setTimeout to simulate
  3808. task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
  3809. }
  3810. break;
  3811. }
  3812. throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
  3813. }
  3814. break;
  3815. case 'eventTask':
  3816. task = delegate.scheduleTask(target, task);
  3817. break;
  3818. }
  3819. return task;
  3820. };
  3821. FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  3822. switch (task.source) {
  3823. case 'setTimeout':
  3824. case 'requestAnimationFrame':
  3825. case 'webkitRequestAnimationFrame':
  3826. case 'mozRequestAnimationFrame':
  3827. return this._clearTimeout(task.data['handleId']);
  3828. case 'setInterval':
  3829. return this._clearInterval(task.data['handleId']);
  3830. default:
  3831. // user can define which macroTask they want to support by passing
  3832. // macroTaskOptions
  3833. var macroTaskOption = this.findMacroTaskOption(task);
  3834. if (macroTaskOption) {
  3835. var handleId = task.data['handleId'];
  3836. return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
  3837. this._clearTimeout(handleId);
  3838. }
  3839. return delegate.cancelTask(target, task);
  3840. }
  3841. };
  3842. FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
  3843. try {
  3844. FakeAsyncTestZoneSpec.patchDate();
  3845. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  3846. }
  3847. finally {
  3848. if (!this.patchDateLocked) {
  3849. FakeAsyncTestZoneSpec.resetDate();
  3850. }
  3851. }
  3852. };
  3853. FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
  3854. if (!this.macroTaskOptions) {
  3855. return null;
  3856. }
  3857. for (var i = 0; i < this.macroTaskOptions.length; i++) {
  3858. var macroTaskOption = this.macroTaskOptions[i];
  3859. if (macroTaskOption.source === task.source) {
  3860. return macroTaskOption;
  3861. }
  3862. }
  3863. return null;
  3864. };
  3865. FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  3866. this._lastError = error;
  3867. return false; // Don't propagate error to parent zone.
  3868. };
  3869. return FakeAsyncTestZoneSpec;
  3870. }());
  3871. // Export the class so that new instances can be created with proper
  3872. // constructor params.
  3873. Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
  3874. })(typeof window === 'object' && window || typeof self === 'object' && self || global);
  3875. /**
  3876. * @license
  3877. * Copyright Google Inc. All Rights Reserved.
  3878. *
  3879. * Use of this source code is governed by an MIT-style license that can be
  3880. * found in the LICENSE file at https://angular.io/license
  3881. */
  3882. Zone.__load_patch('fakeasync', function (global, Zone, api) {
  3883. var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
  3884. var ProxyZoneSpec = Zone && Zone['ProxyZoneSpec'];
  3885. var _fakeAsyncTestZoneSpec = null;
  3886. /**
  3887. * Clears out the shared fake async zone for a test.
  3888. * To be called in a global `beforeEach`.
  3889. *
  3890. * @experimental
  3891. */
  3892. function resetFakeAsyncZone() {
  3893. if (_fakeAsyncTestZoneSpec) {
  3894. _fakeAsyncTestZoneSpec.unlockDatePatch();
  3895. }
  3896. _fakeAsyncTestZoneSpec = null;
  3897. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  3898. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
  3899. }
  3900. /**
  3901. * Wraps a function to be executed in the fakeAsync zone:
  3902. * - microtasks are manually executed by calling `flushMicrotasks()`,
  3903. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  3904. *
  3905. * If there are any pending timers at the end of the function, an exception will be thrown.
  3906. *
  3907. * Can be used to wrap inject() calls.
  3908. *
  3909. * ## Example
  3910. *
  3911. * {@example core/testing/ts/fake_async.ts region='basic'}
  3912. *
  3913. * @param fn
  3914. * @returns The function wrapped to be executed in the fakeAsync zone
  3915. *
  3916. * @experimental
  3917. */
  3918. function fakeAsync(fn) {
  3919. // Not using an arrow function to preserve context passed from call site
  3920. return function () {
  3921. var args = [];
  3922. for (var _i = 0; _i < arguments.length; _i++) {
  3923. args[_i] = arguments[_i];
  3924. }
  3925. var proxyZoneSpec = ProxyZoneSpec.assertPresent();
  3926. if (Zone.current.get('FakeAsyncTestZoneSpec')) {
  3927. throw new Error('fakeAsync() calls can not be nested');
  3928. }
  3929. try {
  3930. // in case jasmine.clock init a fakeAsyncTestZoneSpec
  3931. if (!_fakeAsyncTestZoneSpec) {
  3932. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  3933. throw new Error('fakeAsync() calls can not be nested');
  3934. }
  3935. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  3936. }
  3937. var res = void 0;
  3938. var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  3939. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  3940. _fakeAsyncTestZoneSpec.lockDatePatch();
  3941. try {
  3942. res = fn.apply(this, args);
  3943. flushMicrotasks();
  3944. }
  3945. finally {
  3946. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  3947. }
  3948. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  3949. throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
  3950. "periodic timer(s) still in the queue.");
  3951. }
  3952. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  3953. throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
  3954. }
  3955. return res;
  3956. }
  3957. finally {
  3958. resetFakeAsyncZone();
  3959. }
  3960. };
  3961. }
  3962. function _getFakeAsyncZoneSpec() {
  3963. if (_fakeAsyncTestZoneSpec == null) {
  3964. _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3965. if (_fakeAsyncTestZoneSpec == null) {
  3966. throw new Error('The code should be running in the fakeAsync zone to call this function');
  3967. }
  3968. }
  3969. return _fakeAsyncTestZoneSpec;
  3970. }
  3971. /**
  3972. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  3973. *
  3974. * The microtasks queue is drained at the very start of this function and after any timer callback
  3975. * has been executed.
  3976. *
  3977. * ## Example
  3978. *
  3979. * {@example core/testing/ts/fake_async.ts region='basic'}
  3980. *
  3981. * @experimental
  3982. */
  3983. function tick(millis) {
  3984. if (millis === void 0) { millis = 0; }
  3985. _getFakeAsyncZoneSpec().tick(millis);
  3986. }
  3987. /**
  3988. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  3989. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  3990. * of time that would have been elapsed.
  3991. *
  3992. * @param maxTurns
  3993. * @returns The simulated time elapsed, in millis.
  3994. *
  3995. * @experimental
  3996. */
  3997. function flush(maxTurns) {
  3998. return _getFakeAsyncZoneSpec().flush(maxTurns);
  3999. }
  4000. /**
  4001. * Discard all remaining periodic tasks.
  4002. *
  4003. * @experimental
  4004. */
  4005. function discardPeriodicTasks() {
  4006. var zoneSpec = _getFakeAsyncZoneSpec();
  4007. var pendingTimers = zoneSpec.pendingPeriodicTimers;
  4008. zoneSpec.pendingPeriodicTimers.length = 0;
  4009. }
  4010. /**
  4011. * Flush any pending microtasks.
  4012. *
  4013. * @experimental
  4014. */
  4015. function flushMicrotasks() {
  4016. _getFakeAsyncZoneSpec().flushMicrotasks();
  4017. }
  4018. Zone[api.symbol('fakeAsyncTest')] =
  4019. { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
  4020. });
  4021. /**
  4022. * @license
  4023. * Copyright Google Inc. All Rights Reserved.
  4024. *
  4025. * Use of this source code is governed by an MIT-style license that can be
  4026. * found in the LICENSE file at https://angular.io/license
  4027. */
  4028. /**
  4029. * Promise for async/fakeAsync zoneSpec test
  4030. * can support async operation which not supported by zone.js
  4031. * such as
  4032. * it ('test jsonp in AsyncZone', async() => {
  4033. * new Promise(res => {
  4034. * jsonp(url, (data) => {
  4035. * // success callback
  4036. * res(data);
  4037. * });
  4038. * }).then((jsonpResult) => {
  4039. * // get jsonp result.
  4040. *
  4041. * // user will expect AsyncZoneSpec wait for
  4042. * // then, but because jsonp is not zone aware
  4043. * // AsyncZone will finish before then is called.
  4044. * });
  4045. * });
  4046. */
  4047. Zone.__load_patch('promisefortest', function (global, Zone, api) {
  4048. var symbolState = api.symbol('state');
  4049. var UNRESOLVED = null;
  4050. var symbolParentUnresolved = api.symbol('parentUnresolved');
  4051. // patch Promise.prototype.then to keep an internal
  4052. // number for tracking unresolved chained promise
  4053. // we will decrease this number when the parent promise
  4054. // being resolved/rejected and chained promise was
  4055. // scheduled as a microTask.
  4056. // so we can know such kind of chained promise still
  4057. // not resolved in AsyncTestZone
  4058. Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
  4059. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4060. if (oriThen) {
  4061. return;
  4062. }
  4063. oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
  4064. Promise.prototype.then = function () {
  4065. var chained = oriThen.apply(this, arguments);
  4066. if (this[symbolState] === UNRESOLVED) {
  4067. // parent promise is unresolved.
  4068. var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
  4069. if (asyncTestZoneSpec) {
  4070. asyncTestZoneSpec.unresolvedChainedPromiseCount++;
  4071. chained[symbolParentUnresolved] = true;
  4072. }
  4073. }
  4074. return chained;
  4075. };
  4076. };
  4077. Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
  4078. // restore origin then
  4079. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4080. if (oriThen) {
  4081. Promise.prototype.then = oriThen;
  4082. Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
  4083. }
  4084. };
  4085. });
  4086. /**
  4087. * @license
  4088. * Copyright Google Inc. All Rights Reserved.
  4089. *
  4090. * Use of this source code is governed by an MIT-style license that can be
  4091. * found in the LICENSE file at https://angular.io/license
  4092. */
  4093. // load test related files into bundle in correct order
  4094. /**
  4095. * @license
  4096. * Copyright Google Inc. All Rights Reserved.
  4097. *
  4098. * Use of this source code is governed by an MIT-style license that can be
  4099. * found in the LICENSE file at https://angular.io/license
  4100. */
  4101. // load test related files into bundle
  4102. })));