polyfills-es2015.js 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257
  1. (window["webpackJsonp"] = window["webpackJsonp"] || []).push([["polyfills"],{
  2. /***/ 2:
  3. /*!********************************!*\
  4. !*** multi ./src/polyfills.ts ***!
  5. \********************************/
  6. /*! no static exports found */
  7. /***/ (function(module, exports, __webpack_require__) {
  8. module.exports = __webpack_require__(/*! /Users/federicaspinelli/TEAMOVI/evt-angular-ovi/src/polyfills.ts */"hN/g");
  9. /***/ }),
  10. /***/ "N/DB":
  11. /*!*********************************************************!*\
  12. !*** ./node_modules/@angular/localize/fesm2015/init.js ***!
  13. \*********************************************************/
  14. /*! no static exports found */
  15. /***/ (function(module, exports) {
  16. /**
  17. * @license Angular v11.0.4
  18. * (c) 2010-2020 Google LLC. https://angular.io/
  19. * License: MIT
  20. */
  21. /**
  22. * @license
  23. * Copyright Google LLC All Rights Reserved.
  24. *
  25. * Use of this source code is governed by an MIT-style license that can be
  26. * found in the LICENSE file at https://angular.io/license
  27. */
  28. const __globalThis = typeof globalThis !== 'undefined' && globalThis;
  29. const __window = typeof window !== 'undefined' && window;
  30. const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  31. self instanceof WorkerGlobalScope && self;
  32. const __global = typeof global !== 'undefined' && global;
  33. // Always use __globalThis if available; this is the spec-defined global variable across all
  34. // environments.
  35. // Then fallback to __global first; in Node tests both __global and __window may be defined.
  36. const _global = __globalThis || __global || __window || __self;
  37. /**
  38. * @license
  39. * Copyright Google LLC All Rights Reserved.
  40. *
  41. * Use of this source code is governed by an MIT-style license that can be
  42. * found in the LICENSE file at https://angular.io/license
  43. */
  44. /**
  45. * Tag a template literal string for localization.
  46. *
  47. * For example:
  48. *
  49. * ```ts
  50. * $localize `some string to localize`
  51. * ```
  52. *
  53. * **Providing meaning, description and id**
  54. *
  55. * You can optionally specify one or more of `meaning`, `description` and `id` for a localized
  56. * string by pre-pending it with a colon delimited block of the form:
  57. *
  58. * ```ts
  59. * $localize`:meaning|description@@id:source message text`;
  60. *
  61. * $localize`:meaning|:source message text`;
  62. * $localize`:description:source message text`;
  63. * $localize`:@@id:source message text`;
  64. * ```
  65. *
  66. * This format is the same as that used for `i18n` markers in Angular templates. See the
  67. * [Angular 18n guide](guide/i18n#template-translations).
  68. *
  69. * **Naming placeholders**
  70. *
  71. * If the template literal string contains expressions, then the expressions will be automatically
  72. * associated with placeholder names for you.
  73. *
  74. * For example:
  75. *
  76. * ```ts
  77. * $localize `Hi ${name}! There are ${items.length} items.`;
  78. * ```
  79. *
  80. * will generate a message-source of `Hi {$PH}! There are {$PH_1} items`.
  81. *
  82. * The recommended practice is to name the placeholder associated with each expression though.
  83. *
  84. * Do this by providing the placeholder name wrapped in `:` characters directly after the
  85. * expression. These placeholder names are stripped out of the rendered localized string.
  86. *
  87. * For example, to name the `items.length` expression placeholder `itemCount` you write:
  88. *
  89. * ```ts
  90. * $localize `There are ${items.length}:itemCount: items`;
  91. * ```
  92. *
  93. * **Escaping colon markers**
  94. *
  95. * If you need to use a `:` character directly at the start of a tagged string that has no
  96. * metadata block, or directly after a substitution expression that has no name you must escape
  97. * the `:` by preceding it with a backslash:
  98. *
  99. * For example:
  100. *
  101. * ```ts
  102. * // message has a metadata block so no need to escape colon
  103. * $localize `:some description::this message starts with a colon (:)`;
  104. * // no metadata block so the colon must be escaped
  105. * $localize `\:this message starts with a colon (:)`;
  106. * ```
  107. *
  108. * ```ts
  109. * // named substitution so no need to escape colon
  110. * $localize `${label}:label:: ${}`
  111. * // anonymous substitution so colon must be escaped
  112. * $localize `${label}\: ${}`
  113. * ```
  114. *
  115. * **Processing localized strings:**
  116. *
  117. * There are three scenarios:
  118. *
  119. * * **compile-time inlining**: the `$localize` tag is transformed at compile time by a
  120. * transpiler, removing the tag and replacing the template literal string with a translated
  121. * literal string from a collection of translations provided to the transpilation tool.
  122. *
  123. * * **run-time evaluation**: the `$localize` tag is a run-time function that replaces and
  124. * reorders the parts (static strings and expressions) of the template literal string with strings
  125. * from a collection of translations loaded at run-time.
  126. *
  127. * * **pass-through evaluation**: the `$localize` tag is a run-time function that simply evaluates
  128. * the original template literal string without applying any translations to the parts. This
  129. * version is used during development or where there is no need to translate the localized
  130. * template literals.
  131. * @param messageParts a collection of the static parts of the template string.
  132. * @param expressions a collection of the values of each placeholder in the template string.
  133. * @returns the translated string, with the `messageParts` and `expressions` interleaved together.
  134. */
  135. const $localize = function (messageParts, ...expressions) {
  136. if ($localize.translate) {
  137. // Don't use array expansion here to avoid the compiler adding `__read()` helper unnecessarily.
  138. const translation = $localize.translate(messageParts, expressions);
  139. messageParts = translation[0];
  140. expressions = translation[1];
  141. }
  142. let message = stripBlock(messageParts[0], messageParts.raw[0]);
  143. for (let i = 1; i < messageParts.length; i++) {
  144. message += expressions[i - 1] + stripBlock(messageParts[i], messageParts.raw[i]);
  145. }
  146. return message;
  147. };
  148. const BLOCK_MARKER = ':';
  149. /**
  150. * Strip a delimited "block" from the start of the `messagePart`, if it is found.
  151. *
  152. * If a marker character (:) actually appears in the content at the start of a tagged string or
  153. * after a substitution expression, where a block has not been provided the character must be
  154. * escaped with a backslash, `\:`. This function checks for this by looking at the `raw`
  155. * messagePart, which should still contain the backslash.
  156. *
  157. * @param messagePart The cooked message part to process.
  158. * @param rawMessagePart The raw message part to check.
  159. * @returns the message part with the placeholder name stripped, if found.
  160. * @throws an error if the block is unterminated
  161. */
  162. function stripBlock(messagePart, rawMessagePart) {
  163. return rawMessagePart.charAt(0) === BLOCK_MARKER ?
  164. messagePart.substring(findEndOfBlock(messagePart, rawMessagePart) + 1) :
  165. messagePart;
  166. }
  167. /**
  168. * Find the end of a "marked block" indicated by the first non-escaped colon.
  169. *
  170. * @param cooked The cooked string (where escaped chars have been processed)
  171. * @param raw The raw string (where escape sequences are still in place)
  172. *
  173. * @returns the index of the end of block marker
  174. * @throws an error if the block is unterminated
  175. */
  176. function findEndOfBlock(cooked, raw) {
  177. /***********************************************************************************************
  178. * This function is repeated in `src/utils/messages.ts` and the two should be kept in sync.
  179. * The reason is that this file is marked as having side-effects, and if we import `messages.ts`
  180. * into it, the whole of `src/utils` will be included in this bundle and none of the functions
  181. * will be tree shaken.
  182. ***********************************************************************************************/
  183. for (let cookedIndex = 1, rawIndex = 1; cookedIndex < cooked.length; cookedIndex++, rawIndex++) {
  184. if (raw[rawIndex] === '\\') {
  185. rawIndex++;
  186. }
  187. else if (cooked[cookedIndex] === BLOCK_MARKER) {
  188. return cookedIndex;
  189. }
  190. }
  191. throw new Error(`Unterminated $localize metadata block in "${raw}".`);
  192. }
  193. /**
  194. * @license
  195. * Copyright Google LLC All Rights Reserved.
  196. *
  197. * Use of this source code is governed by an MIT-style license that can be
  198. * found in the LICENSE file at https://angular.io/license
  199. */
  200. /**
  201. * @license
  202. * Copyright Google LLC All Rights Reserved.
  203. *
  204. * Use of this source code is governed by an MIT-style license that can be
  205. * found in the LICENSE file at https://angular.io/license
  206. */
  207. // Attach $localize to the global context, as a side-effect of this module.
  208. _global.$localize = $localize;
  209. //# sourceMappingURL=init.js.map
  210. /***/ }),
  211. /***/ "hN/g":
  212. /*!**************************!*\
  213. !*** ./src/polyfills.ts ***!
  214. \**************************/
  215. /*! no exports provided */
  216. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  217. "use strict";
  218. __webpack_require__.r(__webpack_exports__);
  219. /* harmony import */ var _angular_localize_init__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/localize/init */ "N/DB");
  220. /* harmony import */ var _angular_localize_init__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_angular_localize_init__WEBPACK_IMPORTED_MODULE_0__);
  221. /* harmony import */ var zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! zone.js/dist/zone */ "pDpN");
  222. /* harmony import */ var zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_1__);
  223. /***************************************************************************************************
  224. * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
  225. */
  226. /**
  227. * This file includes polyfills needed by Angular and is loaded before the app.
  228. * You can add your own extra polyfills to this file.
  229. *
  230. * This file is divided into 2 sections:
  231. * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
  232. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
  233. * file.
  234. *
  235. * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
  236. * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
  237. * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
  238. *
  239. * Learn more in https://angular.io/guide/browser-support
  240. */
  241. /***************************************************************************************************
  242. * BROWSER POLYFILLS
  243. */
  244. /** IE10 and IE11 requires the following for NgClass support on SVG elements */
  245. // import 'classlist.js'; // Run `npm install --save classlist.js`.
  246. /**
  247. * Web Animations `@angular/platform-browser/animations`
  248. * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
  249. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
  250. */
  251. // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
  252. /**
  253. * By default, zone.js will patch all possible macroTask and DomEvents
  254. * user can disable parts of macroTask/DomEvents patch by setting following flags
  255. * because those flags need to be set before `zone.js` being loaded, and webpack
  256. * will put import in the top of bundle, so user need to create a separate file
  257. * in this directory (for example: zone-flags.ts), and put the following flags
  258. * into that file, and then add the following code before importing zone.js.
  259. * import './zone-flags.ts';
  260. *
  261. * The flags allowed in zone-flags.ts are listed here.
  262. *
  263. * The following flags will work for all browsers.
  264. *
  265. * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
  266. * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
  267. * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
  268. *
  269. * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
  270. * with the following flag, it will bypass `zone.js` patch for IE/Edge
  271. *
  272. * (window as any).__Zone_enable_cross_context_check = true;
  273. *
  274. */
  275. /***************************************************************************************************
  276. * Zone JS is required by default for Angular itself.
  277. */
  278. // Included with Angular CLI.
  279. /***************************************************************************************************
  280. * APPLICATION IMPORTS
  281. */
  282. /***/ }),
  283. /***/ "pDpN":
  284. /*!*****************************************************!*\
  285. !*** ./node_modules/zone.js/dist/zone-evergreen.js ***!
  286. \*****************************************************/
  287. /*! no static exports found */
  288. /***/ (function(module, exports, __webpack_require__) {
  289. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
  290. * @license Angular v9.1.0-next.4+61.sha-e552591.with-local-changes
  291. * (c) 2010-2020 Google LLC. https://angular.io/
  292. * License: MIT
  293. */
  294. (function (factory) {
  295. true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  296. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  297. (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
  298. __WEBPACK_AMD_DEFINE_FACTORY__),
  299. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) :
  300. undefined;
  301. }((function () { 'use strict';
  302. /**
  303. * @license
  304. * Copyright Google Inc. All Rights Reserved.
  305. *
  306. * Use of this source code is governed by an MIT-style license that can be
  307. * found in the LICENSE file at https://angular.io/license
  308. */
  309. const Zone$1 = (function (global) {
  310. const performance = global['performance'];
  311. function mark(name) { performance && performance['mark'] && performance['mark'](name); }
  312. function performanceMeasure(name, label) {
  313. performance && performance['measure'] && performance['measure'](name, label);
  314. }
  315. mark('Zone');
  316. // Initialize before it's accessed below.
  317. // __Zone_symbol_prefix global can be used to override the default zone
  318. // symbol prefix with a custom one if needed.
  319. const symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
  320. function __symbol__(name) { return symbolPrefix + name; }
  321. const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  322. if (global['Zone']) {
  323. // if global['Zone'] already exists (maybe zone.js was already loaded or
  324. // some other lib also registered a global object named Zone), we may need
  325. // to throw an error, but sometimes user may not want this error.
  326. // For example,
  327. // we have two web pages, page1 includes zone.js, page2 doesn't.
  328. // and the 1st time user load page1 and page2, everything work fine,
  329. // but when user load page2 again, error occurs because global['Zone'] already exists.
  330. // so we add a flag to let user choose whether to throw this error or not.
  331. // By default, if existing Zone is from zone.js, we will not throw the error.
  332. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  333. throw new Error('Zone already loaded.');
  334. }
  335. else {
  336. return global['Zone'];
  337. }
  338. }
  339. class Zone {
  340. constructor(parent, zoneSpec) {
  341. this._parent = parent;
  342. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  343. this._properties = zoneSpec && zoneSpec.properties || {};
  344. this._zoneDelegate =
  345. new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  346. }
  347. static assertZonePatched() {
  348. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  349. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  350. 'has been overwritten.\n' +
  351. 'Most likely cause is that a Promise polyfill has been loaded ' +
  352. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  353. 'If you must load one, do so before loading zone.js.)');
  354. }
  355. }
  356. static get root() {
  357. let zone = Zone.current;
  358. while (zone.parent) {
  359. zone = zone.parent;
  360. }
  361. return zone;
  362. }
  363. static get current() { return _currentZoneFrame.zone; }
  364. static get currentTask() { return _currentTask; }
  365. // tslint:disable-next-line:require-internal-with-underscore
  366. static __load_patch(name, fn) {
  367. if (patches.hasOwnProperty(name)) {
  368. if (checkDuplicate) {
  369. throw Error('Already loaded patch: ' + name);
  370. }
  371. }
  372. else if (!global['__Zone_disable_' + name]) {
  373. const perfName = 'Zone:' + name;
  374. mark(perfName);
  375. patches[name] = fn(global, Zone, _api);
  376. performanceMeasure(perfName, perfName);
  377. }
  378. }
  379. get parent() { return this._parent; }
  380. get name() { return this._name; }
  381. get(key) {
  382. const zone = this.getZoneWith(key);
  383. if (zone)
  384. return zone._properties[key];
  385. }
  386. getZoneWith(key) {
  387. let current = this;
  388. while (current) {
  389. if (current._properties.hasOwnProperty(key)) {
  390. return current;
  391. }
  392. current = current._parent;
  393. }
  394. return null;
  395. }
  396. fork(zoneSpec) {
  397. if (!zoneSpec)
  398. throw new Error('ZoneSpec required!');
  399. return this._zoneDelegate.fork(this, zoneSpec);
  400. }
  401. wrap(callback, source) {
  402. if (typeof callback !== 'function') {
  403. throw new Error('Expecting function got: ' + callback);
  404. }
  405. const _callback = this._zoneDelegate.intercept(this, callback, source);
  406. const zone = this;
  407. return function () {
  408. return zone.runGuarded(_callback, this, arguments, source);
  409. };
  410. }
  411. run(callback, applyThis, applyArgs, source) {
  412. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  413. try {
  414. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  415. }
  416. finally {
  417. _currentZoneFrame = _currentZoneFrame.parent;
  418. }
  419. }
  420. runGuarded(callback, applyThis = null, applyArgs, source) {
  421. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  422. try {
  423. try {
  424. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  425. }
  426. catch (error) {
  427. if (this._zoneDelegate.handleError(this, error)) {
  428. throw error;
  429. }
  430. }
  431. }
  432. finally {
  433. _currentZoneFrame = _currentZoneFrame.parent;
  434. }
  435. }
  436. runTask(task, applyThis, applyArgs) {
  437. if (task.zone != this) {
  438. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  439. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  440. }
  441. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  442. // will run in notScheduled(canceled) state, we should not try to
  443. // run such kind of task but just return
  444. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  445. return;
  446. }
  447. const reEntryGuard = task.state != running;
  448. reEntryGuard && task._transitionTo(running, scheduled);
  449. task.runCount++;
  450. const previousTask = _currentTask;
  451. _currentTask = task;
  452. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  453. try {
  454. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  455. task.cancelFn = undefined;
  456. }
  457. try {
  458. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  459. }
  460. catch (error) {
  461. if (this._zoneDelegate.handleError(this, error)) {
  462. throw error;
  463. }
  464. }
  465. }
  466. finally {
  467. // if the task's state is notScheduled or unknown, then it has already been cancelled
  468. // we should not reset the state to scheduled
  469. if (task.state !== notScheduled && task.state !== unknown) {
  470. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  471. reEntryGuard && task._transitionTo(scheduled, running);
  472. }
  473. else {
  474. task.runCount = 0;
  475. this._updateTaskCount(task, -1);
  476. reEntryGuard &&
  477. task._transitionTo(notScheduled, running, notScheduled);
  478. }
  479. }
  480. _currentZoneFrame = _currentZoneFrame.parent;
  481. _currentTask = previousTask;
  482. }
  483. }
  484. scheduleTask(task) {
  485. if (task.zone && task.zone !== this) {
  486. // check if the task was rescheduled, the newZone
  487. // should not be the children of the original zone
  488. let newZone = this;
  489. while (newZone) {
  490. if (newZone === task.zone) {
  491. throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`);
  492. }
  493. newZone = newZone.parent;
  494. }
  495. }
  496. task._transitionTo(scheduling, notScheduled);
  497. const zoneDelegates = [];
  498. task._zoneDelegates = zoneDelegates;
  499. task._zone = this;
  500. try {
  501. task = this._zoneDelegate.scheduleTask(this, task);
  502. }
  503. catch (err) {
  504. // should set task's state to unknown when scheduleTask throw error
  505. // because the err may from reschedule, so the fromState maybe notScheduled
  506. task._transitionTo(unknown, scheduling, notScheduled);
  507. // TODO: @JiaLiPassion, should we check the result from handleError?
  508. this._zoneDelegate.handleError(this, err);
  509. throw err;
  510. }
  511. if (task._zoneDelegates === zoneDelegates) {
  512. // we have to check because internally the delegate can reschedule the task.
  513. this._updateTaskCount(task, 1);
  514. }
  515. if (task.state == scheduling) {
  516. task._transitionTo(scheduled, scheduling);
  517. }
  518. return task;
  519. }
  520. scheduleMicroTask(source, callback, data, customSchedule) {
  521. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  522. }
  523. scheduleMacroTask(source, callback, data, customSchedule, customCancel) {
  524. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  525. }
  526. scheduleEventTask(source, callback, data, customSchedule, customCancel) {
  527. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  528. }
  529. cancelTask(task) {
  530. if (task.zone != this)
  531. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  532. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  533. task._transitionTo(canceling, scheduled, running);
  534. try {
  535. this._zoneDelegate.cancelTask(this, task);
  536. }
  537. catch (err) {
  538. // if error occurs when cancelTask, transit the state to unknown
  539. task._transitionTo(unknown, canceling);
  540. this._zoneDelegate.handleError(this, err);
  541. throw err;
  542. }
  543. this._updateTaskCount(task, -1);
  544. task._transitionTo(notScheduled, canceling);
  545. task.runCount = 0;
  546. return task;
  547. }
  548. _updateTaskCount(task, count) {
  549. const zoneDelegates = task._zoneDelegates;
  550. if (count == -1) {
  551. task._zoneDelegates = null;
  552. }
  553. for (let i = 0; i < zoneDelegates.length; i++) {
  554. zoneDelegates[i]._updateTaskCount(task.type, count);
  555. }
  556. }
  557. }
  558. // tslint:disable-next-line:require-internal-with-underscore
  559. Zone.__symbol__ = __symbol__;
  560. const DELEGATE_ZS = {
  561. name: '',
  562. onHasTask: (delegate, _, target, hasTaskState) => delegate.hasTask(target, hasTaskState),
  563. onScheduleTask: (delegate, _, target, task) => delegate.scheduleTask(target, task),
  564. onInvokeTask: (delegate, _, target, task, applyThis, applyArgs) => delegate.invokeTask(target, task, applyThis, applyArgs),
  565. onCancelTask: (delegate, _, target, task) => delegate.cancelTask(target, task)
  566. };
  567. class ZoneDelegate {
  568. constructor(zone, parentDelegate, zoneSpec) {
  569. this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
  570. this.zone = zone;
  571. this._parentDelegate = parentDelegate;
  572. this._forkZS =
  573. zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  574. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  575. this._forkCurrZone =
  576. zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate._forkCurrZone);
  577. this._interceptZS =
  578. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  579. this._interceptDlgt =
  580. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  581. this._interceptCurrZone =
  582. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate._interceptCurrZone);
  583. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  584. this._invokeDlgt =
  585. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  586. this._invokeCurrZone =
  587. zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate._invokeCurrZone);
  588. this._handleErrorZS =
  589. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  590. this._handleErrorDlgt = zoneSpec &&
  591. (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  592. this._handleErrorCurrZone =
  593. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate._handleErrorCurrZone);
  594. this._scheduleTaskZS =
  595. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  596. this._scheduleTaskDlgt = zoneSpec &&
  597. (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  598. this._scheduleTaskCurrZone = zoneSpec &&
  599. (zoneSpec.onScheduleTask ? this.zone : parentDelegate._scheduleTaskCurrZone);
  600. this._invokeTaskZS =
  601. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  602. this._invokeTaskDlgt =
  603. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  604. this._invokeTaskCurrZone =
  605. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate._invokeTaskCurrZone);
  606. this._cancelTaskZS =
  607. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  608. this._cancelTaskDlgt =
  609. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  610. this._cancelTaskCurrZone =
  611. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate._cancelTaskCurrZone);
  612. this._hasTaskZS = null;
  613. this._hasTaskDlgt = null;
  614. this._hasTaskDlgtOwner = null;
  615. this._hasTaskCurrZone = null;
  616. const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  617. const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  618. if (zoneSpecHasTask || parentHasTask) {
  619. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  620. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  621. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  622. this._hasTaskDlgt = parentDelegate;
  623. this._hasTaskDlgtOwner = this;
  624. this._hasTaskCurrZone = zone;
  625. if (!zoneSpec.onScheduleTask) {
  626. this._scheduleTaskZS = DELEGATE_ZS;
  627. this._scheduleTaskDlgt = parentDelegate;
  628. this._scheduleTaskCurrZone = this.zone;
  629. }
  630. if (!zoneSpec.onInvokeTask) {
  631. this._invokeTaskZS = DELEGATE_ZS;
  632. this._invokeTaskDlgt = parentDelegate;
  633. this._invokeTaskCurrZone = this.zone;
  634. }
  635. if (!zoneSpec.onCancelTask) {
  636. this._cancelTaskZS = DELEGATE_ZS;
  637. this._cancelTaskDlgt = parentDelegate;
  638. this._cancelTaskCurrZone = this.zone;
  639. }
  640. }
  641. }
  642. fork(targetZone, zoneSpec) {
  643. return this._forkZS ?
  644. this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  645. new Zone(targetZone, zoneSpec);
  646. }
  647. intercept(targetZone, callback, source) {
  648. return this._interceptZS ?
  649. this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  650. callback;
  651. }
  652. invoke(targetZone, callback, applyThis, applyArgs, source) {
  653. return this._invokeZS ?
  654. this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
  655. callback.apply(applyThis, applyArgs);
  656. }
  657. handleError(targetZone, error) {
  658. return this._handleErrorZS ?
  659. this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  660. true;
  661. }
  662. scheduleTask(targetZone, task) {
  663. let returnTask = task;
  664. if (this._scheduleTaskZS) {
  665. if (this._hasTaskZS) {
  666. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  667. }
  668. // clang-format off
  669. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  670. // clang-format on
  671. if (!returnTask)
  672. returnTask = task;
  673. }
  674. else {
  675. if (task.scheduleFn) {
  676. task.scheduleFn(task);
  677. }
  678. else if (task.type == microTask) {
  679. scheduleMicroTask(task);
  680. }
  681. else {
  682. throw new Error('Task is missing scheduleFn.');
  683. }
  684. }
  685. return returnTask;
  686. }
  687. invokeTask(targetZone, task, applyThis, applyArgs) {
  688. return this._invokeTaskZS ?
  689. this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
  690. task.callback.apply(applyThis, applyArgs);
  691. }
  692. cancelTask(targetZone, task) {
  693. let value;
  694. if (this._cancelTaskZS) {
  695. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  696. }
  697. else {
  698. if (!task.cancelFn) {
  699. throw Error('Task is not cancelable');
  700. }
  701. value = task.cancelFn(task);
  702. }
  703. return value;
  704. }
  705. hasTask(targetZone, isEmpty) {
  706. // hasTask should not throw error so other ZoneDelegate
  707. // can still trigger hasTask callback
  708. try {
  709. this._hasTaskZS &&
  710. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  711. }
  712. catch (err) {
  713. this.handleError(targetZone, err);
  714. }
  715. }
  716. // tslint:disable-next-line:require-internal-with-underscore
  717. _updateTaskCount(type, count) {
  718. const counts = this._taskCounts;
  719. const prev = counts[type];
  720. const next = counts[type] = prev + count;
  721. if (next < 0) {
  722. throw new Error('More tasks executed then were scheduled.');
  723. }
  724. if (prev == 0 || next == 0) {
  725. const isEmpty = {
  726. microTask: counts['microTask'] > 0,
  727. macroTask: counts['macroTask'] > 0,
  728. eventTask: counts['eventTask'] > 0,
  729. change: type
  730. };
  731. this.hasTask(this.zone, isEmpty);
  732. }
  733. }
  734. }
  735. class ZoneTask {
  736. constructor(type, source, callback, options, scheduleFn, cancelFn) {
  737. // tslint:disable-next-line:require-internal-with-underscore
  738. this._zone = null;
  739. this.runCount = 0;
  740. // tslint:disable-next-line:require-internal-with-underscore
  741. this._zoneDelegates = null;
  742. // tslint:disable-next-line:require-internal-with-underscore
  743. this._state = 'notScheduled';
  744. this.type = type;
  745. this.source = source;
  746. this.data = options;
  747. this.scheduleFn = scheduleFn;
  748. this.cancelFn = cancelFn;
  749. if (!callback) {
  750. throw new Error('callback is not defined');
  751. }
  752. this.callback = callback;
  753. const self = this;
  754. // TODO: @JiaLiPassion options should have interface
  755. if (type === eventTask && options && options.useG) {
  756. this.invoke = ZoneTask.invokeTask;
  757. }
  758. else {
  759. this.invoke = function () {
  760. return ZoneTask.invokeTask.call(global, self, this, arguments);
  761. };
  762. }
  763. }
  764. static invokeTask(task, target, args) {
  765. if (!task) {
  766. task = this;
  767. }
  768. _numberOfNestedTaskFrames++;
  769. try {
  770. task.runCount++;
  771. return task.zone.runTask(task, target, args);
  772. }
  773. finally {
  774. if (_numberOfNestedTaskFrames == 1) {
  775. drainMicroTaskQueue();
  776. }
  777. _numberOfNestedTaskFrames--;
  778. }
  779. }
  780. get zone() { return this._zone; }
  781. get state() { return this._state; }
  782. cancelScheduleRequest() { this._transitionTo(notScheduled, scheduling); }
  783. // tslint:disable-next-line:require-internal-with-underscore
  784. _transitionTo(toState, fromState1, fromState2) {
  785. if (this._state === fromState1 || this._state === fromState2) {
  786. this._state = toState;
  787. if (toState == notScheduled) {
  788. this._zoneDelegates = null;
  789. }
  790. }
  791. else {
  792. throw new Error(`${this.type} '${this.source}': can not transition to '${toState}', expecting state '${fromState1}'${fromState2 ? ' or \'' + fromState2 + '\'' : ''}, was '${this._state}'.`);
  793. }
  794. }
  795. toString() {
  796. if (this.data && typeof this.data.handleId !== 'undefined') {
  797. return this.data.handleId.toString();
  798. }
  799. else {
  800. return Object.prototype.toString.call(this);
  801. }
  802. }
  803. // add toJSON method to prevent cyclic error when
  804. // call JSON.stringify(zoneTask)
  805. toJSON() {
  806. return {
  807. type: this.type,
  808. state: this.state,
  809. source: this.source,
  810. zone: this.zone.name,
  811. runCount: this.runCount
  812. };
  813. }
  814. }
  815. //////////////////////////////////////////////////////
  816. //////////////////////////////////////////////////////
  817. /// MICROTASK QUEUE
  818. //////////////////////////////////////////////////////
  819. //////////////////////////////////////////////////////
  820. const symbolSetTimeout = __symbol__('setTimeout');
  821. const symbolPromise = __symbol__('Promise');
  822. const symbolThen = __symbol__('then');
  823. let _microTaskQueue = [];
  824. let _isDrainingMicrotaskQueue = false;
  825. let nativeMicroTaskQueuePromise;
  826. function scheduleMicroTask(task) {
  827. // if we are not running in any task, and there has not been anything scheduled
  828. // we must bootstrap the initial task creation by manually scheduling the drain
  829. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  830. // We are not running in Task, so we need to kickstart the microtask queue.
  831. if (!nativeMicroTaskQueuePromise) {
  832. if (global[symbolPromise]) {
  833. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  834. }
  835. }
  836. if (nativeMicroTaskQueuePromise) {
  837. let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  838. if (!nativeThen) {
  839. // native Promise is not patchable, we need to use `then` directly
  840. // issue 1078
  841. nativeThen = nativeMicroTaskQueuePromise['then'];
  842. }
  843. nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
  844. }
  845. else {
  846. global[symbolSetTimeout](drainMicroTaskQueue, 0);
  847. }
  848. }
  849. task && _microTaskQueue.push(task);
  850. }
  851. function drainMicroTaskQueue() {
  852. if (!_isDrainingMicrotaskQueue) {
  853. _isDrainingMicrotaskQueue = true;
  854. while (_microTaskQueue.length) {
  855. const queue = _microTaskQueue;
  856. _microTaskQueue = [];
  857. for (let i = 0; i < queue.length; i++) {
  858. const task = queue[i];
  859. try {
  860. task.zone.runTask(task, null, null);
  861. }
  862. catch (error) {
  863. _api.onUnhandledError(error);
  864. }
  865. }
  866. }
  867. _api.microtaskDrainDone();
  868. _isDrainingMicrotaskQueue = false;
  869. }
  870. }
  871. //////////////////////////////////////////////////////
  872. //////////////////////////////////////////////////////
  873. /// BOOTSTRAP
  874. //////////////////////////////////////////////////////
  875. //////////////////////////////////////////////////////
  876. const NO_ZONE = { name: 'NO ZONE' };
  877. const notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  878. const microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  879. const patches = {};
  880. const _api = {
  881. symbol: __symbol__,
  882. currentZoneFrame: () => _currentZoneFrame,
  883. onUnhandledError: noop,
  884. microtaskDrainDone: noop,
  885. scheduleMicroTask: scheduleMicroTask,
  886. showUncaughtError: () => !Zone[__symbol__('ignoreConsoleErrorUncaughtError')],
  887. patchEventTarget: () => [],
  888. patchOnProperties: noop,
  889. patchMethod: () => noop,
  890. bindArguments: () => [],
  891. patchThen: () => noop,
  892. patchMacroTask: () => noop,
  893. setNativePromise: (NativePromise) => {
  894. // sometimes NativePromise.resolve static function
  895. // is not ready yet, (such as core-js/es6.promise)
  896. // so we need to check here.
  897. if (NativePromise && typeof NativePromise.resolve === 'function') {
  898. nativeMicroTaskQueuePromise = NativePromise.resolve(0);
  899. }
  900. },
  901. patchEventPrototype: () => noop,
  902. isIEOrEdge: () => false,
  903. getGlobalObjects: () => undefined,
  904. ObjectDefineProperty: () => noop,
  905. ObjectGetOwnPropertyDescriptor: () => undefined,
  906. ObjectCreate: () => undefined,
  907. ArraySlice: () => [],
  908. patchClass: () => noop,
  909. wrapWithCurrentZone: () => noop,
  910. filterProperties: () => [],
  911. attachOriginToPatched: () => noop,
  912. _redefineProperty: () => noop,
  913. patchCallbacks: () => noop
  914. };
  915. let _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
  916. let _currentTask = null;
  917. let _numberOfNestedTaskFrames = 0;
  918. function noop() { }
  919. performanceMeasure('Zone', 'Zone');
  920. return global['Zone'] = Zone;
  921. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  922. /**
  923. * @license
  924. * Copyright Google Inc. All Rights Reserved.
  925. *
  926. * Use of this source code is governed by an MIT-style license that can be
  927. * found in the LICENSE file at https://angular.io/license
  928. */
  929. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  930. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  931. const ObjectDefineProperty = Object.defineProperty;
  932. function readableObjectToString(obj) {
  933. if (obj && obj.toString === Object.prototype.toString) {
  934. const className = obj.constructor && obj.constructor.name;
  935. return (className ? className : '') + ': ' + JSON.stringify(obj);
  936. }
  937. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  938. }
  939. const __symbol__ = api.symbol;
  940. const _uncaughtPromiseErrors = [];
  941. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
  942. const symbolPromise = __symbol__('Promise');
  943. const symbolThen = __symbol__('then');
  944. const creationTrace = '__creationTrace__';
  945. api.onUnhandledError = (e) => {
  946. if (api.showUncaughtError()) {
  947. const rejection = e && e.rejection;
  948. if (rejection) {
  949. 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);
  950. }
  951. else {
  952. console.error(e);
  953. }
  954. }
  955. };
  956. api.microtaskDrainDone = () => {
  957. while (_uncaughtPromiseErrors.length) {
  958. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  959. try {
  960. uncaughtPromiseError.zone.runGuarded(() => { throw uncaughtPromiseError; });
  961. }
  962. catch (error) {
  963. handleUnhandledRejection(error);
  964. }
  965. }
  966. };
  967. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  968. function handleUnhandledRejection(e) {
  969. api.onUnhandledError(e);
  970. try {
  971. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  972. if (typeof handler === 'function') {
  973. handler.call(this, e);
  974. }
  975. }
  976. catch (err) {
  977. }
  978. }
  979. function isThenable(value) { return value && value.then; }
  980. function forwardResolution(value) { return value; }
  981. function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); }
  982. const symbolState = __symbol__('state');
  983. const symbolValue = __symbol__('value');
  984. const symbolFinally = __symbol__('finally');
  985. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  986. const symbolParentPromiseState = __symbol__('parentPromiseState');
  987. const source = 'Promise.then';
  988. const UNRESOLVED = null;
  989. const RESOLVED = true;
  990. const REJECTED = false;
  991. const REJECTED_NO_CATCH = 0;
  992. function makeResolver(promise, state) {
  993. return (v) => {
  994. try {
  995. resolvePromise(promise, state, v);
  996. }
  997. catch (err) {
  998. resolvePromise(promise, false, err);
  999. }
  1000. // Do not return value or you will break the Promise spec.
  1001. };
  1002. }
  1003. const once = function () {
  1004. let wasCalled = false;
  1005. return function wrapper(wrappedFunction) {
  1006. return function () {
  1007. if (wasCalled) {
  1008. return;
  1009. }
  1010. wasCalled = true;
  1011. wrappedFunction.apply(null, arguments);
  1012. };
  1013. };
  1014. };
  1015. const TYPE_ERROR = 'Promise resolved with itself';
  1016. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1017. // Promise Resolution
  1018. function resolvePromise(promise, state, value) {
  1019. const onceWrapper = once();
  1020. if (promise === value) {
  1021. throw new TypeError(TYPE_ERROR);
  1022. }
  1023. if (promise[symbolState] === UNRESOLVED) {
  1024. // should only get value.then once based on promise spec.
  1025. let then = null;
  1026. try {
  1027. if (typeof value === 'object' || typeof value === 'function') {
  1028. then = value && value.then;
  1029. }
  1030. }
  1031. catch (err) {
  1032. onceWrapper(() => { resolvePromise(promise, false, err); })();
  1033. return promise;
  1034. }
  1035. // if (value instanceof ZoneAwarePromise) {
  1036. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  1037. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  1038. value[symbolState] !== UNRESOLVED) {
  1039. clearRejectedNoCatch(value);
  1040. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1041. }
  1042. else if (state !== REJECTED && typeof then === 'function') {
  1043. try {
  1044. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1045. }
  1046. catch (err) {
  1047. onceWrapper(() => { resolvePromise(promise, false, err); })();
  1048. }
  1049. }
  1050. else {
  1051. promise[symbolState] = state;
  1052. const queue = promise[symbolValue];
  1053. promise[symbolValue] = value;
  1054. if (promise[symbolFinally] === symbolFinally) {
  1055. // the promise is generated by Promise.prototype.finally
  1056. if (state === RESOLVED) {
  1057. // the state is resolved, should ignore the value
  1058. // and use parent promise value
  1059. promise[symbolState] = promise[symbolParentPromiseState];
  1060. promise[symbolValue] = promise[symbolParentPromiseValue];
  1061. }
  1062. }
  1063. // record task information in value when error occurs, so we can
  1064. // do some additional work such as render longStackTrace
  1065. if (state === REJECTED && value instanceof Error) {
  1066. // check if longStackTraceZone is here
  1067. const trace = Zone.currentTask && Zone.currentTask.data &&
  1068. Zone.currentTask.data[creationTrace];
  1069. if (trace) {
  1070. // only keep the long stack trace into error when in longStackTraceZone
  1071. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  1072. }
  1073. }
  1074. for (let i = 0; i < queue.length;) {
  1075. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1076. }
  1077. if (queue.length == 0 && state == REJECTED) {
  1078. promise[symbolState] = REJECTED_NO_CATCH;
  1079. let uncaughtPromiseError = value;
  1080. if (!isDisableWrappingUncaughtPromiseRejection) {
  1081. // If disable wrapping uncaught promise reject
  1082. // and the rejected value is an Error object,
  1083. // use the value instead of wrapping it.
  1084. try {
  1085. // Here we throws a new Error to print more readable error log
  1086. // and if the value is not an error, zone.js builds an `Error`
  1087. // Object here to attach the stack information.
  1088. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  1089. (value && value.stack ? '\n' + value.stack : ''));
  1090. }
  1091. catch (err) {
  1092. uncaughtPromiseError = err;
  1093. }
  1094. }
  1095. uncaughtPromiseError.rejection = value;
  1096. uncaughtPromiseError.promise = promise;
  1097. uncaughtPromiseError.zone = Zone.current;
  1098. uncaughtPromiseError.task = Zone.currentTask;
  1099. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1100. api.scheduleMicroTask(); // to make sure that it is running
  1101. }
  1102. }
  1103. }
  1104. // Resolving an already resolved promise is a noop.
  1105. return promise;
  1106. }
  1107. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1108. function clearRejectedNoCatch(promise) {
  1109. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1110. // if the promise is rejected no catch status
  1111. // and queue.length > 0, means there is a error handler
  1112. // here to handle the rejected promise, we should trigger
  1113. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1114. // eventHandler
  1115. try {
  1116. const handler = Zone[REJECTION_HANDLED_HANDLER];
  1117. if (handler && typeof handler === 'function') {
  1118. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1119. }
  1120. }
  1121. catch (err) {
  1122. }
  1123. promise[symbolState] = REJECTED;
  1124. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1125. if (promise === _uncaughtPromiseErrors[i].promise) {
  1126. _uncaughtPromiseErrors.splice(i, 1);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1132. clearRejectedNoCatch(promise);
  1133. const promiseState = promise[symbolState];
  1134. const delegate = promiseState ?
  1135. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  1136. (typeof onRejected === 'function') ? onRejected : forwardRejection;
  1137. zone.scheduleMicroTask(source, () => {
  1138. try {
  1139. const parentPromiseValue = promise[symbolValue];
  1140. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1141. if (isFinallyPromise) {
  1142. // if the promise is generated from finally call, keep parent promise's state and value
  1143. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1144. chainPromise[symbolParentPromiseState] = promiseState;
  1145. }
  1146. // should not pass value to finally callback
  1147. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  1148. [] :
  1149. [parentPromiseValue]);
  1150. resolvePromise(chainPromise, true, value);
  1151. }
  1152. catch (error) {
  1153. // if error occurs, should always return this error
  1154. resolvePromise(chainPromise, false, error);
  1155. }
  1156. }, chainPromise);
  1157. }
  1158. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1159. const noop = function () { };
  1160. class ZoneAwarePromise {
  1161. static toString() { return ZONE_AWARE_PROMISE_TO_STRING; }
  1162. static resolve(value) {
  1163. return resolvePromise(new this(null), RESOLVED, value);
  1164. }
  1165. static reject(error) {
  1166. return resolvePromise(new this(null), REJECTED, error);
  1167. }
  1168. static race(values) {
  1169. let resolve;
  1170. let reject;
  1171. let promise = new this((res, rej) => {
  1172. resolve = res;
  1173. reject = rej;
  1174. });
  1175. function onResolve(value) { resolve(value); }
  1176. function onReject(error) { reject(error); }
  1177. for (let value of values) {
  1178. if (!isThenable(value)) {
  1179. value = this.resolve(value);
  1180. }
  1181. value.then(onResolve, onReject);
  1182. }
  1183. return promise;
  1184. }
  1185. static all(values) { return ZoneAwarePromise.allWithCallback(values); }
  1186. static allSettled(values) {
  1187. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1188. return P.allWithCallback(values, {
  1189. thenCallback: (value) => ({ status: 'fulfilled', value }),
  1190. errorCallback: (err) => ({ status: 'rejected', reason: err })
  1191. });
  1192. }
  1193. static allWithCallback(values, callback) {
  1194. let resolve;
  1195. let reject;
  1196. let promise = new this((res, rej) => {
  1197. resolve = res;
  1198. reject = rej;
  1199. });
  1200. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1201. let unresolvedCount = 2;
  1202. let valueIndex = 0;
  1203. const resolvedValues = [];
  1204. for (let value of values) {
  1205. if (!isThenable(value)) {
  1206. value = this.resolve(value);
  1207. }
  1208. const curValueIndex = valueIndex;
  1209. try {
  1210. value.then((value) => {
  1211. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1212. unresolvedCount--;
  1213. if (unresolvedCount === 0) {
  1214. resolve(resolvedValues);
  1215. }
  1216. }, (err) => {
  1217. if (!callback) {
  1218. reject(err);
  1219. }
  1220. else {
  1221. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1222. unresolvedCount--;
  1223. if (unresolvedCount === 0) {
  1224. resolve(resolvedValues);
  1225. }
  1226. }
  1227. });
  1228. }
  1229. catch (thenErr) {
  1230. reject(thenErr);
  1231. }
  1232. unresolvedCount++;
  1233. valueIndex++;
  1234. }
  1235. // Make the unresolvedCount zero-based again.
  1236. unresolvedCount -= 2;
  1237. if (unresolvedCount === 0) {
  1238. resolve(resolvedValues);
  1239. }
  1240. return promise;
  1241. }
  1242. constructor(executor) {
  1243. const promise = this;
  1244. if (!(promise instanceof ZoneAwarePromise)) {
  1245. throw new Error('Must be an instanceof Promise.');
  1246. }
  1247. promise[symbolState] = UNRESOLVED;
  1248. promise[symbolValue] = []; // queue;
  1249. try {
  1250. executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
  1251. }
  1252. catch (error) {
  1253. resolvePromise(promise, false, error);
  1254. }
  1255. }
  1256. get [Symbol.toStringTag]() { return 'Promise'; }
  1257. get [Symbol.species]() { return ZoneAwarePromise; }
  1258. then(onFulfilled, onRejected) {
  1259. let C = this.constructor[Symbol.species];
  1260. if (!C || typeof C !== 'function') {
  1261. C = this.constructor || ZoneAwarePromise;
  1262. }
  1263. const chainPromise = new C(noop);
  1264. const zone = Zone.current;
  1265. if (this[symbolState] == UNRESOLVED) {
  1266. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1267. }
  1268. else {
  1269. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1270. }
  1271. return chainPromise;
  1272. }
  1273. catch(onRejected) {
  1274. return this.then(null, onRejected);
  1275. }
  1276. finally(onFinally) {
  1277. let C = this.constructor[Symbol.species];
  1278. if (!C || typeof C !== 'function') {
  1279. C = ZoneAwarePromise;
  1280. }
  1281. const chainPromise = new C(noop);
  1282. chainPromise[symbolFinally] = symbolFinally;
  1283. const zone = Zone.current;
  1284. if (this[symbolState] == UNRESOLVED) {
  1285. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1286. }
  1287. else {
  1288. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1289. }
  1290. return chainPromise;
  1291. }
  1292. }
  1293. // Protect against aggressive optimizers dropping seemingly unused properties.
  1294. // E.g. Closure Compiler in advanced mode.
  1295. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1296. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1297. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1298. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1299. const NativePromise = global[symbolPromise] = global['Promise'];
  1300. const ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
  1301. let desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
  1302. if (!desc || desc.configurable) {
  1303. desc && delete desc.writable;
  1304. desc && delete desc.value;
  1305. if (!desc) {
  1306. desc = { configurable: true, enumerable: true };
  1307. }
  1308. desc.get = function () {
  1309. // if we already set ZoneAwarePromise, use patched one
  1310. // otherwise return native one.
  1311. return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
  1312. };
  1313. desc.set = function (NewNativePromise) {
  1314. if (NewNativePromise === ZoneAwarePromise) {
  1315. // if the NewNativePromise is ZoneAwarePromise
  1316. // save to global
  1317. global[ZONE_AWARE_PROMISE] = NewNativePromise;
  1318. }
  1319. else {
  1320. // if the NewNativePromise is not ZoneAwarePromise
  1321. // for example: after load zone.js, some library just
  1322. // set es6-promise to global, if we set it to global
  1323. // directly, assertZonePatched will fail and angular
  1324. // will not loaded, so we just set the NewNativePromise
  1325. // to global[symbolPromise], so the result is just like
  1326. // we load ES6 Promise before zone.js
  1327. global[symbolPromise] = NewNativePromise;
  1328. if (!NewNativePromise.prototype[symbolThen]) {
  1329. patchThen(NewNativePromise);
  1330. }
  1331. api.setNativePromise(NewNativePromise);
  1332. }
  1333. };
  1334. ObjectDefineProperty(global, 'Promise', desc);
  1335. }
  1336. global['Promise'] = ZoneAwarePromise;
  1337. const symbolThenPatched = __symbol__('thenPatched');
  1338. function patchThen(Ctor) {
  1339. const proto = Ctor.prototype;
  1340. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1341. if (prop && (prop.writable === false || !prop.configurable)) {
  1342. // check Ctor.prototype.then propertyDescriptor is writable or not
  1343. // in meteor env, writable is false, we should ignore such case
  1344. return;
  1345. }
  1346. const originalThen = proto.then;
  1347. // Keep a reference to the original method.
  1348. proto[symbolThen] = originalThen;
  1349. Ctor.prototype.then = function (onResolve, onReject) {
  1350. const wrapped = new ZoneAwarePromise((resolve, reject) => { originalThen.call(this, resolve, reject); });
  1351. return wrapped.then(onResolve, onReject);
  1352. };
  1353. Ctor[symbolThenPatched] = true;
  1354. }
  1355. api.patchThen = patchThen;
  1356. function zoneify(fn) {
  1357. return function () {
  1358. let resultPromise = fn.apply(this, arguments);
  1359. if (resultPromise instanceof ZoneAwarePromise) {
  1360. return resultPromise;
  1361. }
  1362. let ctor = resultPromise.constructor;
  1363. if (!ctor[symbolThenPatched]) {
  1364. patchThen(ctor);
  1365. }
  1366. return resultPromise;
  1367. };
  1368. }
  1369. if (NativePromise) {
  1370. patchThen(NativePromise);
  1371. const fetch = global['fetch'];
  1372. if (typeof fetch == 'function') {
  1373. global[api.symbol('fetch')] = fetch;
  1374. global['fetch'] = zoneify(fetch);
  1375. }
  1376. }
  1377. // This is not part of public API, but it is useful for tests, so we expose it.
  1378. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1379. return ZoneAwarePromise;
  1380. });
  1381. /**
  1382. * @license
  1383. * Copyright Google Inc. All Rights Reserved.
  1384. *
  1385. * Use of this source code is governed by an MIT-style license that can be
  1386. * found in the LICENSE file at https://angular.io/license
  1387. */
  1388. /**
  1389. * Suppress closure compiler errors about unknown 'Zone' variable
  1390. * @fileoverview
  1391. * @suppress {undefinedVars,globalThis,missingRequire}
  1392. */
  1393. /// <reference types="node"/>
  1394. // issue #989, to reduce bundle size, use short name
  1395. /** Object.getOwnPropertyDescriptor */
  1396. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1397. /** Object.defineProperty */
  1398. const ObjectDefineProperty = Object.defineProperty;
  1399. /** Object.getPrototypeOf */
  1400. const ObjectGetPrototypeOf = Object.getPrototypeOf;
  1401. /** Object.create */
  1402. const ObjectCreate = Object.create;
  1403. /** Array.prototype.slice */
  1404. const ArraySlice = Array.prototype.slice;
  1405. /** addEventListener string const */
  1406. const ADD_EVENT_LISTENER_STR = 'addEventListener';
  1407. /** removeEventListener string const */
  1408. const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  1409. /** zoneSymbol addEventListener */
  1410. const ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  1411. /** zoneSymbol removeEventListener */
  1412. const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  1413. /** true string const */
  1414. const TRUE_STR = 'true';
  1415. /** false string const */
  1416. const FALSE_STR = 'false';
  1417. /** Zone symbol prefix string const. */
  1418. const ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  1419. function wrapWithCurrentZone(callback, source) {
  1420. return Zone.current.wrap(callback, source);
  1421. }
  1422. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  1423. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  1424. }
  1425. const zoneSymbol = Zone.__symbol__;
  1426. const isWindowExists = typeof window !== 'undefined';
  1427. const internalWindow = isWindowExists ? window : undefined;
  1428. const _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  1429. const REMOVE_ATTRIBUTE = 'removeAttribute';
  1430. const NULL_ON_PROP_VALUE = [null];
  1431. function bindArguments(args, source) {
  1432. for (let i = args.length - 1; i >= 0; i--) {
  1433. if (typeof args[i] === 'function') {
  1434. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  1435. }
  1436. }
  1437. return args;
  1438. }
  1439. function patchPrototype(prototype, fnNames) {
  1440. const source = prototype.constructor['name'];
  1441. for (let i = 0; i < fnNames.length; i++) {
  1442. const name = fnNames[i];
  1443. const delegate = prototype[name];
  1444. if (delegate) {
  1445. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
  1446. if (!isPropertyWritable(prototypeDesc)) {
  1447. continue;
  1448. }
  1449. prototype[name] = ((delegate) => {
  1450. const patched = function () {
  1451. return delegate.apply(this, bindArguments(arguments, source + '.' + name));
  1452. };
  1453. attachOriginToPatched(patched, delegate);
  1454. return patched;
  1455. })(delegate);
  1456. }
  1457. }
  1458. }
  1459. function isPropertyWritable(propertyDesc) {
  1460. if (!propertyDesc) {
  1461. return true;
  1462. }
  1463. if (propertyDesc.writable === false) {
  1464. return false;
  1465. }
  1466. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  1467. }
  1468. const isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  1469. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  1470. // this code.
  1471. const isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  1472. {}.toString.call(_global.process) === '[object process]');
  1473. const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  1474. // we are in electron of nw, so we are both browser and nodejs
  1475. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  1476. // this code.
  1477. const isMix = typeof _global.process !== 'undefined' &&
  1478. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  1479. !!(isWindowExists && internalWindow['HTMLElement']);
  1480. const zoneSymbolEventNames = {};
  1481. const wrapFn = function (event) {
  1482. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1483. // event will be undefined, so we need to use window.event
  1484. event = event || _global.event;
  1485. if (!event) {
  1486. return;
  1487. }
  1488. let eventNameSymbol = zoneSymbolEventNames[event.type];
  1489. if (!eventNameSymbol) {
  1490. eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  1491. }
  1492. const target = this || event.target || _global;
  1493. const listener = target[eventNameSymbol];
  1494. let result;
  1495. if (isBrowser && target === internalWindow && event.type === 'error') {
  1496. // window.onerror have different signiture
  1497. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  1498. // and onerror callback will prevent default when callback return true
  1499. const errorEvent = event;
  1500. result = listener &&
  1501. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  1502. if (result === true) {
  1503. event.preventDefault();
  1504. }
  1505. }
  1506. else {
  1507. result = listener && listener.apply(this, arguments);
  1508. if (result != undefined && !result) {
  1509. event.preventDefault();
  1510. }
  1511. }
  1512. return result;
  1513. };
  1514. function patchProperty(obj, prop, prototype) {
  1515. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  1516. if (!desc && prototype) {
  1517. // when patch window object, use prototype to check prop exist or not
  1518. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  1519. if (prototypeDesc) {
  1520. desc = { enumerable: true, configurable: true };
  1521. }
  1522. }
  1523. // if the descriptor not exists or is not configurable
  1524. // just return
  1525. if (!desc || !desc.configurable) {
  1526. return;
  1527. }
  1528. const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  1529. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  1530. return;
  1531. }
  1532. // A property descriptor cannot have getter/setter and be writable
  1533. // deleting the writable and value properties avoids this error:
  1534. //
  1535. // TypeError: property descriptors must not specify a value or be writable when a
  1536. // getter or setter has been specified
  1537. delete desc.writable;
  1538. delete desc.value;
  1539. const originalDescGet = desc.get;
  1540. const originalDescSet = desc.set;
  1541. // substr(2) cuz 'onclick' -> 'click', etc
  1542. const eventName = prop.substr(2);
  1543. let eventNameSymbol = zoneSymbolEventNames[eventName];
  1544. if (!eventNameSymbol) {
  1545. eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  1546. }
  1547. desc.set = function (newValue) {
  1548. // in some of windows's onproperty callback, this is undefined
  1549. // so we need to check it
  1550. let target = this;
  1551. if (!target && obj === _global) {
  1552. target = _global;
  1553. }
  1554. if (!target) {
  1555. return;
  1556. }
  1557. let previousValue = target[eventNameSymbol];
  1558. if (previousValue) {
  1559. target.removeEventListener(eventName, wrapFn);
  1560. }
  1561. // issue #978, when onload handler was added before loading zone.js
  1562. // we should remove it with originalDescSet
  1563. if (originalDescSet) {
  1564. originalDescSet.apply(target, NULL_ON_PROP_VALUE);
  1565. }
  1566. if (typeof newValue === 'function') {
  1567. target[eventNameSymbol] = newValue;
  1568. target.addEventListener(eventName, wrapFn, false);
  1569. }
  1570. else {
  1571. target[eventNameSymbol] = null;
  1572. }
  1573. };
  1574. // The getter would return undefined for unassigned properties but the default value of an
  1575. // unassigned property is null
  1576. desc.get = function () {
  1577. // in some of windows's onproperty callback, this is undefined
  1578. // so we need to check it
  1579. let target = this;
  1580. if (!target && obj === _global) {
  1581. target = _global;
  1582. }
  1583. if (!target) {
  1584. return null;
  1585. }
  1586. const listener = target[eventNameSymbol];
  1587. if (listener) {
  1588. return listener;
  1589. }
  1590. else if (originalDescGet) {
  1591. // result will be null when use inline event attribute,
  1592. // such as <button onclick="func();">OK</button>
  1593. // because the onclick function is internal raw uncompiled handler
  1594. // the onclick will be evaluated when first time event was triggered or
  1595. // the property is accessed, https://github.com/angular/zone.js/issues/525
  1596. // so we should use original native get to retrieve the handler
  1597. let value = originalDescGet && originalDescGet.call(this);
  1598. if (value) {
  1599. desc.set.call(this, value);
  1600. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  1601. target.removeAttribute(prop);
  1602. }
  1603. return value;
  1604. }
  1605. }
  1606. return null;
  1607. };
  1608. ObjectDefineProperty(obj, prop, desc);
  1609. obj[onPropPatchedSymbol] = true;
  1610. }
  1611. function patchOnProperties(obj, properties, prototype) {
  1612. if (properties) {
  1613. for (let i = 0; i < properties.length; i++) {
  1614. patchProperty(obj, 'on' + properties[i], prototype);
  1615. }
  1616. }
  1617. else {
  1618. const onProperties = [];
  1619. for (const prop in obj) {
  1620. if (prop.substr(0, 2) == 'on') {
  1621. onProperties.push(prop);
  1622. }
  1623. }
  1624. for (let j = 0; j < onProperties.length; j++) {
  1625. patchProperty(obj, onProperties[j], prototype);
  1626. }
  1627. }
  1628. }
  1629. const originalInstanceKey = zoneSymbol('originalInstance');
  1630. // wrap some native API on `window`
  1631. function patchClass(className) {
  1632. const OriginalClass = _global[className];
  1633. if (!OriginalClass)
  1634. return;
  1635. // keep original class in global
  1636. _global[zoneSymbol(className)] = OriginalClass;
  1637. _global[className] = function () {
  1638. const a = bindArguments(arguments, className);
  1639. switch (a.length) {
  1640. case 0:
  1641. this[originalInstanceKey] = new OriginalClass();
  1642. break;
  1643. case 1:
  1644. this[originalInstanceKey] = new OriginalClass(a[0]);
  1645. break;
  1646. case 2:
  1647. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  1648. break;
  1649. case 3:
  1650. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  1651. break;
  1652. case 4:
  1653. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  1654. break;
  1655. default:
  1656. throw new Error('Arg list too long.');
  1657. }
  1658. };
  1659. // attach original delegate to patched function
  1660. attachOriginToPatched(_global[className], OriginalClass);
  1661. const instance = new OriginalClass(function () { });
  1662. let prop;
  1663. for (prop in instance) {
  1664. // https://bugs.webkit.org/show_bug.cgi?id=44721
  1665. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  1666. continue;
  1667. (function (prop) {
  1668. if (typeof instance[prop] === 'function') {
  1669. _global[className].prototype[prop] = function () {
  1670. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  1671. };
  1672. }
  1673. else {
  1674. ObjectDefineProperty(_global[className].prototype, prop, {
  1675. set: function (fn) {
  1676. if (typeof fn === 'function') {
  1677. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  1678. // keep callback in wrapped function so we can
  1679. // use it in Function.prototype.toString to return
  1680. // the native one.
  1681. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  1682. }
  1683. else {
  1684. this[originalInstanceKey][prop] = fn;
  1685. }
  1686. },
  1687. get: function () { return this[originalInstanceKey][prop]; }
  1688. });
  1689. }
  1690. }(prop));
  1691. }
  1692. for (prop in OriginalClass) {
  1693. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  1694. _global[className][prop] = OriginalClass[prop];
  1695. }
  1696. }
  1697. }
  1698. function copySymbolProperties(src, dest) {
  1699. if (typeof Object.getOwnPropertySymbols !== 'function') {
  1700. return;
  1701. }
  1702. const symbols = Object.getOwnPropertySymbols(src);
  1703. symbols.forEach((symbol) => {
  1704. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  1705. Object.defineProperty(dest, symbol, {
  1706. get: function () { return src[symbol]; },
  1707. set: function (value) {
  1708. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1709. // if src[symbol] is not writable or not have a setter, just return
  1710. return;
  1711. }
  1712. src[symbol] = value;
  1713. },
  1714. enumerable: desc ? desc.enumerable : true,
  1715. configurable: desc ? desc.configurable : true
  1716. });
  1717. });
  1718. }
  1719. let shouldCopySymbolProperties = false;
  1720. function patchMethod(target, name, patchFn) {
  1721. let proto = target;
  1722. while (proto && !proto.hasOwnProperty(name)) {
  1723. proto = ObjectGetPrototypeOf(proto);
  1724. }
  1725. if (!proto && target[name]) {
  1726. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1727. proto = target;
  1728. }
  1729. const delegateName = zoneSymbol(name);
  1730. let delegate = null;
  1731. if (proto && !(delegate = proto[delegateName])) {
  1732. delegate = proto[delegateName] = proto[name];
  1733. // check whether proto[name] is writable
  1734. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1735. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1736. if (isPropertyWritable(desc)) {
  1737. const patchDelegate = patchFn(delegate, delegateName, name);
  1738. proto[name] = function () { return patchDelegate(this, arguments); };
  1739. attachOriginToPatched(proto[name], delegate);
  1740. if (shouldCopySymbolProperties) {
  1741. copySymbolProperties(delegate, proto[name]);
  1742. }
  1743. }
  1744. }
  1745. return delegate;
  1746. }
  1747. // TODO: @JiaLiPassion, support cancel task later if necessary
  1748. function patchMacroTask(obj, funcName, metaCreator) {
  1749. let setNative = null;
  1750. function scheduleTask(task) {
  1751. const data = task.data;
  1752. data.args[data.cbIdx] = function () { task.invoke.apply(this, arguments); };
  1753. setNative.apply(data.target, data.args);
  1754. return task;
  1755. }
  1756. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1757. const meta = metaCreator(self, args);
  1758. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1759. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1760. }
  1761. else {
  1762. // cause an error by calling it directly.
  1763. return delegate.apply(self, args);
  1764. }
  1765. });
  1766. }
  1767. function attachOriginToPatched(patched, original) {
  1768. patched[zoneSymbol('OriginalDelegate')] = original;
  1769. }
  1770. let isDetectedIEOrEdge = false;
  1771. let ieOrEdge = false;
  1772. function isIE() {
  1773. try {
  1774. const ua = internalWindow.navigator.userAgent;
  1775. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
  1776. return true;
  1777. }
  1778. }
  1779. catch (error) {
  1780. }
  1781. return false;
  1782. }
  1783. function isIEOrEdge() {
  1784. if (isDetectedIEOrEdge) {
  1785. return ieOrEdge;
  1786. }
  1787. isDetectedIEOrEdge = true;
  1788. try {
  1789. const ua = internalWindow.navigator.userAgent;
  1790. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1791. ieOrEdge = true;
  1792. }
  1793. }
  1794. catch (error) {
  1795. }
  1796. return ieOrEdge;
  1797. }
  1798. /**
  1799. * @license
  1800. * Copyright Google Inc. All Rights Reserved.
  1801. *
  1802. * Use of this source code is governed by an MIT-style license that can be
  1803. * found in the LICENSE file at https://angular.io/license
  1804. */
  1805. // override Function.prototype.toString to make zone.js patched function
  1806. // look like native function
  1807. Zone.__load_patch('toString', (global) => {
  1808. // patch Func.prototype.toString to let them look like native
  1809. const originalFunctionToString = Function.prototype.toString;
  1810. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1811. const PROMISE_SYMBOL = zoneSymbol('Promise');
  1812. const ERROR_SYMBOL = zoneSymbol('Error');
  1813. const newFunctionToString = function toString() {
  1814. if (typeof this === 'function') {
  1815. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1816. if (originalDelegate) {
  1817. if (typeof originalDelegate === 'function') {
  1818. return originalFunctionToString.call(originalDelegate);
  1819. }
  1820. else {
  1821. return Object.prototype.toString.call(originalDelegate);
  1822. }
  1823. }
  1824. if (this === Promise) {
  1825. const nativePromise = global[PROMISE_SYMBOL];
  1826. if (nativePromise) {
  1827. return originalFunctionToString.call(nativePromise);
  1828. }
  1829. }
  1830. if (this === Error) {
  1831. const nativeError = global[ERROR_SYMBOL];
  1832. if (nativeError) {
  1833. return originalFunctionToString.call(nativeError);
  1834. }
  1835. }
  1836. }
  1837. return originalFunctionToString.call(this);
  1838. };
  1839. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1840. Function.prototype.toString = newFunctionToString;
  1841. // patch Object.prototype.toString to let them look like native
  1842. const originalObjectToString = Object.prototype.toString;
  1843. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1844. Object.prototype.toString = function () {
  1845. if (this instanceof Promise) {
  1846. return PROMISE_OBJECT_TO_STRING;
  1847. }
  1848. return originalObjectToString.call(this);
  1849. };
  1850. });
  1851. /**
  1852. * @license
  1853. * Copyright Google Inc. All Rights Reserved.
  1854. *
  1855. * Use of this source code is governed by an MIT-style license that can be
  1856. * found in the LICENSE file at https://angular.io/license
  1857. */
  1858. let passiveSupported = false;
  1859. if (typeof window !== 'undefined') {
  1860. try {
  1861. const options = Object.defineProperty({}, 'passive', { get: function () { passiveSupported = true; } });
  1862. window.addEventListener('test', options, options);
  1863. window.removeEventListener('test', options, options);
  1864. }
  1865. catch (err) {
  1866. passiveSupported = false;
  1867. }
  1868. }
  1869. // an identifier to tell ZoneTask do not create a new invoke closure
  1870. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1871. useG: true
  1872. };
  1873. const zoneSymbolEventNames$1 = {};
  1874. const globalSources = {};
  1875. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1876. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1877. function prepareEventNames(eventName, eventNameToString) {
  1878. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1879. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1880. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1881. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1882. zoneSymbolEventNames$1[eventName] = {};
  1883. zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
  1884. zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
  1885. }
  1886. function patchEventTarget(_global, apis, patchOptions) {
  1887. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1888. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1889. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1890. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1891. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1892. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1893. const PREPEND_EVENT_LISTENER = 'prependListener';
  1894. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1895. const invokeTask = function (task, target, event) {
  1896. // for better performance, check isRemoved which is set
  1897. // by removeEventListener
  1898. if (task.isRemoved) {
  1899. return;
  1900. }
  1901. const delegate = task.callback;
  1902. if (typeof delegate === 'object' && delegate.handleEvent) {
  1903. // create the bind version of handleEvent when invoke
  1904. task.callback = (event) => delegate.handleEvent(event);
  1905. task.originalDelegate = delegate;
  1906. }
  1907. // invoke static task.invoke
  1908. task.invoke(task, target, [event]);
  1909. const options = task.options;
  1910. if (options && typeof options === 'object' && options.once) {
  1911. // if options.once is true, after invoke once remove listener here
  1912. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1913. // inside EventEmitter.once
  1914. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1915. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1916. }
  1917. };
  1918. // global shared zoneAwareCallback to handle all event callback with capture = false
  1919. const globalZoneAwareCallback = function (event) {
  1920. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1921. // event will be undefined, so we need to use window.event
  1922. event = event || _global.event;
  1923. if (!event) {
  1924. return;
  1925. }
  1926. // event.target is needed for Samsung TV and SourceBuffer
  1927. // || global is needed https://github.com/angular/zone.js/issues/190
  1928. const target = this || event.target || _global;
  1929. const tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
  1930. if (tasks) {
  1931. // invoke all tasks which attached to current target with given event.type and capture = false
  1932. // for performance concern, if task.length === 1, just invoke
  1933. if (tasks.length === 1) {
  1934. invokeTask(tasks[0], target, event);
  1935. }
  1936. else {
  1937. // https://github.com/angular/zone.js/issues/836
  1938. // copy the tasks array before invoke, to avoid
  1939. // the callback will remove itself or other listener
  1940. const copyTasks = tasks.slice();
  1941. for (let i = 0; i < copyTasks.length; i++) {
  1942. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1943. break;
  1944. }
  1945. invokeTask(copyTasks[i], target, event);
  1946. }
  1947. }
  1948. }
  1949. };
  1950. // global shared zoneAwareCallback to handle all event callback with capture = true
  1951. const globalZoneAwareCaptureCallback = function (event) {
  1952. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1953. // event will be undefined, so we need to use window.event
  1954. event = event || _global.event;
  1955. if (!event) {
  1956. return;
  1957. }
  1958. // event.target is needed for Samsung TV and SourceBuffer
  1959. // || global is needed https://github.com/angular/zone.js/issues/190
  1960. const target = this || event.target || _global;
  1961. const tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
  1962. if (tasks) {
  1963. // invoke all tasks which attached to current target with given event.type and capture = false
  1964. // for performance concern, if task.length === 1, just invoke
  1965. if (tasks.length === 1) {
  1966. invokeTask(tasks[0], target, event);
  1967. }
  1968. else {
  1969. // https://github.com/angular/zone.js/issues/836
  1970. // copy the tasks array before invoke, to avoid
  1971. // the callback will remove itself or other listener
  1972. const copyTasks = tasks.slice();
  1973. for (let i = 0; i < copyTasks.length; i++) {
  1974. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1975. break;
  1976. }
  1977. invokeTask(copyTasks[i], target, event);
  1978. }
  1979. }
  1980. }
  1981. };
  1982. function patchEventTargetMethods(obj, patchOptions) {
  1983. if (!obj) {
  1984. return false;
  1985. }
  1986. let useGlobalCallback = true;
  1987. if (patchOptions && patchOptions.useG !== undefined) {
  1988. useGlobalCallback = patchOptions.useG;
  1989. }
  1990. const validateHandler = patchOptions && patchOptions.vh;
  1991. let checkDuplicate = true;
  1992. if (patchOptions && patchOptions.chkDup !== undefined) {
  1993. checkDuplicate = patchOptions.chkDup;
  1994. }
  1995. let returnTarget = false;
  1996. if (patchOptions && patchOptions.rt !== undefined) {
  1997. returnTarget = patchOptions.rt;
  1998. }
  1999. let proto = obj;
  2000. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  2001. proto = ObjectGetPrototypeOf(proto);
  2002. }
  2003. if (!proto && obj[ADD_EVENT_LISTENER]) {
  2004. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  2005. proto = obj;
  2006. }
  2007. if (!proto) {
  2008. return false;
  2009. }
  2010. if (proto[zoneSymbolAddEventListener]) {
  2011. return false;
  2012. }
  2013. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  2014. // a shared global taskData to pass data for scheduleEventTask
  2015. // so we do not need to create a new object just for pass some data
  2016. const taskData = {};
  2017. const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  2018. const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  2019. proto[REMOVE_EVENT_LISTENER];
  2020. const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  2021. proto[LISTENERS_EVENT_LISTENER];
  2022. const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  2023. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  2024. let nativePrependEventListener;
  2025. if (patchOptions && patchOptions.prepend) {
  2026. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  2027. proto[patchOptions.prepend];
  2028. }
  2029. /**
  2030. * This util function will build an option object with passive option
  2031. * to handle all possible input from the user.
  2032. */
  2033. function buildEventListenerOptions(options, passive) {
  2034. if (!passiveSupported && typeof options === 'object' && options) {
  2035. // doesn't support passive but user want to pass an object as options.
  2036. // this will not work on some old browser, so we just pass a boolean
  2037. // as useCapture parameter
  2038. return !!options.capture;
  2039. }
  2040. if (!passiveSupported || !passive) {
  2041. return options;
  2042. }
  2043. if (typeof options === 'boolean') {
  2044. return { capture: options, passive: true };
  2045. }
  2046. if (!options) {
  2047. return { passive: true };
  2048. }
  2049. if (typeof options === 'object' && options.passive !== false) {
  2050. return Object.assign(Object.assign({}, options), { passive: true });
  2051. }
  2052. return options;
  2053. }
  2054. const customScheduleGlobal = function (task) {
  2055. // if there is already a task for the eventName + capture,
  2056. // just return, because we use the shared globalZoneAwareCallback here.
  2057. if (taskData.isExisting) {
  2058. return;
  2059. }
  2060. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  2061. };
  2062. const customCancelGlobal = function (task) {
  2063. // if task is not marked as isRemoved, this call is directly
  2064. // from Zone.prototype.cancelTask, we should remove the task
  2065. // from tasksList of target first
  2066. if (!task.isRemoved) {
  2067. const symbolEventNames = zoneSymbolEventNames$1[task.eventName];
  2068. let symbolEventName;
  2069. if (symbolEventNames) {
  2070. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  2071. }
  2072. const existingTasks = symbolEventName && task.target[symbolEventName];
  2073. if (existingTasks) {
  2074. for (let i = 0; i < existingTasks.length; i++) {
  2075. const existingTask = existingTasks[i];
  2076. if (existingTask === task) {
  2077. existingTasks.splice(i, 1);
  2078. // set isRemoved to data for faster invokeTask check
  2079. task.isRemoved = true;
  2080. if (existingTasks.length === 0) {
  2081. // all tasks for the eventName + capture have gone,
  2082. // remove globalZoneAwareCallback and remove the task cache from target
  2083. task.allRemoved = true;
  2084. task.target[symbolEventName] = null;
  2085. }
  2086. break;
  2087. }
  2088. }
  2089. }
  2090. }
  2091. // if all tasks for the eventName + capture have gone,
  2092. // we will really remove the global event callback,
  2093. // if not, return
  2094. if (!task.allRemoved) {
  2095. return;
  2096. }
  2097. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  2098. };
  2099. const customScheduleNonGlobal = function (task) {
  2100. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  2101. };
  2102. const customSchedulePrepend = function (task) {
  2103. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  2104. };
  2105. const customCancelNonGlobal = function (task) {
  2106. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  2107. };
  2108. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  2109. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  2110. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2111. const typeOfDelegate = typeof delegate;
  2112. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  2113. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  2114. };
  2115. const compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  2116. const blackListedEvents = Zone[zoneSymbol('BLACK_LISTED_EVENTS')];
  2117. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  2118. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  2119. return function () {
  2120. const target = this || _global;
  2121. let eventName = arguments[0];
  2122. if (patchOptions && patchOptions.transferEventName) {
  2123. eventName = patchOptions.transferEventName(eventName);
  2124. }
  2125. let delegate = arguments[1];
  2126. if (!delegate) {
  2127. return nativeListener.apply(this, arguments);
  2128. }
  2129. if (isNode && eventName === 'uncaughtException') {
  2130. // don't patch uncaughtException of nodejs to prevent endless loop
  2131. return nativeListener.apply(this, arguments);
  2132. }
  2133. // don't create the bind delegate function for handleEvent
  2134. // case here to improve addEventListener performance
  2135. // we will create the bind delegate when invoke
  2136. let isHandleEvent = false;
  2137. if (typeof delegate !== 'function') {
  2138. if (!delegate.handleEvent) {
  2139. return nativeListener.apply(this, arguments);
  2140. }
  2141. isHandleEvent = true;
  2142. }
  2143. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  2144. return;
  2145. }
  2146. const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  2147. const options = buildEventListenerOptions(arguments[2], passive);
  2148. if (blackListedEvents) {
  2149. // check black list
  2150. for (let i = 0; i < blackListedEvents.length; i++) {
  2151. if (eventName === blackListedEvents[i]) {
  2152. if (passive) {
  2153. return nativeListener.call(target, eventName, delegate, options);
  2154. }
  2155. else {
  2156. return nativeListener.apply(this, arguments);
  2157. }
  2158. }
  2159. }
  2160. }
  2161. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2162. const once = options && typeof options === 'object' ? options.once : false;
  2163. const zone = Zone.current;
  2164. let symbolEventNames = zoneSymbolEventNames$1[eventName];
  2165. if (!symbolEventNames) {
  2166. prepareEventNames(eventName, eventNameToString);
  2167. symbolEventNames = zoneSymbolEventNames$1[eventName];
  2168. }
  2169. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2170. let existingTasks = target[symbolEventName];
  2171. let isExisting = false;
  2172. if (existingTasks) {
  2173. // already have task registered
  2174. isExisting = true;
  2175. if (checkDuplicate) {
  2176. for (let i = 0; i < existingTasks.length; i++) {
  2177. if (compare(existingTasks[i], delegate)) {
  2178. // same callback, same capture, same event name, just return
  2179. return;
  2180. }
  2181. }
  2182. }
  2183. }
  2184. else {
  2185. existingTasks = target[symbolEventName] = [];
  2186. }
  2187. let source;
  2188. const constructorName = target.constructor['name'];
  2189. const targetSource = globalSources[constructorName];
  2190. if (targetSource) {
  2191. source = targetSource[eventName];
  2192. }
  2193. if (!source) {
  2194. source = constructorName + addSource +
  2195. (eventNameToString ? eventNameToString(eventName) : eventName);
  2196. }
  2197. // do not create a new object as task.data to pass those things
  2198. // just use the global shared one
  2199. taskData.options = options;
  2200. if (once) {
  2201. // if addEventListener with once options, we don't pass it to
  2202. // native addEventListener, instead we keep the once setting
  2203. // and handle ourselves.
  2204. taskData.options.once = false;
  2205. }
  2206. taskData.target = target;
  2207. taskData.capture = capture;
  2208. taskData.eventName = eventName;
  2209. taskData.isExisting = isExisting;
  2210. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  2211. // keep taskData into data to allow onScheduleEventTask to access the task information
  2212. if (data) {
  2213. data.taskData = taskData;
  2214. }
  2215. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  2216. // should clear taskData.target to avoid memory leak
  2217. // issue, https://github.com/angular/angular/issues/20442
  2218. taskData.target = null;
  2219. // need to clear up taskData because it is a global object
  2220. if (data) {
  2221. data.taskData = null;
  2222. }
  2223. // have to save those information to task in case
  2224. // application may call task.zone.cancelTask() directly
  2225. if (once) {
  2226. options.once = true;
  2227. }
  2228. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  2229. // if not support passive, and we pass an option object
  2230. // to addEventListener, we should save the options to task
  2231. task.options = options;
  2232. }
  2233. task.target = target;
  2234. task.capture = capture;
  2235. task.eventName = eventName;
  2236. if (isHandleEvent) {
  2237. // save original delegate for compare to check duplicate
  2238. task.originalDelegate = delegate;
  2239. }
  2240. if (!prepend) {
  2241. existingTasks.push(task);
  2242. }
  2243. else {
  2244. existingTasks.unshift(task);
  2245. }
  2246. if (returnTarget) {
  2247. return target;
  2248. }
  2249. };
  2250. };
  2251. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  2252. if (nativePrependEventListener) {
  2253. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  2254. }
  2255. proto[REMOVE_EVENT_LISTENER] = function () {
  2256. const target = this || _global;
  2257. let eventName = arguments[0];
  2258. if (patchOptions && patchOptions.transferEventName) {
  2259. eventName = patchOptions.transferEventName(eventName);
  2260. }
  2261. const options = arguments[2];
  2262. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2263. const delegate = arguments[1];
  2264. if (!delegate) {
  2265. return nativeRemoveEventListener.apply(this, arguments);
  2266. }
  2267. if (validateHandler &&
  2268. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2269. return;
  2270. }
  2271. const symbolEventNames = zoneSymbolEventNames$1[eventName];
  2272. let symbolEventName;
  2273. if (symbolEventNames) {
  2274. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2275. }
  2276. const existingTasks = symbolEventName && target[symbolEventName];
  2277. if (existingTasks) {
  2278. for (let i = 0; i < existingTasks.length; i++) {
  2279. const existingTask = existingTasks[i];
  2280. if (compare(existingTask, delegate)) {
  2281. existingTasks.splice(i, 1);
  2282. // set isRemoved to data for faster invokeTask check
  2283. existingTask.isRemoved = true;
  2284. if (existingTasks.length === 0) {
  2285. // all tasks for the eventName + capture have gone,
  2286. // remove globalZoneAwareCallback and remove the task cache from target
  2287. existingTask.allRemoved = true;
  2288. target[symbolEventName] = null;
  2289. // in the target, we have an event listener which is added by on_property
  2290. // such as target.onclick = function() {}, so we need to clear this internal
  2291. // property too if all delegates all removed
  2292. if (typeof eventName === 'string') {
  2293. const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2294. target[onPropertySymbol] = null;
  2295. }
  2296. }
  2297. existingTask.zone.cancelTask(existingTask);
  2298. if (returnTarget) {
  2299. return target;
  2300. }
  2301. return;
  2302. }
  2303. }
  2304. }
  2305. // issue 930, didn't find the event name or callback
  2306. // from zone kept existingTasks, the callback maybe
  2307. // added outside of zone, we need to call native removeEventListener
  2308. // to try to remove it.
  2309. return nativeRemoveEventListener.apply(this, arguments);
  2310. };
  2311. proto[LISTENERS_EVENT_LISTENER] = function () {
  2312. const target = this || _global;
  2313. let eventName = arguments[0];
  2314. if (patchOptions && patchOptions.transferEventName) {
  2315. eventName = patchOptions.transferEventName(eventName);
  2316. }
  2317. const listeners = [];
  2318. const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2319. for (let i = 0; i < tasks.length; i++) {
  2320. const task = tasks[i];
  2321. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2322. listeners.push(delegate);
  2323. }
  2324. return listeners;
  2325. };
  2326. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2327. const target = this || _global;
  2328. let eventName = arguments[0];
  2329. if (!eventName) {
  2330. const keys = Object.keys(target);
  2331. for (let i = 0; i < keys.length; i++) {
  2332. const prop = keys[i];
  2333. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2334. let evtName = match && match[1];
  2335. // in nodejs EventEmitter, removeListener event is
  2336. // used for monitoring the removeListener call,
  2337. // so just keep removeListener eventListener until
  2338. // all other eventListeners are removed
  2339. if (evtName && evtName !== 'removeListener') {
  2340. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2341. }
  2342. }
  2343. // remove removeListener listener finally
  2344. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2345. }
  2346. else {
  2347. if (patchOptions && patchOptions.transferEventName) {
  2348. eventName = patchOptions.transferEventName(eventName);
  2349. }
  2350. const symbolEventNames = zoneSymbolEventNames$1[eventName];
  2351. if (symbolEventNames) {
  2352. const symbolEventName = symbolEventNames[FALSE_STR];
  2353. const symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2354. const tasks = target[symbolEventName];
  2355. const captureTasks = target[symbolCaptureEventName];
  2356. if (tasks) {
  2357. const removeTasks = tasks.slice();
  2358. for (let i = 0; i < removeTasks.length; i++) {
  2359. const task = removeTasks[i];
  2360. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2361. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2362. }
  2363. }
  2364. if (captureTasks) {
  2365. const removeTasks = captureTasks.slice();
  2366. for (let i = 0; i < removeTasks.length; i++) {
  2367. const task = removeTasks[i];
  2368. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2369. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2370. }
  2371. }
  2372. }
  2373. }
  2374. if (returnTarget) {
  2375. return this;
  2376. }
  2377. };
  2378. // for native toString patch
  2379. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2380. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2381. if (nativeRemoveAllListeners) {
  2382. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2383. }
  2384. if (nativeListeners) {
  2385. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2386. }
  2387. return true;
  2388. }
  2389. let results = [];
  2390. for (let i = 0; i < apis.length; i++) {
  2391. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2392. }
  2393. return results;
  2394. }
  2395. function findEventTasks(target, eventName) {
  2396. if (!eventName) {
  2397. const foundTasks = [];
  2398. for (let prop in target) {
  2399. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2400. let evtName = match && match[1];
  2401. if (evtName && (!eventName || evtName === eventName)) {
  2402. const tasks = target[prop];
  2403. if (tasks) {
  2404. for (let i = 0; i < tasks.length; i++) {
  2405. foundTasks.push(tasks[i]);
  2406. }
  2407. }
  2408. }
  2409. }
  2410. return foundTasks;
  2411. }
  2412. let symbolEventName = zoneSymbolEventNames$1[eventName];
  2413. if (!symbolEventName) {
  2414. prepareEventNames(eventName);
  2415. symbolEventName = zoneSymbolEventNames$1[eventName];
  2416. }
  2417. const captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2418. const captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2419. if (!captureFalseTasks) {
  2420. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2421. }
  2422. else {
  2423. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  2424. captureFalseTasks.slice();
  2425. }
  2426. }
  2427. function patchEventPrototype(global, api) {
  2428. const Event = global['Event'];
  2429. if (Event && Event.prototype) {
  2430. api.patchMethod(Event.prototype, 'stopImmediatePropagation', (delegate) => function (self, args) {
  2431. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  2432. // we need to call the native stopImmediatePropagation
  2433. // in case in some hybrid application, some part of
  2434. // application will be controlled by zone, some are not
  2435. delegate && delegate.apply(self, args);
  2436. });
  2437. }
  2438. }
  2439. /**
  2440. * @license
  2441. * Copyright Google Inc. All Rights Reserved.
  2442. *
  2443. * Use of this source code is governed by an MIT-style license that can be
  2444. * found in the LICENSE file at https://angular.io/license
  2445. */
  2446. function patchCallbacks(api, target, targetName, method, callbacks) {
  2447. const symbol = Zone.__symbol__(method);
  2448. if (target[symbol]) {
  2449. return;
  2450. }
  2451. const nativeDelegate = target[symbol] = target[method];
  2452. target[method] = function (name, opts, options) {
  2453. if (opts && opts.prototype) {
  2454. callbacks.forEach(function (callback) {
  2455. const source = `${targetName}.${method}::` + callback;
  2456. const prototype = opts.prototype;
  2457. if (prototype.hasOwnProperty(callback)) {
  2458. const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2459. if (descriptor && descriptor.value) {
  2460. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2461. api._redefineProperty(opts.prototype, callback, descriptor);
  2462. }
  2463. else if (prototype[callback]) {
  2464. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2465. }
  2466. }
  2467. else if (prototype[callback]) {
  2468. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2469. }
  2470. });
  2471. }
  2472. return nativeDelegate.call(target, name, opts, options);
  2473. };
  2474. api.attachOriginToPatched(target[method], nativeDelegate);
  2475. }
  2476. /**
  2477. * @license
  2478. * Copyright Google Inc. All Rights Reserved.
  2479. *
  2480. * Use of this source code is governed by an MIT-style license that can be
  2481. * found in the LICENSE file at https://angular.io/license
  2482. */
  2483. const globalEventHandlersEventNames = [
  2484. 'abort',
  2485. 'animationcancel',
  2486. 'animationend',
  2487. 'animationiteration',
  2488. 'auxclick',
  2489. 'beforeinput',
  2490. 'blur',
  2491. 'cancel',
  2492. 'canplay',
  2493. 'canplaythrough',
  2494. 'change',
  2495. 'compositionstart',
  2496. 'compositionupdate',
  2497. 'compositionend',
  2498. 'cuechange',
  2499. 'click',
  2500. 'close',
  2501. 'contextmenu',
  2502. 'curechange',
  2503. 'dblclick',
  2504. 'drag',
  2505. 'dragend',
  2506. 'dragenter',
  2507. 'dragexit',
  2508. 'dragleave',
  2509. 'dragover',
  2510. 'drop',
  2511. 'durationchange',
  2512. 'emptied',
  2513. 'ended',
  2514. 'error',
  2515. 'focus',
  2516. 'focusin',
  2517. 'focusout',
  2518. 'gotpointercapture',
  2519. 'input',
  2520. 'invalid',
  2521. 'keydown',
  2522. 'keypress',
  2523. 'keyup',
  2524. 'load',
  2525. 'loadstart',
  2526. 'loadeddata',
  2527. 'loadedmetadata',
  2528. 'lostpointercapture',
  2529. 'mousedown',
  2530. 'mouseenter',
  2531. 'mouseleave',
  2532. 'mousemove',
  2533. 'mouseout',
  2534. 'mouseover',
  2535. 'mouseup',
  2536. 'mousewheel',
  2537. 'orientationchange',
  2538. 'pause',
  2539. 'play',
  2540. 'playing',
  2541. 'pointercancel',
  2542. 'pointerdown',
  2543. 'pointerenter',
  2544. 'pointerleave',
  2545. 'pointerlockchange',
  2546. 'mozpointerlockchange',
  2547. 'webkitpointerlockerchange',
  2548. 'pointerlockerror',
  2549. 'mozpointerlockerror',
  2550. 'webkitpointerlockerror',
  2551. 'pointermove',
  2552. 'pointout',
  2553. 'pointerover',
  2554. 'pointerup',
  2555. 'progress',
  2556. 'ratechange',
  2557. 'reset',
  2558. 'resize',
  2559. 'scroll',
  2560. 'seeked',
  2561. 'seeking',
  2562. 'select',
  2563. 'selectionchange',
  2564. 'selectstart',
  2565. 'show',
  2566. 'sort',
  2567. 'stalled',
  2568. 'submit',
  2569. 'suspend',
  2570. 'timeupdate',
  2571. 'volumechange',
  2572. 'touchcancel',
  2573. 'touchmove',
  2574. 'touchstart',
  2575. 'touchend',
  2576. 'transitioncancel',
  2577. 'transitionend',
  2578. 'waiting',
  2579. 'wheel'
  2580. ];
  2581. const documentEventNames = [
  2582. 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
  2583. 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
  2584. 'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
  2585. 'visibilitychange', 'resume'
  2586. ];
  2587. const windowEventNames = [
  2588. 'absolutedeviceorientation',
  2589. 'afterinput',
  2590. 'afterprint',
  2591. 'appinstalled',
  2592. 'beforeinstallprompt',
  2593. 'beforeprint',
  2594. 'beforeunload',
  2595. 'devicelight',
  2596. 'devicemotion',
  2597. 'deviceorientation',
  2598. 'deviceorientationabsolute',
  2599. 'deviceproximity',
  2600. 'hashchange',
  2601. 'languagechange',
  2602. 'message',
  2603. 'mozbeforepaint',
  2604. 'offline',
  2605. 'online',
  2606. 'paint',
  2607. 'pageshow',
  2608. 'pagehide',
  2609. 'popstate',
  2610. 'rejectionhandled',
  2611. 'storage',
  2612. 'unhandledrejection',
  2613. 'unload',
  2614. 'userproximity',
  2615. 'vrdisplayconnected',
  2616. 'vrdisplaydisconnected',
  2617. 'vrdisplaypresentchange'
  2618. ];
  2619. const htmlElementEventNames = [
  2620. 'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
  2621. 'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
  2622. 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
  2623. ];
  2624. const mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
  2625. const ieElementEventNames = [
  2626. 'activate',
  2627. 'afterupdate',
  2628. 'ariarequest',
  2629. 'beforeactivate',
  2630. 'beforedeactivate',
  2631. 'beforeeditfocus',
  2632. 'beforeupdate',
  2633. 'cellchange',
  2634. 'controlselect',
  2635. 'dataavailable',
  2636. 'datasetchanged',
  2637. 'datasetcomplete',
  2638. 'errorupdate',
  2639. 'filterchange',
  2640. 'layoutcomplete',
  2641. 'losecapture',
  2642. 'move',
  2643. 'moveend',
  2644. 'movestart',
  2645. 'propertychange',
  2646. 'resizeend',
  2647. 'resizestart',
  2648. 'rowenter',
  2649. 'rowexit',
  2650. 'rowsdelete',
  2651. 'rowsinserted',
  2652. 'command',
  2653. 'compassneedscalibration',
  2654. 'deactivate',
  2655. 'help',
  2656. 'mscontentzoom',
  2657. 'msmanipulationstatechanged',
  2658. 'msgesturechange',
  2659. 'msgesturedoubletap',
  2660. 'msgestureend',
  2661. 'msgesturehold',
  2662. 'msgesturestart',
  2663. 'msgesturetap',
  2664. 'msgotpointercapture',
  2665. 'msinertiastart',
  2666. 'mslostpointercapture',
  2667. 'mspointercancel',
  2668. 'mspointerdown',
  2669. 'mspointerenter',
  2670. 'mspointerhover',
  2671. 'mspointerleave',
  2672. 'mspointermove',
  2673. 'mspointerout',
  2674. 'mspointerover',
  2675. 'mspointerup',
  2676. 'pointerout',
  2677. 'mssitemodejumplistitemremoved',
  2678. 'msthumbnailclick',
  2679. 'stop',
  2680. 'storagecommit'
  2681. ];
  2682. const webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
  2683. const formEventNames = ['autocomplete', 'autocompleteerror'];
  2684. const detailEventNames = ['toggle'];
  2685. const frameEventNames = ['load'];
  2686. const frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
  2687. const marqueeEventNames = ['bounce', 'finish', 'start'];
  2688. const XMLHttpRequestEventNames = [
  2689. 'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend',
  2690. 'readystatechange'
  2691. ];
  2692. const IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
  2693. const websocketEventNames = ['close', 'error', 'open', 'message'];
  2694. const workerEventNames = ['error', 'message'];
  2695. const eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
  2696. function filterProperties(target, onProperties, ignoreProperties) {
  2697. if (!ignoreProperties || ignoreProperties.length === 0) {
  2698. return onProperties;
  2699. }
  2700. const tip = ignoreProperties.filter(ip => ip.target === target);
  2701. if (!tip || tip.length === 0) {
  2702. return onProperties;
  2703. }
  2704. const targetIgnoreProperties = tip[0].ignoreProperties;
  2705. return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
  2706. }
  2707. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  2708. // check whether target is available, sometimes target will be undefined
  2709. // because different browser or some 3rd party plugin.
  2710. if (!target) {
  2711. return;
  2712. }
  2713. const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  2714. patchOnProperties(target, filteredProperties, prototype);
  2715. }
  2716. function propertyDescriptorPatch(api, _global) {
  2717. if (isNode && !isMix) {
  2718. return;
  2719. }
  2720. if (Zone[api.symbol('patchEvents')]) {
  2721. // events are already been patched by legacy patch.
  2722. return;
  2723. }
  2724. const supportsWebSocket = typeof WebSocket !== 'undefined';
  2725. const ignoreProperties = _global['__Zone_ignore_on_properties'];
  2726. // for browsers that we can patch the descriptor: Chrome & Firefox
  2727. if (isBrowser) {
  2728. const internalWindow = window;
  2729. const ignoreErrorProperties = isIE ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
  2730. // in IE/Edge, onProp not exist in window object, but in WindowPrototype
  2731. // so we need to pass WindowPrototype to check onProp exist or not
  2732. patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
  2733. patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
  2734. if (typeof internalWindow['SVGElement'] !== 'undefined') {
  2735. patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
  2736. }
  2737. patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
  2738. patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
  2739. patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
  2740. patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
  2741. patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
  2742. patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
  2743. patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
  2744. const HTMLMarqueeElement = internalWindow['HTMLMarqueeElement'];
  2745. if (HTMLMarqueeElement) {
  2746. patchFilteredProperties(HTMLMarqueeElement.prototype, marqueeEventNames, ignoreProperties);
  2747. }
  2748. const Worker = internalWindow['Worker'];
  2749. if (Worker) {
  2750. patchFilteredProperties(Worker.prototype, workerEventNames, ignoreProperties);
  2751. }
  2752. }
  2753. const XMLHttpRequest = _global['XMLHttpRequest'];
  2754. if (XMLHttpRequest) {
  2755. // XMLHttpRequest is not available in ServiceWorker, so we need to check here
  2756. patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
  2757. }
  2758. const XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
  2759. if (XMLHttpRequestEventTarget) {
  2760. patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
  2761. }
  2762. if (typeof IDBIndex !== 'undefined') {
  2763. patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
  2764. patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
  2765. patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
  2766. patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
  2767. patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
  2768. patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
  2769. }
  2770. if (supportsWebSocket) {
  2771. patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
  2772. }
  2773. }
  2774. /**
  2775. * @license
  2776. * Copyright Google Inc. All Rights Reserved.
  2777. *
  2778. * Use of this source code is governed by an MIT-style license that can be
  2779. * found in the LICENSE file at https://angular.io/license
  2780. */
  2781. Zone.__load_patch('util', (global, Zone, api) => {
  2782. api.patchOnProperties = patchOnProperties;
  2783. api.patchMethod = patchMethod;
  2784. api.bindArguments = bindArguments;
  2785. api.patchMacroTask = patchMacroTask;
  2786. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
  2787. // define which events will not be patched by `Zone.js`.
  2788. // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
  2789. // the name consistent with angular repo.
  2790. // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
  2791. // backwards compatibility.
  2792. const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2793. const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2794. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2795. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2796. }
  2797. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2798. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2799. global[SYMBOL_BLACK_LISTED_EVENTS];
  2800. }
  2801. api.patchEventPrototype = patchEventPrototype;
  2802. api.patchEventTarget = patchEventTarget;
  2803. api.isIEOrEdge = isIEOrEdge;
  2804. api.ObjectDefineProperty = ObjectDefineProperty;
  2805. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2806. api.ObjectCreate = ObjectCreate;
  2807. api.ArraySlice = ArraySlice;
  2808. api.patchClass = patchClass;
  2809. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2810. api.filterProperties = filterProperties;
  2811. api.attachOriginToPatched = attachOriginToPatched;
  2812. api._redefineProperty = Object.defineProperty;
  2813. api.patchCallbacks = patchCallbacks;
  2814. api.getGlobalObjects = () => ({ globalSources, zoneSymbolEventNames: zoneSymbolEventNames$1, eventNames, isBrowser, isMix, isNode, TRUE_STR,
  2815. FALSE_STR, ZONE_SYMBOL_PREFIX, ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR });
  2816. });
  2817. /**
  2818. * @license
  2819. * Copyright Google Inc. All Rights Reserved.
  2820. *
  2821. * Use of this source code is governed by an MIT-style license that can be
  2822. * found in the LICENSE file at https://angular.io/license
  2823. */
  2824. const taskSymbol = zoneSymbol('zoneTask');
  2825. function patchTimer(window, setName, cancelName, nameSuffix) {
  2826. let setNative = null;
  2827. let clearNative = null;
  2828. setName += nameSuffix;
  2829. cancelName += nameSuffix;
  2830. const tasksByHandleId = {};
  2831. function scheduleTask(task) {
  2832. const data = task.data;
  2833. function timer() {
  2834. try {
  2835. task.invoke.apply(this, arguments);
  2836. }
  2837. finally {
  2838. // issue-934, task will be cancelled
  2839. // even it is a periodic task such as
  2840. // setInterval
  2841. if (!(task.data && task.data.isPeriodic)) {
  2842. if (typeof data.handleId === 'number') {
  2843. // in non-nodejs env, we remove timerId
  2844. // from local cache
  2845. delete tasksByHandleId[data.handleId];
  2846. }
  2847. else if (data.handleId) {
  2848. // Node returns complex objects as handleIds
  2849. // we remove task reference from timer object
  2850. data.handleId[taskSymbol] = null;
  2851. }
  2852. }
  2853. }
  2854. }
  2855. data.args[0] = timer;
  2856. data.handleId = setNative.apply(window, data.args);
  2857. return task;
  2858. }
  2859. function clearTask(task) { return clearNative(task.data.handleId); }
  2860. setNative =
  2861. patchMethod(window, setName, (delegate) => function (self, args) {
  2862. if (typeof args[0] === 'function') {
  2863. const options = {
  2864. isPeriodic: nameSuffix === 'Interval',
  2865. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2866. undefined,
  2867. args: args
  2868. };
  2869. const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2870. if (!task) {
  2871. return task;
  2872. }
  2873. // Node.js must additionally support the ref and unref functions.
  2874. const handle = task.data.handleId;
  2875. if (typeof handle === 'number') {
  2876. // for non nodejs env, we save handleId: task
  2877. // mapping in local cache for clearTimeout
  2878. tasksByHandleId[handle] = task;
  2879. }
  2880. else if (handle) {
  2881. // for nodejs env, we save task
  2882. // reference in timerId Object for clearTimeout
  2883. handle[taskSymbol] = task;
  2884. }
  2885. // check whether handle is null, because some polyfill or browser
  2886. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2887. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2888. typeof handle.unref === 'function') {
  2889. task.ref = handle.ref.bind(handle);
  2890. task.unref = handle.unref.bind(handle);
  2891. }
  2892. if (typeof handle === 'number' || handle) {
  2893. return handle;
  2894. }
  2895. return task;
  2896. }
  2897. else {
  2898. // cause an error by calling it directly.
  2899. return delegate.apply(window, args);
  2900. }
  2901. });
  2902. clearNative =
  2903. patchMethod(window, cancelName, (delegate) => function (self, args) {
  2904. const id = args[0];
  2905. let task;
  2906. if (typeof id === 'number') {
  2907. // non nodejs env.
  2908. task = tasksByHandleId[id];
  2909. }
  2910. else {
  2911. // nodejs env.
  2912. task = id && id[taskSymbol];
  2913. // other environments.
  2914. if (!task) {
  2915. task = id;
  2916. }
  2917. }
  2918. if (task && typeof task.type === 'string') {
  2919. if (task.state !== 'notScheduled' &&
  2920. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2921. if (typeof id === 'number') {
  2922. delete tasksByHandleId[id];
  2923. }
  2924. else if (id) {
  2925. id[taskSymbol] = null;
  2926. }
  2927. // Do not cancel already canceled functions
  2928. task.zone.cancelTask(task);
  2929. }
  2930. }
  2931. else {
  2932. // cause an error by calling it directly.
  2933. delegate.apply(window, args);
  2934. }
  2935. });
  2936. }
  2937. /**
  2938. * @license
  2939. * Copyright Google Inc. All Rights Reserved.
  2940. *
  2941. * Use of this source code is governed by an MIT-style license that can be
  2942. * found in the LICENSE file at https://angular.io/license
  2943. */
  2944. function patchCustomElements(_global, api) {
  2945. const { isBrowser, isMix } = api.getGlobalObjects();
  2946. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  2947. return;
  2948. }
  2949. const callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
  2950. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  2951. }
  2952. /**
  2953. * @license
  2954. * Copyright Google Inc. All Rights Reserved.
  2955. *
  2956. * Use of this source code is governed by an MIT-style license that can be
  2957. * found in the LICENSE file at https://angular.io/license
  2958. */
  2959. function eventTargetPatch(_global, api) {
  2960. if (Zone[api.symbol('patchEventTarget')]) {
  2961. // EventTarget is already patched.
  2962. return;
  2963. }
  2964. const { eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX } = api.getGlobalObjects();
  2965. // predefine all __zone_symbol__ + eventName + true/false string
  2966. for (let i = 0; i < eventNames.length; i++) {
  2967. const eventName = eventNames[i];
  2968. const falseEventName = eventName + FALSE_STR;
  2969. const trueEventName = eventName + TRUE_STR;
  2970. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  2971. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  2972. zoneSymbolEventNames[eventName] = {};
  2973. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  2974. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  2975. }
  2976. const EVENT_TARGET = _global['EventTarget'];
  2977. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  2978. return;
  2979. }
  2980. api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
  2981. return true;
  2982. }
  2983. function patchEvent(global, api) {
  2984. api.patchEventPrototype(global, api);
  2985. }
  2986. /**
  2987. * @license
  2988. * Copyright Google Inc. All Rights Reserved.
  2989. *
  2990. * Use of this source code is governed by an MIT-style license that can be
  2991. * found in the LICENSE file at https://angular.io/license
  2992. */
  2993. Zone.__load_patch('legacy', (global) => {
  2994. const legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2995. if (legacyPatch) {
  2996. legacyPatch();
  2997. }
  2998. });
  2999. Zone.__load_patch('timers', (global) => {
  3000. const set = 'set';
  3001. const clear = 'clear';
  3002. patchTimer(global, set, clear, 'Timeout');
  3003. patchTimer(global, set, clear, 'Interval');
  3004. patchTimer(global, set, clear, 'Immediate');
  3005. });
  3006. Zone.__load_patch('requestAnimationFrame', (global) => {
  3007. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  3008. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  3009. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  3010. });
  3011. Zone.__load_patch('blocking', (global, Zone) => {
  3012. const blockingMethods = ['alert', 'prompt', 'confirm'];
  3013. for (let i = 0; i < blockingMethods.length; i++) {
  3014. const name = blockingMethods[i];
  3015. patchMethod(global, name, (delegate, symbol, name) => {
  3016. return function (s, args) {
  3017. return Zone.current.run(delegate, global, args, name);
  3018. };
  3019. });
  3020. }
  3021. });
  3022. Zone.__load_patch('EventTarget', (global, Zone, api) => {
  3023. patchEvent(global, api);
  3024. eventTargetPatch(global, api);
  3025. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  3026. const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  3027. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  3028. api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
  3029. }
  3030. patchClass('MutationObserver');
  3031. patchClass('WebKitMutationObserver');
  3032. patchClass('IntersectionObserver');
  3033. patchClass('FileReader');
  3034. });
  3035. Zone.__load_patch('on_property', (global, Zone, api) => {
  3036. propertyDescriptorPatch(api, global);
  3037. });
  3038. Zone.__load_patch('customElements', (global, Zone, api) => {
  3039. patchCustomElements(global, api);
  3040. });
  3041. Zone.__load_patch('XHR', (global, Zone) => {
  3042. // Treat XMLHttpRequest as a macrotask.
  3043. patchXHR(global);
  3044. const XHR_TASK = zoneSymbol('xhrTask');
  3045. const XHR_SYNC = zoneSymbol('xhrSync');
  3046. const XHR_LISTENER = zoneSymbol('xhrListener');
  3047. const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  3048. const XHR_URL = zoneSymbol('xhrURL');
  3049. const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  3050. function patchXHR(window) {
  3051. const XMLHttpRequest = window['XMLHttpRequest'];
  3052. if (!XMLHttpRequest) {
  3053. // XMLHttpRequest is not available in service worker
  3054. return;
  3055. }
  3056. const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  3057. function findPendingTask(target) { return target[XHR_TASK]; }
  3058. let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  3059. let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  3060. if (!oriAddListener) {
  3061. const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
  3062. if (XMLHttpRequestEventTarget) {
  3063. const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
  3064. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  3065. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  3066. }
  3067. }
  3068. const READY_STATE_CHANGE = 'readystatechange';
  3069. const SCHEDULED = 'scheduled';
  3070. function scheduleTask(task) {
  3071. const data = task.data;
  3072. const target = data.target;
  3073. target[XHR_SCHEDULED] = false;
  3074. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  3075. // remove existing event listener
  3076. const listener = target[XHR_LISTENER];
  3077. if (!oriAddListener) {
  3078. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  3079. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  3080. }
  3081. if (listener) {
  3082. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  3083. }
  3084. const newListener = target[XHR_LISTENER] = () => {
  3085. if (target.readyState === target.DONE) {
  3086. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  3087. // readyState=4 multiple times, so we need to check task state here
  3088. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  3089. // check whether the xhr has registered onload listener
  3090. // if that is the case, the task should invoke after all
  3091. // onload listeners finish.
  3092. const loadTasks = target[Zone.__symbol__('loadfalse')];
  3093. if (loadTasks && loadTasks.length > 0) {
  3094. const oriInvoke = task.invoke;
  3095. task.invoke = function () {
  3096. // need to load the tasks again, because in other
  3097. // load listener, they may remove themselves
  3098. const loadTasks = target[Zone.__symbol__('loadfalse')];
  3099. for (let i = 0; i < loadTasks.length; i++) {
  3100. if (loadTasks[i] === task) {
  3101. loadTasks.splice(i, 1);
  3102. }
  3103. }
  3104. if (!data.aborted && task.state === SCHEDULED) {
  3105. oriInvoke.call(task);
  3106. }
  3107. };
  3108. loadTasks.push(task);
  3109. }
  3110. else {
  3111. task.invoke();
  3112. }
  3113. }
  3114. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  3115. // error occurs when xhr.send()
  3116. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  3117. }
  3118. }
  3119. };
  3120. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  3121. const storedTask = target[XHR_TASK];
  3122. if (!storedTask) {
  3123. target[XHR_TASK] = task;
  3124. }
  3125. sendNative.apply(target, data.args);
  3126. target[XHR_SCHEDULED] = true;
  3127. return task;
  3128. }
  3129. function placeholderCallback() { }
  3130. function clearTask(task) {
  3131. const data = task.data;
  3132. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  3133. // to prevent it from firing. So instead, we store info for the event listener.
  3134. data.aborted = true;
  3135. return abortNative.apply(data.target, data.args);
  3136. }
  3137. const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
  3138. self[XHR_SYNC] = args[2] == false;
  3139. self[XHR_URL] = args[1];
  3140. return openNative.apply(self, args);
  3141. });
  3142. const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  3143. const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  3144. const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  3145. const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
  3146. if (Zone.current[fetchTaskScheduling] === true) {
  3147. // a fetch is scheduling, so we are using xhr to polyfill fetch
  3148. // and because we already schedule macroTask for fetch, we should
  3149. // not schedule a macroTask for xhr again
  3150. return sendNative.apply(self, args);
  3151. }
  3152. if (self[XHR_SYNC]) {
  3153. // if the XHR is sync there is no task to schedule, just execute the code.
  3154. return sendNative.apply(self, args);
  3155. }
  3156. else {
  3157. const options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
  3158. const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  3159. if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
  3160. task.state === SCHEDULED) {
  3161. // xhr request throw error when send
  3162. // we should invoke task instead of leaving a scheduled
  3163. // pending macroTask
  3164. task.invoke();
  3165. }
  3166. }
  3167. });
  3168. const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
  3169. const task = findPendingTask(self);
  3170. if (task && typeof task.type == 'string') {
  3171. // If the XHR has already completed, do nothing.
  3172. // If the XHR has already been aborted, do nothing.
  3173. // Fix #569, call abort multiple times before done will cause
  3174. // macroTask task count be negative number
  3175. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  3176. return;
  3177. }
  3178. task.zone.cancelTask(task);
  3179. }
  3180. else if (Zone.current[fetchTaskAborting] === true) {
  3181. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  3182. return abortNative.apply(self, args);
  3183. }
  3184. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  3185. // task
  3186. // to cancel. Do nothing.
  3187. });
  3188. }
  3189. });
  3190. Zone.__load_patch('geolocation', (global) => {
  3191. /// GEO_LOCATION
  3192. if (global['navigator'] && global['navigator'].geolocation) {
  3193. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  3194. }
  3195. });
  3196. Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
  3197. // handle unhandled promise rejection
  3198. function findPromiseRejectionHandler(evtName) {
  3199. return function (e) {
  3200. const eventTasks = findEventTasks(global, evtName);
  3201. eventTasks.forEach(eventTask => {
  3202. // windows has added unhandledrejection event listener
  3203. // trigger the event listener
  3204. const PromiseRejectionEvent = global['PromiseRejectionEvent'];
  3205. if (PromiseRejectionEvent) {
  3206. const evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
  3207. eventTask.invoke(evt);
  3208. }
  3209. });
  3210. };
  3211. }
  3212. if (global['PromiseRejectionEvent']) {
  3213. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  3214. findPromiseRejectionHandler('unhandledrejection');
  3215. Zone[zoneSymbol('rejectionHandledHandler')] =
  3216. findPromiseRejectionHandler('rejectionhandled');
  3217. }
  3218. });
  3219. })));
  3220. /***/ })
  3221. },[[2,"runtime"]]]);
  3222. //# sourceMappingURL=polyfills-es2015.js.map