diff --git a/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts b/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts index 7fe8c68030fc..4c864abf5eb9 100644 --- a/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts +++ b/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts @@ -1100,4 +1100,81 @@ describe('adjust-static-class-members oxc-transform implementation', () => { `, }), ); + + it( + 'wraps class with Angular static fields and ngDevMode-guarded ɵsetClassMetadata static block', + testCase({ + input: ` + export class SomeComponent { + static ɵfac = function SomeComponent_Factory(t) { return new (t || SomeComponent)(); }; + static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ + type: SomeComponent, + selectors: [['some-cmp']], + decls: 0, + vars: 0, + template: function(rf, ctx) {}, + }); + static { + (typeof ngDevMode === "undefined" || ngDevMode) && + i0.ɵsetClassMetadata(SomeComponent, [{ type: Component, args: [{ selector: 'some-cmp', template: '' }] }], null, null); + } + } + `, + expected: ` + export let SomeComponent = /*#__PURE__*/ (() => { + class SomeComponent { + static ɵfac = function SomeComponent_Factory(t) { return new (t || SomeComponent)(); }; + static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ + type: SomeComponent, + selectors: [['some-cmp']], + decls: 0, + vars: 0, + template: function(rf, ctx) {}, + }); + } + return SomeComponent; + })(); + `, + }), + ); + + it( + 'wraps class with Angular static fields and internal setClassMetadata static block', + testCase({ + input: ` + class PlatformRef { + static ɵfac = function PlatformRef_Factory(t) { return new (t || PlatformRef)(); }; + static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: PlatformRef, factory: PlatformRef.ɵfac, providedIn: 'platform' }); + static { + (typeof ngDevMode === "undefined" || ngDevMode) && + setClassMetadata(PlatformRef, [{ type: Injectable, args: [{ providedIn: 'platform' }] }], null, null); + } + } + `, + expected: ` + let PlatformRef = /*#__PURE__*/ (() => { + class PlatformRef { + static ɵfac = function PlatformRef_Factory(t) { return new (t || PlatformRef)(); }; + static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: PlatformRef, factory: PlatformRef.ɵfac, providedIn: 'platform' }); + } + return PlatformRef; + })(); + `, + }), + ); + + it( + 'does not wrap class with unguarded non-ɵ setClassMetadata call in static block', + testCase({ + input: ` + class CustomClass { + static ɵprov = 42; + static { + setClassMetadata(CustomClass); + } + } + `, + expected: NO_CHANGE, + }), + ); }); diff --git a/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts b/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts index f4d6c09b6c19..6818b8a48779 100644 --- a/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts +++ b/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts @@ -210,4 +210,111 @@ describe('elide-angular-metadata oxc-transform implementation', () => { `, }), ); + + it( + 'elides ɵsetClassMetadata inside a class static block (ngtsc)', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass { + static { + (typeof ngDevMode === "undefined" || ngDevMode) && + i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'app-lazy', template: '' }] }], null, null); + } + } + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + `, + }), + ); + + it( + 'elides parenthesized ɵsetClassMetadata inside a class static block (ngp)', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass { + static { + (((typeof ngDevMode === "undefined") || ngDevMode) && + i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'app-lazy', template: '' }] }], null, null)); + } + } + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + `, + }), + ); + + it( + 'elides ɵsetClassMetadataAsync inside a class static block', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass { + static { + (typeof ngDevMode === "undefined" || ngDevMode) && + i0.ɵsetClassMetadataAsync( + SomeClass, + () => [import("./cmp-a").then((m) => m.CmpA)], + (CmpA) => { + i0.ɵsetClassMetadata( + SomeClass, + [{ type: Component, args: [{ selector: 'test-cmp', imports: [CmpA], template: '' }] }], + null, + null, + ); + }, + ); + } + } + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + `, + }), + ); + + it( + 'elides ngDevMode-guarded internal setClassMetadata inside a class static block (@angular/core FESM)', + testCase({ + input: ` + export class PlatformRef { + static { + (typeof ngDevMode === "undefined" || ngDevMode) && + setClassMetadata(PlatformRef, [{ type: Injectable, args: [{ providedIn: 'platform' }] }], null, null); + } + } + `, + expected: ` + export class PlatformRef {} + `, + }), + ); + + it( + 'elides ɵsetClassMetadata statement inside a multi-statement static block while preserving side effects', + testCase({ + input: ` + export class SomeClass { + static { + console.log('keep'); + (typeof ngDevMode === "undefined" || ngDevMode) && + i0.ɵsetClassMetadata(SomeClass, [], null, null); + } + } + `, + expected: ` + export class SomeClass { + static { + console.log('keep'); + } + } + `, + }), + ); }); diff --git a/packages/angular/build/src/tools/oxc/oxc-transform.ts b/packages/angular/build/src/tools/oxc/oxc-transform.ts index e0d6ba26a252..e123d745a2f0 100644 --- a/packages/angular/build/src/tools/oxc/oxc-transform.ts +++ b/packages/angular/build/src/tools/oxc/oxc-transform.ts @@ -110,6 +110,122 @@ const angularMetadataFunctions = new Set([ 'ɵsetClassDebugInfo', ]); +/** + * A set of internal `@angular/core` metadata helper names emitted without the `ɵ` prefix + * inside `@angular/core`'s own Rollup FESM bundles when guarded by `ngDevMode`/`ngJitMode`. + */ +const internalAngularMetadataFunctions = new Set([ + 'setClassMetadata', + 'setClassMetadataAsync', + 'setClassDebugInfo', +]); + +/** + * Strips any numeric bundler rename suffix (e.g. `$1`) from an identifier name. + */ +function stripBundlerSuffix(name: string): string { + const dollarIndex = name.indexOf('$'); + if (dollarIndex === -1) { + return name; + } + const suffix = name.slice(dollarIndex + 1); + + return /^\d+$/.test(suffix) ? name.slice(0, dollarIndex) : name; +} + +/** + * Determines whether an AST node is a call to an Angular class metadata helper. + */ +function isAngularMetadataCall(node: Node, allowInternalName = false): boolean { + const expr = unwrapParentheses(node); + if (expr.type !== 'CallExpression') { + return false; + } + + const callee = unwrapParentheses(expr.callee); + let calleeName: string | undefined; + if (callee.type === 'Identifier') { + calleeName = callee.name; + } else if ( + callee.type === 'MemberExpression' && + !callee.computed && + callee.property.type === 'Identifier' + ) { + calleeName = callee.property.name; + } + + if (!calleeName) { + return false; + } + + const baseName = stripBundlerSuffix(calleeName); + + return ( + angularMetadataFunctions.has(baseName) || + (allowInternalName && internalAngularMetadataFunctions.has(baseName)) + ); +} + +/** + * Determines whether an AST node is an `(typeof ngDevMode === "undefined" || ngDevMode)` + * or `(typeof ngJitMode === "undefined" || ngJitMode)` guard expression. + */ +function isAngularModeGuard(node: Node): boolean { + const expr = unwrapParentheses(node); + if (expr.type !== 'LogicalExpression' || expr.operator !== '||') { + return false; + } + + const right = unwrapParentheses(expr.right); + if (right.type !== 'Identifier' || (right.name !== 'ngDevMode' && right.name !== 'ngJitMode')) { + return false; + } + + const left = unwrapParentheses(expr.left); + if (left.type !== 'BinaryExpression' || (left.operator !== '===' && left.operator !== '==')) { + return false; + } + + const binLeft = unwrapParentheses(left.left); + const binRight = unwrapParentheses(left.right); + const isTypeofGuard = (typeofSide: Node, literalSide: Node): boolean => { + if (typeofSide.type !== 'UnaryExpression' || typeofSide.operator !== 'typeof') { + return false; + } + const arg = unwrapParentheses(typeofSide.argument); + + return ( + arg.type === 'Identifier' && + arg.name === right.name && + literalSide.type === 'Literal' && + literalSide.value === 'undefined' + ); + }; + + return isTypeofGuard(binLeft, binRight) || isTypeofGuard(binRight, binLeft); +} + +/** + * Determines whether a statement inside a `static {}` block is an elidable Angular metadata call. + */ +function isAngularMetadataStatement(node: Node): boolean { + if (node.type !== 'ExpressionStatement') { + return false; + } + + const expr = unwrapParentheses(node.expression); + if (isAngularMetadataCall(expr)) { + return true; + } + + return ( + expr.type === 'LogicalExpression' && + expr.operator === '&&' && + isAngularModeGuard(expr.left) && + isAngularMetadataCall(expr.right, true) + ); +} + /** * A map of static properties and their matcher predicate functions to check if they * can be safely elided from class declarations. @@ -216,33 +332,33 @@ function analyzeClassStaticProperties(classNode: Node, code: string): boolean { break; } } else if (element.type === 'StaticBlock') { - const blockBody = element.body; - if (blockBody.length === 0) { - continue; - } - if (blockBody.length > 1) { - shouldWrap = false; - break; - } - const expressionStatement = blockBody[0]; - if (expressionStatement && expressionStatement.type === 'ExpressionStatement') { - const assignment = expressionStatement.expression; - if ( - assignment && - assignment.type === 'AssignmentExpression' && - assignment.left.type === 'MemberExpression' - ) { - const left = assignment.left; - if (left.object.type === 'ThisExpression' && left.property.type === 'Identifier') { - if (canWrapProperty(left.property.name, assignment.right, code)) { - shouldWrap = true; - continue; + let hasInvalidStatement = false; + for (const stmt of element.body) { + if (stmt.type === 'EmptyStatement' || isAngularMetadataStatement(stmt)) { + continue; + } + if (stmt.type === 'ExpressionStatement') { + const assignment = unwrapParentheses(stmt.expression); + if ( + assignment.type === 'AssignmentExpression' && + assignment.left.type === 'MemberExpression' + ) { + const left = assignment.left; + if (left.object.type === 'ThisExpression' && left.property.type === 'Identifier') { + if (canWrapProperty(left.property.name, assignment.right, code)) { + shouldWrap = true; + continue; + } } } } + hasInvalidStatement = true; + break; + } + if (hasInvalidStatement) { + shouldWrap = false; + break; } - shouldWrap = false; - break; } } @@ -626,114 +742,142 @@ export function transform(filename: string, code: string, options: OxcTransformO } } - traversePostOrder(program, (node, { functionDepth, classDepth, parentFunc }) => { - switch (node.type) { - case 'Program': - case 'BlockStatement': - if (advancedOptimizations) { - adjustTypeScriptEnumsInStatements(node.body); - adjustStaticMembersInStatements(node.body); - } - break; + traversePostOrder( + program, + (node, { functionDepth, classDepth, staticBlockDepth, parentFunc }) => { + switch (node.type) { + case 'Program': + case 'BlockStatement': + if (advancedOptimizations) { + adjustTypeScriptEnumsInStatements(node.body); + adjustStaticMembersInStatements(node.body); + } + break; - case 'CallExpression': { - if (isAlreadyEdited(node.start, node.end)) { - return; + case 'StaticBlock': { + if (!advancedOptimizations || node.body.length === 0) { + break; + } + if ( + node.body.every( + (stmt) => stmt.type === 'EmptyStatement' || isAngularMetadataStatement(stmt), + ) + ) { + if (node.body.some(isAngularMetadataStatement)) { + source.remove(node.start, node.end); + markEdited(node.start, node.end); + } + } else { + for (const stmt of node.body) { + if (isAngularMetadataStatement(stmt)) { + source.remove(stmt.start, stmt.end); + markEdited(stmt.start, stmt.end); + } + } + } + break; } - if (linker) { - const linkedCode = linker.linkCallExpression(node); - if (linkedCode !== undefined) { - source.overwrite(node.start, node.end, linkedCode); - markEdited(node.start, node.end); - + case 'CallExpression': { + if (isAlreadyEdited(node.start, node.end)) { return; } - } - if (!advancedOptimizations) { - return; - } - - // 1. Elide Angular Metadata check - let calleeName: string | undefined; - if (node.callee.type === 'Identifier') { - calleeName = node.callee.name; - } else if ( - node.callee.type === 'MemberExpression' && - node.callee.property.type === 'Identifier' - ) { - calleeName = node.callee.property.name; - } + if (linker) { + const linkedCode = linker.linkCallExpression(node); + if (linkedCode !== undefined) { + source.overwrite(node.start, node.end, linkedCode); + markEdited(node.start, node.end); - if (calleeName && angularMetadataFunctions.has(calleeName)) { - if ( - parentFunc && - (parentFunc.type === 'FunctionExpression' || - parentFunc.type === 'ArrowFunctionExpression') - ) { - source.overwrite(node.start, node.end, 'void 0'); - markEdited(node.start, node.end); + return; + } + } + if (!advancedOptimizations) { return; } - } - // 2. Mark Top-Level Pure Functions check - if (!pureAnnotate || functionDepth > 0 || classDepth > 0 || topLevelSafeMode) { - return; - } + // 1. Elide Angular Metadata check + let calleeName: string | undefined; + if (node.callee.type === 'Identifier') { + calleeName = node.callee.name; + } else if ( + node.callee.type === 'MemberExpression' && + node.callee.property.type === 'Identifier' + ) { + calleeName = node.callee.property.name; + } - const callee = unwrapParentheses(node.callee); - if ( - (callee.type === 'FunctionExpression' || callee.type === 'ArrowFunctionExpression') && - node.arguments.length !== 0 - ) { - return; - } + if (calleeName && angularMetadataFunctions.has(stripBundlerSuffix(calleeName))) { + if ( + staticBlockDepth > 0 || + (parentFunc && + (parentFunc.type === 'FunctionExpression' || + parentFunc.type === 'ArrowFunctionExpression')) + ) { + source.overwrite(node.start, node.end, 'void 0'); + markEdited(node.start, node.end); + + return; + } + } - if ( - callee.type === 'Identifier' && - (isTslibHelperName(callee.name) || isBabelHelperName(callee.name)) - ) { - return; - } + // 2. Mark Top-Level Pure Functions check + if (!pureAnnotate || functionDepth > 0 || classDepth > 0 || topLevelSafeMode) { + return; + } - if (!hasPureComment(node.start)) { - source.appendLeft(node.start, '/*#__PURE__*/ '); - } - break; - } + const callee = unwrapParentheses(node.callee); + if ( + (callee.type === 'FunctionExpression' || callee.type === 'ArrowFunctionExpression') && + node.arguments.length !== 0 + ) { + return; + } - case 'NewExpression': { - if ( - !advancedOptimizations || - !pureAnnotate || - functionDepth > 0 || - classDepth > 0 || - isAlreadyEdited(node.start, node.end) - ) { - return; - } + if ( + callee.type === 'Identifier' && + (isTslibHelperName(callee.name) || isBabelHelperName(callee.name)) + ) { + return; + } - if (!topLevelSafeMode) { if (!hasPureComment(node.start)) { source.appendLeft(node.start, '/*#__PURE__*/ '); } - - return; + break; } - const newCallee = node.callee; - if (newCallee.type === 'Identifier' && sideEffectFreeConstructors.has(newCallee.name)) { - if (!hasPureComment(node.start)) { - source.appendLeft(node.start, '/*#__PURE__*/ '); + case 'NewExpression': { + if ( + !advancedOptimizations || + !pureAnnotate || + functionDepth > 0 || + classDepth > 0 || + isAlreadyEdited(node.start, node.end) + ) { + return; + } + + if (!topLevelSafeMode) { + if (!hasPureComment(node.start)) { + source.appendLeft(node.start, '/*#__PURE__*/ '); + } + + return; + } + + const newCallee = node.callee; + if (newCallee.type === 'Identifier' && sideEffectFreeConstructors.has(newCallee.name)) { + if (!hasPureComment(node.start)) { + source.appendLeft(node.start, '/*#__PURE__*/ '); + } } + break; } - break; } - } - }); + }, + ); let map: DecodedSourceMap | undefined; if (options.sourcemap) { diff --git a/packages/angular/build/src/tools/oxc/traversal.ts b/packages/angular/build/src/tools/oxc/traversal.ts index f25f4bc78664..610cde17c6b1 100644 --- a/packages/angular/build/src/tools/oxc/traversal.ts +++ b/packages/angular/build/src/tools/oxc/traversal.ts @@ -23,6 +23,11 @@ export interface TraversalContext { */ classDepth: number; + /** + * The current class static block nesting depth. Code outside static blocks has depth 0. + */ + staticBlockDepth: number; + /** * The immediate enclosing function AST node, if currently inside a function. */ @@ -312,6 +317,7 @@ export function traversePostOrder( const stack: (Node | null)[] = [root]; let functionDepth = 0; let classDepth = 0; + let staticBlockDepth = 0; const functionStack: Node[] = []; while (stack.length > 0) { @@ -330,10 +336,13 @@ export function traversePostOrder( functionStack.pop(); } else if (isClass(type)) { classDepth--; + } else if (type === 'StaticBlock') { + staticBlockDepth--; } visit(node, { functionDepth, classDepth, + staticBlockDepth, parentFunc: functionStack[functionStack.length - 1], }); continue; @@ -347,6 +356,8 @@ export function traversePostOrder( functionStack.push(current); } else if (isClass(type)) { classDepth++; + } else if (type === 'StaticBlock') { + staticBlockDepth++; } pushChildNodes(current, stack);