zone-evergreen-testing-bundle.js 210 KB

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