a zip code crypto-currency system good for red ONLY

zone-testing-node-bundle.js 164KB

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