zone-evergreen-testing-bundle.js 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790
  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. /**
  2715. * @fileoverview
  2716. * @suppress {missingRequire}
  2717. */
  2718. var taskSymbol = zoneSymbol('zoneTask');
  2719. function patchTimer(window, setName, cancelName, nameSuffix) {
  2720. var setNative = null;
  2721. var clearNative = null;
  2722. setName += nameSuffix;
  2723. cancelName += nameSuffix;
  2724. var tasksByHandleId = {};
  2725. function scheduleTask(task) {
  2726. var data = task.data;
  2727. function timer() {
  2728. try {
  2729. task.invoke.apply(this, arguments);
  2730. }
  2731. finally {
  2732. // issue-934, task will be cancelled
  2733. // even it is a periodic task such as
  2734. // setInterval
  2735. if (!(task.data && task.data.isPeriodic)) {
  2736. if (typeof data.handleId === 'number') {
  2737. // in non-nodejs env, we remove timerId
  2738. // from local cache
  2739. delete tasksByHandleId[data.handleId];
  2740. }
  2741. else if (data.handleId) {
  2742. // Node returns complex objects as handleIds
  2743. // we remove task reference from timer object
  2744. data.handleId[taskSymbol] = null;
  2745. }
  2746. }
  2747. }
  2748. }
  2749. data.args[0] = timer;
  2750. data.handleId = setNative.apply(window, data.args);
  2751. return task;
  2752. }
  2753. function clearTask(task) {
  2754. return clearNative(task.data.handleId);
  2755. }
  2756. setNative =
  2757. patchMethod(window, setName, function (delegate) { return function (self, args) {
  2758. if (typeof args[0] === 'function') {
  2759. var options = {
  2760. isPeriodic: nameSuffix === 'Interval',
  2761. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2762. undefined,
  2763. args: args
  2764. };
  2765. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2766. if (!task) {
  2767. return task;
  2768. }
  2769. // Node.js must additionally support the ref and unref functions.
  2770. var handle = task.data.handleId;
  2771. if (typeof handle === 'number') {
  2772. // for non nodejs env, we save handleId: task
  2773. // mapping in local cache for clearTimeout
  2774. tasksByHandleId[handle] = task;
  2775. }
  2776. else if (handle) {
  2777. // for nodejs env, we save task
  2778. // reference in timerId Object for clearTimeout
  2779. handle[taskSymbol] = task;
  2780. }
  2781. // check whether handle is null, because some polyfill or browser
  2782. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2783. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2784. typeof handle.unref === 'function') {
  2785. task.ref = handle.ref.bind(handle);
  2786. task.unref = handle.unref.bind(handle);
  2787. }
  2788. if (typeof handle === 'number' || handle) {
  2789. return handle;
  2790. }
  2791. return task;
  2792. }
  2793. else {
  2794. // cause an error by calling it directly.
  2795. return delegate.apply(window, args);
  2796. }
  2797. }; });
  2798. clearNative =
  2799. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  2800. var id = args[0];
  2801. var task;
  2802. if (typeof id === 'number') {
  2803. // non nodejs env.
  2804. task = tasksByHandleId[id];
  2805. }
  2806. else {
  2807. // nodejs env.
  2808. task = id && id[taskSymbol];
  2809. // other environments.
  2810. if (!task) {
  2811. task = id;
  2812. }
  2813. }
  2814. if (task && typeof task.type === 'string') {
  2815. if (task.state !== 'notScheduled' &&
  2816. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2817. if (typeof id === 'number') {
  2818. delete tasksByHandleId[id];
  2819. }
  2820. else if (id) {
  2821. id[taskSymbol] = null;
  2822. }
  2823. // Do not cancel already canceled functions
  2824. task.zone.cancelTask(task);
  2825. }
  2826. }
  2827. else {
  2828. // cause an error by calling it directly.
  2829. delegate.apply(window, args);
  2830. }
  2831. }; });
  2832. }
  2833. /**
  2834. * @license
  2835. * Copyright Google Inc. All Rights Reserved.
  2836. *
  2837. * Use of this source code is governed by an MIT-style license that can be
  2838. * found in the LICENSE file at https://angular.io/license
  2839. */
  2840. function patchCustomElements(_global, api) {
  2841. var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
  2842. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  2843. return;
  2844. }
  2845. var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
  2846. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  2847. }
  2848. /**
  2849. * @license
  2850. * Copyright Google Inc. All Rights Reserved.
  2851. *
  2852. * Use of this source code is governed by an MIT-style license that can be
  2853. * found in the LICENSE file at https://angular.io/license
  2854. */
  2855. function eventTargetPatch(_global, api) {
  2856. if (Zone[api.symbol('patchEventTarget')]) {
  2857. // EventTarget is already patched.
  2858. return;
  2859. }
  2860. 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;
  2861. // predefine all __zone_symbol__ + eventName + true/false string
  2862. for (var i = 0; i < eventNames.length; i++) {
  2863. var eventName = eventNames[i];
  2864. var falseEventName = eventName + FALSE_STR;
  2865. var trueEventName = eventName + TRUE_STR;
  2866. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  2867. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  2868. zoneSymbolEventNames[eventName] = {};
  2869. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  2870. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  2871. }
  2872. var EVENT_TARGET = _global['EventTarget'];
  2873. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  2874. return;
  2875. }
  2876. api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
  2877. return true;
  2878. }
  2879. function patchEvent(global, api) {
  2880. api.patchEventPrototype(global, api);
  2881. }
  2882. /**
  2883. * @license
  2884. * Copyright Google Inc. All Rights Reserved.
  2885. *
  2886. * Use of this source code is governed by an MIT-style license that can be
  2887. * found in the LICENSE file at https://angular.io/license
  2888. */
  2889. /**
  2890. * @fileoverview
  2891. * @suppress {missingRequire}
  2892. */
  2893. Zone.__load_patch('legacy', function (global) {
  2894. var legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2895. if (legacyPatch) {
  2896. legacyPatch();
  2897. }
  2898. });
  2899. Zone.__load_patch('timers', function (global) {
  2900. var set = 'set';
  2901. var clear = 'clear';
  2902. patchTimer(global, set, clear, 'Timeout');
  2903. patchTimer(global, set, clear, 'Interval');
  2904. patchTimer(global, set, clear, 'Immediate');
  2905. });
  2906. Zone.__load_patch('requestAnimationFrame', function (global) {
  2907. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2908. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2909. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2910. });
  2911. Zone.__load_patch('blocking', function (global, Zone) {
  2912. var blockingMethods = ['alert', 'prompt', 'confirm'];
  2913. for (var i = 0; i < blockingMethods.length; i++) {
  2914. var name_1 = blockingMethods[i];
  2915. patchMethod(global, name_1, function (delegate, symbol, name) {
  2916. return function (s, args) {
  2917. return Zone.current.run(delegate, global, args, name);
  2918. };
  2919. });
  2920. }
  2921. });
  2922. Zone.__load_patch('EventTarget', function (global, Zone, api) {
  2923. patchEvent(global, api);
  2924. eventTargetPatch(global, api);
  2925. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2926. var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2927. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2928. api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
  2929. }
  2930. patchClass('MutationObserver');
  2931. patchClass('WebKitMutationObserver');
  2932. patchClass('IntersectionObserver');
  2933. patchClass('FileReader');
  2934. });
  2935. Zone.__load_patch('on_property', function (global, Zone, api) {
  2936. propertyDescriptorPatch(api, global);
  2937. propertyPatch();
  2938. });
  2939. Zone.__load_patch('customElements', function (global, Zone, api) {
  2940. patchCustomElements(global, api);
  2941. });
  2942. Zone.__load_patch('XHR', function (global, Zone) {
  2943. // Treat XMLHttpRequest as a macrotask.
  2944. patchXHR(global);
  2945. var XHR_TASK = zoneSymbol('xhrTask');
  2946. var XHR_SYNC = zoneSymbol('xhrSync');
  2947. var XHR_LISTENER = zoneSymbol('xhrListener');
  2948. var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2949. var XHR_URL = zoneSymbol('xhrURL');
  2950. var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2951. function patchXHR(window) {
  2952. var XMLHttpRequest = window['XMLHttpRequest'];
  2953. if (!XMLHttpRequest) {
  2954. // XMLHttpRequest is not available in service worker
  2955. return;
  2956. }
  2957. var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2958. function findPendingTask(target) {
  2959. return target[XHR_TASK];
  2960. }
  2961. var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2962. var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2963. if (!oriAddListener) {
  2964. var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
  2965. if (XMLHttpRequestEventTarget_1) {
  2966. var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
  2967. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2968. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2969. }
  2970. }
  2971. var READY_STATE_CHANGE = 'readystatechange';
  2972. var SCHEDULED = 'scheduled';
  2973. function scheduleTask(task) {
  2974. var data = task.data;
  2975. var target = data.target;
  2976. target[XHR_SCHEDULED] = false;
  2977. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2978. // remove existing event listener
  2979. var listener = target[XHR_LISTENER];
  2980. if (!oriAddListener) {
  2981. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2982. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2983. }
  2984. if (listener) {
  2985. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2986. }
  2987. var newListener = target[XHR_LISTENER] = function () {
  2988. if (target.readyState === target.DONE) {
  2989. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2990. // readyState=4 multiple times, so we need to check task state here
  2991. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2992. // check whether the xhr has registered onload listener
  2993. // if that is the case, the task should invoke after all
  2994. // onload listeners finish.
  2995. var loadTasks = target['__zone_symbol__loadfalse'];
  2996. if (loadTasks && loadTasks.length > 0) {
  2997. var oriInvoke_1 = task.invoke;
  2998. task.invoke = function () {
  2999. // need to load the tasks again, because in other
  3000. // load listener, they may remove themselves
  3001. var loadTasks = target['__zone_symbol__loadfalse'];
  3002. for (var i = 0; i < loadTasks.length; i++) {
  3003. if (loadTasks[i] === task) {
  3004. loadTasks.splice(i, 1);
  3005. }
  3006. }
  3007. if (!data.aborted && task.state === SCHEDULED) {
  3008. oriInvoke_1.call(task);
  3009. }
  3010. };
  3011. loadTasks.push(task);
  3012. }
  3013. else {
  3014. task.invoke();
  3015. }
  3016. }
  3017. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  3018. // error occurs when xhr.send()
  3019. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  3020. }
  3021. }
  3022. };
  3023. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  3024. var storedTask = target[XHR_TASK];
  3025. if (!storedTask) {
  3026. target[XHR_TASK] = task;
  3027. }
  3028. sendNative.apply(target, data.args);
  3029. target[XHR_SCHEDULED] = true;
  3030. return task;
  3031. }
  3032. function placeholderCallback() { }
  3033. function clearTask(task) {
  3034. var data = task.data;
  3035. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  3036. // to prevent it from firing. So instead, we store info for the event listener.
  3037. data.aborted = true;
  3038. return abortNative.apply(data.target, data.args);
  3039. }
  3040. var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () { return function (self, args) {
  3041. self[XHR_SYNC] = args[2] == false;
  3042. self[XHR_URL] = args[1];
  3043. return openNative.apply(self, args);
  3044. }; });
  3045. var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  3046. var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  3047. var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  3048. var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
  3049. if (Zone.current[fetchTaskScheduling] === true) {
  3050. // a fetch is scheduling, so we are using xhr to polyfill fetch
  3051. // and because we already schedule macroTask for fetch, we should
  3052. // not schedule a macroTask for xhr again
  3053. return sendNative.apply(self, args);
  3054. }
  3055. if (self[XHR_SYNC]) {
  3056. // if the XHR is sync there is no task to schedule, just execute the code.
  3057. return sendNative.apply(self, args);
  3058. }
  3059. else {
  3060. var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
  3061. var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  3062. if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
  3063. task.state === SCHEDULED) {
  3064. // xhr request throw error when send
  3065. // we should invoke task instead of leaving a scheduled
  3066. // pending macroTask
  3067. task.invoke();
  3068. }
  3069. }
  3070. }; });
  3071. var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
  3072. var task = findPendingTask(self);
  3073. if (task && typeof task.type == 'string') {
  3074. // If the XHR has already completed, do nothing.
  3075. // If the XHR has already been aborted, do nothing.
  3076. // Fix #569, call abort multiple times before done will cause
  3077. // macroTask task count be negative number
  3078. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  3079. return;
  3080. }
  3081. task.zone.cancelTask(task);
  3082. }
  3083. else if (Zone.current[fetchTaskAborting] === true) {
  3084. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  3085. return abortNative.apply(self, args);
  3086. }
  3087. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  3088. // task
  3089. // to cancel. Do nothing.
  3090. }; });
  3091. }
  3092. });
  3093. Zone.__load_patch('geolocation', function (global) {
  3094. /// GEO_LOCATION
  3095. if (global['navigator'] && global['navigator'].geolocation) {
  3096. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  3097. }
  3098. });
  3099. Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
  3100. // handle unhandled promise rejection
  3101. function findPromiseRejectionHandler(evtName) {
  3102. return function (e) {
  3103. var eventTasks = findEventTasks(global, evtName);
  3104. eventTasks.forEach(function (eventTask) {
  3105. // windows has added unhandledrejection event listener
  3106. // trigger the event listener
  3107. var PromiseRejectionEvent = global['PromiseRejectionEvent'];
  3108. if (PromiseRejectionEvent) {
  3109. var evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
  3110. eventTask.invoke(evt);
  3111. }
  3112. });
  3113. };
  3114. }
  3115. if (global['PromiseRejectionEvent']) {
  3116. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  3117. findPromiseRejectionHandler('unhandledrejection');
  3118. Zone[zoneSymbol('rejectionHandledHandler')] =
  3119. findPromiseRejectionHandler('rejectionhandled');
  3120. }
  3121. });
  3122. /**
  3123. * @license
  3124. * Copyright Google Inc. All Rights Reserved.
  3125. *
  3126. * Use of this source code is governed by an MIT-style license that can be
  3127. * found in the LICENSE file at https://angular.io/license
  3128. */
  3129. /**
  3130. * @license
  3131. * Copyright Google Inc. All Rights Reserved.
  3132. *
  3133. * Use of this source code is governed by an MIT-style license that can be
  3134. * found in the LICENSE file at https://angular.io/license
  3135. */
  3136. /**
  3137. * @fileoverview
  3138. * @suppress {globalThis}
  3139. */
  3140. var __assign = (undefined && undefined.__assign) || function () {
  3141. __assign = Object.assign || function(t) {
  3142. for (var s, i = 1, n = arguments.length; i < n; i++) {
  3143. s = arguments[i];
  3144. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  3145. t[p] = s[p];
  3146. }
  3147. return t;
  3148. };
  3149. return __assign.apply(this, arguments);
  3150. };
  3151. var NEWLINE = '\n';
  3152. var IGNORE_FRAMES = {};
  3153. var creationTrace = '__creationTrace__';
  3154. var ERROR_TAG = 'STACKTRACE TRACKING';
  3155. var SEP_TAG = '__SEP_TAG__';
  3156. var sepTemplate = SEP_TAG + '@[native]';
  3157. var LongStackTrace = /** @class */ (function () {
  3158. function LongStackTrace() {
  3159. this.error = getStacktrace();
  3160. this.timestamp = new Date();
  3161. }
  3162. return LongStackTrace;
  3163. }());
  3164. function getStacktraceWithUncaughtError() {
  3165. return new Error(ERROR_TAG);
  3166. }
  3167. function getStacktraceWithCaughtError() {
  3168. try {
  3169. throw getStacktraceWithUncaughtError();
  3170. }
  3171. catch (err) {
  3172. return err;
  3173. }
  3174. }
  3175. // Some implementations of exception handling don't create a stack trace if the exception
  3176. // isn't thrown, however it's faster not to actually throw the exception.
  3177. var error = getStacktraceWithUncaughtError();
  3178. var caughtError = getStacktraceWithCaughtError();
  3179. var getStacktrace = error.stack ?
  3180. getStacktraceWithUncaughtError :
  3181. (caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
  3182. function getFrames(error) {
  3183. return error.stack ? error.stack.split(NEWLINE) : [];
  3184. }
  3185. function addErrorStack(lines, error) {
  3186. var trace = getFrames(error);
  3187. for (var i = 0; i < trace.length; i++) {
  3188. var frame = trace[i];
  3189. // Filter out the Frames which are part of stack capturing.
  3190. if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
  3191. lines.push(trace[i]);
  3192. }
  3193. }
  3194. }
  3195. function renderLongStackTrace(frames, stack) {
  3196. var longTrace = [stack ? stack.trim() : ''];
  3197. if (frames) {
  3198. var timestamp = new Date().getTime();
  3199. for (var i = 0; i < frames.length; i++) {
  3200. var traceFrames = frames[i];
  3201. var lastTime = traceFrames.timestamp;
  3202. var separator = "____________________Elapsed " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime;
  3203. separator = separator.replace(/[^\w\d]/g, '_');
  3204. longTrace.push(sepTemplate.replace(SEP_TAG, separator));
  3205. addErrorStack(longTrace, traceFrames.error);
  3206. timestamp = lastTime.getTime();
  3207. }
  3208. }
  3209. return longTrace.join(NEWLINE);
  3210. }
  3211. Zone['longStackTraceZoneSpec'] = {
  3212. name: 'long-stack-trace',
  3213. longStackTraceLimit: 10,
  3214. // add a getLongStackTrace method in spec to
  3215. // handle handled reject promise error.
  3216. getLongStackTrace: function (error) {
  3217. if (!error) {
  3218. return undefined;
  3219. }
  3220. var trace = error[Zone.__symbol__('currentTaskTrace')];
  3221. if (!trace) {
  3222. return error.stack;
  3223. }
  3224. return renderLongStackTrace(trace, error.stack);
  3225. },
  3226. onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
  3227. if (Error.stackTraceLimit > 0) {
  3228. // if Error.stackTraceLimit is 0, means stack trace
  3229. // is disabled, so we don't need to generate long stack trace
  3230. // this will improve performance in some test(some test will
  3231. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  3232. var currentTask = Zone.currentTask;
  3233. var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
  3234. trace = [new LongStackTrace()].concat(trace);
  3235. if (trace.length > this.longStackTraceLimit) {
  3236. trace.length = this.longStackTraceLimit;
  3237. }
  3238. if (!task.data)
  3239. task.data = {};
  3240. if (task.type === 'eventTask') {
  3241. // Fix issue https://github.com/angular/zone.js/issues/1195,
  3242. // For event task of browser, by default, all task will share a
  3243. // singleton instance of data object, we should create a new one here
  3244. // The cast to `any` is required to workaround a closure bug which wrongly applies
  3245. // URL sanitization rules to .data access.
  3246. task.data = __assign({}, task.data);
  3247. }
  3248. task.data[creationTrace] = trace;
  3249. }
  3250. return parentZoneDelegate.scheduleTask(targetZone, task);
  3251. },
  3252. onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
  3253. if (Error.stackTraceLimit > 0) {
  3254. // if Error.stackTraceLimit is 0, means stack trace
  3255. // is disabled, so we don't need to generate long stack trace
  3256. // this will improve performance in some test(some test will
  3257. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  3258. var parentTask = Zone.currentTask || error.task;
  3259. if (error instanceof Error && parentTask) {
  3260. var longStack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
  3261. try {
  3262. error.stack = error.longStack = longStack;
  3263. }
  3264. catch (err) {
  3265. }
  3266. }
  3267. }
  3268. return parentZoneDelegate.handleError(targetZone, error);
  3269. }
  3270. };
  3271. function captureStackTraces(stackTraces, count) {
  3272. if (count > 0) {
  3273. stackTraces.push(getFrames((new LongStackTrace()).error));
  3274. captureStackTraces(stackTraces, count - 1);
  3275. }
  3276. }
  3277. function computeIgnoreFrames() {
  3278. if (Error.stackTraceLimit <= 0) {
  3279. return;
  3280. }
  3281. var frames = [];
  3282. captureStackTraces(frames, 2);
  3283. var frames1 = frames[0];
  3284. var frames2 = frames[1];
  3285. for (var i = 0; i < frames1.length; i++) {
  3286. var frame1 = frames1[i];
  3287. if (frame1.indexOf(ERROR_TAG) == -1) {
  3288. var match = frame1.match(/^\s*at\s+/);
  3289. if (match) {
  3290. sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
  3291. break;
  3292. }
  3293. }
  3294. }
  3295. for (var i = 0; i < frames1.length; i++) {
  3296. var frame1 = frames1[i];
  3297. var frame2 = frames2[i];
  3298. if (frame1 === frame2) {
  3299. IGNORE_FRAMES[frame1] = true;
  3300. }
  3301. else {
  3302. break;
  3303. }
  3304. }
  3305. }
  3306. computeIgnoreFrames();
  3307. /**
  3308. * @license
  3309. * Copyright Google Inc. All Rights Reserved.
  3310. *
  3311. * Use of this source code is governed by an MIT-style license that can be
  3312. * found in the LICENSE file at https://angular.io/license
  3313. */
  3314. var ProxyZoneSpec = /** @class */ (function () {
  3315. function ProxyZoneSpec(defaultSpecDelegate) {
  3316. if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
  3317. this.defaultSpecDelegate = defaultSpecDelegate;
  3318. this.name = 'ProxyZone';
  3319. this._delegateSpec = null;
  3320. this.properties = { 'ProxyZoneSpec': this };
  3321. this.propertyKeys = null;
  3322. this.lastTaskState = null;
  3323. this.isNeedToTriggerHasTask = false;
  3324. this.tasks = [];
  3325. this.setDelegate(defaultSpecDelegate);
  3326. }
  3327. ProxyZoneSpec.get = function () {
  3328. return Zone.current.get('ProxyZoneSpec');
  3329. };
  3330. ProxyZoneSpec.isLoaded = function () {
  3331. return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
  3332. };
  3333. ProxyZoneSpec.assertPresent = function () {
  3334. if (!ProxyZoneSpec.isLoaded()) {
  3335. throw new Error("Expected to be running in 'ProxyZone', but it was not found.");
  3336. }
  3337. return ProxyZoneSpec.get();
  3338. };
  3339. ProxyZoneSpec.prototype.setDelegate = function (delegateSpec) {
  3340. var _this = this;
  3341. var isNewDelegate = this._delegateSpec !== delegateSpec;
  3342. this._delegateSpec = delegateSpec;
  3343. this.propertyKeys && this.propertyKeys.forEach(function (key) { return delete _this.properties[key]; });
  3344. this.propertyKeys = null;
  3345. if (delegateSpec && delegateSpec.properties) {
  3346. this.propertyKeys = Object.keys(delegateSpec.properties);
  3347. this.propertyKeys.forEach(function (k) { return _this.properties[k] = delegateSpec.properties[k]; });
  3348. }
  3349. // if set a new delegateSpec, shoulde check whether need to
  3350. // trigger hasTask or not
  3351. if (isNewDelegate && this.lastTaskState &&
  3352. (this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
  3353. this.isNeedToTriggerHasTask = true;
  3354. }
  3355. };
  3356. ProxyZoneSpec.prototype.getDelegate = function () {
  3357. return this._delegateSpec;
  3358. };
  3359. ProxyZoneSpec.prototype.resetDelegate = function () {
  3360. var delegateSpec = this.getDelegate();
  3361. this.setDelegate(this.defaultSpecDelegate);
  3362. };
  3363. ProxyZoneSpec.prototype.tryTriggerHasTask = function (parentZoneDelegate, currentZone, targetZone) {
  3364. if (this.isNeedToTriggerHasTask && this.lastTaskState) {
  3365. // last delegateSpec has microTask or macroTask
  3366. // should call onHasTask in current delegateSpec
  3367. this.isNeedToTriggerHasTask = false;
  3368. this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
  3369. }
  3370. };
  3371. ProxyZoneSpec.prototype.removeFromTasks = function (task) {
  3372. if (!this.tasks) {
  3373. return;
  3374. }
  3375. for (var i = 0; i < this.tasks.length; i++) {
  3376. if (this.tasks[i] === task) {
  3377. this.tasks.splice(i, 1);
  3378. return;
  3379. }
  3380. }
  3381. };
  3382. ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function () {
  3383. if (this.tasks.length === 0) {
  3384. return '';
  3385. }
  3386. var taskInfo = this.tasks.map(function (task) {
  3387. var dataInfo = task.data &&
  3388. Object.keys(task.data)
  3389. .map(function (key) {
  3390. return key + ':' + task.data[key];
  3391. })
  3392. .join(',');
  3393. return "type: " + task.type + ", source: " + task.source + ", args: {" + dataInfo + "}";
  3394. });
  3395. var pendingTasksInfo = '--Pendng async tasks are: [' + taskInfo + ']';
  3396. // clear tasks
  3397. this.tasks = [];
  3398. return pendingTasksInfo;
  3399. };
  3400. ProxyZoneSpec.prototype.onFork = function (parentZoneDelegate, currentZone, targetZone, zoneSpec) {
  3401. if (this._delegateSpec && this._delegateSpec.onFork) {
  3402. return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
  3403. }
  3404. else {
  3405. return parentZoneDelegate.fork(targetZone, zoneSpec);
  3406. }
  3407. };
  3408. ProxyZoneSpec.prototype.onIntercept = function (parentZoneDelegate, currentZone, targetZone, delegate, source) {
  3409. if (this._delegateSpec && this._delegateSpec.onIntercept) {
  3410. return this._delegateSpec.onIntercept(parentZoneDelegate, currentZone, targetZone, delegate, source);
  3411. }
  3412. else {
  3413. return parentZoneDelegate.intercept(targetZone, delegate, source);
  3414. }
  3415. };
  3416. ProxyZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  3417. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  3418. if (this._delegateSpec && this._delegateSpec.onInvoke) {
  3419. return this._delegateSpec.onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
  3420. }
  3421. else {
  3422. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  3423. }
  3424. };
  3425. ProxyZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  3426. if (this._delegateSpec && this._delegateSpec.onHandleError) {
  3427. return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
  3428. }
  3429. else {
  3430. return parentZoneDelegate.handleError(targetZone, error);
  3431. }
  3432. };
  3433. ProxyZoneSpec.prototype.onScheduleTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  3434. if (task.type !== 'eventTask') {
  3435. this.tasks.push(task);
  3436. }
  3437. if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
  3438. return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
  3439. }
  3440. else {
  3441. return parentZoneDelegate.scheduleTask(targetZone, task);
  3442. }
  3443. };
  3444. ProxyZoneSpec.prototype.onInvokeTask = function (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  3445. if (task.type !== 'eventTask') {
  3446. this.removeFromTasks(task);
  3447. }
  3448. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  3449. if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
  3450. return this._delegateSpec.onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
  3451. }
  3452. else {
  3453. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  3454. }
  3455. };
  3456. ProxyZoneSpec.prototype.onCancelTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  3457. if (task.type !== 'eventTask') {
  3458. this.removeFromTasks(task);
  3459. }
  3460. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  3461. if (this._delegateSpec && this._delegateSpec.onCancelTask) {
  3462. return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
  3463. }
  3464. else {
  3465. return parentZoneDelegate.cancelTask(targetZone, task);
  3466. }
  3467. };
  3468. ProxyZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  3469. this.lastTaskState = hasTaskState;
  3470. if (this._delegateSpec && this._delegateSpec.onHasTask) {
  3471. this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
  3472. }
  3473. else {
  3474. delegate.hasTask(target, hasTaskState);
  3475. }
  3476. };
  3477. return ProxyZoneSpec;
  3478. }());
  3479. // Export the class so that new instances can be created with proper
  3480. // constructor params.
  3481. Zone['ProxyZoneSpec'] = ProxyZoneSpec;
  3482. /**
  3483. * @license
  3484. * Copyright Google Inc. All Rights Reserved.
  3485. *
  3486. * Use of this source code is governed by an MIT-style license that can be
  3487. * found in the LICENSE file at https://angular.io/license
  3488. */
  3489. var SyncTestZoneSpec = /** @class */ (function () {
  3490. function SyncTestZoneSpec(namePrefix) {
  3491. this.runZone = Zone.current;
  3492. this.name = 'syncTestZone for ' + namePrefix;
  3493. }
  3494. SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3495. switch (task.type) {
  3496. case 'microTask':
  3497. case 'macroTask':
  3498. throw new Error("Cannot call " + task.source + " from within a sync test.");
  3499. case 'eventTask':
  3500. task = delegate.scheduleTask(target, task);
  3501. break;
  3502. }
  3503. return task;
  3504. };
  3505. return SyncTestZoneSpec;
  3506. }());
  3507. // Export the class so that new instances can be created with proper
  3508. // constructor params.
  3509. Zone['SyncTestZoneSpec'] = SyncTestZoneSpec;
  3510. /**
  3511. * @license
  3512. * Copyright Google Inc. All Rights Reserved.
  3513. *
  3514. * Use of this source code is governed by an MIT-style license that can be
  3515. * found in the LICENSE file at https://angular.io/license
  3516. */
  3517. (function () {
  3518. var __extends = function (d, b) {
  3519. for (var p in b)
  3520. if (b.hasOwnProperty(p))
  3521. d[p] = b[p];
  3522. function __() {
  3523. this.constructor = d;
  3524. }
  3525. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3526. };
  3527. var _global = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  3528. // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
  3529. // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
  3530. if (!Zone)
  3531. throw new Error('Missing: zone.js');
  3532. if (typeof jasmine == 'undefined')
  3533. throw new Error('Missing: jasmine.js');
  3534. if (jasmine['__zone_patch__'])
  3535. throw new Error("'jasmine' has already been patched with 'Zone'.");
  3536. jasmine['__zone_patch__'] = true;
  3537. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  3538. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  3539. if (!SyncTestZoneSpec)
  3540. throw new Error('Missing: SyncTestZoneSpec');
  3541. if (!ProxyZoneSpec)
  3542. throw new Error('Missing: ProxyZoneSpec');
  3543. var ambientZone = Zone.current;
  3544. // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
  3545. // error if any asynchronous operations are attempted inside of a `describe` but outside of
  3546. // a `beforeEach` or `it`.
  3547. var syncZone = ambientZone.fork(new SyncTestZoneSpec('jasmine.describe'));
  3548. var symbol = Zone.__symbol__;
  3549. // whether patch jasmine clock when in fakeAsync
  3550. var disablePatchingJasmineClock = _global[symbol('fakeAsyncDisablePatchingClock')] === true;
  3551. // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
  3552. // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
  3553. // automatically disable the auto jump into fakeAsync feature
  3554. var enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
  3555. ((_global[symbol('fakeAsyncPatchLock')] === true) ||
  3556. (_global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
  3557. var ignoreUnhandledRejection = _global[symbol('ignoreUnhandledRejection')] === true;
  3558. if (!ignoreUnhandledRejection) {
  3559. var globalErrors_1 = jasmine.GlobalErrors;
  3560. if (globalErrors_1 && !jasmine[symbol('GlobalErrors')]) {
  3561. jasmine[symbol('GlobalErrors')] = globalErrors_1;
  3562. jasmine.GlobalErrors = function () {
  3563. var instance = new globalErrors_1();
  3564. var originalInstall = instance.install;
  3565. if (originalInstall && !instance[symbol('install')]) {
  3566. instance[symbol('install')] = originalInstall;
  3567. instance.install = function () {
  3568. var originalHandlers = process.listeners('unhandledRejection');
  3569. var r = originalInstall.apply(this, arguments);
  3570. process.removeAllListeners('unhandledRejection');
  3571. if (originalHandlers) {
  3572. originalHandlers.forEach(function (h) { return process.on('unhandledRejection', h); });
  3573. }
  3574. return r;
  3575. };
  3576. }
  3577. return instance;
  3578. };
  3579. }
  3580. }
  3581. // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
  3582. var jasmineEnv = jasmine.getEnv();
  3583. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  3584. var originalJasmineFn = jasmineEnv[methodName];
  3585. jasmineEnv[methodName] = function (description, specDefinitions) {
  3586. return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
  3587. };
  3588. });
  3589. ['it', 'xit', 'fit'].forEach(function (methodName) {
  3590. var originalJasmineFn = jasmineEnv[methodName];
  3591. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  3592. jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
  3593. arguments[1] = wrapTestInZone(specDefinitions);
  3594. return originalJasmineFn.apply(this, arguments);
  3595. };
  3596. });
  3597. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  3598. var originalJasmineFn = jasmineEnv[methodName];
  3599. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  3600. jasmineEnv[methodName] = function (specDefinitions, timeout) {
  3601. arguments[0] = wrapTestInZone(specDefinitions);
  3602. return originalJasmineFn.apply(this, arguments);
  3603. };
  3604. });
  3605. if (!disablePatchingJasmineClock) {
  3606. // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
  3607. // they can work properly in FakeAsyncTest
  3608. var originalClockFn_1 = (jasmine[symbol('clock')] = jasmine['clock']);
  3609. jasmine['clock'] = function () {
  3610. var clock = originalClockFn_1.apply(this, arguments);
  3611. if (!clock[symbol('patched')]) {
  3612. clock[symbol('patched')] = symbol('patched');
  3613. var originalTick_1 = (clock[symbol('tick')] = clock.tick);
  3614. clock.tick = function () {
  3615. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3616. if (fakeAsyncZoneSpec) {
  3617. return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
  3618. }
  3619. return originalTick_1.apply(this, arguments);
  3620. };
  3621. var originalMockDate_1 = (clock[symbol('mockDate')] = clock.mockDate);
  3622. clock.mockDate = function () {
  3623. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3624. if (fakeAsyncZoneSpec) {
  3625. var dateTime = arguments.length > 0 ? arguments[0] : new Date();
  3626. return fakeAsyncZoneSpec.setCurrentRealTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
  3627. arguments);
  3628. }
  3629. return originalMockDate_1.apply(this, arguments);
  3630. };
  3631. // for auto go into fakeAsync feature, we need the flag to enable it
  3632. if (enableAutoFakeAsyncWhenClockPatched) {
  3633. ['install', 'uninstall'].forEach(function (methodName) {
  3634. var originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
  3635. clock[methodName] = function () {
  3636. var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  3637. if (FakeAsyncTestZoneSpec) {
  3638. jasmine[symbol('clockInstalled')] = 'install' === methodName;
  3639. return;
  3640. }
  3641. return originalClockFn.apply(this, arguments);
  3642. };
  3643. });
  3644. }
  3645. }
  3646. return clock;
  3647. };
  3648. }
  3649. /**
  3650. * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
  3651. * synchronous-only zone.
  3652. */
  3653. function wrapDescribeInZone(describeBody) {
  3654. return function () {
  3655. return syncZone.run(describeBody, this, arguments);
  3656. };
  3657. }
  3658. function runInTestZone(testBody, applyThis, queueRunner, done) {
  3659. var isClockInstalled = !!jasmine[symbol('clockInstalled')];
  3660. var testProxyZoneSpec = queueRunner.testProxyZoneSpec;
  3661. var testProxyZone = queueRunner.testProxyZone;
  3662. if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
  3663. // auto run a fakeAsync
  3664. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  3665. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  3666. testBody = fakeAsyncModule.fakeAsync(testBody);
  3667. }
  3668. }
  3669. if (done) {
  3670. return testProxyZone.run(testBody, applyThis, [done]);
  3671. }
  3672. else {
  3673. return testProxyZone.run(testBody, applyThis);
  3674. }
  3675. }
  3676. /**
  3677. * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
  3678. * execute in a ProxyZone zone.
  3679. * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
  3680. */
  3681. function wrapTestInZone(testBody) {
  3682. // The `done` callback is only passed through if the function expects at least one argument.
  3683. // Note we have to make a function with correct number of arguments, otherwise jasmine will
  3684. // think that all functions are sync or async.
  3685. return (testBody && (testBody.length ? function (done) {
  3686. return runInTestZone(testBody, this, this.queueRunner, done);
  3687. } : function () {
  3688. return runInTestZone(testBody, this, this.queueRunner);
  3689. }));
  3690. }
  3691. var QueueRunner = jasmine.QueueRunner;
  3692. jasmine.QueueRunner = (function (_super) {
  3693. __extends(ZoneQueueRunner, _super);
  3694. function ZoneQueueRunner(attrs) {
  3695. var _this = this;
  3696. attrs.onComplete = (function (fn) { return function () {
  3697. // All functions are done, clear the test zone.
  3698. _this.testProxyZone = null;
  3699. _this.testProxyZoneSpec = null;
  3700. ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
  3701. }; })(attrs.onComplete);
  3702. var nativeSetTimeout = _global['__zone_symbol__setTimeout'];
  3703. var nativeClearTimeout = _global['__zone_symbol__clearTimeout'];
  3704. if (nativeSetTimeout) {
  3705. // should run setTimeout inside jasmine outside of zone
  3706. attrs.timeout = {
  3707. setTimeout: nativeSetTimeout ? nativeSetTimeout : _global.setTimeout,
  3708. clearTimeout: nativeClearTimeout ? nativeClearTimeout : _global.clearTimeout
  3709. };
  3710. }
  3711. // create a userContext to hold the queueRunner itself
  3712. // so we can access the testProxy in it/xit/beforeEach ...
  3713. if (jasmine.UserContext) {
  3714. if (!attrs.userContext) {
  3715. attrs.userContext = new jasmine.UserContext();
  3716. }
  3717. attrs.userContext.queueRunner = this;
  3718. }
  3719. else {
  3720. if (!attrs.userContext) {
  3721. attrs.userContext = {};
  3722. }
  3723. attrs.userContext.queueRunner = this;
  3724. }
  3725. // patch attrs.onException
  3726. var onException = attrs.onException;
  3727. attrs.onException = function (error) {
  3728. if (error &&
  3729. error.message ===
  3730. 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
  3731. // jasmine timeout, we can make the error message more
  3732. // reasonable to tell what tasks are pending
  3733. var proxyZoneSpec = this && this.testProxyZoneSpec;
  3734. if (proxyZoneSpec) {
  3735. var pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
  3736. try {
  3737. // try catch here in case error.message is not writable
  3738. error.message += pendingTasksInfo;
  3739. }
  3740. catch (err) {
  3741. }
  3742. }
  3743. }
  3744. if (onException) {
  3745. onException.call(this, error);
  3746. }
  3747. };
  3748. _super.call(this, attrs);
  3749. }
  3750. ZoneQueueRunner.prototype.execute = function () {
  3751. var _this = this;
  3752. var zone = Zone.current;
  3753. var isChildOfAmbientZone = false;
  3754. while (zone) {
  3755. if (zone === ambientZone) {
  3756. isChildOfAmbientZone = true;
  3757. break;
  3758. }
  3759. zone = zone.parent;
  3760. }
  3761. if (!isChildOfAmbientZone)
  3762. throw new Error('Unexpected Zone: ' + Zone.current.name);
  3763. // This is the zone which will be used for running individual tests.
  3764. // It will be a proxy zone, so that the tests function can retroactively install
  3765. // different zones.
  3766. // Example:
  3767. // - In beforeEach() do childZone = Zone.current.fork(...);
  3768. // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
  3769. // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
  3770. // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
  3771. // fakeAsync behavior to the childZone.
  3772. this.testProxyZoneSpec = new ProxyZoneSpec();
  3773. this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
  3774. if (!Zone.currentTask) {
  3775. // if we are not running in a task then if someone would register a
  3776. // element.addEventListener and then calling element.click() the
  3777. // addEventListener callback would think that it is the top most task and would
  3778. // drain the microtask queue on element.click() which would be incorrect.
  3779. // For this reason we always force a task when running jasmine tests.
  3780. Zone.current.scheduleMicroTask('jasmine.execute().forceTask', function () { return QueueRunner.prototype.execute.call(_this); });
  3781. }
  3782. else {
  3783. _super.prototype.execute.call(this);
  3784. }
  3785. };
  3786. return ZoneQueueRunner;
  3787. })(QueueRunner);
  3788. })();
  3789. /**
  3790. * @license
  3791. * Copyright Google Inc. All Rights Reserved.
  3792. *
  3793. * Use of this source code is governed by an MIT-style license that can be
  3794. * found in the LICENSE file at https://angular.io/license
  3795. */
  3796. var _global$1 = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
  3797. var AsyncTestZoneSpec = /** @class */ (function () {
  3798. function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
  3799. this.finishCallback = finishCallback;
  3800. this.failCallback = failCallback;
  3801. this._pendingMicroTasks = false;
  3802. this._pendingMacroTasks = false;
  3803. this._alreadyErrored = false;
  3804. this._isSync = false;
  3805. this.runZone = Zone.current;
  3806. this.unresolvedChainedPromiseCount = 0;
  3807. this.supportWaitUnresolvedChainedPromise = false;
  3808. this.name = 'asyncTestZone for ' + namePrefix;
  3809. this.properties = { 'AsyncTestZoneSpec': this };
  3810. this.supportWaitUnresolvedChainedPromise =
  3811. _global$1[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  3812. }
  3813. AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
  3814. return this.unresolvedChainedPromiseCount > 0;
  3815. };
  3816. AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
  3817. var _this = this;
  3818. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  3819. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  3820. // We do this because we would like to catch unhandled rejected promises.
  3821. this.runZone.run(function () {
  3822. setTimeout(function () {
  3823. if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
  3824. _this.finishCallback();
  3825. }
  3826. }, 0);
  3827. });
  3828. }
  3829. };
  3830. AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
  3831. if (!this.supportWaitUnresolvedChainedPromise) {
  3832. return;
  3833. }
  3834. var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  3835. if (patchPromiseForTest) {
  3836. patchPromiseForTest();
  3837. }
  3838. };
  3839. AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
  3840. if (!this.supportWaitUnresolvedChainedPromise) {
  3841. return;
  3842. }
  3843. var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  3844. if (unPatchPromiseForTest) {
  3845. unPatchPromiseForTest();
  3846. }
  3847. };
  3848. AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3849. if (task.type !== 'eventTask') {
  3850. this._isSync = false;
  3851. }
  3852. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  3853. // check whether the promise is a chained promise
  3854. if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
  3855. // chained promise is being scheduled
  3856. this.unresolvedChainedPromiseCount--;
  3857. }
  3858. }
  3859. return delegate.scheduleTask(target, task);
  3860. };
  3861. AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
  3862. if (task.type !== 'eventTask') {
  3863. this._isSync = false;
  3864. }
  3865. return delegate.invokeTask(target, task, applyThis, applyArgs);
  3866. };
  3867. AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  3868. if (task.type !== 'eventTask') {
  3869. this._isSync = false;
  3870. }
  3871. return delegate.cancelTask(target, task);
  3872. };
  3873. // Note - we need to use onInvoke at the moment to call finish when a test is
  3874. // fully synchronous. TODO(juliemr): remove this when the logic for
  3875. // onHasTask changes and it calls whenever the task queues are dirty.
  3876. // updated by(JiaLiPassion), only call finish callback when no task
  3877. // was scheduled/invoked/canceled.
  3878. AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  3879. try {
  3880. this._isSync = true;
  3881. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  3882. }
  3883. finally {
  3884. var afterTaskCounts = parentZoneDelegate._taskCounts;
  3885. if (this._isSync) {
  3886. this._finishCallbackIfDone();
  3887. }
  3888. }
  3889. };
  3890. AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  3891. // Let the parent try to handle the error.
  3892. var result = parentZoneDelegate.handleError(targetZone, error);
  3893. if (result) {
  3894. this.failCallback(error);
  3895. this._alreadyErrored = true;
  3896. }
  3897. return false;
  3898. };
  3899. AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  3900. delegate.hasTask(target, hasTaskState);
  3901. if (hasTaskState.change == 'microTask') {
  3902. this._pendingMicroTasks = hasTaskState.microTask;
  3903. this._finishCallbackIfDone();
  3904. }
  3905. else if (hasTaskState.change == 'macroTask') {
  3906. this._pendingMacroTasks = hasTaskState.macroTask;
  3907. this._finishCallbackIfDone();
  3908. }
  3909. };
  3910. AsyncTestZoneSpec.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
  3911. return AsyncTestZoneSpec;
  3912. }());
  3913. // Export the class so that new instances can be created with proper
  3914. // constructor params.
  3915. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  3916. /**
  3917. * @license
  3918. * Copyright Google Inc. All Rights Reserved.
  3919. *
  3920. * Use of this source code is governed by an MIT-style license that can be
  3921. * found in the LICENSE file at https://angular.io/license
  3922. */
  3923. Zone.__load_patch('asynctest', function (global, Zone, api) {
  3924. /**
  3925. * Wraps a test function in an asynchronous test zone. The test will automatically
  3926. * complete when all asynchronous calls within this zone are done.
  3927. */
  3928. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  3929. // If we're running using the Jasmine test framework, adapt to call the 'done'
  3930. // function when asynchronous activity is finished.
  3931. if (global.jasmine) {
  3932. // Not using an arrow function to preserve context passed from call site
  3933. return function (done) {
  3934. if (!done) {
  3935. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  3936. // fake it here and assume sync.
  3937. done = function () { };
  3938. done.fail = function (e) {
  3939. throw e;
  3940. };
  3941. }
  3942. runInTestZone(fn, this, done, function (err) {
  3943. if (typeof err === 'string') {
  3944. return done.fail(new Error(err));
  3945. }
  3946. else {
  3947. done.fail(err);
  3948. }
  3949. });
  3950. };
  3951. }
  3952. // Otherwise, return a promise which will resolve when asynchronous activity
  3953. // is finished. This will be correctly consumed by the Mocha framework with
  3954. // it('...', async(myFn)); or can be used in a custom framework.
  3955. // Not using an arrow function to preserve context passed from call site
  3956. return function () {
  3957. var _this = this;
  3958. return new Promise(function (finishCallback, failCallback) {
  3959. runInTestZone(fn, _this, finishCallback, failCallback);
  3960. });
  3961. };
  3962. };
  3963. function runInTestZone(fn, context, finishCallback, failCallback) {
  3964. var currentZone = Zone.current;
  3965. var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  3966. if (AsyncTestZoneSpec === undefined) {
  3967. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  3968. 'Please make sure that your environment includes zone.js/dist/async-test.js');
  3969. }
  3970. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  3971. if (ProxyZoneSpec === undefined) {
  3972. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  3973. 'Please make sure that your environment includes zone.js/dist/proxy.js');
  3974. }
  3975. var proxyZoneSpec = ProxyZoneSpec.get();
  3976. ProxyZoneSpec.assertPresent();
  3977. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  3978. // If we do it in ProxyZone then we will get to infinite recursion.
  3979. var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  3980. var previousDelegate = proxyZoneSpec.getDelegate();
  3981. proxyZone.parent.run(function () {
  3982. var testZoneSpec = new AsyncTestZoneSpec(function () {
  3983. // Need to restore the original zone.
  3984. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3985. // Only reset the zone spec if it's
  3986. // sill this one. Otherwise, assume
  3987. // it's OK.
  3988. proxyZoneSpec.setDelegate(previousDelegate);
  3989. }
  3990. testZoneSpec.unPatchPromiseForTest();
  3991. currentZone.run(function () {
  3992. finishCallback();
  3993. });
  3994. }, function (error) {
  3995. // Need to restore the original zone.
  3996. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3997. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  3998. proxyZoneSpec.setDelegate(previousDelegate);
  3999. }
  4000. testZoneSpec.unPatchPromiseForTest();
  4001. currentZone.run(function () {
  4002. failCallback(error);
  4003. });
  4004. }, 'test');
  4005. proxyZoneSpec.setDelegate(testZoneSpec);
  4006. testZoneSpec.patchPromiseForTest();
  4007. });
  4008. return Zone.current.runGuarded(fn, context);
  4009. }
  4010. });
  4011. /**
  4012. * @license
  4013. * Copyright Google Inc. All Rights Reserved.
  4014. *
  4015. * Use of this source code is governed by an MIT-style license that can be
  4016. * found in the LICENSE file at https://angular.io/license
  4017. */
  4018. var __read = (undefined && undefined.__read) || function (o, n) {
  4019. var m = typeof Symbol === "function" && o[Symbol.iterator];
  4020. if (!m) return o;
  4021. var i = m.call(o), r, ar = [], e;
  4022. try {
  4023. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  4024. }
  4025. catch (error) { e = { error: error }; }
  4026. finally {
  4027. try {
  4028. if (r && !r.done && (m = i["return"])) m.call(i);
  4029. }
  4030. finally { if (e) throw e.error; }
  4031. }
  4032. return ar;
  4033. };
  4034. var __spread = (undefined && undefined.__spread) || function () {
  4035. for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
  4036. return ar;
  4037. };
  4038. (function (global) {
  4039. var OriginalDate = global.Date;
  4040. var FakeDate = /** @class */ (function () {
  4041. function FakeDate() {
  4042. if (arguments.length === 0) {
  4043. var d = new OriginalDate();
  4044. d.setTime(FakeDate.now());
  4045. return d;
  4046. }
  4047. else {
  4048. var args = Array.prototype.slice.call(arguments);
  4049. return new (OriginalDate.bind.apply(OriginalDate, __spread([void 0], args)))();
  4050. }
  4051. }
  4052. FakeDate.now = function () {
  4053. var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  4054. if (fakeAsyncTestZoneSpec) {
  4055. return fakeAsyncTestZoneSpec.getCurrentRealTime() + fakeAsyncTestZoneSpec.getCurrentTime();
  4056. }
  4057. return OriginalDate.now.apply(this, arguments);
  4058. };
  4059. return FakeDate;
  4060. }());
  4061. FakeDate.UTC = OriginalDate.UTC;
  4062. FakeDate.parse = OriginalDate.parse;
  4063. // keep a reference for zone patched timer function
  4064. var timers = {
  4065. setTimeout: global.setTimeout,
  4066. setInterval: global.setInterval,
  4067. clearTimeout: global.clearTimeout,
  4068. clearInterval: global.clearInterval
  4069. };
  4070. var Scheduler = /** @class */ (function () {
  4071. function Scheduler() {
  4072. // Scheduler queue with the tuple of end time and callback function - sorted by end time.
  4073. this._schedulerQueue = [];
  4074. // Current simulated time in millis.
  4075. this._currentTime = 0;
  4076. // Current real time in millis.
  4077. this._currentRealTime = OriginalDate.now();
  4078. }
  4079. Scheduler.prototype.getCurrentTime = function () {
  4080. return this._currentTime;
  4081. };
  4082. Scheduler.prototype.getCurrentRealTime = function () {
  4083. return this._currentRealTime;
  4084. };
  4085. Scheduler.prototype.setCurrentRealTime = function (realTime) {
  4086. this._currentRealTime = realTime;
  4087. };
  4088. Scheduler.prototype.scheduleFunction = function (cb, delay, args, isPeriodic, isRequestAnimationFrame, id) {
  4089. if (args === void 0) { args = []; }
  4090. if (isPeriodic === void 0) { isPeriodic = false; }
  4091. if (isRequestAnimationFrame === void 0) { isRequestAnimationFrame = false; }
  4092. if (id === void 0) { id = -1; }
  4093. var currentId = id < 0 ? Scheduler.nextId++ : id;
  4094. var endTime = this._currentTime + delay;
  4095. // Insert so that scheduler queue remains sorted by end time.
  4096. var newEntry = {
  4097. endTime: endTime,
  4098. id: currentId,
  4099. func: cb,
  4100. args: args,
  4101. delay: delay,
  4102. isPeriodic: isPeriodic,
  4103. isRequestAnimationFrame: isRequestAnimationFrame
  4104. };
  4105. var i = 0;
  4106. for (; i < this._schedulerQueue.length; i++) {
  4107. var currentEntry = this._schedulerQueue[i];
  4108. if (newEntry.endTime < currentEntry.endTime) {
  4109. break;
  4110. }
  4111. }
  4112. this._schedulerQueue.splice(i, 0, newEntry);
  4113. return currentId;
  4114. };
  4115. Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
  4116. for (var i = 0; i < this._schedulerQueue.length; i++) {
  4117. if (this._schedulerQueue[i].id == id) {
  4118. this._schedulerQueue.splice(i, 1);
  4119. break;
  4120. }
  4121. }
  4122. };
  4123. Scheduler.prototype.tick = function (millis, doTick) {
  4124. if (millis === void 0) { millis = 0; }
  4125. var finalTime = this._currentTime + millis;
  4126. var lastCurrentTime = 0;
  4127. if (this._schedulerQueue.length === 0 && doTick) {
  4128. doTick(millis);
  4129. return;
  4130. }
  4131. while (this._schedulerQueue.length > 0) {
  4132. var current = this._schedulerQueue[0];
  4133. if (finalTime < current.endTime) {
  4134. // Done processing the queue since it's sorted by endTime.
  4135. break;
  4136. }
  4137. else {
  4138. // Time to run scheduled function. Remove it from the head of queue.
  4139. var current_1 = this._schedulerQueue.shift();
  4140. lastCurrentTime = this._currentTime;
  4141. this._currentTime = current_1.endTime;
  4142. if (doTick) {
  4143. doTick(this._currentTime - lastCurrentTime);
  4144. }
  4145. var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTime] : current_1.args);
  4146. if (!retval) {
  4147. // Uncaught exception in the current scheduled function. Stop processing the queue.
  4148. break;
  4149. }
  4150. }
  4151. }
  4152. lastCurrentTime = this._currentTime;
  4153. this._currentTime = finalTime;
  4154. if (doTick) {
  4155. doTick(this._currentTime - lastCurrentTime);
  4156. }
  4157. };
  4158. Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
  4159. if (limit === void 0) { limit = 20; }
  4160. if (flushPeriodic === void 0) { flushPeriodic = false; }
  4161. if (flushPeriodic) {
  4162. return this.flushPeriodic(doTick);
  4163. }
  4164. else {
  4165. return this.flushNonPeriodic(limit, doTick);
  4166. }
  4167. };
  4168. Scheduler.prototype.flushPeriodic = function (doTick) {
  4169. if (this._schedulerQueue.length === 0) {
  4170. return 0;
  4171. }
  4172. // Find the last task currently queued in the scheduler queue and tick
  4173. // till that time.
  4174. var startTime = this._currentTime;
  4175. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  4176. this.tick(lastTask.endTime - startTime, doTick);
  4177. return this._currentTime - startTime;
  4178. };
  4179. Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
  4180. var startTime = this._currentTime;
  4181. var lastCurrentTime = 0;
  4182. var count = 0;
  4183. while (this._schedulerQueue.length > 0) {
  4184. count++;
  4185. if (count > limit) {
  4186. throw new Error('flush failed after reaching the limit of ' + limit +
  4187. ' tasks. Does your code use a polling timeout?');
  4188. }
  4189. // flush only non-periodic timers.
  4190. // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
  4191. if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
  4192. .length === 0) {
  4193. break;
  4194. }
  4195. var current = this._schedulerQueue.shift();
  4196. lastCurrentTime = this._currentTime;
  4197. this._currentTime = current.endTime;
  4198. if (doTick) {
  4199. // Update any secondary schedulers like Jasmine mock Date.
  4200. doTick(this._currentTime - lastCurrentTime);
  4201. }
  4202. var retval = current.func.apply(global, current.args);
  4203. if (!retval) {
  4204. // Uncaught exception in the current scheduled function. Stop processing the queue.
  4205. break;
  4206. }
  4207. }
  4208. return this._currentTime - startTime;
  4209. };
  4210. // Next scheduler id.
  4211. Scheduler.nextId = 1;
  4212. return Scheduler;
  4213. }());
  4214. var FakeAsyncTestZoneSpec = /** @class */ (function () {
  4215. function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
  4216. if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
  4217. this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
  4218. this.macroTaskOptions = macroTaskOptions;
  4219. this._scheduler = new Scheduler();
  4220. this._microtasks = [];
  4221. this._lastError = null;
  4222. this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
  4223. this.pendingPeriodicTimers = [];
  4224. this.pendingTimers = [];
  4225. this.patchDateLocked = false;
  4226. this.properties = { 'FakeAsyncTestZoneSpec': this };
  4227. this.name = 'fakeAsyncTestZone for ' + namePrefix;
  4228. // in case user can't access the construction of FakeAsyncTestSpec
  4229. // user can also define macroTaskOptions by define a global variable.
  4230. if (!this.macroTaskOptions) {
  4231. this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
  4232. }
  4233. }
  4234. FakeAsyncTestZoneSpec.assertInZone = function () {
  4235. if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
  4236. throw new Error('The code should be running in the fakeAsync zone to call this function');
  4237. }
  4238. };
  4239. FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
  4240. var _this = this;
  4241. return function () {
  4242. var args = [];
  4243. for (var _i = 0; _i < arguments.length; _i++) {
  4244. args[_i] = arguments[_i];
  4245. }
  4246. fn.apply(global, args);
  4247. if (_this._lastError === null) { // Success
  4248. if (completers.onSuccess != null) {
  4249. completers.onSuccess.apply(global);
  4250. }
  4251. // Flush microtasks only on success.
  4252. _this.flushMicrotasks();
  4253. }
  4254. else { // Failure
  4255. if (completers.onError != null) {
  4256. completers.onError.apply(global);
  4257. }
  4258. }
  4259. // Return true if there were no errors, false otherwise.
  4260. return _this._lastError === null;
  4261. };
  4262. };
  4263. FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
  4264. var index = timers.indexOf(id);
  4265. if (index > -1) {
  4266. timers.splice(index, 1);
  4267. }
  4268. };
  4269. FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
  4270. var _this = this;
  4271. return function () {
  4272. FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
  4273. };
  4274. };
  4275. FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
  4276. var _this = this;
  4277. return function () {
  4278. // Requeue the timer callback if it's not been canceled.
  4279. if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
  4280. _this._scheduler.scheduleFunction(fn, interval, args, true, false, id);
  4281. }
  4282. };
  4283. };
  4284. FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
  4285. var _this = this;
  4286. return function () {
  4287. FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
  4288. };
  4289. };
  4290. FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
  4291. if (isTimer === void 0) { isTimer = true; }
  4292. var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
  4293. // Queue the callback and dequeue the timer on success and error.
  4294. var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
  4295. var id = this._scheduler.scheduleFunction(cb, delay, args, false, !isTimer);
  4296. if (isTimer) {
  4297. this.pendingTimers.push(id);
  4298. }
  4299. return id;
  4300. };
  4301. FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
  4302. FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
  4303. this._scheduler.removeScheduledFunctionWithId(id);
  4304. };
  4305. FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
  4306. var id = Scheduler.nextId;
  4307. var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
  4308. var cb = this._fnAndFlush(fn, completers);
  4309. // Use the callback created above to requeue on success.
  4310. completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
  4311. // Queue the callback and dequeue the periodic timer only on error.
  4312. this._scheduler.scheduleFunction(cb, interval, args, true);
  4313. this.pendingPeriodicTimers.push(id);
  4314. return id;
  4315. };
  4316. FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
  4317. FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
  4318. this._scheduler.removeScheduledFunctionWithId(id);
  4319. };
  4320. FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
  4321. var error = this._lastError || this._uncaughtPromiseErrors[0];
  4322. this._uncaughtPromiseErrors.length = 0;
  4323. this._lastError = null;
  4324. throw error;
  4325. };
  4326. FakeAsyncTestZoneSpec.prototype.getCurrentTime = function () {
  4327. return this._scheduler.getCurrentTime();
  4328. };
  4329. FakeAsyncTestZoneSpec.prototype.getCurrentRealTime = function () {
  4330. return this._scheduler.getCurrentRealTime();
  4331. };
  4332. FakeAsyncTestZoneSpec.prototype.setCurrentRealTime = function (realTime) {
  4333. this._scheduler.setCurrentRealTime(realTime);
  4334. };
  4335. FakeAsyncTestZoneSpec.patchDate = function () {
  4336. if (!!global[Zone.__symbol__('disableDatePatching')]) {
  4337. // we don't want to patch global Date
  4338. // because in some case, global Date
  4339. // is already being patched, we need to provide
  4340. // an option to let user still use their
  4341. // own version of Date.
  4342. return;
  4343. }
  4344. if (global['Date'] === FakeDate) {
  4345. // already patched
  4346. return;
  4347. }
  4348. global['Date'] = FakeDate;
  4349. FakeDate.prototype = OriginalDate.prototype;
  4350. // try check and reset timers
  4351. // because jasmine.clock().install() may
  4352. // have replaced the global timer
  4353. FakeAsyncTestZoneSpec.checkTimerPatch();
  4354. };
  4355. FakeAsyncTestZoneSpec.resetDate = function () {
  4356. if (global['Date'] === FakeDate) {
  4357. global['Date'] = OriginalDate;
  4358. }
  4359. };
  4360. FakeAsyncTestZoneSpec.checkTimerPatch = function () {
  4361. if (global.setTimeout !== timers.setTimeout) {
  4362. global.setTimeout = timers.setTimeout;
  4363. global.clearTimeout = timers.clearTimeout;
  4364. }
  4365. if (global.setInterval !== timers.setInterval) {
  4366. global.setInterval = timers.setInterval;
  4367. global.clearInterval = timers.clearInterval;
  4368. }
  4369. };
  4370. FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
  4371. this.patchDateLocked = true;
  4372. FakeAsyncTestZoneSpec.patchDate();
  4373. };
  4374. FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
  4375. this.patchDateLocked = false;
  4376. FakeAsyncTestZoneSpec.resetDate();
  4377. };
  4378. FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick) {
  4379. if (millis === void 0) { millis = 0; }
  4380. FakeAsyncTestZoneSpec.assertInZone();
  4381. this.flushMicrotasks();
  4382. this._scheduler.tick(millis, doTick);
  4383. if (this._lastError !== null) {
  4384. this._resetLastErrorAndThrow();
  4385. }
  4386. };
  4387. FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
  4388. var _this = this;
  4389. FakeAsyncTestZoneSpec.assertInZone();
  4390. var flushErrors = function () {
  4391. if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
  4392. // If there is an error stop processing the microtask queue and rethrow the error.
  4393. _this._resetLastErrorAndThrow();
  4394. }
  4395. };
  4396. while (this._microtasks.length > 0) {
  4397. var microtask = this._microtasks.shift();
  4398. microtask.func.apply(microtask.target, microtask.args);
  4399. }
  4400. flushErrors();
  4401. };
  4402. FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
  4403. FakeAsyncTestZoneSpec.assertInZone();
  4404. this.flushMicrotasks();
  4405. var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
  4406. if (this._lastError !== null) {
  4407. this._resetLastErrorAndThrow();
  4408. }
  4409. return elapsed;
  4410. };
  4411. FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  4412. switch (task.type) {
  4413. case 'microTask':
  4414. var args = task.data && task.data.args;
  4415. // should pass additional arguments to callback if have any
  4416. // currently we know process.nextTick will have such additional
  4417. // arguments
  4418. var additionalArgs = void 0;
  4419. if (args) {
  4420. var callbackIndex = task.data.cbIdx;
  4421. if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
  4422. additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
  4423. }
  4424. }
  4425. this._microtasks.push({
  4426. func: task.invoke,
  4427. args: additionalArgs,
  4428. target: task.data && task.data.target
  4429. });
  4430. break;
  4431. case 'macroTask':
  4432. switch (task.source) {
  4433. case 'setTimeout':
  4434. task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  4435. break;
  4436. case 'setImmediate':
  4437. task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
  4438. break;
  4439. case 'setInterval':
  4440. task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  4441. break;
  4442. case 'XMLHttpRequest.send':
  4443. throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
  4444. task.data['url']);
  4445. case 'requestAnimationFrame':
  4446. case 'webkitRequestAnimationFrame':
  4447. case 'mozRequestAnimationFrame':
  4448. // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
  4449. // (60 frames per second)
  4450. task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
  4451. break;
  4452. default:
  4453. // user can define which macroTask they want to support by passing
  4454. // macroTaskOptions
  4455. var macroTaskOption = this.findMacroTaskOption(task);
  4456. if (macroTaskOption) {
  4457. var args_1 = task.data && task.data['args'];
  4458. var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
  4459. var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
  4460. if (!!macroTaskOption.isPeriodic) {
  4461. // periodic macroTask, use setInterval to simulate
  4462. task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
  4463. task.data.isPeriodic = true;
  4464. }
  4465. else {
  4466. // not periodic, use setTimeout to simulate
  4467. task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
  4468. }
  4469. break;
  4470. }
  4471. throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
  4472. }
  4473. break;
  4474. case 'eventTask':
  4475. task = delegate.scheduleTask(target, task);
  4476. break;
  4477. }
  4478. return task;
  4479. };
  4480. FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  4481. switch (task.source) {
  4482. case 'setTimeout':
  4483. case 'requestAnimationFrame':
  4484. case 'webkitRequestAnimationFrame':
  4485. case 'mozRequestAnimationFrame':
  4486. return this._clearTimeout(task.data['handleId']);
  4487. case 'setInterval':
  4488. return this._clearInterval(task.data['handleId']);
  4489. default:
  4490. // user can define which macroTask they want to support by passing
  4491. // macroTaskOptions
  4492. var macroTaskOption = this.findMacroTaskOption(task);
  4493. if (macroTaskOption) {
  4494. var handleId = task.data['handleId'];
  4495. return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
  4496. this._clearTimeout(handleId);
  4497. }
  4498. return delegate.cancelTask(target, task);
  4499. }
  4500. };
  4501. FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
  4502. try {
  4503. FakeAsyncTestZoneSpec.patchDate();
  4504. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  4505. }
  4506. finally {
  4507. if (!this.patchDateLocked) {
  4508. FakeAsyncTestZoneSpec.resetDate();
  4509. }
  4510. }
  4511. };
  4512. FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
  4513. if (!this.macroTaskOptions) {
  4514. return null;
  4515. }
  4516. for (var i = 0; i < this.macroTaskOptions.length; i++) {
  4517. var macroTaskOption = this.macroTaskOptions[i];
  4518. if (macroTaskOption.source === task.source) {
  4519. return macroTaskOption;
  4520. }
  4521. }
  4522. return null;
  4523. };
  4524. FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  4525. this._lastError = error;
  4526. return false; // Don't propagate error to parent zone.
  4527. };
  4528. return FakeAsyncTestZoneSpec;
  4529. }());
  4530. // Export the class so that new instances can be created with proper
  4531. // constructor params.
  4532. Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
  4533. })(typeof window === 'object' && window || typeof self === 'object' && self || global);
  4534. /**
  4535. * @license
  4536. * Copyright Google Inc. All Rights Reserved.
  4537. *
  4538. * Use of this source code is governed by an MIT-style license that can be
  4539. * found in the LICENSE file at https://angular.io/license
  4540. */
  4541. Zone.__load_patch('fakeasync', function (global, Zone, api) {
  4542. var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
  4543. var ProxyZoneSpec = Zone && Zone['ProxyZoneSpec'];
  4544. var _fakeAsyncTestZoneSpec = null;
  4545. /**
  4546. * Clears out the shared fake async zone for a test.
  4547. * To be called in a global `beforeEach`.
  4548. *
  4549. * @experimental
  4550. */
  4551. function resetFakeAsyncZone() {
  4552. if (_fakeAsyncTestZoneSpec) {
  4553. _fakeAsyncTestZoneSpec.unlockDatePatch();
  4554. }
  4555. _fakeAsyncTestZoneSpec = null;
  4556. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  4557. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
  4558. }
  4559. /**
  4560. * Wraps a function to be executed in the fakeAsync zone:
  4561. * - microtasks are manually executed by calling `flushMicrotasks()`,
  4562. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  4563. *
  4564. * If there are any pending timers at the end of the function, an exception will be thrown.
  4565. *
  4566. * Can be used to wrap inject() calls.
  4567. *
  4568. * ## Example
  4569. *
  4570. * {@example core/testing/ts/fake_async.ts region='basic'}
  4571. *
  4572. * @param fn
  4573. * @returns The function wrapped to be executed in the fakeAsync zone
  4574. *
  4575. * @experimental
  4576. */
  4577. function fakeAsync(fn) {
  4578. // Not using an arrow function to preserve context passed from call site
  4579. return function () {
  4580. var args = [];
  4581. for (var _i = 0; _i < arguments.length; _i++) {
  4582. args[_i] = arguments[_i];
  4583. }
  4584. var proxyZoneSpec = ProxyZoneSpec.assertPresent();
  4585. if (Zone.current.get('FakeAsyncTestZoneSpec')) {
  4586. throw new Error('fakeAsync() calls can not be nested');
  4587. }
  4588. try {
  4589. // in case jasmine.clock init a fakeAsyncTestZoneSpec
  4590. if (!_fakeAsyncTestZoneSpec) {
  4591. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  4592. throw new Error('fakeAsync() calls can not be nested');
  4593. }
  4594. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  4595. }
  4596. var res = void 0;
  4597. var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  4598. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  4599. _fakeAsyncTestZoneSpec.lockDatePatch();
  4600. try {
  4601. res = fn.apply(this, args);
  4602. flushMicrotasks();
  4603. }
  4604. finally {
  4605. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  4606. }
  4607. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  4608. throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
  4609. "periodic timer(s) still in the queue.");
  4610. }
  4611. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  4612. throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
  4613. }
  4614. return res;
  4615. }
  4616. finally {
  4617. resetFakeAsyncZone();
  4618. }
  4619. };
  4620. }
  4621. function _getFakeAsyncZoneSpec() {
  4622. if (_fakeAsyncTestZoneSpec == null) {
  4623. _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  4624. if (_fakeAsyncTestZoneSpec == null) {
  4625. throw new Error('The code should be running in the fakeAsync zone to call this function');
  4626. }
  4627. }
  4628. return _fakeAsyncTestZoneSpec;
  4629. }
  4630. /**
  4631. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  4632. *
  4633. * The microtasks queue is drained at the very start of this function and after any timer callback
  4634. * has been executed.
  4635. *
  4636. * ## Example
  4637. *
  4638. * {@example core/testing/ts/fake_async.ts region='basic'}
  4639. *
  4640. * @experimental
  4641. */
  4642. function tick(millis) {
  4643. if (millis === void 0) { millis = 0; }
  4644. _getFakeAsyncZoneSpec().tick(millis);
  4645. }
  4646. /**
  4647. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  4648. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  4649. * of time that would have been elapsed.
  4650. *
  4651. * @param maxTurns
  4652. * @returns The simulated time elapsed, in millis.
  4653. *
  4654. * @experimental
  4655. */
  4656. function flush(maxTurns) {
  4657. return _getFakeAsyncZoneSpec().flush(maxTurns);
  4658. }
  4659. /**
  4660. * Discard all remaining periodic tasks.
  4661. *
  4662. * @experimental
  4663. */
  4664. function discardPeriodicTasks() {
  4665. var zoneSpec = _getFakeAsyncZoneSpec();
  4666. var pendingTimers = zoneSpec.pendingPeriodicTimers;
  4667. zoneSpec.pendingPeriodicTimers.length = 0;
  4668. }
  4669. /**
  4670. * Flush any pending microtasks.
  4671. *
  4672. * @experimental
  4673. */
  4674. function flushMicrotasks() {
  4675. _getFakeAsyncZoneSpec().flushMicrotasks();
  4676. }
  4677. Zone[api.symbol('fakeAsyncTest')] =
  4678. { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
  4679. });
  4680. /**
  4681. * @license
  4682. * Copyright Google Inc. All Rights Reserved.
  4683. *
  4684. * Use of this source code is governed by an MIT-style license that can be
  4685. * found in the LICENSE file at https://angular.io/license
  4686. */
  4687. /**
  4688. * Promise for async/fakeAsync zoneSpec test
  4689. * can support async operation which not supported by zone.js
  4690. * such as
  4691. * it ('test jsonp in AsyncZone', async() => {
  4692. * new Promise(res => {
  4693. * jsonp(url, (data) => {
  4694. * // success callback
  4695. * res(data);
  4696. * });
  4697. * }).then((jsonpResult) => {
  4698. * // get jsonp result.
  4699. *
  4700. * // user will expect AsyncZoneSpec wait for
  4701. * // then, but because jsonp is not zone aware
  4702. * // AsyncZone will finish before then is called.
  4703. * });
  4704. * });
  4705. */
  4706. Zone.__load_patch('promisefortest', function (global, Zone, api) {
  4707. var symbolState = api.symbol('state');
  4708. var UNRESOLVED = null;
  4709. var symbolParentUnresolved = api.symbol('parentUnresolved');
  4710. // patch Promise.prototype.then to keep an internal
  4711. // number for tracking unresolved chained promise
  4712. // we will decrease this number when the parent promise
  4713. // being resolved/rejected and chained promise was
  4714. // scheduled as a microTask.
  4715. // so we can know such kind of chained promise still
  4716. // not resolved in AsyncTestZone
  4717. Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
  4718. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4719. if (oriThen) {
  4720. return;
  4721. }
  4722. oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
  4723. Promise.prototype.then = function () {
  4724. var chained = oriThen.apply(this, arguments);
  4725. if (this[symbolState] === UNRESOLVED) {
  4726. // parent promise is unresolved.
  4727. var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
  4728. if (asyncTestZoneSpec) {
  4729. asyncTestZoneSpec.unresolvedChainedPromiseCount++;
  4730. chained[symbolParentUnresolved] = true;
  4731. }
  4732. }
  4733. return chained;
  4734. };
  4735. };
  4736. Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
  4737. // restore origin then
  4738. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4739. if (oriThen) {
  4740. Promise.prototype.then = oriThen;
  4741. Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
  4742. }
  4743. };
  4744. });
  4745. /**
  4746. * @license
  4747. * Copyright Google Inc. All Rights Reserved.
  4748. *
  4749. * Use of this source code is governed by an MIT-style license that can be
  4750. * found in the LICENSE file at https://angular.io/license
  4751. */
  4752. // load test related files into bundle in correct order
  4753. /**
  4754. * @license
  4755. * Copyright Google Inc. All Rights Reserved.
  4756. *
  4757. * Use of this source code is governed by an MIT-style license that can be
  4758. * found in the LICENSE file at https://angular.io/license
  4759. */
  4760. // load test related files into bundle
  4761. })));