Commit graph

211 commits

Author SHA1 Message Date
arturovt
eddca4280b fix(zone.js): allow draining microtasks in Promise.then (through flag)
These changes are essentially the same as those introduced in
angular#45273, but they include backward compatibility
for applications that explicitly rely on the order in which microtasks are drained.

This is critically important for our code and other third-party code, which is
beyond our control, to work properly. If a microtask is scheduled within an event
listener to be executed "later", it should indeed be executed later and not synchronously,
as this would break the expected flow of code execution.

The simple code that reproduces the behavior that exists now:

```ts
Zone.current.fork({name: 'child'}).run(() => {
  const div = document.createElement('div');
  div.style.height = '200px';
  div.style.width = '200px';
  div.style.backgroundColor = 'red';
  document.body.appendChild(div);

  function listener() {
    Promise.resolve().then(() => {
      div.style.height = '400px';
    });
  }

  div.addEventListener('fakeEvent', listener);
  div.dispatchEvent(new Event('fakeEvent'));
  console.log(div.getBoundingClientRect().height); // 400
});
```

The code above logs 400 as the height, but it should actually log 200 because the
height is updated in a microtask within the event listener.

When using Angular with microfrontend applications, especially when other apps might be
using React, zone.js can disrupt the classical order of operations. For example, when using a
`react-component/trigger`, it schedules a microtask within an event listener using
`Promise.resolve().then(...)` to determine whether the event needs to be re-dispatched.
The event is re-dispatched when the layout has changed, which is why a microtask is used.

With this change, we introduce a global configuration flag,
`__zone_symbol__enable_native_microtask_draining`, to allow consumers to enable
microtask draining within a browser microtask.

This flag is necessary to prevent any breaking changes resulting from this modification.
The previous attempt to address this issue caused a significant number of failures in g3.
Therefore, we are hiding that fix behind the configuration flag.

Closes angular#44446
Closes angular#55590
Closes angular#51328

(cherry picked from commit fc6a7eea68)
2026-04-15 10:31:33 -04:00
Andrew Scott
fc557f0276 fix(zone.js): support passthrough of Promise.try API
When Zone patches Promise, it uses ZoneAwarePromise. The new Promise.try API was undefined on ZoneAwarePromise, making it unavailable when zone was present. This change gracefully passes through Promise.try to the native Promise implementation, if available, without patching it to execute in the right zone (our stance is not to add new patches but avoid destructively making new APIs unavailable).

Fixes #67057
2026-02-17 11:32:49 -08:00
Andrew Scott
48abe007d9 fix(zone.js): Support jasmine v6
This fixes the jasmine patch to ensure we are patching the private APIs
off of the right location, which changed in v6.

see 168ff0a751
2025-10-24 18:46:04 +02:00
Andrew Scott
ced2fa5253 refactor(zone.js): Improve missing proxy zone error for jest imported (#64497)
test functions

This improves the fakeAsync error message when importing it, describe,
etc from jest

We will not be further expanding the ZoneJS patches to support
additional use-cases.

fixes #47603

PR Close #64497
2025-10-22 23:26:23 +00:00
Matthieu Riegler
2e4659648a refactor(zone.js): remove legacy browser support (#63511)
This commit removes the support for legacy browsers.

BREAKING CHANGE: IE/Non-Chromium Edge are not supported anymore.

PR Close #63511
2025-10-16 14:58:45 +00:00
Rahul Kamat
a943e7cb05 refactor(core): Update async-test.ts to use globalThis polyfill (#57505)
This updates async-test to use globalThis instead of what it was using.

PR Close #57505
2025-09-16 15:10:04 +00:00
Joey Perrott
fe349827ef build: separate zone.js dependencies into their own directory (#63425)
Separate out zone.js dependencies

PR Close #63425
2025-09-05 12:52:55 -07:00
Joey Perrott
2fcafb65c5 build: rename defaults2.bzl to defaults.bzl (#63383)
Use defaults.bzl for the common macros

PR Close #63383
2025-08-25 15:45:01 -07:00
Matthieu Riegler
9aef481172 refactor(zone.js): remove unused jasmine globalerror monkey patching. (#63077)
This is for testing purposes for now. See discussion on the related issue.

fixes #63072

PR Close #63077
2025-08-11 16:41:09 -07:00
Andrew Scott
0a827f9284 refactor(zone.js): Add internal implementation for auto ticking fakeAsync (#62135)
Benefits of auto-ticking mock clocks have been described in other PRs,
such as https://github.com/jasmine/jasmine/pull/2042 and
https://github.com/sinonjs/fake-timers/pull/509. In short, `fakeAsync`
cannot work when some tasks are required to be truly async, such as XHRs
or observers like ResizeObserver. In addition, auto ticking mock clocks
can be applied to tests without the tests then needing to update
everything to manually flush timers.

PR Close #62135
2025-08-08 08:39:24 -07:00
Joey Perrott
cbc258eec8 build: remove ts_project_interop infrastructure (#62908)
Remove the interop macros and final usages

PR Close #62908
2025-07-31 09:12:58 +00:00
Joey Perrott
7c06aca4f0 build: move from using rollup to esbuild for bundling zone.js (#62775)
Use esbuild to bundle zone.js

PR Close #62775
2025-07-25 16:53:00 +02:00
Joey Perrott
dd02bfe743 build: migrate zone.js to use ts_project instead of ts_library (#62673)
Use ts_project instead of ts_library for building zone.js

PR Close #62673
2025-07-17 13:59:37 -04:00
Andrew Scott
3c216c1ec6 fix(zone.js): waitForAsync should pass args to the test function (#61755)
This ensures that test functions with arguments (e.g. `it.each` in jest)
are forwarded to the test function. This does not apply to jasmine,
which assumes the only arguments needed would be the `done` function.

fixes #61717

PR Close #61755
2025-06-09 11:22:22 -07:00
Andrew Scott
1ea39e050c refactor(zone.js): Add a withProxyZone helper that might be used for unpatched test frameworks (#61626)
As an alternative to monkey patching vitest, this change adds a method that could be used
for manually running functions inside a shared proxy zone. If used inocrrectly,
this would mean that
the `fakeAsync` closure may not capture all timers and microtasks if it
invokes things created in a zone that was already forked (e.g. creating
a component in a beforeEach:
2699dd6555/packages/zone.js/lib/jasmine/jasmine.ts (L363-L371))

PR Close #61626
2025-05-22 13:39:30 -07:00
Andrew Scott
ad8931cb49 fix(zone.js): classes that extend Error should retain cause property (#61599)
ZoneAwareError previously did not copy the cause property over to the
`this` object when an error extends the native error class.

PR Close #61599
2025-05-21 20:43:09 -07:00
Paul Gschwendtner
b71c35a6b5 refactor: update packages/core:{core,src} to ts_project (#61275)
Updates `packages/core:core` and `packages/core/src/...` to `ts_project`
of `rules_js`.

PR Close #61275
2025-05-14 12:01:51 +00:00
arturovt
2235699b65 refactor(zone.js): drop isIE checks (#61091)
This should not be considered as a breaking change, because Angular doesn't support IE.

PR Close #61091
2025-05-02 07:53:35 -07:00
arturovt
5f31c953ed refactor(zone.js): drop passive supported check (#58010)
https://caniuse.com/passive-event-listener
Passive event listeners are supported in all major evergreen browsers.
Thus, we don't need to check whether passives are supported.

PR Close #58010
2025-05-01 11:42:13 -07:00
Andrew Scott
962b59b14e fix(core): Ensure ComponentFixture does not duplicate error reporting from FakeAsync (#60104)
When using `fakeAsync`, if errors happen inside the Angular zone, they
are also handled by the fakeAsync machinery. Rethrowing errors from the
`NgZone.onError` subscription is not appropriate in this case because it
results in the error being thrown twice.

db2f2d99c8/packages/zone.js/lib/zone-spec/fake-async-test.ts (L783-L784)
db2f2d99c8/packages/zone.js/lib/zone-spec/fake-async-test.ts (L473-L478)

PR Close #60104
2025-02-26 11:56:18 -05:00
hawkgs
b9155b5121 docs: set syntax highlighting to the remaining Markdown code examples blocks (#59088)
There are some code blocks that slipped through the initial Regex-es.

Related to #59026

PR Close #59088
2025-01-14 15:14:02 -05:00
Johnson Chu
a6cdbec09f refactor: remove unnecessary TSLint rule flags (#59365)
There are many TSLint rule flags in the source code that have no effect, and they can be safely removed to keep the code clean.

PR Close #59365
2025-01-07 16:06:21 +00:00
Utku Gultopu
0f1c71869e docs: capitalize webpack with a lowercase W (#56812)
PR Close #56812
2024-11-26 22:24:11 +00:00
Costin Sin
2e54d6dea8 refactor(zone.js): Change the type of _taskCounts to an IndexSignature that can have keys (#51739)
named as the values of the `TaskType` type.

The Closure Compiler used at Google has a property renaming optimization
that can change the property names when minifying code. Having the
correct type helps the TSJS team that develops a tool to identfy
property renaming issues directly in TypeScript.

Signed-off-by: Costin Sin <sin.costinrobert@gmail.com>

PR Close #51739
2024-11-01 15:44:06 +00:00
arturovt
69763491c3 fix(zone.js): remove abort listener once fetch is settled (#57882)
This commit updates the `fetch` patch for zone.js. Currently, we're attaching an
`abort` event listener on the signal (when it's provided) and never removing it.
We should be good citizens and remove event listeners whenever objects need to be
properly collected. In Firefox, when saving a heap snapshot and running it through
`fxsnapshot`, querying `AbortSignal` will print a so-called "CaptureMap" with a list
of "lambdas," indicating that the signal is not garbage collected because of the event
listener lambda function.

PR Close #57882
2024-10-07 08:27:53 -07:00
Joey Perrott
9dbe6fc18b refactor: update license text to point to angular.dev (#57901)
Update license text to point to angular.dev instead of angular.io

PR Close #57901
2024-09-24 15:33:00 +02:00
Kristiyan Kostadinov
e608e6cfbb fix(zone.js): more robust check for promise-like objects (#57388)
Fixes that Zone.js wasn't checking properly if an object is promise-like.

Fixes #57385.

PR Close #57388
2024-08-23 12:58:29 -07:00
Matthieu Riegler
e1240c6f5d fix(zone.js): Add support for addition jest functions. (#57280)
This commit add support for `test.failing` and `it.failing`.

Fixes #57277

PR Close #57280
2024-08-07 18:13:51 +00:00
Andrew Scott
70e8b40750 fix(zone.js): Update the default behavior of fakeAsync to flush after the test (#57240)
From the internal issue on the matter:

> When using the standard Jasmine version of it promises returned by the body function are automatically awaited. The Catalyst version of it is fake-async, so awaiting the promise does not make sense; however it would be nice if Catalyst automatically flushed the promise to replicate the experience of using standard it. This would allow users to do the following:

```
it('should fail later', async () => {
  await new Promise(r => setTimeout(r));
  fail('failure');
});
```
> In Catalyst today the above test will pass. If this proposal to automatically flush the resulting promise were implemented it would fail.

Flushing after the tests complete has been the default behavior inside
Google since 2020. Very few tests remain that use the old behavior of
only flushing microtasks. The example above would actually fail with
`fakeAsync` due to the pending timer, but the argument still remains the
same. We might as well just flush if we're going to fail the test
anyways by throwing if there's no flush at the end.

BREAKING CHANGE: `fakeAsync` will now flush pending timers at the end of
the given function by default. To opt-out of this, you can use `{flush:
false}` in options parameter of `fakeAsync`

PR Close #57240
2024-08-05 20:24:54 +00:00
Andrew Scott
99d679d606 feat(zone.js): Add 'flush' parameter option to fakeAsync to flush after the test (#57137)
From the internal issue on the matter:

> When using the standard Jasmine version of it promises returned by the body function are automatically awaited. The Catalyst version of it is fake-async, so awaiting the promise does not make sense; however it would be nice if Catalyst automatically flushed the promise to replicate the experience of using standard it. This would allow users to do the following:

```
it('should fail later', async () => {
  await new Promise(r => setTimeout(r));
  fail('failure');
});
```
> In Catalyst today the above test will pass. If this proposal to automatically flush the resulting promise were implemented it would fail.

Flushing after the tests complete has been the default behavior inside
Google since 2020. Very few tests remain that use the old behavior of
only flushing microtasks. The example above would actually fail with
`fakeAsync` due to the pending timer, but the argument still remains the
same. We might as well just flush if we're going to fail the test
anyways by throwing if there's no flush at the end.

PR Close #57137
2024-08-02 16:52:07 +00:00
Alan Agius
982f1b1251 fix(zone.js): support Timeout.refresh in Node.js (#56852)
The `Timeout` object in Node.js has a `refresh` method, used to restart `setTimeout`/`setInterval` timers. Before this commit, `Timeout.refresh` was not handled, leading to memory leaks when using `fetch` in Node.js. This issue arose because `undici` (the Node.js fetch implementation) uses a refreshed `setTimeout` for cleanup operations.

For reference, see: 1dff4fd9b1/lib/util/timers.js (L45)

Fixes: #56586

PR Close #56852
2024-07-16 12:46:51 -07:00
arturovt
b8d5882127 fix(zone.js): allow enabling default beforeunload handling (#55875)
Prior to this commit, when zone.js was included, it wasn't possible to handle `beforeunload`
events correctly if event handlers returned strings to prompt the user.

With this change, we introduce a global configuration flag,
`__zone_symbol__enable_beforeunload`, to allow consumers to enable the default
`beforeunload` handling behavior.

This flag is necessary to prevent any breaking changes resulting from this modification.
The previous attempt to fix it caused a large number of failures in G3. Hence, we're
hiding that fix behind the configuration flag.

Closes #47579

PR Close #55875
2024-06-12 13:06:21 -07:00
arturovt
4a3800a6a0 fix(zone.js): store remove abort listener on the scheduled task (#56160)
Prior to this commit, a memory leak occurred when the `abort` listener was
not removed from the `AbortSignal`. We introduced a fix to remove the event
listener, but it was erroneously stored on the `taskData`, which is a shared
global object. Consequently, when something attempted to remove an event listener,
it immediately removed the last stored abort listener. As a result, events would
never be canceled.

We have now rectified this by storing the remove abort listener function directly on
the task itself. This adjustment ensures that the abort listener is tied only to the
specific task. When the `abort` function is called, it cancels the task. Therefore, it
is safe to associate the cleanup function directly with the task.

Closes: #56148

PR Close #56160
2024-06-04 17:29:05 +00:00
arturovt
85c171920a fix(zone.js): do not mutate event listener options (may be readonly) (#55796)
Prior to this commit, event listener options were mutated directly, for example,
`options.signal = undefined` or `options.once = false`.

This issue arises in apps using third-party libraries where the responsibility lies
with the library provider. Some libraries, like WalletConnect, pass an abort controller
as `addEventListener` options. Because the abort controller has the `signal` property,
this is a valid case. Thus, mutating options would throw an error since `signal`
is a readonly property.

Even though zone.js is being deprecated as Angular moves towards zoneless change detection,
this fix is necessary for apps that still use zone.js and cannot migrate to zoneless change
detection because they rely on third-party libraries and are not responsible for the code
used in them.

Closes #54142

PR Close #55796
2024-05-22 16:20:34 -07:00
Kristiyan Kostadinov
aa8df1d029 refactor(core): clean up clang comments and workarounds (#55750)
Since we aren't using clang anymore, we can remove the comments and the workarounds that were in place to prevent it from doing the wrong thing.

PR Close #55750
2024-05-13 11:10:36 -07:00
arturovt
a9460d08a0 fix(zone.js): remove abort listener on a signal when actual event is removed (#55339)
This commit updates the implementation of the `addEventListener` patcher.

We're currently creating an abort event listener on the signal (when it's provided)
and never remove it. The abort event listener creates a closure which captures `task`
(tasks capture zones and other stuff too) and prevent `task`, zones and signals from
being garbage collected.

We now store the function which removes the abort event listener when the actual event
listener is being removed. The function is stored on task data since task data is already
being used to store different types of information that's necessary to be shared between
`addEventListener` and `removeEventListener`.

Closes #54739

PR Close #55339
2024-05-07 08:07:33 -07:00
arturovt
9e07b621ea fix(zone.js): add missing APIs to Node.js fs patch (#54396)
This commit updates the list of Node.js `fs` APIs to be patched because
they haven't been updated for a long time. It adds `opendir,lutimes,writev`.
For example, the `opendir` method was added to Node.js in version 12.12.0 in
2019, causing some of the APIs to potentially be always called within the
`<root>` context.

**Note:** There are missing unit tests for these changes because in unit tests,
`fs` is patched by Bazel's Node.js rules and its `node_patches.cjs`. However,
the APIs are successfully patched in the real production code and are called
with the correct context.

PR Close #54396
2024-05-03 08:03:25 -07:00
Doug Parker
3312727aec refactor(zone.js): use Object.prototype.toString directly for improved tree shakability (#55412)
These lines were not tree shakable by Closure Compiler because `.toString()` is special cased as a "pure" function eligible to eliminated if it's return value is unused. However `.toString.call` circumvents this and makes Closure Compiler think the function may have side effects. Switching to `.toString()` should be fine here as `process.toString()` in Node outputs `[object process]` so this should be safe. Presumably the original motivation for this roundabout approach was for type safety reasons which no longer apply as `_global` is `any`.

PR Close #55412
2024-04-30 14:06:43 -07:00
Joey Perrott
f307e95459 refactor: migrate zone.js to prettier formatting (#55427)
Migrate formatting to prettier for zone.js from clang-format

PR Close #55427
2024-04-29 09:52:05 -07:00
JiaLiPassion
ddbf6bb038 fix(zone.js): make sure fakeasync use the same id pool with native (#54600)
Close #54323

fakeAsync should use the same timerId pool with native, so they will not
conflict.

PR Close #54600
2024-03-28 10:30:25 -07:00
JiaLiPassion
e44b077cbd fix(zone.js): should not clear onhandler when remove capture listener (#54602)
Close #54581

Should not clear `onHandler` when remove capture event listeners.

PR Close #54602
2024-03-27 10:40:05 -07:00
Andrew Scott
b3d045b9a4 fix(zone.js): Add 'declare' to each interface to prevent renaming (#54966)
This commit adds `declare` to each interface in the `zone-impl` to
prevent renaming of any interface properties by compiler optimizations.
This would otherwise cause issues if multiple applications depend on ZoneJS and
compile the interface properties to different names.

PR Close #54966
2024-03-20 09:16:07 -07:00
Doug Parker
5328be6660 refactor(zone.js): formatting recently changed files (#53443)
For some reason CI started complaining about lack of formatting here.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
635227b881 refactor(zone.js): package Zone *.d.ts files (#53443)
This was a bit complicated, but the typings test (`packages/zone.js/test/typings/...`) was failing due to an unresolved import on `./zone-impl`.

The main cause is that `//packages/zone.js:zone_js_d_ts` was generating the output `zone.d.ts` file by _concatenating_ `zone.d.ts` with `zone.api.extensions.d.ts` and `zone.configurations.api.d.ts`. Now that `zone.d.ts` imports `zone-impl.d.ts`, concatenation is no longer a viable means of bundling this content.

To fix this, I created a new `packages/zone.js/zone.ts` entry point and imported the underlying `zone.ts` file as well as the two extensions. I added `extract_types` to pull the `*.d.ts` files out of the target (because all the JS is bundled separately) and used those files in the final NPM package. This is sufficient to pass the typings test and should be equivalent to what exists today.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
54a1fe05df refactor(zone.js): fix fake async test by reading parentUnresolved symbol lazily (#53443)
As this was, `__symbol__` was being called as a static field initializer, which runs during module evaluation, meaning it happened at import time. However for tests, the Zone prefix is overridden which changes the result of `__symbol__`. This change happens too late to be picked up by `__symbol__` at top-level execution, so instead we defer it until `symbolParentUnresolved` is actually read.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
b334e29d59 refactor(zone.js): read patched timers after they are patched (#53443)
This moves timer patching from a top-level side effect into the `patchFakeAsyncTest` function. Top-level statements are evaluated before the Node patches run and have a chance to patch them with the Zone versions of these timers, meaning `FakeAsyncTestZoneSpec` was repatching the native versions between tests. The fix here is to grab the patched versions of these timers during the `patchFakeAsyncTest` function where we can be confident Node patches have already run.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
6ca1911967 refactor(zone.js): export fake-async-test.ts functions (#53443)
This moves the internals of `fake-async-test.ts` outside `patchFakeAsyncTest` and exports them. This way they can be imported without depending on the top-level side effects of loading Zone.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
33c08e5aba refactor(zone.js): switch async-test.ts to use __symbol__ from an import (#53443)
This removes a dependency on the top-level side effect of `Zone` global initialization.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
181121dd9e refactor(zone.js): rename __global variable (#53443)
For some reason the `_global` name appears to conflict with another `_global` name. Not entirely sure how or why, but the easiest fix seems to be to just give the variable a unique name.

PR Close #53443
2024-03-15 18:11:34 -07:00
Doug Parker
5e45bb771b refactor(zone.js): delay reading __Zone_symbol_prefix until needed (#53443)
While reading this is not a top-level side effect, it does _depend_ on a top-level side effect. Specifically, `node-env-setup.ts` set this value. Now that its side effect is moved into a function, we can't read it as the top-level of `zone-impl.ts` and need to wait until `__symbol__` is actually called outside of top-level scope.

PR Close #53443
2024-03-15 18:11:34 -07:00