fix(core): resolve closure and reference retention leaks

Resolves several V8 closure-context and reference retention issues
across `@angular/core`, including isolating closure scopes in
`injectAsync`, `ɵɵboundaryUpdate`, and incremental hydration triggers,
skipping non-`jsaction` elements in event replay stashing, clearing
recovered signal error references, and avoiding retaining the document
reference in `InertDocumentHelper`.

(cherry picked from commit 5f51154197)
This commit is contained in:
Matthieu Riegler
2026-11-11 19:12:23 +00:00
committed by Jessica Janiuk
parent 59d5f0d1c4
commit 596a40061f
11 changed files with 85 additions and 39 deletions
@@ -153,6 +153,7 @@ const COMPUTED_NODE: Omit<ComputedNode<unknown>, 'computation'> = /* @__PURE__ *
oldValue !== ERRORED &&
newValue !== ERRORED &&
node.equal(oldValue, newValue);
node.error = null;
} catch (err) {
newValue = ERRORED;
node.error = err;
@@ -107,6 +107,7 @@ export function linkedSignalSetFn<S, D>(node: LinkedSignalNode<S, D>, newValue:
producerUpdateValueVersion(node);
signalSetFn(node, newValue);
producerMarkClean(node);
node.error = null;
}
export function linkedSignalUpdateFn<S, D>(
@@ -171,6 +172,7 @@ export const LINKED_SIGNAL_NODE: Omit<
// to track any reactive reads inside `equal`.
setActiveConsumer(null);
wasEqual = oldValueValid && newValue !== ERRORED && node.equal(oldValue, newValue);
node.error = null;
} catch (err) {
newValue = ERRORED;
node.error = err;
+12 -12
View File
@@ -725,36 +725,36 @@ export function processAndInitTriggers(
}
function setIdleTriggers(injector: Injector, elementTriggers: ElementTrigger[]) {
for (const elementTrigger of elementTriggers) {
for (const {blockName} of elementTriggers) {
const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
const onInvoke = () => triggerHydrationFromBlockName(injector, blockName);
const cleanupFn = onIdle(onInvoke, injector);
registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
registry.addCleanupFn(blockName, cleanupFn);
}
}
function setViewportTriggers(injector: Injector, elementTriggers: ElementTrigger[]) {
if (elementTriggers.length > 0) {
const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
for (let elementTrigger of elementTriggers) {
for (const {el, blockName, intersectionObserverOptions} of elementTriggers) {
const cleanupFn = onViewportWrapper(
elementTrigger.el,
() => triggerHydrationFromBlockName(injector, elementTrigger.blockName),
el,
() => triggerHydrationFromBlockName(injector, blockName),
injector,
elementTrigger.intersectionObserverOptions,
intersectionObserverOptions,
);
registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
registry.addCleanupFn(blockName, cleanupFn);
}
}
}
function setTimerTriggers(injector: Injector, elementTriggers: ElementTrigger[]) {
for (const elementTrigger of elementTriggers) {
for (const {blockName, delay} of elementTriggers) {
const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
const timerFn = onTimer(elementTrigger.delay!);
const onInvoke = () => triggerHydrationFromBlockName(injector, blockName);
const timerFn = onTimer(delay!);
const cleanupFn = timerFn(onInvoke, injector);
registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
registry.addCleanupFn(blockName, cleanupFn);
}
}
+18 -9
View File
@@ -64,19 +64,12 @@ export function injectAsync<T>(
}
const injector = inject(Injector);
let loadedPromise: Promise<InjectAsyncLoaderResult<T>> | null = null;
const load = () => {
if (!loadedPromise) {
loadedPromise = loader();
}
return loadedPromise;
};
const load = createLoader(loader);
if (options?.prefetch) {
options
.prefetch()
.then(() => load())
.then(load)
.catch(() => {});
}
@@ -84,6 +77,22 @@ export function injectAsync<T>(
return () => load().then((loadedToken) => injector.get(maybeUnwrapDefaultExport(loadedToken))!);
}
/**
* Creates the memoized loader function in its own lexical scope so that the
* prefetch callback does not share a closure context with `injector`.
*/
function createLoader<T>(
loader: () => Promise<InjectAsyncLoaderResult<T>>,
): () => Promise<InjectAsyncLoaderResult<T>> {
let loadedPromise: Promise<InjectAsyncLoaderResult<T>> | null = null;
return () => {
if (!loadedPromise) {
loadedPromise = loader();
}
return loadedPromise;
};
}
/**
* Interface for `options` argument used within `injectAsync` call.
*
+8 -2
View File
@@ -7,6 +7,7 @@
*/
import {
Attribute,
isEarlyEventType,
isCaptureEventType,
EventContractContainer,
@@ -115,8 +116,13 @@ export function withEventReplay(): Provider[] {
(rEl: RNode, eventName: string, listenerFn: VoidFunction) => {
// If a user binds to a ng-container and uses a directive that binds using a host listener,
// this element could be a comment node. So we need to ensure we have an actual element
// node before stashing anything.
if ((rEl as Node).nodeType !== Node.ELEMENT_NODE) return;
// node with a `jsaction` attribute before stashing anything.
if (
(rEl as Node).nodeType !== Node.ELEMENT_NODE ||
!(rEl as Element).hasAttribute(Attribute.JSACTION)
) {
return;
}
sharedStashFunction(rEl as RElement, eventName, listenerFn);
sharedMapFunction(rEl as RElement, jsActionMap);
},
@@ -422,8 +422,6 @@ export function ɵɵanimateLeaveListener(value: AnimationFunction): typeof ɵɵa
const lView = getLView();
const tNode = getCurrentTNode()!;
allLeavingAnimations.add(lView[ID]);
// Capture NgZone and MAX_ANIMATION_TIMEOUT eagerly while the injector is
// still valid. The animation function runs later from the queue, at which
// point the lView injector may have been destroyed.
@@ -461,6 +459,7 @@ function runLeaveAnimationFunction(
const renderer = lView[RENDERER];
const animationsDisabled = areAnimationsDisabled(lView);
allLeavingAnimations.add(lView[ID]);
(getLViewLeaveAnimations(lView).get(tNode.index)!.resolvers ??= []).push(resolve);
const resolvers = getLViewLeaveAnimations(lView).get(tNode.index)?.resolvers;
@@ -118,7 +118,7 @@ export function ɵɵboundaryUpdate(
const context =
matchingTemplateIndex === primaryTemplateIndex
? undefined
: {$error: boundary.error, $reset: () => boundary.reset()};
: {$error: boundary.error, $reset: createBoundaryResetFn(boundary)};
embeddedLView = createAndRenderEmbeddedLView(hostLView, templateTNode, context, {
dehydratedView,
});
@@ -134,7 +134,7 @@ export function ɵɵboundaryUpdate(
const boundaryType: Type<unknown> = boundaryComponentView.constructor;
(details as Writable<ErrorDetails>).boundary = {
type: boundaryType,
reset: () => boundary.reset(),
reset: createBoundaryResetFn(boundary),
};
if (errorHandler.onViewError) {
@@ -166,7 +166,7 @@ export function ɵɵboundaryUpdate(
declarationType,
boundary: {
type: declarationType,
reset: () => boundary.reset(),
reset: createBoundaryResetFn(boundary),
},
};
if (errorHandler.onViewError) {
@@ -204,3 +204,12 @@ export function ɵɵboundaryUpdate(
}
}
}
/**
* Creates a reset callback for an `LBoundary` outside `ɵɵboundaryUpdate` so that
* `$reset` and `details.boundary.reset` do not share a closure context with
* `nextContainer` or `embeddedLView`.
*/
function createBoundaryResetFn(boundary: LBoundary): () => void {
return () => boundary.reset();
}
+10 -8
View File
@@ -236,17 +236,19 @@ function executeLeaveAnimations(
// to be safe here.
const runningAnimations: Promise<unknown>[] = [];
if (animations && animations.leave) {
for (const [index] of nodesWithExitAnimations) {
if (!animations.leave.has(index)) continue;
if (animations) {
if (animations.leave) {
for (const [index] of nodesWithExitAnimations) {
if (!animations.leave.has(index)) continue;
const currentAnimationData = animations.leave.get(index)!;
for (const animationFn of currentAnimationData.animateFns) {
const {promise} = animationFn() as ReturnType<RunLeaveAnimationFn>;
runningAnimations.push(promise);
const currentAnimationData = animations.leave.get(index)!;
for (const animationFn of currentAnimationData.animateFns) {
const {promise} = animationFn() as ReturnType<RunLeaveAnimationFn>;
runningAnimations.push(promise);
}
}
animations.detachedLeaveAnimationFns = undefined;
}
animations.detachedLeaveAnimationFns = undefined;
}
// Also add nested view animations
+2 -2
View File
@@ -66,8 +66,8 @@ class DOMParserHelper implements InertBodyHelper {
class InertDocumentHelper implements InertBodyHelper {
private inertDocument: Document;
constructor(private defaultDoc: Document) {
this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
constructor(defaultDoc: Document) {
this.inertDocument = defaultDoc.implementation.createHTMLDocument('sanitization-inert');
}
getInertBodyElement(html: string): HTMLElement | null {
@@ -327,6 +327,7 @@ describe('computed', () => {
shouldThrow = false;
source.set(2);
expect(derived()).toBe(2);
expect((derived as any)[SIGNAL].error).toBeNull();
});
});
@@ -7,7 +7,7 @@
*/
import {isSignal, linkedSignal, signal, computed} from '../../src/core';
import {defaultEquals, setPostProducerCreatedFn} from '../../primitives/signals';
import {defaultEquals, setPostProducerCreatedFn, SIGNAL} from '../../primitives/signals';
import {global} from '../../src/util/global';
import {flushEffects, testingEffect} from './effect_util';
@@ -566,4 +566,21 @@ describe('linkedSignal', () => {
}
});
});
it('should clear stored error on node after recovering from an error', () => {
const shouldThrow = signal(true);
const state = linkedSignal(() => {
if (shouldThrow()) {
throw new Error('computation failed');
}
return 'ok';
});
expect(() => state()).toThrowError('computation failed');
expect((state as any)[SIGNAL].error).toEqual(jasmine.any(Error));
shouldThrow.set(false);
expect(state()).toBe('ok');
expect((state as any)[SIGNAL].error).toBeNull();
});
});