zone-testing-bundle.js 215 KB

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