zone-testing-node-bundle.js 178 KB

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