zone-testing-node-bundle.umd.js 225 KB

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