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
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
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
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
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
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
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
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
Since each patch no longer contains top-level side effects, each bundled entry point needs to import and call its associated patch. For the most part this just means that each entry point imports the associated patch and invokes it at the top-level scope.
Note that many of these entry points did not actually have a dependency on `Zone` and had no guarantee that it was loaded prior to execution. To maintain consistency, the missing dependencies on `Zone` are left as-is. They will use the global instance of `Zone` and if users fail to load it prior to importing a specific patch, then the patch will fail just as it did previously.
PR Close#53443
This removes top-level side effects from each of these files and drops the dependency on global `Zone`, instead allowing it to be provided to each patch as a parameter.
Most of these are pure mechanical transformations. A couple notable files which were somewhat unique:
* `async-test.ts`, `fake-async-test.ts`, and `wtf.ts` had unique IIFE usage and patch `Zone` itself. This removes the IIFE and exports the function instead.
* `jest.ts` and `jasmine.ts` have a unique `jest` global usage which needs to be declared.
PR Close#53443
This commit updates the implementation of the `fetch` patch and additionally
patches `Response` methods which return promises. These are `arrayBuffer`, `blob`,
`formData`, `json` and `text`. This fixes the issue when zone becomes stable too early
before all of the `fetch` tasks complete. Given the following code:
```ts
appRef.isStable.subscribe(console.log);
fetch(...).then(response => response.json()).then(console.log);
```
The `isStable` observer would log `false, true, false, true`. This was happening because
`json()` was returning a native promise (and not a `ZoneAwarePromise`). But calling `then`
on the native promise returns a `ZoneAwarePromise` which notifies Angular about the task
being scheduled and forces to re-calculate the `isStable` state.
Issue: #50327
PR Close#50653
Make Zone.js compatible with moduleDetection:force by turning files that
are currently incompatible from scripts into modules using an empty
export statement.
PR Close#53445
fetch support AbortSignal, zone.js schedules a macroTask when fetch()
```
fetch(..., {signal: abortSignal});
```
we should also be able to cancel fetch with `zoneTask.cancel` call.
So this commit create an internal AbortSignal to handle
`zoneTask.cancel()` call and also delegate the `options.signal` from the
user code.
PR Close#49595
Close#49591
```
const ac = new AbortController();
addEventListener(eventName, handler, {signal: ac.signal);`
ac.abort();
```
Currently `zone.js` doesn't support the `signal` option, this PR allows
the user to use AbortContoller to remove the event listener.
PR Close#49595
In the original `Promise` impelmentation, zone.js follow the spec from
https://promisesaplus.com/#point-51.
```
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
p1 === p2; // false
```
in this case, `p2` should be the same status with `p1` but they are
still different instances.
And for some edge case.
```
class MyPromise extends Promise {
constructor(sub) {
super((res) => res(null));
this.sub = sub;
}
then(onFufilled, onRejected) {
this.sub.then(onFufilled, onRejected);
}
}
const p1 = new Promise(setTimeout(res), 100);
const myP = new MyPromise(p1);
const r = await myP;
r === 1; // false
```
So in the above code, `myP` is not the same instance with `p1`,
and since `myP` is resolved in constructor, so `await myP` will
just pass without waiting for `p1`.
And in the current `tc39` spec here https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-resolve
`Promise.resolve(subP)` should return `subP`.
```
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
p1 === p2; // true
```
So the above `MyPromise` can wait for the `p1` correctly.
PR Close#53423
Before this commit, zone.js wraps the uncaught promise rejection error
to a new Error object includes more information such as Zone stack
traces. This feature is provided from the very beginning of Zone.js,
but this feature becomes very annoying and make the user difficult to
debug.
So this commit disable this wrapping behavior by default, and user can
enable this feature back by setting
`DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION` to `false`.
PR Close#52492
`globalThis` global property contains the global `this` value, which is usually akin to the global object. This is needed for better compatibility with CloudFlare workers were global nor window are defined as globals.
PR Close#52367
We have a file called `test-events.js` (named in an ambiguous way
anyway) that runs for all Karma web tests and configures ZoneJS to
not patch the `scroll` event. There are two issues:
1. The patch applies to all web tests. This could cause unexpected
issues.
2. The file is named ambiguously and also is placed at the project root,
in a wrong spot.
Additionally, the test doesn't even fail when the file is removed. This
commit applies the Zone config locally to the closest build target and
also reworks the test to actually ensure it's testing what it describes.
PR Close#46511
The native promise implementation logs unhandled promise rejections after `onFinally`
has been called. We may rely on the `scheduledByFinally` argument, which is `false` by
default, to avoid creating a breaking change; this will also allow us to reduce the number of
changes. The `finally` function should not silence unhandled promise rejections, because
they're not silenced in any implementation. If the `scheduleResolveOrReject` is called within
the `finally` we won't clear unhandled rejections. We'll keep the same behaviour if the
`scheduleResolveOrReject` is called within the `then`.
PR Close#43206
PR Close#45449
Close#44913
The following case is not handled correctly by `zone.js`.
```
const delayedPromise = new Promise((resolve) => {
setTimeout(resolve, 1, 'timeout');
});
new Promise((resolve) => {
resolve(delayedPromise);
resolve('second call');
}).then(console.log);
```
It should output `timeout`, since the promise is resolved by the
1st resolve, the `second call` should be ignored.
So this is a bug that the original implementation not ensure the
`resolve` is only called once.
PR Close#45283
We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
may be an object without a prototype (created through `Object.create(null)`); thus
`this.constructor` will be undefined. One of the use cases is SystemJS creating
prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
object and copies promise properties into that object (within the `getOrCreateLoad`
function). The zone.js then checks if the resolved value has the `then` method and invokes
it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
properties of undefined (reading 'Symbol(Symbol.species)')`.
PR Close#45369
.substr() is deprecated so we replace it with functions which work similarily but aren't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
PR Close#45397
For legacy browsers, we still use the eventNames array to patch event instead of
using `Object.getOwnPropertyNames()` to keep backward compatibility.
PR Close#40962
Zone.js supports the google closure compiler in the advance optimization mode,
to prevent closure compiler modify the `onProperty` name such as `Element.prototype.onclick`,
Zone.js implements the `onProperty` patch logic by declaring all the
event names in the source code, this increases the bundle size and also require
updating the event names array to keep the information updated.
Now google closure compiler has the required event names defined in the built-in
externs files, so zone.js can use more simple implementation and decrease the bundle size
of zone.js (about 4k).
PR Close#40962
Close#41867
In the previous commit https://github.com/angular/angular/pull/41562#issuecomment-822696973,
the error thrown in the event listener will be caught and re-thrown, but there is a bug
in the commit, if there is only one listener for the specified event name, the error
will not be re-thrown, so this commit fixes the issue and make sure the error is re-thrown.
PR Close#41868
Switches the repository to TypeScript 4.3 and the latest
version of tslib. This involves updating the peer dependency
ranges on `typescript` for the compiler CLI and for the Bazel
package. Tests for new TypeScript features have been added to
ensure compatibility with Angular's ngtsc compiler.
PR Close#42022
Close#41522
`zone.js` patches event listeners and run all event listeners together, if
one event handler throws error, the listeners afterward may not be invoked.
Reproduction:
```
export class AppComponent implements AfterViewInit {
@ViewChild('btn') btn: ElementRef;
title = 'event-error';
constructor(private ngZone: NgZone) {}
ngAfterViewInit() {
this.ngZone.runOutsideAngular(() => {
this.btn.nativeElement.addEventListener('click', () => {
throw new Error('test1');
});
this.btn.nativeElement.addEventListener('click', () => {
console.log('add eventlistener click');
});
});
}
}
```
Until now no Angular users report this issue becuase in the `ngZone`, all
error will be caught and will not rethrow, so the event listeners afterward
will still continue to execute, but if the event handlers are outside of `ngZone`,
the error will break the execution.
This commit catch all errors, and after all event listeners finished invocation,
rethrow the errors in seperate `microTasks`, the reason I am using `microTask` here
is to handle multiple errors case.
PR Close#41562
Close#41522
`zone.js` patches event listeners and run all event listeners together, if
one event handler throws error, the listeners afterward may not be invoked.
Reproduction:
```
export class AppComponent implements AfterViewInit {
@ViewChild('btn') btn: ElementRef;
title = 'event-error';
constructor(private ngZone: NgZone) {}
ngAfterViewInit() {
this.ngZone.runOutsideAngular(() => {
this.btn.nativeElement.addEventListener('click', () => {
throw new Error('test1');
});
this.btn.nativeElement.addEventListener('click', () => {
console.log('add eventlistener click');
});
});
}
}
```
Until now no Angular users report this issue becuase in the `ngZone`, all
error will be caught and will not rethrow, so the event listeners afterward
will still continue to execute, but if the event handlers are outside of `ngZone`,
the error will break the execution.
This commit catch all errors, and after all event listeners finished invocation,
rethrow the errors in seperate `microTasks`, the reason I am using `microTask` here
is to handle multiple errors case.
PR Close#41562
Close#40387
Currently zone.js patches `setTimeout` and keeps a `tasksByHandleId` map to keep `timerId` <-> `ZoneTask`
relationship. This is needed so that when `clearTimeout(timerId)` is called, zone.js can find the associated
`ZoneTask`. Now zone.js set the `tasksByHandleId` map in the `scheduleTask` function, but if the `setTimeout`
is running in the `FakeAsyncZoneSpec` or any other `ZoneSpec` with `onScheduleTask` hooks. The `scheduleTask`
in `timer` patch may not be invoked.
For example:
```
fakeAsync(() => {
setTimeout(() => {});
tick();
});
```
In this case, the `timerId` kept in the `tasksByHandleId` map is not cleared.
This is because the `FakeAsyncZoneSpec` in the `onScheduleTask` hook looks like this.
```
onScheduleTask(delegate, ..., task) {
fakeAsyncScheduler.setTimeout(task);
return task;
}
```
Because `FakeAsyncZoneSpec` handles the task itself and it doesn't call `parentDelegate.onScheduleTask`,
therefore the default `scheduleTask` in the `timer` patch is not invoked.
In this commit, the cleanup logic is moved from `scheduleTask` to `setTimeout` patch entry to
avoid the memory leak.
PR Close#40586
Fix a case where, if the parent class had already been patched, it would
not patch the child class. In addition to checking if the method is
defined in the prototype, and not inherited, it also does the same for
the unpatched method.
PR Close#39850