zone-testing-node-bundle.js 196 KB

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