From c5562c2a8ce38e5586a888d57906da56165feb58 Mon Sep 17 00:00:00 2001 From: Gabriel Silva Date: Sun, 15 Nov 2026 19:33:26 -0300 Subject: [PATCH 1/3] fix(r3): report an empty event handler and a two-way binding that cannot be written to --- .../src/component/metadata.rs | 9 ++ .../src/transform/html_to_r3.rs | 94 +++++++++++++++---- .../tests/integration_test.rs | 46 +++++++-- .../tests/r3_template_transform_test.rs | 74 +++++++++++++++ 4 files changed, 196 insertions(+), 27 deletions(-) diff --git a/crates/oxc_angular_compiler/src/component/metadata.rs b/crates/oxc_angular_compiler/src/component/metadata.rs index 5912678f2..0555013e7 100644 --- a/crates/oxc_angular_compiler/src/component/metadata.rs +++ b/crates/oxc_angular_compiler/src/component/metadata.rs @@ -113,6 +113,15 @@ impl AngularVersion { self.major > 20 || (self.major == 20 && self.minor >= 2) } + /// Check if a two-way binding rejects a `?.` anywhere on its target (v20.2.0+). + /// + /// Angular v20.2.0-next.3 (#62852) made `hasRecursiveSafeReceiver` part of the check, + /// so `[(x)]="a?.b.c"` is an error. Before, only a target that is itself a safe read + /// (`a?.b`) was. + pub fn rejects_safe_reads_in_two_way_bindings(&self) -> bool { + self.major > 20 || (self.major == 20 && self.minor >= 2) + } + /// Check if `animate.leave` needs `ɵɵAnimationsFeature()` (v20.2.0 to v20.3.0). /// /// In those versions only that feature sets up the registry `ɵɵanimateLeave` diff --git a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs index 3a4d82be5..6a6d42356 100644 --- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs +++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs @@ -90,6 +90,45 @@ fn property_binding_key_span(name: &str, key_span: Span) -> Span { /// The key span of an event named `name` (the identifier `parseAttribute` passes to /// `parseEvent`): a legacy animation event's `@` is not part of it. /// Reference: binding_parser.ts lines 660-667 (`parseEvent`) +/// Angular's error for an event handler with no expression. +const EMPTY_EXPRESSION: &str = "Empty expressions are not allowed"; + +/// Whether a two-way binding can write `$event` back to `ast`: a property or keyed read, also +/// behind `!` or `$any(...)`, with no `?.` on the way to it when `rejects_safe_reads` (v20.2+). +/// Angular's `_isAllowedAssignmentEvent` in `binding_parser.ts`; `this.$any(a)` is not allowed. +fn is_allowed_assignment_event(ast: &AngularExpression<'_>, rejects_safe_reads: bool) -> bool { + match ast { + AngularExpression::NonNullAssert(e) => { + is_allowed_assignment_event(&e.expression, rejects_safe_reads) + } + AngularExpression::Call(call) if call.args.len() == 1 && is_any(&call.receiver) => { + is_allowed_assignment_event(&call.args[0], rejects_safe_reads) + } + AngularExpression::PropertyRead(_) | AngularExpression::KeyedRead(_) => { + !rejects_safe_reads || !has_recursive_safe_receiver(ast) + } + _ => false, + } +} + +/// Whether `ast` is `$any` read from the component, as in `$any(a)`. +fn is_any(ast: &AngularExpression<'_>) -> bool { + matches!(ast, AngularExpression::PropertyRead(read) + if read.name == "$any" && matches!(read.receiver, AngularExpression::ImplicitReceiver(_))) +} + +/// Whether a read goes through `?.` anywhere on its receiver chain (`hasRecursiveSafeReceiver`). +fn has_recursive_safe_receiver(ast: &AngularExpression<'_>) -> bool { + match ast { + AngularExpression::SafePropertyRead(_) | AngularExpression::SafeKeyedRead(_) => true, + AngularExpression::ParenthesizedExpression(e) => has_recursive_safe_receiver(&e.expression), + AngularExpression::PropertyRead(e) => has_recursive_safe_receiver(&e.receiver), + AngularExpression::KeyedRead(e) => has_recursive_safe_receiver(&e.receiver), + AngularExpression::Call(e) => has_recursive_safe_receiver(&e.receiver), + _ => false, + } +} + fn event_key_span(name: &str, key_span: Span) -> Span { if name.starts_with('@') { Span::new(key_span.start + 1, key_span.end) } else { key_span } } @@ -4073,32 +4112,42 @@ impl<'a> HtmlToR3Transform<'a> { ) -> R3BoundEvent<'a> { let handler_span = self.calculate_event_handler_span(attr); let name_atom = Ident::from(self.allocator.alloc_str(name)); + let errors_before = self.errors.len(); // From v20.2 `animate.xChange` is an animation event, as Angular's // `_parseRegularEvent` gives it that type over two-way. Its handler is // the action itself (`return ctx.x`), with no `$event` assignment. - if name.starts_with("animate.") && self.supports_animate() { - let handler = self.parse_event_expression(&attr.value, handler_span); - return R3BoundEvent { - name: name_atom, - event_type: ParsedEventType::Animation, - handler, - target: None, - phase: None, - source_span: attr.span, - handler_span, - key_span, - }; + let is_animation = name.starts_with("animate.") && self.supports_animate(); + let handler = if is_animation { + self.parse_event_expression(&attr.value, handler_span) + } else { + // For two-way binding, the handler is just the target expression (e.g., `name`) + // NOT the full assignment `name = $event`. + // The $event reference and TwoWayBindingSetExpr are created in the ingest phase. + let handler = self.parse_binding_expression(&attr.value, handler_span); + if self.errors.len() == errors_before && matches!(handler, AngularExpression::Empty(_)) + { + self.report_error(EMPTY_EXPRESSION, handler_span); + } + handler + }; + // As Angular's `_parseEvent` for an assignment event, an expression `$event` cannot be + // written to (`a + b`, `a?.b`) is an error, unless parsing reported one already. + let rejects_safe_reads = + self.angular_version.is_none_or(|v| v.rejects_safe_reads_in_two_way_bindings()); + if self.errors.len() == errors_before + && !is_allowed_assignment_event(&handler, rejects_safe_reads) + { + self.report_error("Unsupported expression in a two-way binding", attr.span); } - // For two-way binding, the handler is just the target expression (e.g., `name`) - // NOT the full assignment `name = $event`. - // The $event reference and TwoWayBindingSetExpr are created in the ingest phase. - let handler = self.parse_binding_expression(&attr.value, handler_span); - R3BoundEvent { name: name_atom, - event_type: ParsedEventType::TwoWay, + event_type: if is_animation { + ParsedEventType::Animation + } else { + ParsedEventType::TwoWay + }, handler, target: None, phase: None, @@ -4108,19 +4157,26 @@ impl<'a> HtmlToR3Transform<'a> { } } - /// Parses an event handler expression. + /// Parses an event handler expression. A handler with no expression is an error, as in + /// Angular's `_parseAction`. fn parse_event_expression(&mut self, value: &Ident<'a>, span: Span) -> AngularExpression<'a> { let value_str = value.as_str(); if value_str.is_empty() { + self.report_error(EMPTY_EXPRESSION, span); return self.create_empty_expression(span); } let result = self.binding_parser.parse_event(value_str, span); + let is_empty = + result.errors.is_empty() && matches!(result.ast, AngularExpression::Empty(_)); // Collect any parse errors for error in result.errors { self.errors.push(error); } + if is_empty { + self.report_error(EMPTY_EXPRESSION, span); + } result.ast } diff --git a/crates/oxc_angular_compiler/tests/integration_test.rs b/crates/oxc_angular_compiler/tests/integration_test.rs index 39bfa2315..c21980b7c 100644 --- a/crates/oxc_angular_compiler/tests/integration_test.rs +++ b/crates/oxc_angular_compiler/tests/integration_test.rs @@ -27,6 +27,20 @@ fn compile_template_to_js_with_version( component_name: &str, angular_version: Option, ) -> String { + let (js, errors) = compile_template_to_js_and_errors(template, component_name, angular_version); + if !errors.is_empty() { + panic!("Transform errors: {errors:?}"); + } + js +} + +/// Compiles an Angular template to JavaScript and returns the transform errors with it, for a +/// template Angular rejects that the compiler still emits code for. +fn compile_template_to_js_and_errors( + template: &str, + component_name: &str, + angular_version: Option, +) -> (String, Vec) { use oxc_angular_compiler::pipeline::ingest::{IngestOptions, ingest_component_with_options}; let allocator = Allocator::default(); @@ -49,11 +63,7 @@ fn compile_template_to_js_with_version( ); let r3_result = transformer.transform(&html_result.nodes); - // Check for transform errors - if !r3_result.errors.is_empty() { - let errors: Vec<_> = r3_result.errors.iter().map(|e| e.msg.clone()).collect(); - panic!("Transform errors: {errors:?}"); - } + let errors: Vec<_> = r3_result.errors.iter().map(|e| e.msg.clone()).collect(); // Stage 3: Ingest R3 AST into IR let mut job = if let Some(version) = angular_version { @@ -83,7 +93,7 @@ fn compile_template_to_js_with_version( // Emit the main template function output.push_str(&emit_function(&emitter, &result.template_fn)); - output + (output, errors) } /// Emit a FunctionExpr to JavaScript. @@ -2456,12 +2466,14 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { // write-back assignment target. `a?.b = $event` is a JS SyntaxError (an // optional chain is not a legal assignment target), so the LHS of the // `|| (target = value)` clause must stay a plain member access even when the - // bound expression uses safe navigation under Angular v22. - let js = compile_template_to_js_with_version( + // bound expression uses safe navigation under Angular v22. Angular rejects such a + // target since v20.2, and so does the transform, but code is still emitted for it. + let (js, errors) = compile_template_to_js_and_errors( r#""#, "TestComponent", Some(AngularVersion::new(22, 0, 0)), ); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); // The twoWayBindingSet argument keeps its `?.` (it is only read, never assigned)... assert!(js.contains("ɵɵtwoWayBindingSet(ctx.a?.b"), "read side should keep `?.`, got:\n{js}"); // ...but the write-back assignment target must be a plain, assignable read. @@ -2472,6 +2484,24 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { ); } +#[test] +fn test_two_way_binding_with_a_safe_read_in_its_target_before_v20_2() { + // Before v20.2 (#62852) Angular only rejects a target that is itself a safe read. + let v20_1 = Some(AngularVersion::new(20, 1, 0)); + let (_, errors) = + compile_template_to_js_and_errors(r#""#, "TestComponent", v20_1); + assert!(errors.is_empty(), "{errors:?}"); + let (_, errors) = + compile_template_to_js_and_errors(r#""#, "TestComponent", v20_1); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); + let (_, errors) = compile_template_to_js_and_errors( + r#""#, + "TestComponent", + Some(AngularVersion::new(20, 2, 0)), + ); + assert_eq!(errors, ["Unsupported expression in a two-way binding"]); +} + #[test] fn test_safe_navigation_migration_ignores_qualified_call() { // Only the *unqualified* `$safeNavigationMigration(...)` helper is magic. A diff --git a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs index e796a7d0a..cb035b44b 100644 --- a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs +++ b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs @@ -1013,6 +1013,80 @@ mod events { vec![h!["Element", "div"], h!["BoundEvent", 0, "event", "", "v"]] ); } + #[test] + fn should_report_an_event_binding_with_no_expression() { + // Angular's `_parseAction`: "Empty expressions are not allowed". + for html in [ + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#"
"#, + r#""#, + r#""#, + ] { + assert_eq!( + get_transform_errors(html), + vec!["Empty expressions are not allowed".to_string()], + "{html}" + ); + } + } + + #[test] + fn should_report_a_two_way_binding_that_cannot_be_written_to() { + // Angular's `_isAllowedAssignmentEvent`: the expressions ngc 22.2.2 rejects. + for expr in [ + "a + b", + "a?.b", + "a?.b.c", + "a?.[0]", + "(a?.b).c", + "a()", + "a.b()", + "$any(a, b)", + "$any(a + b)", + "this.$any(a)", + "!a", + "(a)", + ] { + for html in + [format!(r#""#), format!(r#""#)] + { + assert_eq!( + get_transform_errors(&html), + vec!["Unsupported expression in a two-way binding".to_string()], + "{html}" + ); + } + } + assert_eq!( + get_transform_errors(r#""#), + vec!["Unsupported expression in a two-way binding".to_string()], + "an animation binding is checked too" + ); + } + + #[test] + fn should_accept_a_two_way_binding_that_can_be_written_to() { + for expr in ["a", "a.b", "a[0]", "a!", "a.b!", "$any(a)", "$any(a.b)", "(a).b"] { + let html = format!(r#""#); + assert!( + get_transform_errors(&html).is_empty(), + "{html}: {:?}", + get_transform_errors(&html) + ); + } + } + + #[test] + fn should_report_only_the_parse_error_of_a_two_way_binding_that_fails_to_parse() { + // `isValid` in Angular's `_parseEvent`: no second error on top of a parse error. + let errors = get_transform_errors(r#""#); + assert!(!errors.is_empty()); + assert!(!errors.iter().any(|e| e.contains("two-way")), "{errors:?}"); + } } // ============================================================================ From 2486bd0db97e7627b2897160e65ab154e177392d Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 18 Nov 2026 14:54:42 +0800 Subject: [PATCH 2/3] fix(r3): match ngc's two-way target check across versions - `rejects_safe_reads_in_two_way_bindings`: the `?.` check is in 20.1.4 and 20.2.0-next.3 (angular/angular#62852), not from 20.2.0. - Before 19.1.0-rc.0 `$any(a)` is not a two-way target; before 20.0.0-next.2 the parser dropped `(a)`, so `(a)` is `a`. - Parse the event side of a two-way binding as an action, as `_parseRegularEvent` does: `[(x)]="a | p"` reports the pipe error, and `a; b` / `a = b` report the same errors as ngc. - Report `Empty expressions are not allowed` also after a parse error, as `_parseAction` does (`(click)=")"`, `++;`). - Give `event_key_span` its doc comment back; use the upstream spec names and cases for the tests. Co-Authored-By: Claude Opus 5.5 --- .../src/component/metadata.rs | 31 +++- .../src/transform/html_to_r3.rs | 104 ++++++----- .../tests/increment_decrement_test.rs | 14 +- .../tests/integration_test.rs | 15 +- .../tests/r3_template_transform_test.rs | 169 +++++++++++++----- 5 files changed, 231 insertions(+), 102 deletions(-) diff --git a/crates/oxc_angular_compiler/src/component/metadata.rs b/crates/oxc_angular_compiler/src/component/metadata.rs index 0555013e7..51594ac59 100644 --- a/crates/oxc_angular_compiler/src/component/metadata.rs +++ b/crates/oxc_angular_compiler/src/component/metadata.rs @@ -113,13 +113,34 @@ impl AngularVersion { self.major > 20 || (self.major == 20 && self.minor >= 2) } - /// Check if a two-way binding rejects a `?.` anywhere on its target (v20.2.0+). + /// Check if a two-way binding rejects a `?.` anywhere on its target + /// (v20.1.4+ / v20.2.0-next.3+). /// - /// Angular v20.2.0-next.3 (#62852) made `hasRecursiveSafeReceiver` part of the check, - /// so `[(x)]="a?.b.c"` is an error. Before, only a target that is itself a safe read - /// (`a?.b`) was. + /// `angular/angular#62852` added `hasRecursiveSafeReceiver` to + /// `_isAllowedAssignmentEvent`, so `[(x)]="a?.b.c"` is an error. Before, only + /// a target that is itself a safe read (`a?.b`) was. First in 20.1.4 and + /// 20.2.0-next.3; the 20.0.x and 19.2.x lines never got it. pub fn rejects_safe_reads_in_two_way_bindings(&self) -> bool { - self.major > 20 || (self.major == 20 && self.minor >= 2) + self.fixed_since(&[ + Self::new(20, 1, 4), + Self::new(20, 2, 0).with_prerelease(Prerelease::Next(3)), + ]) + } + + /// Check if a two-way binding accepts `$any(a)` as its target (v19.1.0-rc.0+). + /// + /// Before, `_isAllowedAssignmentEvent` had no `$any(...)` case, so the call + /// was an error. The 19.0.x line never got it. + pub fn allows_any_in_two_way_bindings(&self) -> bool { + self.cmp_release(&Self::new(19, 1, 0).with_prerelease(Prerelease::Rc(0))).is_ge() + } + + /// Check if the expression parser keeps `(a)` as its own node (v20.0.0-next.2+). + /// + /// Before, `parsePrimary` returned the inner expression, so a two-way + /// target `(a)` was the read `a` and allowed. + pub fn keeps_parenthesized_expressions(&self) -> bool { + self.cmp_release(&Self::new(20, 0, 0).with_prerelease(Prerelease::Next(2))).is_ge() } /// Check if `animate.leave` needs `ɵɵAnimationsFeature()` (v20.2.0 to v20.3.0). diff --git a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs index 6a6d42356..a87bd2671 100644 --- a/crates/oxc_angular_compiler/src/transform/html_to_r3.rs +++ b/crates/oxc_angular_compiler/src/transform/html_to_r3.rs @@ -87,34 +87,64 @@ fn property_binding_key_span(name: &str, key_span: Span) -> Span { } } -/// The key span of an event named `name` (the identifier `parseAttribute` passes to -/// `parseEvent`): a legacy animation event's `@` is not part of it. -/// Reference: binding_parser.ts lines 660-667 (`parseEvent`) /// Angular's error for an event handler with no expression. const EMPTY_EXPRESSION: &str = "Empty expressions are not allowed"; +/// The parts of Angular's `_isAllowedAssignmentEvent` that depend on the version. +#[derive(Clone, Copy)] +struct AssignmentTargetRules { + /// `$any(a)` is unwrapped (v19.1.0-rc.0+); before, the call is an error. + allows_any: bool, + /// `(a)` is its own node, which is an error (v20.0.0-next.2+); before, it is `a`. + keeps_parens: bool, + /// A `?.` anywhere on the target is an error (v20.1.4+ / v20.2.0-next.3+); before, only a + /// target that is itself a safe read is. + rejects_safe_reads: bool, +} + +impl AssignmentTargetRules { + fn new(version: Option) -> Self { + Self { + allows_any: version.is_none_or(|v| v.allows_any_in_two_way_bindings()), + keeps_parens: version.is_none_or(|v| v.keeps_parenthesized_expressions()), + rejects_safe_reads: version.is_none_or(|v| v.rejects_safe_reads_in_two_way_bindings()), + } + } +} + /// Whether a two-way binding can write `$event` back to `ast`: a property or keyed read, also -/// behind `!` or `$any(...)`, with no `?.` on the way to it when `rejects_safe_reads` (v20.2+). -/// Angular's `_isAllowedAssignmentEvent` in `binding_parser.ts`; `this.$any(a)` is not allowed. -fn is_allowed_assignment_event(ast: &AngularExpression<'_>, rejects_safe_reads: bool) -> bool { +/// behind `!` or `$any(...)`, with no `?.` on the way to it, as far as `rules` (the version) +/// asks. Angular's `_isAllowedAssignmentEvent` in `binding_parser.ts`; `this.$any(a)` is not +/// allowed. +fn is_allowed_assignment_event(ast: &AngularExpression<'_>, rules: AssignmentTargetRules) -> bool { match ast { - AngularExpression::NonNullAssert(e) => { - is_allowed_assignment_event(&e.expression, rejects_safe_reads) + AngularExpression::NonNullAssert(e) => is_allowed_assignment_event(&e.expression, rules), + AngularExpression::ParenthesizedExpression(e) if !rules.keeps_parens => { + is_allowed_assignment_event(&e.expression, rules) } - AngularExpression::Call(call) if call.args.len() == 1 && is_any(&call.receiver) => { - is_allowed_assignment_event(&call.args[0], rejects_safe_reads) + AngularExpression::Call(call) + if rules.allows_any && call.args.len() == 1 && is_any(&call.receiver, rules) => + { + is_allowed_assignment_event(&call.args[0], rules) } AngularExpression::PropertyRead(_) | AngularExpression::KeyedRead(_) => { - !rejects_safe_reads || !has_recursive_safe_receiver(ast) + !rules.rejects_safe_reads || !has_recursive_safe_receiver(ast) } _ => false, } } /// Whether `ast` is `$any` read from the component, as in `$any(a)`. -fn is_any(ast: &AngularExpression<'_>) -> bool { - matches!(ast, AngularExpression::PropertyRead(read) - if read.name == "$any" && matches!(read.receiver, AngularExpression::ImplicitReceiver(_))) +fn is_any(ast: &AngularExpression<'_>, rules: AssignmentTargetRules) -> bool { + match ast { + AngularExpression::ParenthesizedExpression(e) if !rules.keeps_parens => { + is_any(&e.expression, rules) + } + AngularExpression::PropertyRead(read) => { + read.name == "$any" && matches!(read.receiver, AngularExpression::ImplicitReceiver(_)) + } + _ => false, + } } /// Whether a read goes through `?.` anywhere on its receiver chain (`hasRecursiveSafeReceiver`). @@ -129,6 +159,9 @@ fn has_recursive_safe_receiver(ast: &AngularExpression<'_>) -> bool { } } +/// The key span of an event named `name` (the identifier `parseAttribute` passes to +/// `parseEvent`): a legacy animation event's `@` is not part of it. +/// Reference: binding_parser.ts lines 660-667 (`parseEvent`) fn event_key_span(name: &str, key_span: Span) -> Span { if name.starts_with('@') { Span::new(key_span.start + 1, key_span.end) } else { key_span } } @@ -4118,25 +4151,18 @@ impl<'a> HtmlToR3Transform<'a> { // `_parseRegularEvent` gives it that type over two-way. Its handler is // the action itself (`return ctx.x`), with no `$event` assignment. let is_animation = name.starts_with("animate.") && self.supports_animate(); - let handler = if is_animation { - self.parse_event_expression(&attr.value, handler_span) - } else { - // For two-way binding, the handler is just the target expression (e.g., `name`) - // NOT the full assignment `name = $event`. - // The $event reference and TwoWayBindingSetExpr are created in the ingest phase. - let handler = self.parse_binding_expression(&attr.value, handler_span); - if self.errors.len() == errors_before && matches!(handler, AngularExpression::Empty(_)) - { - self.report_error(EMPTY_EXPRESSION, handler_span); - } - handler - }; - // As Angular's `_parseEvent` for an assignment event, an expression `$event` cannot be - // written to (`a + b`, `a?.b`) is an error, unless parsing reported one already. - let rejects_safe_reads = - self.angular_version.is_none_or(|v| v.rejects_safe_reads_in_two_way_bindings()); + // As in Angular's `_parseRegularEvent`, the event side is parsed as an action, also for + // two-way. The handler is just the target expression (e.g., `name`), NOT the full + // assignment `name = $event`: the $event reference and TwoWayBindingSetExpr are created + // in the ingest phase. + let handler = self.parse_event_expression(&attr.value, handler_span); + // A target that `$event` cannot be written to (`a + b`, `a?.b`) is an error, unless + // parsing already reported one (`isValid` upstream). if self.errors.len() == errors_before - && !is_allowed_assignment_event(&handler, rejects_safe_reads) + && !is_allowed_assignment_event( + &handler, + AssignmentTargetRules::new(self.angular_version), + ) { self.report_error("Unsupported expression in a two-way binding", attr.span); } @@ -4157,8 +4183,8 @@ impl<'a> HtmlToR3Transform<'a> { } } - /// Parses an event handler expression. A handler with no expression is an error, as in - /// Angular's `_parseAction`. + /// Parses an event handler expression. A handler with no expression is an error, also after + /// a parse error, as in Angular's `_parseAction`. fn parse_event_expression(&mut self, value: &Ident<'a>, span: Span) -> AngularExpression<'a> { let value_str = value.as_str(); if value_str.is_empty() { @@ -4167,14 +4193,8 @@ impl<'a> HtmlToR3Transform<'a> { } let result = self.binding_parser.parse_event(value_str, span); - let is_empty = - result.errors.is_empty() && matches!(result.ast, AngularExpression::Empty(_)); - - // Collect any parse errors - for error in result.errors { - self.errors.push(error); - } - if is_empty { + self.errors.extend(result.errors); + if matches!(result.ast, AngularExpression::Empty(_)) { self.report_error(EMPTY_EXPRESSION, span); } diff --git a/crates/oxc_angular_compiler/tests/increment_decrement_test.rs b/crates/oxc_angular_compiler/tests/increment_decrement_test.rs index f453e44c1..cae95e70d 100644 --- a/crates/oxc_angular_compiler/tests/increment_decrement_test.rs +++ b/crates/oxc_angular_compiler/tests/increment_decrement_test.rs @@ -322,14 +322,20 @@ fn assert_errors(template: &str, expected: &[&str]) { #[test] fn missing_operand_errors() { // ngc 22.3.0-next.4 messages (`Parser Error: ... in [...]`). For `++;` and - // `++,a` it also reports `Empty expressions are not allowed`, which this - // compiler does not report for any empty action. + // `++,a` the action is empty, so `_parseAction` also reports + // `Empty expressions are not allowed`. for (template, expected) in [ - (r#""#, &["Unexpected token ; at column 3 in [++;]"][..]), + ( + r#""#, + &["Unexpected token ; at column 3 in [++;]", "Empty expressions are not allowed"][..], + ), (r#""#, &["Unexpected token ) at column 6 in [fn(++)]"]), (r#""#, &["Unexpected token ] at column 4 in [[++]]"]), (r#""#, &["Unexpected token ) at column 4 in [(++)]"]), - (r#""#, &["Unexpected token , at column 3 in [++,x]"]), + ( + r#""#, + &["Unexpected token , at column 3 in [++,x]", "Empty expressions are not allowed"], + ), (r#""#, &["Unexpected token ; at column 4 in [++ ;x]"]), ( r#""#, diff --git a/crates/oxc_angular_compiler/tests/integration_test.rs b/crates/oxc_angular_compiler/tests/integration_test.rs index c21980b7c..c9c4bb9ff 100644 --- a/crates/oxc_angular_compiler/tests/integration_test.rs +++ b/crates/oxc_angular_compiler/tests/integration_test.rs @@ -28,9 +28,7 @@ fn compile_template_to_js_with_version( angular_version: Option, ) -> String { let (js, errors) = compile_template_to_js_and_errors(template, component_name, angular_version); - if !errors.is_empty() { - panic!("Transform errors: {errors:?}"); - } + assert!(errors.is_empty(), "Transform errors: {errors:?}"); js } @@ -2467,7 +2465,7 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { // optional chain is not a legal assignment target), so the LHS of the // `|| (target = value)` clause must stay a plain member access even when the // bound expression uses safe navigation under Angular v22. Angular rejects such a - // target since v20.2, and so does the transform, but code is still emitted for it. + // target, and so does the transform, but code is still emitted for it. let (js, errors) = compile_template_to_js_and_errors( r#""#, "TestComponent", @@ -2485,9 +2483,10 @@ fn test_two_way_binding_writeback_target_is_never_optional_v22() { } #[test] -fn test_two_way_binding_with_a_safe_read_in_its_target_before_v20_2() { - // Before v20.2 (#62852) Angular only rejects a target that is itself a safe read. - let v20_1 = Some(AngularVersion::new(20, 1, 0)); +fn test_two_way_binding_with_a_safe_read_in_its_target_before_v20_1_4() { + // Before 20.1.4 / 20.2.0-next.3 (#62852) Angular only rejects a target that is itself a + // safe read. + let v20_1 = Some(AngularVersion::new(20, 1, 3)); let (_, errors) = compile_template_to_js_and_errors(r#""#, "TestComponent", v20_1); assert!(errors.is_empty(), "{errors:?}"); @@ -2497,7 +2496,7 @@ fn test_two_way_binding_with_a_safe_read_in_its_target_before_v20_2() { let (_, errors) = compile_template_to_js_and_errors( r#""#, "TestComponent", - Some(AngularVersion::new(20, 2, 0)), + Some(AngularVersion::new(20, 1, 4)), ); assert_eq!(errors, ["Unsupported expression in a two-way binding"]); } diff --git a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs index cb035b44b..aad490f98 100644 --- a/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs +++ b/crates/oxc_angular_compiler/tests/r3_template_transform_test.rs @@ -11,6 +11,7 @@ use oxc_angular_compiler::ast::expression::BindingType; use oxc_angular_compiler::ast::r3::R3Node; use oxc_angular_compiler::parser::html::HtmlParser; use oxc_angular_compiler::transform::html_to_r3::{HtmlToR3Transform, TransformOptions}; +use oxc_angular_compiler::{AngularVersion, Prerelease}; use utils::unparse; @@ -810,6 +811,19 @@ fn get_transform_errors(html: &str) -> Vec { r3_result.errors.iter().map(|e| e.msg.clone()).collect() } +/// Like `get_transform_errors`, targeting an Angular version. +fn get_transform_errors_with_version(html: &str, version: AngularVersion) -> Vec { + let allocator = Allocator::default(); + let html_result = HtmlParser::new(&allocator, html, "test.html").parse(); + let options = TransformOptions { + collect_comment_nodes: false, + angular_version: Some(version), + ..Default::default() + }; + let r3_result = HtmlToR3Transform::new(&allocator, html, options).transform(&html_result.nodes); + r3_result.errors.iter().map(|e| e.msg.clone()).collect() +} + // ============================================================================ // Tests: Nodes without binding // ============================================================================ @@ -1013,12 +1027,14 @@ mod events { vec![h!["Element", "div"], h!["BoundEvent", 0, "event", "", "v"]] ); } + #[test] - fn should_report_an_event_binding_with_no_expression() { - // Angular's `_parseAction`: "Empty expressions are not allowed". + fn should_report_an_error_on_empty_expression() { + // TS: it("should report an error on empty expression") + // Angular's `_parseAction`, which two-way and animation events go through too. for html in [ - r#""#, - r#""#, + r#"
"#, + r#"
"#, r#""#, r#""#, r#""#, @@ -1026,66 +1042,133 @@ mod events { r#""#, r#""#, ] { - assert_eq!( - get_transform_errors(html), - vec!["Empty expressions are not allowed".to_string()], - "{html}" - ); + assert_eq!(get_transform_errors(html), ["Empty expressions are not allowed"], "{html}"); } + // Also after a parse error, as `_parseAction` checks the AST. + assert_eq!( + get_transform_errors(r#""#), + ["Unexpected token ) at column 1 in [)]", "Empty expressions are not allowed"] + ); } #[test] - fn should_report_a_two_way_binding_that_cannot_be_written_to() { - // Angular's `_isAllowedAssignmentEvent`: the expressions ngc 22.2.2 rejects. - for expr in [ - "a + b", - "a?.b", - "a?.b.c", - "a?.[0]", - "(a?.b).c", - "a()", + fn should_report_pipes_in_two_way_bindings() { + // TS: it("should report pipes in two-way bindings") + // The event side is parsed as an action, so it is a parse error, not an unsupported target. + let errors = get_transform_errors(r#"
"#); + assert!( + errors.iter().any(|e| e.starts_with("Cannot have a pipe in an action expression")), + "{errors:?}" + ); + assert!(!errors.iter().any(|e| e.contains("two-way")), "{errors:?}"); + } + + #[test] + fn should_report_unsupported_expressions_in_two_way_bindings() { + // TS: it("should report unsupported expressions in two-way bindings") + let upstream = [ + "v + 1", + "foo.bar?.baz", + "foo.bar?.['baz']", + "foo?.bar.baz[0]", + "foo?.bar.baz[0].boo[0]", + "foo?.bar.baz()", + "(foo?.bar).baz", + "true", + "123", "a.b()", - "$any(a, b)", - "$any(a + b)", - "this.$any(a)", + "v()", + "[1, 2, 3]", + "{a: 1, b: 2, c: 3}", + "v === 1", + "a || b", + "a && b", + "a ?? b", "!a", - "(a)", - ] { - for html in - [format!(r#""#), format!(r#""#)] - { + "!!a", + "a ? b : c", + "$any(a || b)", + "this.$any(a)", + "$any(a, b)", + ]; + // More targets ngc 22.2.2 rejects. + let more = ["a?.b", "a?.[0]", "$any(a + b)", "(a)"]; + for expr in upstream.into_iter().chain(more) { + for html in [ + format!(r#"
"#), + format!(r#"
"#), + ] { assert_eq!( get_transform_errors(&html), - vec!["Unsupported expression in a two-way binding".to_string()], + ["Unsupported expression in a two-way binding"], "{html}" ); } } assert_eq!( get_transform_errors(r#""#), - vec!["Unsupported expression in a two-way binding".to_string()], + ["Unsupported expression in a two-way binding"], "an animation binding is checked too" ); - } + // An error from the event side comes alone (`isValid` in `_parseRegularEvent`), but one + // from the property side does not stop the check. + let errors = get_transform_errors(r#"
"#); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("Binding expression cannot contain chained expression")); + assert_eq!(errors[1], "Unsupported expression in a two-way binding"); + let errors = get_transform_errors(r#"
"#); + assert!(!errors.is_empty() && !errors.iter().any(|e| e.contains("two-way")), "{errors:?}"); - #[test] - fn should_accept_a_two_way_binding_that_can_be_written_to() { - for expr in ["a", "a.b", "a[0]", "a!", "a.b!", "$any(a)", "$any(a.b)", "(a).b"] { - let html = format!(r#""#); - assert!( - get_transform_errors(&html).is_empty(), - "{html}: {:?}", - get_transform_errors(&html) - ); + for expr in [ + "(foo?.bar ?? bar).baz", + "a", + "a.b", + "a[0]", + "a!", + "a.b!", + "$any(a)", + "$any(a.b)", + "(a).b", + ] { + let html = format!(r#"
"#); + let errors = get_transform_errors(&html); + assert!(errors.is_empty(), "{html}: {errors:?}"); } } #[test] - fn should_report_only_the_parse_error_of_a_two_way_binding_that_fails_to_parse() { - // `isValid` in Angular's `_parseEvent`: no second error on top of a parse error. - let errors = get_transform_errors(r#""#); - assert!(!errors.is_empty()); - assert!(!errors.iter().any(|e| e.contains("two-way")), "{errors:?}"); + fn should_check_a_two_way_target_as_its_angular_version_does() { + let errors = |version: AngularVersion, expr: &str| { + get_transform_errors_with_version(&format!(r#"
"#), version) + }; + let unsupported = ["Unsupported expression in a two-way binding"]; + let next = |major, minor, n| { + AngularVersion::new(major, minor, 0).with_prerelease(Prerelease::Next(n)) + }; + // `?.` anywhere on the target: from 20.1.4 and 20.2.0-next.3 (angular/angular#62852). + for version in + [AngularVersion::new(20, 0, 7), AngularVersion::new(20, 1, 3), next(20, 2, 2)] + { + assert!(errors(version, "a?.b.c").is_empty(), "{version:?}"); + assert_eq!(errors(version, "a?.b"), unsupported, "{version:?}"); + } + for version in + [AngularVersion::new(20, 1, 4), next(20, 2, 3), AngularVersion::new(20, 2, 0)] + { + assert_eq!(errors(version, "a?.b.c"), unsupported, "{version:?}"); + } + // `$any(a)`: from 19.1.0-rc.0. + let rc0 = AngularVersion::new(19, 1, 0).with_prerelease(Prerelease::Rc(0)); + for version in [AngularVersion::new(19, 0, 7), next(19, 1, 4)] { + assert_eq!(errors(version, "$any(a)"), unsupported, "{version:?}"); + } + assert_eq!(errors(rc0, "$any(a)"), Vec::::new()); + // `(a)` is `a` before the parser kept parentheses (20.0.0-next.2). + for expr in ["(a)", "((a))", "(a)!", "$any((a))", "($any)(a)"] { + assert!(errors(AngularVersion::new(19, 2, 15), expr).is_empty(), "{expr}"); + assert_eq!(errors(next(20, 0, 2), expr), unsupported, "{expr}"); + } + assert_eq!(errors(AngularVersion::new(19, 2, 15), "(a + b)"), unsupported); } } From 0cd3afa7d56fac1e13877601fa191e68a2453dbf Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 18 Nov 2026 18:09:20 +0800 Subject: [PATCH 3/3] fix(linker): report a partial component whose template has errors The linker dropped template errors (`.ok()?`): the declaration stayed unlinked and the build passed, so an AOT app failed at runtime. With the new two-way check, a 20.1.3 library with `[(x)]="a?.b.c"` linked for 20.1.4+ hits this. - `LinkResult.errors` (Rust and napi): one error per such component, "Errors found in the template:" and each error with its place in the template, labelled at the `template` string, as Angular's `PartialComponentLinkerVersion1` throws a `FatalLinkerError`. The component is left as it is; the rest of the file still links. - The Vite linker plugin fails the build on them, in the transform hook and in the dependency optimizer (as the Angular CLI's prebundle does). - `describeDiagnostic` moves to `vite-plugin/utils/diagnostic.ts` for both plugins. Checked on every partial package file available locally (67 files, 124 components, Angular 22.x cdk/material/router and analogjs): no errors, and ngc's Babel linker links them all too. Co-Authored-By: Claude Opus 5.5 --- .../src/component/transform.rs | 9 +- crates/oxc_angular_compiler/src/linker/mod.rs | 76 +++++++++++++++-- .../oxc_angular_compiler/tests/linker_test.rs | 82 +++++++++++++++++++ napi/angular-compiler/index.d.ts | 10 ++- napi/angular-compiler/src/lib.rs | 11 ++- napi/angular-compiler/test/linker.test.ts | 56 +++++++++++++ .../vite-plugin/angular-linker-plugin.ts | 22 ++++- napi/angular-compiler/vite-plugin/index.ts | 12 +-- .../vite-plugin/utils/diagnostic.ts | 13 +++ 9 files changed, 266 insertions(+), 25 deletions(-) create mode 100644 napi/angular-compiler/vite-plugin/utils/diagnostic.ts diff --git a/crates/oxc_angular_compiler/src/component/transform.rs b/crates/oxc_angular_compiler/src/component/transform.rs index c9a58f241..4c987b455 100644 --- a/crates/oxc_angular_compiler/src/component/transform.rs +++ b/crates/oxc_angular_compiler/src/component/transform.rs @@ -9082,8 +9082,15 @@ pub fn compile_template_for_linker<'a>( let r3_result = transformer.transform(nodes); if !r3_result.errors.is_empty() { + let template_origin = TemplateOrigin::Unknown; for error in &r3_result.errors { - diagnostics.push(OxcDiagnostic::error(error.msg.clone())); + // An expression parser error has no position (an empty default span); its message + // quotes the expression instead. + diagnostics.push(if error.span.start.file.content.is_empty() { + OxcDiagnostic::error(error.msg.clone()) + } else { + html_parse_error_diagnostic(error, &template_origin) + }); } return Err(diagnostics); } diff --git a/crates/oxc_angular_compiler/src/linker/mod.rs b/crates/oxc_angular_compiler/src/linker/mod.rs index 282a708c9..b9c0529a6 100644 --- a/crates/oxc_angular_compiler/src/linker/mod.rs +++ b/crates/oxc_angular_compiler/src/linker/mod.rs @@ -43,6 +43,7 @@ use oxc_ast::ast::{ PropertyKind, Statement, }; use oxc_ast_visit::{Visit, walk}; +use oxc_diagnostics::OxcDiagnostic; use oxc_parser::Parser; use oxc_semantic::{Scoping, SemanticBuilder}; use oxc_span::{GetSpan, SourceType, Span}; @@ -104,6 +105,9 @@ pub struct LinkResult { pub map: Option, /// Whether any declarations were linked. pub linked: bool, + /// The errors of each component whose template has errors. That component stays as it is; + /// a build should fail on them, as Angular's linker throws a `FatalLinkerError`. + pub errors: Vec, } /// Options for linking Angular partial declarations. @@ -139,24 +143,33 @@ pub fn link_with_options( // Quick check: if no declarations, return early. Match without the `ɵɵ` prefix because // minifiers may write it as `\u0275` escapes; the AST below has them decoded. if !code.contains("ngDeclare") { - return LinkResult { code: code.to_string(), map: None, linked: false }; + return LinkResult { code: code.to_string(), ..LinkResult::default() }; } let source_type = SourceType::from_path(filename).unwrap_or(SourceType::mjs()); let parser_result = Parser::new(allocator, code, source_type).parse(); if parser_result.fatal_error || !parser_result.diagnostics.is_empty() { - return LinkResult { code: code.to_string(), map: None, linked: false }; + return LinkResult { code: code.to_string(), ..LinkResult::default() }; } let program = parser_result.program; let mut edits: Vec = Vec::new(); + let mut errors: Vec = Vec::new(); // Walk all statements looking for ɵɵngDeclare* calls - collect_declaration_edits(allocator, &program, code, filename, options, &mut edits); + collect_declaration_edits( + allocator, + &program, + code, + filename, + options, + &mut edits, + &mut errors, + ); if edits.is_empty() { - return LinkResult { code: code.to_string(), map: None, linked: false }; + return LinkResult { code: code.to_string(), map: None, linked: false, errors }; } let (linked_code, map) = if options.sourcemap { @@ -165,7 +178,7 @@ pub fn link_with_options( (crate::optimizer::apply_edits(code, edits), None) }; - LinkResult { code: linked_code, map, linked: true } + LinkResult { code: linked_code, map, linked: true, errors } } /// Find all ɵɵngDeclare* calls and generate edits. @@ -179,6 +192,7 @@ fn collect_declaration_edits<'a>( filename: &str, options: &LinkOptions, edits: &mut Vec, + errors: &mut Vec, ) { let scoping = SemanticBuilder::new().build(program).semantic.into_scoping(); let mut collector = DeclarationCollector { @@ -187,6 +201,7 @@ fn collect_declaration_edits<'a>( filename, options, edits, + errors, statement_start: None, decorator: None, scoping, @@ -250,6 +265,8 @@ struct DeclarationCollector<'s, 'a> { filename: &'s str, options: &'s LinkOptions, edits: &'s mut Vec, + /// Errors of the declarations that do not link (see [`LinkResult::errors`]) + errors: &'s mut Vec, /// The expression of the statement being visited, and whether a `;` may go before it: true for a statement in /// a statement list, false for `export default` or the bare body of `if`, a loop or a label statement_start: Option<(Span, bool)>, @@ -326,6 +343,7 @@ impl<'a> DeclarationCollector<'_, 'a> { self.options, self.allocator, &mut pool, + self.errors, )?; let replacement = if statements.is_empty() { definition @@ -353,6 +371,7 @@ impl<'a> DeclarationCollector<'_, 'a> { self.options, self.allocator, &mut emit_scope.pool, + self.errors, ) else { emit_scope.pool = saved; return None; @@ -1109,6 +1128,8 @@ fn get_factory_target(obj: &ObjectExpression<'_>, source: &str) -> &'static str /// Link a single ɵɵngDeclare* call, generating the definition and the /// statements its constants and child template functions need, with `pool`. +/// What keeps it from linking and should fail the build goes to `errors`. +#[expect(clippy::too_many_arguments)] fn link_declaration<'a>( name: &str, call: &CallExpression<'_>, @@ -1117,6 +1138,7 @@ fn link_declaration<'a>( options: &LinkOptions, allocator: &'a Allocator, pool: &mut LinkPool<'a>, + errors: &mut Vec, ) -> Option<(String, String)> { let meta = get_metadata_object(call)?; let ns = get_ng_import_namespace(call); @@ -1135,7 +1157,9 @@ fn link_declaration<'a>( return Some(link_directive(meta, source, ns, type_name, options, allocator, pool)); } DECLARE_COMPONENT => { - return link_component(meta, source, filename, ns, type_name, options, allocator, pool); + return link_component( + meta, source, filename, ns, type_name, options, allocator, pool, errors, + ); } _ => return None, }; @@ -2441,6 +2465,34 @@ fn has_directive_dependencies(meta: &ObjectExpression<'_>) -> bool { }) } +/// The error for a partial component whose template has errors, like the `FatalLinkerError` +/// Angular's `PartialComponentLinkerVersion1` throws: "Errors found in the template:" and each +/// error, at the `template` string. +fn template_errors( + diagnostics: &[OxcDiagnostic], + template: Option, + source: &str, + filename: &str, +) -> OxcDiagnostic { + let mut message = String::from("Errors found in the template:"); + for diagnostic in diagnostics { + message.push('\n'); + message.push_str(&diagnostic.message); + if let Some(help) = &diagnostic.help { + message.push_str(" ("); + message.push_str(help); + message.push(')'); + } + } + let error = OxcDiagnostic::error(message); + let Some(span) = template else { return error }; + let before = &source[..(span.start as usize).min(source.len())]; + let line_start = before.rfind('\n').map_or(0, |i| i + 1); + let (line, column) = + (before.matches('\n').count() + 1, before[line_start..].chars().count() + 1); + error.with_label(span).with_help(format!("{filename}:{line}:{column}")) +} + /// Link ɵɵngDeclareComponent → ɵɵdefineComponent. /// /// A component extends a directive with template compilation and additional @@ -2464,6 +2516,7 @@ fn link_component<'a>( options: &LinkOptions, allocator: &'a Allocator, pool: &mut LinkPool<'a>, + errors: &mut Vec, ) -> Option<(String, String)> { // Extract template string - required for component linking let template = get_string_property(meta, "template")?; @@ -2547,8 +2600,15 @@ fn link_component<'a>( legacy_optional_chaining, pool.next_index, &mut pool.shared, - ) - .ok()?; + ); + let template_output = match template_output { + Ok(output) => output, + Err(diagnostics) => { + let template = get_property_expression(meta, "template").map(GetSpan::span); + errors.push(template_errors(&diagnostics, template, source, filename)); + return None; + } + }; pool.next_index = template_output.next_pool_index; // Build the defineComponent properties diff --git a/crates/oxc_angular_compiler/tests/linker_test.rs b/crates/oxc_angular_compiler/tests/linker_test.rs index bab0de545..d54791ec2 100644 --- a/crates/oxc_angular_compiler/tests/linker_test.rs +++ b/crates/oxc_angular_compiler/tests/linker_test.rs @@ -1662,3 +1662,85 @@ fn test_link_keys_that_are_not_identifiers_stay_quoted() { assert!(parsed.diagnostics.is_empty(), "does not parse:\n{linked}"); } } + +/// A partial component whose template ngc 20.1.3 accepts and 20.1.4 rejects. +fn two_way_safe_read_component(type_name: &str, template: &str) -> String { + format!( + r#"{type_name}.ɵcmp = i0.ɵɵngDeclareComponent({{ minVersion: "14.0.0", version: "20.1.3", type: {type_name}, isStandalone: true, selector: "x-{type_name}", ngImport: i0, template: '{template}' }}); +"# + ) +} + +/// A template error keeps the component from linking and is reported, as Angular's linker +/// throws `Errors found in the template:` for it. +#[test] +fn test_link_reports_a_template_error() { + let code = format!( + "import * as i0 from \"@angular/core\";\nclass Bad {{\n}}\n{}", + two_way_safe_read_component("Bad", r#""#) + ); + let link_for = |version| { + let allocator = Allocator::default(); + let options = LinkOptions { angular_version: Some(version), ..LinkOptions::default() }; + let result = link_with_options(&allocator, &code, "lib.mjs", &options); + let errors: Vec<_> = result + .errors + .iter() + .map(|e| (e.message.to_string(), e.help.as_deref().map(str::to_string))) + .collect(); + (result.linked, result.code, errors) + }; + + let (linked, _, errors) = link_for(AngularVersion::new(20, 1, 3)); + assert!(linked); + assert_eq!(errors, []); + + let (linked, linked_code, errors) = link_for(AngularVersion::new(20, 1, 4)); + assert!(!linked); + assert_eq!(linked_code, code, "the declaration stays as it is"); + // In characters: the line has `ɵ`s before it. + let line = code.lines().nth(3).unwrap(); + let template_column = line[..line.find("'"#), + two_way_safe_read_component("Good", r#""#), + ); + let allocator = Allocator::default(); + let result = link(&allocator, &code, "lib.mjs"); + assert!(result.linked); + assert_eq!(result.errors.len(), 1, "{:?}", result.errors); + assert!(result.code.contains("Bad.ɵcmp = i0.ɵɵngDeclareComponent("), "{}", result.code); + assert!(!result.code.contains("Good.ɵcmp = i0.ɵɵngDeclareComponent("), "{}", result.code); + // A template parse error is reported the same way. + let code = code.replace(r#""#, "
"); + let result = link(&allocator, &code, "lib.mjs"); + assert_eq!(result.errors.len(), 1, "{:?}", result.errors); + assert!( + result.errors[0] + .message + .starts_with("Errors found in the template:\nUnexpected closing tag"), + "{:?}", + result.errors + ); + // An expression error has no position in the template, so none is made up for it. + let code = code.replace("
", "

\\n{{ a + }}

"); + let result = link(&allocator, &code, "lib.mjs"); + assert!(!result.errors.is_empty(), "{}", result.code); + for error in &result.errors { + assert!(error.message.contains("[ a + ]"), "{}", error.message); + assert!(!error.message.contains("of the template)"), "{}", error.message); + } +} diff --git a/napi/angular-compiler/index.d.ts b/napi/angular-compiler/index.d.ts index 23f08ca84..3156c83db 100644 --- a/napi/angular-compiler/index.d.ts +++ b/napi/angular-compiler/index.d.ts @@ -886,7 +886,9 @@ export declare function linkAngularPackage( * # Returns * * A `LinkResult` containing the linked code. If no partial declarations - * were found, the original code is returned with `linked: false`. + * were found, the original code is returned with `linked: false`. A + * component whose template has errors is left as it is and reported in + * `errors`. */ export declare function linkAngularPackageSync( code: string, @@ -919,6 +921,12 @@ export interface LinkResult { map?: string /** Whether any declarations were linked. */ linked: boolean + /** + * The errors of each component whose template has errors. That component + * is left as it is; a build should fail on them, as Angular's linker + * throws for them. + */ + errors: Array } /** diff --git a/napi/angular-compiler/src/lib.rs b/napi/angular-compiler/src/lib.rs index 86c403228..d3d4164b8 100644 --- a/napi/angular-compiler/src/lib.rs +++ b/napi/angular-compiler/src/lib.rs @@ -3274,6 +3274,10 @@ pub struct LinkResult { pub map: Option, /// Whether any declarations were linked. pub linked: bool, + /// The errors of each component whose template has errors. That component + /// is left as it is; a build should fail on them, as Angular's linker + /// throws for them. + pub errors: Vec, } /// Link Angular partial declarations in a JavaScript file (sync). @@ -3294,7 +3298,9 @@ pub struct LinkResult { /// # Returns /// /// A `LinkResult` containing the linked code. If no partial declarations -/// were found, the original code is returned with `linked: false`. +/// were found, the original code is returned with `linked: false`. A +/// component whose template has errors is left as it is and reported in +/// `errors`. #[napi] pub fn link_angular_package_sync( code: String, @@ -3311,7 +3317,8 @@ pub fn link_angular_package_sync( }; let result = link_with_options(&allocator, &code, &filename, &rust_options); - LinkResult { code: result.code, map: result.map, linked: result.linked } + let errors = OxcError::from_diagnostics(&filename, &code, result.errors); + LinkResult { code: result.code, map: result.map, linked: result.linked, errors } } /// Options for linking Angular partial declarations. diff --git a/napi/angular-compiler/test/linker.test.ts b/napi/angular-compiler/test/linker.test.ts index ae509ccdc..68d172950 100644 --- a/napi/angular-compiler/test/linker.test.ts +++ b/napi/angular-compiler/test/linker.test.ts @@ -435,6 +435,62 @@ describe('linker: sourcemap', () => { }) }) +/** + * A template ngc 20.1.3 accepts and 20.1.4 rejects (`?.` in a two-way target). Angular's linker + * throws `Errors found in the template:` for it, which fails the build. + */ +const TWO_WAY_SAFE_READ_COMPONENT = IMG_SRC_COMPONENT.replace( + `''`, + `''`, +) + +describe('linker: template errors', () => { + const id = 'node_modules/x-preview/fesm2022/x-preview.mjs' + const v20_1_4 = { major: 20, minor: 1, patch: 4 } + const message = + 'Errors found in the template:\nUnsupported expression in a two-way binding (line 1, column 8 of the template)' + // A Rollup plugin context whose `error` throws, as Rollup's does. + const context = { + fs: { readFile: async () => TWO_WAY_SAFE_READ_COMPONENT }, + error(error: string): never { + throw new Error(error) + }, + } + + it('reports the error and leaves the declaration as it is', () => { + const result = linkAngularPackageSync(TWO_WAY_SAFE_READ_COMPONENT, id, { + angularVersion: v20_1_4, + }) + + expect(result.linked).toBe(false) + expect(result.code).toBe(TWO_WAY_SAFE_READ_COMPONENT) + expect(result.errors.map((e) => e.message)).toEqual([message]) + expect(result.errors[0].helpMessage).toMatch(/^node_modules\/x-preview\/.*\.mjs:\d+:\d+$/) + expect( + linkAngularPackageSync(TWO_WAY_SAFE_READ_COMPONENT, id, { + angularVersion: { major: 20, minor: 1, patch: 3 }, + }).errors, + ).toEqual([]) + }) + + it('fails the Vite transform hook', async () => { + const plugin = angularLinkerPlugin({ angularVersion: v20_1_4 }) as any + + await expect( + plugin.transform.handler.call(context, TWO_WAY_SAFE_READ_COMPONENT, id), + ).rejects.toThrow(message) + }) + + it('fails the dependency optimizer', async () => { + const plugin = angularLinkerPlugin({ angularVersion: v20_1_4 }) as any + plugin.configResolved({ optimizeDeps: {} }) + const [optimizerPlugin] = plugin.config({}, { command: 'serve' }).optimizeDeps.rolldownOptions + .plugins + + await expect(optimizerPlugin.load.handler.call(context, id)).rejects.toThrow(message) + }) +}) + describe('linker: optimizeDeps.exclude (#695)', () => { const PLATFORM_SERVER = '/app/node_modules/@angular/platform-server/fesm2022/platform-server.mjs' const PRIMENG = '/app/node_modules/primeng/fesm2022/primeng-table.mjs?v=abc' diff --git a/napi/angular-compiler/vite-plugin/angular-linker-plugin.ts b/napi/angular-compiler/vite-plugin/angular-linker-plugin.ts index d671a8b2e..02df0d996 100644 --- a/napi/angular-compiler/vite-plugin/angular-linker-plugin.ts +++ b/napi/angular-compiler/vite-plugin/angular-linker-plugin.ts @@ -1,8 +1,10 @@ import { resolve } from 'node:path' -import { linkAngularPackage, type AngularVersion } from '#binding' +import { linkAngularPackage, type AngularVersion, type LinkResult } from '#binding' import type { Plugin, ResolvedConfig } from 'vite' +import { describeDiagnostic } from './utils/diagnostic.js' + /** * Angular Linker plugin for Vite. * @@ -93,15 +95,25 @@ async function linkCode( id: string, angularVersion: AngularVersion | undefined, sourcemap: boolean, -): Promise<{ code: string; map: string | null; linked: boolean }> { +): Promise<{ code: string; map: string | null; linked: boolean; errors: LinkResult['errors'] }> { const result = await linkAngularPackage(code, id, { angularVersion, sourcemap }) return { code: result.linked ? result.code : code, map: result.map ?? null, linked: result.linked, + errors: result.errors, } } +/** + * The message to fail the build with when a declaration cannot be linked, as Angular's linker + * throws for a component whose template has errors. `undefined` when there is none. + */ +function linkErrorMessage(errors: LinkResult['errors']): string | undefined { + if (errors.length === 0) return undefined + return errors.map(describeDiagnostic).join('\n\n') +} + export interface AngularLinkerPluginOptions { /** * Angular version of the application, forwarded to the linker, or a function @@ -192,6 +204,9 @@ export function angularLinkerPlugin({ const result = await linkCode(code, id, angularVersion, sourcemap) + const error = linkErrorMessage(result.errors) + if (error) this.error(error) + if (!result.linked) { return } @@ -241,6 +256,9 @@ export function angularLinkerPlugin({ const result = await linkCode(code, id, angularVersion, sourcemap) + const error = linkErrorMessage(result.errors) + if (error) this.error(error) + if (!result.linked) { return } diff --git a/napi/angular-compiler/vite-plugin/index.ts b/napi/angular-compiler/vite-plugin/index.ts index bb71eaa03..f7f2e700e 100644 --- a/napi/angular-compiler/vite-plugin/index.ts +++ b/napi/angular-compiler/vite-plugin/index.ts @@ -40,6 +40,7 @@ import { angularLinkerPlugin } from './angular-linker-plugin.js' import { ssrManifestPlugin } from './angular-ssr-manifest-plugin.js' import { installedAngularVersion } from './utils/angular-version.js' import { isFileSystemCaseSensitive } from './utils/case-sensitive.js' +import { describeDiagnostic } from './utils/diagnostic.js' import { dtsMapSource, dtsSourceCandidates, @@ -256,17 +257,6 @@ function plainResources(resources: ResolvedResources): PlainResources { return resources as unknown as PlainResources } -/** - * The text to report for a compiler diagnostic. Rollup shows only this string, so the - * help text is appended to it: for a template parse error that is where the error is - * (`file:line:column`). - */ -function describeDiagnostic(diagnostic: { message: string; helpMessage?: string | null }): string { - return diagnostic.helpMessage - ? `${diagnostic.message}\n${diagnostic.helpMessage}` - : diagnostic.message -} - /** * True for the compiler's COMPONENT_RESOURCE_NOT_FOUND error: a `templateUrl`, * `styleUrl(s)` entry or template stylesheet `` missing from the diff --git a/napi/angular-compiler/vite-plugin/utils/diagnostic.ts b/napi/angular-compiler/vite-plugin/utils/diagnostic.ts new file mode 100644 index 000000000..64c2825ed --- /dev/null +++ b/napi/angular-compiler/vite-plugin/utils/diagnostic.ts @@ -0,0 +1,13 @@ +/** + * The text to report for a compiler diagnostic. Rollup shows only this string, so the + * help text is appended to it: for a template parse error that is where the error is + * (`file:line:column`). + */ +export function describeDiagnostic(diagnostic: { + message: string + helpMessage?: string | null +}): string { + return diagnostic.helpMessage + ? `${diagnostic.message}\n${diagnostic.helpMessage}` + : diagnostic.message +}