zone.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. /**
  9. * Suppress closure compiler errors about unknown 'global' variable
  10. * @fileoverview
  11. * @suppress {undefinedVars}
  12. */
  13. /**
  14. * Zone is a mechanism for intercepting and keeping track of asynchronous work.
  15. *
  16. * A Zone is a global object which is configured with rules about how to intercept and keep track
  17. * of the asynchronous callbacks. Zone has these responsibilities:
  18. *
  19. * 1. Intercept asynchronous task scheduling
  20. * 2. Wrap callbacks for error-handling and zone tracking across async operations.
  21. * 3. Provide a way to attach data to zones
  22. * 4. Provide a context specific last frame error handling
  23. * 5. (Intercept blocking methods)
  24. *
  25. * A zone by itself does not do anything, instead it relies on some other code to route existing
  26. * platform API through it. (The zone library ships with code which monkey patches all of the
  27. * browsers's asynchronous API and redirects them through the zone for interception.)
  28. *
  29. * In its simplest form a zone allows one to intercept the scheduling and calling of asynchronous
  30. * operations, and execute additional code before as well as after the asynchronous task. The rules
  31. * of interception are configured using [ZoneConfig]. There can be many different zone instances in
  32. * a system, but only one zone is active at any given time which can be retrieved using
  33. * [Zone#current].
  34. *
  35. *
  36. *
  37. * ## Callback Wrapping
  38. *
  39. * An important aspect of the zones is that they should persist across asynchronous operations. To
  40. * achieve this, when a future work is scheduled through async API, it is necessary to capture, and
  41. * subsequently restore the current zone. For example if a code is running in zone `b` and it
  42. * invokes `setTimeout` to scheduleTask work later, the `setTimeout` method needs to 1) capture the
  43. * current zone and 2) wrap the `wrapCallback` in code which will restore the current zone `b` once
  44. * the wrapCallback executes. In this way the rules which govern the current code are preserved in
  45. * all future asynchronous tasks. There could be a different zone `c` which has different rules and
  46. * is associated with different asynchronous tasks. As these tasks are processed, each asynchronous
  47. * wrapCallback correctly restores the correct zone, as well as preserves the zone for future
  48. * asynchronous callbacks.
  49. *
  50. * Example: Suppose a browser page consist of application code as well as third-party
  51. * advertisement code. (These two code bases are independent, developed by different mutually
  52. * unaware developers.) The application code may be interested in doing global error handling and
  53. * so it configures the `app` zone to send all of the errors to the server for analysis, and then
  54. * executes the application in the `app` zone. The advertising code is interested in the same
  55. * error processing but it needs to send the errors to a different third-party. So it creates the
  56. * `ads` zone with a different error handler. Now both advertising as well as application code
  57. * create many asynchronous operations, but the [Zone] will ensure that all of the asynchronous
  58. * operations created from the application code will execute in `app` zone with its error
  59. * handler and all of the advertisement code will execute in the `ads` zone with its error handler.
  60. * This will not only work for the async operations created directly, but also for all subsequent
  61. * asynchronous operations.
  62. *
  63. * If you think of chain of asynchronous operations as a thread of execution (bit of a stretch)
  64. * then [Zone#current] will act as a thread local variable.
  65. *
  66. *
  67. *
  68. * ## Asynchronous operation scheduling
  69. *
  70. * In addition to wrapping the callbacks to restore the zone, all operations which cause a
  71. * scheduling of work for later are routed through the current zone which is allowed to intercept
  72. * them by adding work before or after the wrapCallback as well as using different means of
  73. * achieving the request. (Useful for unit testing, or tracking of requests). In some instances
  74. * such as `setTimeout` the wrapping of the wrapCallback and scheduling is done in the same
  75. * wrapCallback, but there are other examples such as `Promises` where the `then` wrapCallback is
  76. * wrapped, but the execution of `then` is triggered by `Promise` scheduling `resolve` work.
  77. *
  78. * Fundamentally there are three kinds of tasks which can be scheduled:
  79. *
  80. * 1. [MicroTask] used for doing work right after the current task. This is non-cancelable which is
  81. * guaranteed to run exactly once and immediately.
  82. * 2. [MacroTask] used for doing work later. Such as `setTimeout`. This is typically cancelable
  83. * which is guaranteed to execute at least once after some well understood delay.
  84. * 3. [EventTask] used for listening on some future event. This may execute zero or more times, with
  85. * an unknown delay.
  86. *
  87. * Each asynchronous API is modeled and routed through one of these APIs.
  88. *
  89. *
  90. * ### [MicroTask]
  91. *
  92. * [MicroTask]s represent work which will be done in current VM turn as soon as possible, before VM
  93. * yielding.
  94. *
  95. *
  96. * ### [MacroTask]
  97. *
  98. * [MacroTask]s represent work which will be done after some delay. (Sometimes the delay is
  99. * approximate such as on next available animation frame). Typically these methods include:
  100. * `setTimeout`, `setImmediate`, `setInterval`, `requestAnimationFrame`, and all browser specific
  101. * variants.
  102. *
  103. *
  104. * ### [EventTask]
  105. *
  106. * [EventTask]s represent a request to create a listener on an event. Unlike the other task
  107. * events they may never be executed, but typically execute more than once. There is no queue of
  108. * events, rather their callbacks are unpredictable both in order and time.
  109. *
  110. *
  111. * ## Global Error Handling
  112. *
  113. *
  114. * ## Composability
  115. *
  116. * Zones can be composed together through [Zone.fork()]. A child zone may create its own set of
  117. * rules. A child zone is expected to either:
  118. *
  119. * 1. Delegate the interception to a parent zone, and optionally add before and after wrapCallback
  120. * hooks.
  121. * 2. Process the request itself without delegation.
  122. *
  123. * Composability allows zones to keep their concerns clean. For example a top most zone may choose
  124. * to handle error handling, while child zones may choose to do user action tracking.
  125. *
  126. *
  127. * ## Root Zone
  128. *
  129. * At the start the browser will run in a special root zone, which is configured to behave exactly
  130. * like the platform, making any existing code which is not zone-aware behave as expected. All
  131. * zones are children of the root zone.
  132. *
  133. */
  134. interface Zone {
  135. /**
  136. *
  137. * @returns {Zone} The parent Zone.
  138. */
  139. parent: Zone|null;
  140. /**
  141. * @returns {string} The Zone name (useful for debugging)
  142. */
  143. name: string;
  144. /**
  145. * Returns a value associated with the `key`.
  146. *
  147. * If the current zone does not have a key, the request is delegated to the parent zone. Use
  148. * [ZoneSpec.properties] to configure the set of properties associated with the current zone.
  149. *
  150. * @param key The key to retrieve.
  151. * @returns {any} The value for the key, or `undefined` if not found.
  152. */
  153. get(key: string): any;
  154. /**
  155. * Returns a Zone which defines a `key`.
  156. *
  157. * Recursively search the parent Zone until a Zone which has a property `key` is found.
  158. *
  159. * @param key The key to use for identification of the returned zone.
  160. * @returns {Zone} The Zone which defines the `key`, `null` if not found.
  161. */
  162. getZoneWith(key: string): Zone|null;
  163. /**
  164. * Used to create a child zone.
  165. *
  166. * @param zoneSpec A set of rules which the child zone should follow.
  167. * @returns {Zone} A new child zone.
  168. */
  169. fork(zoneSpec: ZoneSpec): Zone;
  170. /**
  171. * Wraps a callback function in a new function which will properly restore the current zone upon
  172. * invocation.
  173. *
  174. * The wrapped function will properly forward `this` as well as `arguments` to the `callback`.
  175. *
  176. * Before the function is wrapped the zone can intercept the `callback` by declaring
  177. * [ZoneSpec.onIntercept].
  178. *
  179. * @param callback the function which will be wrapped in the zone.
  180. * @param source A unique debug location of the API being wrapped.
  181. * @returns {function(): *} A function which will invoke the `callback` through [Zone.runGuarded].
  182. */
  183. wrap<F extends Function>(callback: F, source: string): F;
  184. /**
  185. * Invokes a function in a given zone.
  186. *
  187. * The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke].
  188. *
  189. * @param callback The function to invoke.
  190. * @param applyThis
  191. * @param applyArgs
  192. * @param source A unique debug location of the API being invoked.
  193. * @returns {any} Value from the `callback` function.
  194. */
  195. run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
  196. /**
  197. * Invokes a function in a given zone and catches any exceptions.
  198. *
  199. * Any exceptions thrown will be forwarded to [Zone.HandleError].
  200. *
  201. * The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke]. The
  202. * handling of exceptions can be intercepted by declaring [ZoneSpec.handleError].
  203. *
  204. * @param callback The function to invoke.
  205. * @param applyThis
  206. * @param applyArgs
  207. * @param source A unique debug location of the API being invoked.
  208. * @returns {any} Value from the `callback` function.
  209. */
  210. runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
  211. /**
  212. * Execute the Task by restoring the [Zone.currentTask] in the Task's zone.
  213. *
  214. * @param task to run
  215. * @param applyThis
  216. * @param applyArgs
  217. * @returns {*}
  218. */
  219. runTask(task: Task, applyThis?: any, applyArgs?: any): any;
  220. /**
  221. * Schedule a MicroTask.
  222. *
  223. * @param source
  224. * @param callback
  225. * @param data
  226. * @param customSchedule
  227. */
  228. scheduleMicroTask(
  229. source: string, callback: Function, data?: TaskData,
  230. customSchedule?: (task: Task) => void): MicroTask;
  231. /**
  232. * Schedule a MacroTask.
  233. *
  234. * @param source
  235. * @param callback
  236. * @param data
  237. * @param customSchedule
  238. * @param customCancel
  239. */
  240. scheduleMacroTask(
  241. source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
  242. customCancel?: (task: Task) => void): MacroTask;
  243. /**
  244. * Schedule an EventTask.
  245. *
  246. * @param source
  247. * @param callback
  248. * @param data
  249. * @param customSchedule
  250. * @param customCancel
  251. */
  252. scheduleEventTask(
  253. source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
  254. customCancel?: (task: Task) => void): EventTask;
  255. /**
  256. * Schedule an existing Task.
  257. *
  258. * Useful for rescheduling a task which was already canceled.
  259. *
  260. * @param task
  261. */
  262. scheduleTask<T extends Task>(task: T): T;
  263. /**
  264. * Allows the zone to intercept canceling of scheduled Task.
  265. *
  266. * The interception is configured using [ZoneSpec.onCancelTask]. The default canceler invokes
  267. * the [Task.cancelFn].
  268. *
  269. * @param task
  270. * @returns {any}
  271. */
  272. cancelTask(task: Task): any;
  273. }
  274. interface ZoneType {
  275. /**
  276. * @returns {Zone} Returns the current [Zone]. The only way to change
  277. * the current zone is by invoking a run() method, which will update the current zone for the
  278. * duration of the run method callback.
  279. */
  280. current: Zone;
  281. /**
  282. * @returns {Task} The task associated with the current execution.
  283. */
  284. currentTask: Task|null;
  285. /**
  286. * Verify that Zone has been correctly patched. Specifically that Promise is zone aware.
  287. */
  288. assertZonePatched(): void;
  289. /**
  290. * Return the root zone.
  291. */
  292. root: Zone;
  293. /** @internal */
  294. __load_patch(name: string, fn: _PatchFn): void;
  295. /** @internal */
  296. __symbol__(name: string): string;
  297. }
  298. /** @internal */
  299. type _PatchFn = (global: Window, Zone: ZoneType, api: _ZonePrivate) => void;
  300. /** @internal */
  301. interface _ZonePrivate {
  302. currentZoneFrame: () => _ZoneFrame;
  303. symbol: (name: string) => string;
  304. scheduleMicroTask: (task?: MicroTask) => void;
  305. onUnhandledError: (error: Error) => void;
  306. microtaskDrainDone: () => void;
  307. showUncaughtError: () => boolean;
  308. patchEventTarget: (global: any, apis: any[], options?: any) => boolean[];
  309. patchOnProperties: (obj: any, properties: string[]|null, prototype?: any) => void;
  310. patchThen: (ctro: Function) => void;
  311. setNativePromise: (nativePromise: any) => void;
  312. patchMethod:
  313. (target: any, name: string,
  314. patchFn: (delegate: Function, delegateName: string, name: string) =>
  315. (self: any, args: any[]) => any) => Function | null;
  316. bindArguments: (args: any[], source: string) => any[];
  317. patchMacroTask:
  318. (obj: any, funcName: string, metaCreator: (self: any, args: any[]) => any) => void;
  319. patchEventPrototype: (_global: any, api: _ZonePrivate) => void;
  320. isIEOrEdge: () => boolean;
  321. ObjectDefineProperty:
  322. (o: any, p: PropertyKey, attributes: PropertyDescriptor&ThisType<any>) => any;
  323. ObjectGetOwnPropertyDescriptor: (o: any, p: PropertyKey) => PropertyDescriptor | undefined;
  324. ObjectCreate(o: object|null, properties?: PropertyDescriptorMap&ThisType<any>): any;
  325. ArraySlice(start?: number, end?: number): any[];
  326. patchClass: (className: string) => void;
  327. wrapWithCurrentZone: (callback: any, source: string) => any;
  328. filterProperties: (target: any, onProperties: string[], ignoreProperties: any[]) => string[];
  329. attachOriginToPatched: (target: any, origin: any) => void;
  330. _redefineProperty: (target: any, callback: string, desc: any) => void;
  331. patchCallbacks:
  332. (api: _ZonePrivate, target: any, targetName: string, method: string,
  333. callbacks: string[]) => void;
  334. getGlobalObjects: () => {
  335. globalSources: any, zoneSymbolEventNames: any, eventNames: string[], isBrowser: boolean,
  336. isMix: boolean, isNode: boolean, TRUE_STR: string, FALSE_STR: string,
  337. ZONE_SYMBOL_PREFIX: string, ADD_EVENT_LISTENER_STR: string,
  338. REMOVE_EVENT_LISTENER_STR: string
  339. } | undefined;
  340. }
  341. /** @internal */
  342. interface _ZoneFrame {
  343. parent: _ZoneFrame|null;
  344. zone: Zone;
  345. }
  346. interface UncaughtPromiseError extends Error {
  347. zone: Zone;
  348. task: Task;
  349. promise: Promise<any>;
  350. rejection: any;
  351. }
  352. /**
  353. * Provides a way to configure the interception of zone events.
  354. *
  355. * Only the `name` property is required (all other are optional).
  356. */
  357. interface ZoneSpec {
  358. /**
  359. * The name of the zone. Useful when debugging Zones.
  360. */
  361. name: string;
  362. /**
  363. * A set of properties to be associated with Zone. Use [Zone.get] to retrieve them.
  364. */
  365. properties?: {[key: string]: any};
  366. /**
  367. * Allows the interception of zone forking.
  368. *
  369. * When the zone is being forked, the request is forwarded to this method for interception.
  370. *
  371. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  372. * @param currentZone The current [Zone] where the current interceptor has been declared.
  373. * @param targetZone The [Zone] which originally received the request.
  374. * @param zoneSpec The argument passed into the `fork` method.
  375. */
  376. onFork?:
  377. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  378. zoneSpec: ZoneSpec) => Zone;
  379. /**
  380. * Allows interception of the wrapping of the callback.
  381. *
  382. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  383. * @param currentZone The current [Zone] where the current interceptor has been declared.
  384. * @param targetZone The [Zone] which originally received the request.
  385. * @param delegate The argument passed into the `wrap` method.
  386. * @param source The argument passed into the `wrap` method.
  387. */
  388. onIntercept?:
  389. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
  390. source: string) => Function;
  391. /**
  392. * Allows interception of the callback invocation.
  393. *
  394. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  395. * @param currentZone The current [Zone] where the current interceptor has been declared.
  396. * @param targetZone The [Zone] which originally received the request.
  397. * @param delegate The argument passed into the `run` method.
  398. * @param applyThis The argument passed into the `run` method.
  399. * @param applyArgs The argument passed into the `run` method.
  400. * @param source The argument passed into the `run` method.
  401. */
  402. onInvoke?:
  403. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
  404. applyThis: any, applyArgs?: any[], source?: string) => any;
  405. /**
  406. * Allows interception of the error handling.
  407. *
  408. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  409. * @param currentZone The current [Zone] where the current interceptor has been declared.
  410. * @param targetZone The [Zone] which originally received the request.
  411. * @param error The argument passed into the `handleError` method.
  412. */
  413. onHandleError?:
  414. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  415. error: any) => boolean;
  416. /**
  417. * Allows interception of task scheduling.
  418. *
  419. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  420. * @param currentZone The current [Zone] where the current interceptor has been declared.
  421. * @param targetZone The [Zone] which originally received the request.
  422. * @param task The argument passed into the `scheduleTask` method.
  423. */
  424. onScheduleTask?:
  425. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => Task;
  426. onInvokeTask?:
  427. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
  428. applyThis: any, applyArgs?: any[]) => any;
  429. /**
  430. * Allows interception of task cancellation.
  431. *
  432. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  433. * @param currentZone The current [Zone] where the current interceptor has been declared.
  434. * @param targetZone The [Zone] which originally received the request.
  435. * @param task The argument passed into the `cancelTask` method.
  436. */
  437. onCancelTask?:
  438. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => any;
  439. /**
  440. * Notifies of changes to the task queue empty status.
  441. *
  442. * @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
  443. * @param currentZone The current [Zone] where the current interceptor has been declared.
  444. * @param targetZone The [Zone] which originally received the request.
  445. * @param hasTaskState
  446. */
  447. onHasTask?:
  448. (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
  449. hasTaskState: HasTaskState) => void;
  450. }
  451. /**
  452. * A delegate when intercepting zone operations.
  453. *
  454. * A ZoneDelegate is needed because a child zone can't simply invoke a method on a parent zone. For
  455. * example a child zone wrap can't just call parent zone wrap. Doing so would create a callback
  456. * which is bound to the parent zone. What we are interested in is intercepting the callback before
  457. * it is bound to any zone. Furthermore, we also need to pass the targetZone (zone which received
  458. * the original request) to the delegate.
  459. *
  460. * The ZoneDelegate methods mirror those of Zone with an addition of extra targetZone argument in
  461. * the method signature. (The original Zone which received the request.) Some methods are renamed
  462. * to prevent confusion, because they have slightly different semantics and arguments.
  463. *
  464. * - `wrap` => `intercept`: The `wrap` method delegates to `intercept`. The `wrap` method returns
  465. * a callback which will run in a given zone, where as intercept allows wrapping the callback
  466. * so that additional code can be run before and after, but does not associate the callback
  467. * with the zone.
  468. * - `run` => `invoke`: The `run` method delegates to `invoke` to perform the actual execution of
  469. * the callback. The `run` method switches to new zone; saves and restores the `Zone.current`;
  470. * and optionally performs error handling. The invoke is not responsible for error handling,
  471. * or zone management.
  472. *
  473. * Not every method is usually overwritten in the child zone, for this reason the ZoneDelegate
  474. * stores the closest zone which overwrites this behavior along with the closest ZoneSpec.
  475. *
  476. * NOTE: We have tried to make this API analogous to Event bubbling with target and current
  477. * properties.
  478. *
  479. * Note: The ZoneDelegate treats ZoneSpec as class. This allows the ZoneSpec to use its `this` to
  480. * store internal state.
  481. */
  482. interface ZoneDelegate {
  483. zone: Zone;
  484. fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;
  485. intercept(targetZone: Zone, callback: Function, source: string): Function;
  486. invoke(targetZone: Zone, callback: Function, applyThis?: any, applyArgs?: any[], source?: string):
  487. any;
  488. handleError(targetZone: Zone, error: any): boolean;
  489. scheduleTask(targetZone: Zone, task: Task): Task;
  490. invokeTask(targetZone: Zone, task: Task, applyThis?: any, applyArgs?: any[]): any;
  491. cancelTask(targetZone: Zone, task: Task): any;
  492. hasTask(targetZone: Zone, isEmpty: HasTaskState): void;
  493. }
  494. type HasTaskState = {
  495. microTask: boolean; macroTask: boolean; eventTask: boolean; change: TaskType;
  496. };
  497. /**
  498. * Task type: `microTask`, `macroTask`, `eventTask`.
  499. */
  500. type TaskType = 'microTask'|'macroTask'|'eventTask';
  501. /**
  502. * Task type: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, 'unknown'.
  503. */
  504. type TaskState = 'notScheduled'|'scheduling'|'scheduled'|'running'|'canceling'|'unknown';
  505. /**
  506. */
  507. interface TaskData {
  508. /**
  509. * A periodic [MacroTask] is such which get automatically rescheduled after it is executed.
  510. */
  511. isPeriodic?: boolean;
  512. /**
  513. * Delay in milliseconds when the Task will run.
  514. */
  515. delay?: number;
  516. /**
  517. * identifier returned by the native setTimeout.
  518. */
  519. handleId?: number;
  520. }
  521. /**
  522. * Represents work which is executed with a clean stack.
  523. *
  524. * Tasks are used in Zones to mark work which is performed on clean stack frame. There are three
  525. * kinds of task. [MicroTask], [MacroTask], and [EventTask].
  526. *
  527. * A JS VM can be modeled as a [MicroTask] queue, [MacroTask] queue, and [EventTask] set.
  528. *
  529. * - [MicroTask] queue represents a set of tasks which are executing right after the current stack
  530. * frame becomes clean and before a VM yield. All [MicroTask]s execute in order of insertion
  531. * before VM yield and the next [MacroTask] is executed.
  532. * - [MacroTask] queue represents a set of tasks which are executed one at a time after each VM
  533. * yield. The queue is ordered by time, and insertions can happen in any location.
  534. * - [EventTask] is a set of tasks which can at any time be inserted to the end of the [MacroTask]
  535. * queue. This happens when the event fires.
  536. *
  537. */
  538. interface Task {
  539. /**
  540. * Task type: `microTask`, `macroTask`, `eventTask`.
  541. */
  542. type: TaskType;
  543. /**
  544. * Task state: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, `unknown`.
  545. */
  546. state: TaskState;
  547. /**
  548. * Debug string representing the API which requested the scheduling of the task.
  549. */
  550. source: string;
  551. /**
  552. * The Function to be used by the VM upon entering the [Task]. This function will delegate to
  553. * [Zone.runTask] and delegate to `callback`.
  554. */
  555. invoke: Function;
  556. /**
  557. * Function which needs to be executed by the Task after the [Zone.currentTask] has been set to
  558. * the current task.
  559. */
  560. callback: Function;
  561. /**
  562. * Task specific options associated with the current task. This is passed to the `scheduleFn`.
  563. */
  564. data?: TaskData;
  565. /**
  566. * Represents the default work which needs to be done to schedule the Task by the VM.
  567. *
  568. * A zone may choose to intercept this function and perform its own scheduling.
  569. */
  570. scheduleFn?: (task: Task) => void;
  571. /**
  572. * Represents the default work which needs to be done to un-schedule the Task from the VM. Not all
  573. * Tasks are cancelable, and therefore this method is optional.
  574. *
  575. * A zone may chose to intercept this function and perform its own un-scheduling.
  576. */
  577. cancelFn?: (task: Task) => void;
  578. /**
  579. * @type {Zone} The zone which will be used to invoke the `callback`. The Zone is captured
  580. * at the time of Task creation.
  581. */
  582. readonly zone: Zone;
  583. /**
  584. * Number of times the task has been executed, or -1 if canceled.
  585. */
  586. runCount: number;
  587. /**
  588. * Cancel the scheduling request. This method can be called from `ZoneSpec.onScheduleTask` to
  589. * cancel the current scheduling interception. Once canceled the task can be discarded or
  590. * rescheduled using `Zone.scheduleTask` on a different zone.
  591. */
  592. cancelScheduleRequest(): void;
  593. }
  594. interface MicroTask extends Task {
  595. type: 'microTask';
  596. }
  597. interface MacroTask extends Task {
  598. type: 'macroTask';
  599. }
  600. interface EventTask extends Task {
  601. type: 'eventTask';
  602. }
  603. /** @internal */
  604. type AmbientZone = Zone;
  605. /** @internal */
  606. type AmbientZoneDelegate = ZoneDelegate;
  607. const Zone: ZoneType = (function(global: any) {
  608. const performance: {mark(name: string): void; measure(name: string, label: string): void;} =
  609. global['performance'];
  610. function mark(name: string) {
  611. performance && performance['mark'] && performance['mark'](name);
  612. }
  613. function performanceMeasure(name: string, label: string) {
  614. performance && performance['measure'] && performance['measure'](name, label);
  615. }
  616. mark('Zone');
  617. const checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
  618. if (global['Zone']) {
  619. // if global['Zone'] already exists (maybe zone.js was already loaded or
  620. // some other lib also registered a global object named Zone), we may need
  621. // to throw an error, but sometimes user may not want this error.
  622. // For example,
  623. // we have two web pages, page1 includes zone.js, page2 doesn't.
  624. // and the 1st time user load page1 and page2, everything work fine,
  625. // but when user load page2 again, error occurs because global['Zone'] already exists.
  626. // so we add a flag to let user choose whether to throw this error or not.
  627. // By default, if existing Zone is from zone.js, we will not throw the error.
  628. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  629. throw new Error('Zone already loaded.');
  630. } else {
  631. return global['Zone'];
  632. }
  633. }
  634. class Zone implements AmbientZone {
  635. static __symbol__: (name: string) => string = __symbol__;
  636. static assertZonePatched() {
  637. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  638. throw new Error(
  639. 'Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  640. 'has been overwritten.\n' +
  641. 'Most likely cause is that a Promise polyfill has been loaded ' +
  642. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  643. 'If you must load one, do so before loading zone.js.)');
  644. }
  645. }
  646. static get root(): AmbientZone {
  647. let zone = Zone.current;
  648. while (zone.parent) {
  649. zone = zone.parent;
  650. }
  651. return zone;
  652. }
  653. static get current(): AmbientZone {
  654. return _currentZoneFrame.zone;
  655. }
  656. static get currentTask(): Task|null {
  657. return _currentTask;
  658. }
  659. static __load_patch(name: string, fn: _PatchFn): void {
  660. if (patches.hasOwnProperty(name)) {
  661. if (checkDuplicate) {
  662. throw Error('Already loaded patch: ' + name);
  663. }
  664. } else if (!global['__Zone_disable_' + name]) {
  665. const perfName = 'Zone:' + name;
  666. mark(perfName);
  667. patches[name] = fn(global, Zone, _api);
  668. performanceMeasure(perfName, perfName);
  669. }
  670. }
  671. public get parent(): AmbientZone|null {
  672. return this._parent;
  673. }
  674. public get name(): string {
  675. return this._name;
  676. }
  677. private _parent: Zone|null;
  678. private _name: string;
  679. private _properties: {[key: string]: any};
  680. private _zoneDelegate: ZoneDelegate;
  681. constructor(parent: Zone|null, zoneSpec: ZoneSpec|null) {
  682. this._parent = parent;
  683. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  684. this._properties = zoneSpec && zoneSpec.properties || {};
  685. this._zoneDelegate =
  686. new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  687. }
  688. public get(key: string): any {
  689. const zone: Zone = this.getZoneWith(key) as Zone;
  690. if (zone) return zone._properties[key];
  691. }
  692. public getZoneWith(key: string): AmbientZone|null {
  693. let current: Zone|null = this;
  694. while (current) {
  695. if (current._properties.hasOwnProperty(key)) {
  696. return current;
  697. }
  698. current = current._parent;
  699. }
  700. return null;
  701. }
  702. public fork(zoneSpec: ZoneSpec): AmbientZone {
  703. if (!zoneSpec) throw new Error('ZoneSpec required!');
  704. return this._zoneDelegate.fork(this, zoneSpec);
  705. }
  706. public wrap<T extends Function>(callback: T, source: string): T {
  707. if (typeof callback !== 'function') {
  708. throw new Error('Expecting function got: ' + callback);
  709. }
  710. const _callback = this._zoneDelegate.intercept(this, callback, source);
  711. const zone: Zone = this;
  712. return function() {
  713. return zone.runGuarded(_callback, (this as any), <any>arguments, source);
  714. } as any as T;
  715. }
  716. public run(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
  717. public run<T>(
  718. callback: (...args: any[]) => T, applyThis?: any, applyArgs?: any[], source?: string): T {
  719. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  720. try {
  721. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  722. } finally {
  723. _currentZoneFrame = _currentZoneFrame.parent!;
  724. }
  725. }
  726. public runGuarded(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
  727. public runGuarded<T>(
  728. callback: (...args: any[]) => T, applyThis: any = null, applyArgs?: any[],
  729. source?: string) {
  730. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  731. try {
  732. try {
  733. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  734. } catch (error) {
  735. if (this._zoneDelegate.handleError(this, error)) {
  736. throw error;
  737. }
  738. }
  739. } finally {
  740. _currentZoneFrame = _currentZoneFrame.parent!;
  741. }
  742. }
  743. runTask(task: Task, applyThis?: any, applyArgs?: any): any {
  744. if (task.zone != this) {
  745. throw new Error(
  746. 'A task can only be run in the zone of creation! (Creation: ' +
  747. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  748. }
  749. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  750. // will run in notScheduled(canceled) state, we should not try to
  751. // run such kind of task but just return
  752. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  753. return;
  754. }
  755. const reEntryGuard = task.state != running;
  756. reEntryGuard && (task as ZoneTask<any>)._transitionTo(running, scheduled);
  757. task.runCount++;
  758. const previousTask = _currentTask;
  759. _currentTask = task;
  760. _currentZoneFrame = {parent: _currentZoneFrame, zone: this};
  761. try {
  762. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  763. task.cancelFn = undefined;
  764. }
  765. try {
  766. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  767. } catch (error) {
  768. if (this._zoneDelegate.handleError(this, error)) {
  769. throw error;
  770. }
  771. }
  772. } finally {
  773. // if the task's state is notScheduled or unknown, then it has already been cancelled
  774. // we should not reset the state to scheduled
  775. if (task.state !== notScheduled && task.state !== unknown) {
  776. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  777. reEntryGuard && (task as ZoneTask<any>)._transitionTo(scheduled, running);
  778. } else {
  779. task.runCount = 0;
  780. this._updateTaskCount(task as ZoneTask<any>, -1);
  781. reEntryGuard &&
  782. (task as ZoneTask<any>)._transitionTo(notScheduled, running, notScheduled);
  783. }
  784. }
  785. _currentZoneFrame = _currentZoneFrame.parent!;
  786. _currentTask = previousTask;
  787. }
  788. }
  789. scheduleTask<T extends Task>(task: T): T {
  790. if (task.zone && task.zone !== this) {
  791. // check if the task was rescheduled, the newZone
  792. // should not be the children of the original zone
  793. let newZone: any = this;
  794. while (newZone) {
  795. if (newZone === task.zone) {
  796. throw Error(`can not reschedule task to ${
  797. this.name} which is descendants of the original zone ${task.zone.name}`);
  798. }
  799. newZone = newZone.parent;
  800. }
  801. }
  802. (task as any as ZoneTask<any>)._transitionTo(scheduling, notScheduled);
  803. const zoneDelegates: ZoneDelegate[] = [];
  804. (task as any as ZoneTask<any>)._zoneDelegates = zoneDelegates;
  805. (task as any as ZoneTask<any>)._zone = this;
  806. try {
  807. task = this._zoneDelegate.scheduleTask(this, task) as T;
  808. } catch (err) {
  809. // should set task's state to unknown when scheduleTask throw error
  810. // because the err may from reschedule, so the fromState maybe notScheduled
  811. (task as any as ZoneTask<any>)._transitionTo(unknown, scheduling, notScheduled);
  812. // TODO: @JiaLiPassion, should we check the result from handleError?
  813. this._zoneDelegate.handleError(this, err);
  814. throw err;
  815. }
  816. if ((task as any as ZoneTask<any>)._zoneDelegates === zoneDelegates) {
  817. // we have to check because internally the delegate can reschedule the task.
  818. this._updateTaskCount(task as any as ZoneTask<any>, 1);
  819. }
  820. if ((task as any as ZoneTask<any>).state == scheduling) {
  821. (task as any as ZoneTask<any>)._transitionTo(scheduled, scheduling);
  822. }
  823. return task;
  824. }
  825. scheduleMicroTask(
  826. source: string, callback: Function, data?: TaskData,
  827. customSchedule?: (task: Task) => void): MicroTask {
  828. return this.scheduleTask(
  829. new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  830. }
  831. scheduleMacroTask(
  832. source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
  833. customCancel?: (task: Task) => void): MacroTask {
  834. return this.scheduleTask(
  835. new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  836. }
  837. scheduleEventTask(
  838. source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
  839. customCancel?: (task: Task) => void): EventTask {
  840. return this.scheduleTask(
  841. new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  842. }
  843. cancelTask(task: Task): any {
  844. if (task.zone != this)
  845. throw new Error(
  846. 'A task can only be cancelled in the zone of creation! (Creation: ' +
  847. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  848. (task as ZoneTask<any>)._transitionTo(canceling, scheduled, running);
  849. try {
  850. this._zoneDelegate.cancelTask(this, task);
  851. } catch (err) {
  852. // if error occurs when cancelTask, transit the state to unknown
  853. (task as ZoneTask<any>)._transitionTo(unknown, canceling);
  854. this._zoneDelegate.handleError(this, err);
  855. throw err;
  856. }
  857. this._updateTaskCount(task as ZoneTask<any>, -1);
  858. (task as ZoneTask<any>)._transitionTo(notScheduled, canceling);
  859. task.runCount = 0;
  860. return task;
  861. }
  862. private _updateTaskCount(task: ZoneTask<any>, count: number) {
  863. const zoneDelegates = task._zoneDelegates!;
  864. if (count == -1) {
  865. task._zoneDelegates = null;
  866. }
  867. for (let i = 0; i < zoneDelegates.length; i++) {
  868. zoneDelegates[i]._updateTaskCount(task.type, count);
  869. }
  870. }
  871. }
  872. const DELEGATE_ZS: ZoneSpec = {
  873. name: '',
  874. onHasTask:
  875. (delegate: AmbientZoneDelegate, _: AmbientZone, target: AmbientZone,
  876. hasTaskState: HasTaskState): void => delegate.hasTask(target, hasTaskState),
  877. onScheduleTask:
  878. (delegate: AmbientZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task): Task =>
  879. delegate.scheduleTask(target, task),
  880. onInvokeTask:
  881. (delegate: AmbientZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task,
  882. applyThis: any, applyArgs: any): any =>
  883. delegate.invokeTask(target, task, applyThis, applyArgs),
  884. onCancelTask: (delegate: AmbientZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task):
  885. any => delegate.cancelTask(target, task)
  886. };
  887. class ZoneDelegate implements AmbientZoneDelegate {
  888. public zone: Zone;
  889. private _taskCounts: {microTask: number,
  890. macroTask: number,
  891. eventTask: number} = {'microTask': 0, 'macroTask': 0, 'eventTask': 0};
  892. private _parentDelegate: ZoneDelegate|null;
  893. private _forkDlgt: ZoneDelegate|null;
  894. private _forkZS: ZoneSpec|null;
  895. private _forkCurrZone: Zone|null;
  896. private _interceptDlgt: ZoneDelegate|null;
  897. private _interceptZS: ZoneSpec|null;
  898. private _interceptCurrZone: Zone|null;
  899. private _invokeDlgt: ZoneDelegate|null;
  900. private _invokeZS: ZoneSpec|null;
  901. private _invokeCurrZone: Zone|null;
  902. private _handleErrorDlgt: ZoneDelegate|null;
  903. private _handleErrorZS: ZoneSpec|null;
  904. private _handleErrorCurrZone: Zone|null;
  905. private _scheduleTaskDlgt: ZoneDelegate|null;
  906. private _scheduleTaskZS: ZoneSpec|null;
  907. private _scheduleTaskCurrZone: Zone|null;
  908. private _invokeTaskDlgt: ZoneDelegate|null;
  909. private _invokeTaskZS: ZoneSpec|null;
  910. private _invokeTaskCurrZone: Zone|null;
  911. private _cancelTaskDlgt: ZoneDelegate|null;
  912. private _cancelTaskZS: ZoneSpec|null;
  913. private _cancelTaskCurrZone: Zone|null;
  914. private _hasTaskDlgt: ZoneDelegate|null;
  915. private _hasTaskDlgtOwner: ZoneDelegate|null;
  916. private _hasTaskZS: ZoneSpec|null;
  917. private _hasTaskCurrZone: Zone|null;
  918. constructor(zone: Zone, parentDelegate: ZoneDelegate|null, zoneSpec: ZoneSpec|null) {
  919. this.zone = zone;
  920. this._parentDelegate = parentDelegate;
  921. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate!._forkZS);
  922. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate!._forkDlgt);
  923. this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate!.zone);
  924. this._interceptZS =
  925. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate!._interceptZS);
  926. this._interceptDlgt =
  927. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate!._interceptDlgt);
  928. this._interceptCurrZone =
  929. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate!.zone);
  930. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate!._invokeZS);
  931. this._invokeDlgt =
  932. zoneSpec && (zoneSpec.onInvoke ? parentDelegate! : parentDelegate!._invokeDlgt);
  933. this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate!.zone);
  934. this._handleErrorZS =
  935. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate!._handleErrorZS);
  936. this._handleErrorDlgt =
  937. zoneSpec && (zoneSpec.onHandleError ? parentDelegate! : parentDelegate!._handleErrorDlgt);
  938. this._handleErrorCurrZone =
  939. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate!.zone);
  940. this._scheduleTaskZS =
  941. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate!._scheduleTaskZS);
  942. this._scheduleTaskDlgt = zoneSpec &&
  943. (zoneSpec.onScheduleTask ? parentDelegate! : parentDelegate!._scheduleTaskDlgt);
  944. this._scheduleTaskCurrZone =
  945. zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate!.zone);
  946. this._invokeTaskZS =
  947. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate!._invokeTaskZS);
  948. this._invokeTaskDlgt =
  949. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate! : parentDelegate!._invokeTaskDlgt);
  950. this._invokeTaskCurrZone =
  951. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate!.zone);
  952. this._cancelTaskZS =
  953. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate!._cancelTaskZS);
  954. this._cancelTaskDlgt =
  955. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate! : parentDelegate!._cancelTaskDlgt);
  956. this._cancelTaskCurrZone =
  957. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate!.zone);
  958. this._hasTaskZS = null;
  959. this._hasTaskDlgt = null;
  960. this._hasTaskDlgtOwner = null;
  961. this._hasTaskCurrZone = null;
  962. const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  963. const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  964. if (zoneSpecHasTask || parentHasTask) {
  965. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  966. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  967. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  968. this._hasTaskDlgt = parentDelegate;
  969. this._hasTaskDlgtOwner = this;
  970. this._hasTaskCurrZone = zone;
  971. if (!zoneSpec!.onScheduleTask) {
  972. this._scheduleTaskZS = DELEGATE_ZS;
  973. this._scheduleTaskDlgt = parentDelegate!;
  974. this._scheduleTaskCurrZone = this.zone;
  975. }
  976. if (!zoneSpec!.onInvokeTask) {
  977. this._invokeTaskZS = DELEGATE_ZS;
  978. this._invokeTaskDlgt = parentDelegate!;
  979. this._invokeTaskCurrZone = this.zone;
  980. }
  981. if (!zoneSpec!.onCancelTask) {
  982. this._cancelTaskZS = DELEGATE_ZS;
  983. this._cancelTaskDlgt = parentDelegate!;
  984. this._cancelTaskCurrZone = this.zone;
  985. }
  986. }
  987. }
  988. fork(targetZone: Zone, zoneSpec: ZoneSpec): AmbientZone {
  989. return this._forkZS ? this._forkZS.onFork!(this._forkDlgt!, this.zone, targetZone, zoneSpec) :
  990. new Zone(targetZone, zoneSpec);
  991. }
  992. intercept(targetZone: Zone, callback: Function, source: string): Function {
  993. return this._interceptZS ?
  994. this._interceptZS.onIntercept!
  995. (this._interceptDlgt!, this._interceptCurrZone!, targetZone, callback, source) :
  996. callback;
  997. }
  998. invoke(
  999. targetZone: Zone, callback: Function, applyThis: any, applyArgs?: any[],
  1000. source?: string): any {
  1001. return this._invokeZS ? this._invokeZS.onInvoke!
  1002. (this._invokeDlgt!, this._invokeCurrZone!, targetZone, callback,
  1003. applyThis, applyArgs, source) :
  1004. callback.apply(applyThis, applyArgs);
  1005. }
  1006. handleError(targetZone: Zone, error: any): boolean {
  1007. return this._handleErrorZS ?
  1008. this._handleErrorZS.onHandleError!
  1009. (this._handleErrorDlgt!, this._handleErrorCurrZone!, targetZone, error) :
  1010. true;
  1011. }
  1012. scheduleTask(targetZone: Zone, task: Task): Task {
  1013. let returnTask: ZoneTask<any> = task as ZoneTask<any>;
  1014. if (this._scheduleTaskZS) {
  1015. if (this._hasTaskZS) {
  1016. returnTask._zoneDelegates!.push(this._hasTaskDlgtOwner!);
  1017. }
  1018. returnTask = this._scheduleTaskZS.onScheduleTask!
  1019. (this._scheduleTaskDlgt!, this._scheduleTaskCurrZone!, targetZone, task) as
  1020. ZoneTask<any>;
  1021. if (!returnTask) returnTask = task as ZoneTask<any>;
  1022. } else {
  1023. if (task.scheduleFn) {
  1024. task.scheduleFn(task);
  1025. } else if (task.type == microTask) {
  1026. scheduleMicroTask(<MicroTask>task);
  1027. } else {
  1028. throw new Error('Task is missing scheduleFn.');
  1029. }
  1030. }
  1031. return returnTask;
  1032. }
  1033. invokeTask(targetZone: Zone, task: Task, applyThis: any, applyArgs?: any[]): any {
  1034. return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask!
  1035. (this._invokeTaskDlgt!, this._invokeTaskCurrZone!, targetZone,
  1036. task, applyThis, applyArgs) :
  1037. task.callback.apply(applyThis, applyArgs);
  1038. }
  1039. cancelTask(targetZone: Zone, task: Task): any {
  1040. let value: any;
  1041. if (this._cancelTaskZS) {
  1042. value = this._cancelTaskZS.onCancelTask!
  1043. (this._cancelTaskDlgt!, this._cancelTaskCurrZone!, targetZone, task);
  1044. } else {
  1045. if (!task.cancelFn) {
  1046. throw Error('Task is not cancelable');
  1047. }
  1048. value = task.cancelFn(task);
  1049. }
  1050. return value;
  1051. }
  1052. hasTask(targetZone: Zone, isEmpty: HasTaskState) {
  1053. // hasTask should not throw error so other ZoneDelegate
  1054. // can still trigger hasTask callback
  1055. try {
  1056. this._hasTaskZS &&
  1057. this._hasTaskZS.onHasTask!
  1058. (this._hasTaskDlgt!, this._hasTaskCurrZone!, targetZone, isEmpty);
  1059. } catch (err) {
  1060. this.handleError(targetZone, err);
  1061. }
  1062. }
  1063. _updateTaskCount(type: TaskType, count: number) {
  1064. const counts = this._taskCounts;
  1065. const prev = counts[type];
  1066. const next = counts[type] = prev + count;
  1067. if (next < 0) {
  1068. throw new Error('More tasks executed then were scheduled.');
  1069. }
  1070. if (prev == 0 || next == 0) {
  1071. const isEmpty: HasTaskState = {
  1072. microTask: counts['microTask'] > 0,
  1073. macroTask: counts['macroTask'] > 0,
  1074. eventTask: counts['eventTask'] > 0,
  1075. change: type
  1076. };
  1077. this.hasTask(this.zone, isEmpty);
  1078. }
  1079. }
  1080. }
  1081. class ZoneTask<T extends TaskType> implements Task {
  1082. public type: T;
  1083. public source: string;
  1084. public invoke: Function;
  1085. public callback: Function;
  1086. public data: TaskData|undefined;
  1087. public scheduleFn: ((task: Task) => void)|undefined;
  1088. public cancelFn: ((task: Task) => void)|undefined;
  1089. _zone: Zone|null = null;
  1090. public runCount: number = 0;
  1091. _zoneDelegates: ZoneDelegate[]|null = null;
  1092. _state: TaskState = 'notScheduled';
  1093. constructor(
  1094. type: T, source: string, callback: Function, options: TaskData|undefined,
  1095. scheduleFn: ((task: Task) => void)|undefined, cancelFn: ((task: Task) => void)|undefined) {
  1096. this.type = type;
  1097. this.source = source;
  1098. this.data = options;
  1099. this.scheduleFn = scheduleFn;
  1100. this.cancelFn = cancelFn;
  1101. this.callback = callback;
  1102. const self = this;
  1103. // TODO: @JiaLiPassion options should have interface
  1104. if (type === eventTask && options && (options as any).useG) {
  1105. this.invoke = ZoneTask.invokeTask;
  1106. } else {
  1107. this.invoke = function() {
  1108. return ZoneTask.invokeTask.call(global, self, this, <any>arguments);
  1109. };
  1110. }
  1111. }
  1112. static invokeTask(task: any, target: any, args: any): any {
  1113. if (!task) {
  1114. task = this;
  1115. }
  1116. _numberOfNestedTaskFrames++;
  1117. try {
  1118. task.runCount++;
  1119. return task.zone.runTask(task, target, args);
  1120. } finally {
  1121. if (_numberOfNestedTaskFrames == 1) {
  1122. drainMicroTaskQueue();
  1123. }
  1124. _numberOfNestedTaskFrames--;
  1125. }
  1126. }
  1127. get zone(): Zone {
  1128. return this._zone!;
  1129. }
  1130. get state(): TaskState {
  1131. return this._state;
  1132. }
  1133. public cancelScheduleRequest() {
  1134. this._transitionTo(notScheduled, scheduling);
  1135. }
  1136. _transitionTo(toState: TaskState, fromState1: TaskState, fromState2?: TaskState) {
  1137. if (this._state === fromState1 || this._state === fromState2) {
  1138. this._state = toState;
  1139. if (toState == notScheduled) {
  1140. this._zoneDelegates = null;
  1141. }
  1142. } else {
  1143. throw new Error(`${this.type} '${this.source}': can not transition to '${
  1144. toState}', expecting state '${fromState1}'${
  1145. fromState2 ? ' or \'' + fromState2 + '\'' : ''}, was '${this._state}'.`);
  1146. }
  1147. }
  1148. public toString() {
  1149. if (this.data && typeof this.data.handleId !== 'undefined') {
  1150. return this.data.handleId.toString();
  1151. } else {
  1152. return Object.prototype.toString.call(this);
  1153. }
  1154. }
  1155. // add toJSON method to prevent cyclic error when
  1156. // call JSON.stringify(zoneTask)
  1157. public toJSON() {
  1158. return {
  1159. type: this.type,
  1160. state: this.state,
  1161. source: this.source,
  1162. zone: this.zone.name,
  1163. runCount: this.runCount
  1164. };
  1165. }
  1166. }
  1167. //////////////////////////////////////////////////////
  1168. //////////////////////////////////////////////////////
  1169. /// MICROTASK QUEUE
  1170. //////////////////////////////////////////////////////
  1171. //////////////////////////////////////////////////////
  1172. const symbolSetTimeout = __symbol__('setTimeout');
  1173. const symbolPromise = __symbol__('Promise');
  1174. const symbolThen = __symbol__('then');
  1175. let _microTaskQueue: Task[] = [];
  1176. let _isDrainingMicrotaskQueue: boolean = false;
  1177. let nativeMicroTaskQueuePromise: any;
  1178. function scheduleMicroTask(task?: MicroTask) {
  1179. // if we are not running in any task, and there has not been anything scheduled
  1180. // we must bootstrap the initial task creation by manually scheduling the drain
  1181. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  1182. // We are not running in Task, so we need to kickstart the microtask queue.
  1183. if (!nativeMicroTaskQueuePromise) {
  1184. if (global[symbolPromise]) {
  1185. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  1186. }
  1187. }
  1188. if (nativeMicroTaskQueuePromise) {
  1189. let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  1190. if (!nativeThen) {
  1191. // native Promise is not patchable, we need to use `then` directly
  1192. // issue 1078
  1193. nativeThen = nativeMicroTaskQueuePromise['then'];
  1194. }
  1195. nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
  1196. } else {
  1197. global[symbolSetTimeout](drainMicroTaskQueue, 0);
  1198. }
  1199. }
  1200. task && _microTaskQueue.push(task);
  1201. }
  1202. function drainMicroTaskQueue() {
  1203. if (!_isDrainingMicrotaskQueue) {
  1204. _isDrainingMicrotaskQueue = true;
  1205. while (_microTaskQueue.length) {
  1206. const queue = _microTaskQueue;
  1207. _microTaskQueue = [];
  1208. for (let i = 0; i < queue.length; i++) {
  1209. const task = queue[i];
  1210. try {
  1211. task.zone.runTask(task, null, null);
  1212. } catch (error) {
  1213. _api.onUnhandledError(error);
  1214. }
  1215. }
  1216. }
  1217. _api.microtaskDrainDone();
  1218. _isDrainingMicrotaskQueue = false;
  1219. }
  1220. }
  1221. //////////////////////////////////////////////////////
  1222. //////////////////////////////////////////////////////
  1223. /// BOOTSTRAP
  1224. //////////////////////////////////////////////////////
  1225. //////////////////////////////////////////////////////
  1226. const NO_ZONE = {name: 'NO ZONE'};
  1227. const notScheduled: 'notScheduled' = 'notScheduled', scheduling: 'scheduling' = 'scheduling',
  1228. scheduled: 'scheduled' = 'scheduled', running: 'running' = 'running',
  1229. canceling: 'canceling' = 'canceling', unknown: 'unknown' = 'unknown';
  1230. const microTask: 'microTask' = 'microTask', macroTask: 'macroTask' = 'macroTask',
  1231. eventTask: 'eventTask' = 'eventTask';
  1232. const patches: {[key: string]: any} = {};
  1233. const _api: _ZonePrivate = {
  1234. symbol: __symbol__,
  1235. currentZoneFrame: () => _currentZoneFrame,
  1236. onUnhandledError: noop,
  1237. microtaskDrainDone: noop,
  1238. scheduleMicroTask: scheduleMicroTask,
  1239. showUncaughtError: () => !(Zone as any)[__symbol__('ignoreConsoleErrorUncaughtError')],
  1240. patchEventTarget: () => [],
  1241. patchOnProperties: noop,
  1242. patchMethod: () => noop,
  1243. bindArguments: () => [],
  1244. patchThen: () => noop,
  1245. patchMacroTask: () => noop,
  1246. setNativePromise: (NativePromise: any) => {
  1247. // sometimes NativePromise.resolve static function
  1248. // is not ready yet, (such as core-js/es6.promise)
  1249. // so we need to check here.
  1250. if (NativePromise && typeof NativePromise.resolve === 'function') {
  1251. nativeMicroTaskQueuePromise = NativePromise.resolve(0);
  1252. }
  1253. },
  1254. patchEventPrototype: () => noop,
  1255. isIEOrEdge: () => false,
  1256. getGlobalObjects: () => undefined,
  1257. ObjectDefineProperty: () => noop,
  1258. ObjectGetOwnPropertyDescriptor: () => undefined,
  1259. ObjectCreate: () => undefined,
  1260. ArraySlice: () => [],
  1261. patchClass: () => noop,
  1262. wrapWithCurrentZone: () => noop,
  1263. filterProperties: () => [],
  1264. attachOriginToPatched: () => noop,
  1265. _redefineProperty: () => noop,
  1266. patchCallbacks: () => noop
  1267. };
  1268. let _currentZoneFrame: _ZoneFrame = {parent: null, zone: new Zone(null, null)};
  1269. let _currentTask: Task|null = null;
  1270. let _numberOfNestedTaskFrames = 0;
  1271. function noop() {}
  1272. function __symbol__(name: string) {
  1273. return '__zone_symbol__' + name;
  1274. }
  1275. performanceMeasure('Zone', 'Zone');
  1276. return global['Zone'] = Zone;
  1277. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);