-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtransform.rs
More file actions
5740 lines (5062 loc) · 221 KB
/
transform.rs
File metadata and controls
5740 lines (5062 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Angular file transformation.
//!
//! This module provides the main entry point for transforming TypeScript files
//! containing Angular components into compiled JavaScript.
use std::collections::HashMap;
use std::path::Path;
use oxc_allocator::{Allocator, Vec as OxcVec};
use oxc_ast::ast::{
Argument, ArrayExpressionElement, Declaration, ExportDefaultDeclarationKind, Expression,
ImportDeclarationSpecifier, ImportOrExportKind, ObjectPropertyKind, PropertyKey, Statement,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_parser::Parser;
use oxc_span::{GetSpan, Ident, SourceType, Span};
use rustc_hash::FxHashMap;
use crate::optimizer::{Edit, apply_edits, apply_edits_with_sourcemap};
#[cfg(feature = "cross_file_elision")]
use super::cross_file_elision::CrossFileAnalyzer;
use super::decorator::{
collect_constructor_decorator_spans, collect_member_decorator_spans,
extract_component_metadata, find_component_decorator, find_component_decorator_span,
};
use super::definition::{const_value_to_expression, generate_component_definitions};
use super::import_elision::{ImportElisionAnalyzer, import_elision_edits};
use super::metadata::{AngularVersion, ComponentMetadata, HostMetadata};
use super::namespace_registry::NamespaceRegistry;
use crate::ast::expression::{BindingType, ParsedEventType};
use crate::ast::r3::{R3BoundAttribute, R3BoundEvent, SecurityContext};
use crate::class_metadata::{
R3ClassMetadata, build_ctor_params_metadata, build_decorator_metadata_array,
build_prop_decorators_metadata, compile_class_metadata,
};
use crate::directive::{
R3QueryMetadata, create_content_queries_function, create_view_queries_function,
extract_content_queries, extract_directive_metadata, extract_view_queries,
find_directive_decorator_span, generate_directive_definitions,
};
use crate::dts;
use crate::injectable::{
extract_injectable_metadata, find_injectable_decorator_span,
generate_injectable_definition_from_decorator,
};
use crate::ng_module::{
extract_ng_module_metadata, find_ng_module_decorator_span, generate_full_ng_module_definition,
};
use crate::output::ast::{
DeclareFunctionStmt, FunctionExpr, OutputExpression, OutputStatement, ReadPropExpr,
ReadVarExpr, StmtModifier,
};
use crate::output::emitter::JsEmitter;
use crate::parser::ParseTemplateOptions;
use crate::parser::expression::BindingParser;
use crate::parser::html::{HtmlParser, remove_whitespaces};
use crate::pipe::{
extract_pipe_metadata, find_pipe_decorator_span, generate_full_pipe_definition_from_decorator,
};
use crate::pipeline::compilation::{DeferBlockDepsEmitMode, TemplateCompilationMode};
use crate::pipeline::emit::{
HostBindingCompilationResult, compile_host_bindings, compile_template,
};
use crate::pipeline::ingest::{
HostBindingInput, IngestOptions, ingest_component, ingest_component_with_options,
ingest_host_binding_with_version,
};
use crate::transform::HtmlToR3Transform;
use crate::transform::html_to_r3::TransformOptions as R3TransformOptions;
/// Options for Angular file transformation.
#[derive(Debug, Clone)]
pub struct TransformOptions {
/// Generate source maps.
pub sourcemap: bool,
/// Enable JIT (Just-In-Time) compilation mode.
/// When true, generates code compatible with JIT compilation.
pub jit: bool,
/// Enable HMR (Hot Module Replacement) support.
/// When true, generates HMR initialization and update code.
pub hmr: bool,
/// Enable advanced optimizations.
/// When true, applies additional optimizations like constant folding.
pub advanced_optimizations: bool,
/// i18n message ID strategy.
///
/// When true (default), uses external message IDs for Closure Compiler
/// variable naming (MSG_EXTERNAL_abc123$$SUFFIX).
/// When false, uses file-based naming (MSG_SUFFIX_0).
pub i18n_use_external_ids: bool,
/// Angular core version for version-conditional behavior.
///
/// When set, used to determine defaults like:
/// - `standalone`: defaults to `false` for v18 and earlier, `true` for v19+
///
/// When `None`, assumes latest Angular version (v19+ behavior).
pub angular_version: Option<AngularVersion>,
// Component metadata overrides for template-only compilation.
// These allow the build tool to pass component metadata when compiling
// templates in isolation (e.g., for testing or compare tool).
/// Override the CSS selector for the component.
pub selector: Option<String>,
/// Override the standalone flag for the component.
pub standalone: Option<bool>,
/// Override the view encapsulation mode.
pub encapsulation: Option<super::metadata::ViewEncapsulation>,
/// Override the change detection strategy.
pub change_detection: Option<super::metadata::ChangeDetectionStrategy>,
/// Override the preserve whitespaces setting.
pub preserve_whitespaces: Option<bool>,
/// Host bindings metadata for the component.
/// Contains property bindings, attribute bindings, and event listeners.
pub host: Option<HostMetadataInput>,
/// Enable cross-file import elision analysis.
///
/// When true, resolves imports to source files to check if exports are type-only.
/// This improves import elision accuracy by detecting interfaces and type aliases
/// in external files.
///
/// **Note**: This is intended for compare tests only. In production, bundlers
/// like rolldown handle import elision as part of their tree-shaking process.
#[cfg(feature = "cross_file_elision")]
pub cross_file_elision: bool,
/// Base directory for module resolution.
///
/// Used when `cross_file_elision` is enabled to resolve relative imports.
/// Defaults to the directory containing the source file if not specified.
#[cfg(feature = "cross_file_elision")]
pub base_dir: Option<std::path::PathBuf>,
/// Path to tsconfig.json for path aliases.
///
/// Used when `cross_file_elision` is enabled to resolve path aliases
/// defined in tsconfig.json (e.g., `@app/*` -> `src/app/*`).
#[cfg(feature = "cross_file_elision")]
pub tsconfig_path: Option<std::path::PathBuf>,
/// Resolved import paths for host directives and other imports.
///
/// Maps local identifier name (e.g., "AriaDisableDirective") to the resolved
/// module path (e.g., "../a11y/aria-disable.directive").
///
/// This is used to override barrel export paths with actual file paths.
/// When an identifier is found in this map, the resolved path is used
/// instead of the original import declaration's source.
///
/// Example:
/// ```text
/// // Original import uses barrel export:
/// import { AriaDisableDirective } from '../a11y';
///
/// // resolved_imports maps to actual file:
/// { "AriaDisableDirective": "../a11y/aria-disable.directive" }
/// ```
pub resolved_imports: Option<HashMap<String, String>>,
/// Emit setClassMetadata() calls for TestBed support.
///
/// When true, generates `ɵɵsetClassMetadata()` calls wrapped in a dev-mode guard.
/// This preserves original decorator information for TestBed's recompilation APIs.
///
/// Default: false (metadata is dev-only and usually stripped in production)
pub emit_class_metadata: bool,
/// Minify final component styles before emitting them into `styles: [...]`.
///
/// This runs after Angular style encapsulation, so it applies to the same
/// final CSS strings that are embedded in component definitions.
pub minify_component_styles: bool,
}
/// Input for host metadata when passed via TransformOptions.
/// Uses owned String types for easier NAPI interop.
#[derive(Debug, Clone, Default)]
pub struct HostMetadataInput {
/// Host property bindings: `{ "[class.active]": "isActive" }`
pub properties: Vec<(String, String)>,
/// Host attribute bindings: `{ "role": "button" }`
pub attributes: Vec<(String, String)>,
/// Host event listeners: `{ "(click)": "onClick()" }`
pub listeners: Vec<(String, String)>,
/// Special attribute for static class binding.
pub class_attr: Option<String>,
/// Special attribute for static style binding.
pub style_attr: Option<String>,
}
impl Default for TransformOptions {
fn default() -> Self {
Self {
sourcemap: false,
jit: false,
hmr: false,
advanced_optimizations: false,
i18n_use_external_ids: true, // Angular's JIT default
angular_version: None, // None means assume latest (v19+ behavior)
// Metadata overrides default to None (use extracted/default values)
selector: None,
standalone: None,
encapsulation: None,
change_detection: None,
preserve_whitespaces: None,
host: None,
// Cross-file elision options (feature-gated)
#[cfg(feature = "cross_file_elision")]
cross_file_elision: false,
#[cfg(feature = "cross_file_elision")]
base_dir: None,
#[cfg(feature = "cross_file_elision")]
tsconfig_path: None,
// Resolved imports for host directives
resolved_imports: None,
// Class metadata for TestBed support (disabled by default)
emit_class_metadata: false,
minify_component_styles: false,
}
}
}
impl TransformOptions {
/// Compute the implicit standalone value based on the Angular version.
///
/// - Returns `true` for Angular v19+ or when version is unknown (None)
/// - Returns `false` for Angular v18 and earlier
pub fn implicit_standalone(&self) -> bool {
self.angular_version.map(|v| v.supports_implicit_standalone()).unwrap_or(true) // Default to true when version is unknown
}
}
/// Pre-resolved external resources for component transformation.
///
/// The build tool (e.g., Vite) resolves `templateUrl` and `styleUrls` before
/// calling the Rust compiler, since file I/O and preprocessing (SCSS, etc.)
/// needs to happen in JavaScript.
#[derive(Debug, Default)]
pub struct ResolvedResources {
/// Map from templateUrl path to resolved template content.
pub templates: HashMap<String, String>,
/// Map from styleUrl path to resolved (preprocessed) style content.
pub styles: HashMap<String, Vec<String>>,
}
/// Result of transforming an Angular file.
#[derive(Debug, Default)]
pub struct TransformResult {
/// The transformed code.
pub code: String,
/// Source map (if sourcemap option was enabled).
pub map: Option<String>,
/// Files this file depends on (for watch mode).
/// Includes template URLs and style URLs.
pub dependencies: Vec<String>,
/// Template updates for HMR.
/// Maps component ID (path@ClassName) to compiled template function.
pub template_updates: HashMap<String, String>,
/// Style updates for HMR.
/// Maps component ID to list of styles.
pub style_updates: HashMap<String, Vec<String>>,
/// Compilation diagnostics (errors and warnings).
pub diagnostics: Vec<OxcDiagnostic>,
/// Number of components found in the file.
pub component_count: usize,
/// `.d.ts` type declarations for Angular classes.
///
/// Each entry contains the class name and the static member declarations
/// that should be injected into the corresponding `.d.ts` class body.
/// This enables library builds to include proper Ivy type declarations
/// for template type-checking by consumers.
///
/// The declarations use `i0` as the namespace alias for `@angular/core`.
/// Consumers must ensure their `.d.ts` files include:
/// ```typescript
/// import * as i0 from "@angular/core";
/// ```
pub dts_declarations: Vec<crate::dts::DtsDeclaration>,
}
impl TransformResult {
/// Create a new empty transform result.
pub fn new() -> Self {
Self::default()
}
/// Check if there are any errors.
pub fn has_errors(&self) -> bool {
use miette::Diagnostic;
use oxc_diagnostics::Severity;
self.diagnostics
.iter()
.any(|d| d.severity() == Some(Severity::Error) || d.severity().is_none())
}
/// Check if there are any warnings.
pub fn has_warnings(&self) -> bool {
use miette::Diagnostic;
use oxc_diagnostics::Severity;
self.diagnostics.iter().any(|d| d.severity() == Some(Severity::Warning))
}
}
/// Result of compiling a template to JavaScript.
#[derive(Debug, Default)]
pub struct TemplateCompileOutput {
/// The compiled template function as JavaScript code.
pub code: String,
/// Source map (if sourcemap option was enabled).
pub map: Option<oxc_sourcemap::SourceMap>,
}
impl TemplateCompileOutput {
/// Create a new template compile output with just code.
pub fn new(code: String) -> Self {
Self { code, map: None }
}
/// Create a new template compile output with code and source map.
pub fn with_source_map(code: String, map: Option<oxc_sourcemap::SourceMap>) -> Self {
Self { code, map }
}
}
/// Output from compiling a template for HMR.
/// Includes the template function, constant declarations, extracted styles, and consts array.
#[derive(Debug)]
pub struct HmrTemplateCompileOutput {
/// The compiled template function as JavaScript code.
pub template_js: String,
/// Constant declarations (child view functions, pooled constants) as JavaScript code.
/// These need to be included in the HMR update module before the component definition.
pub declarations_js: String,
/// Styles extracted from `<style>` tags in the template.
/// These must be included in the HMR update module to avoid constant pool mismatches.
pub styles: std::vec::Vec<String>,
/// The consts array as JavaScript code.
/// This must be included in the HMR update module to match the template function's
/// constant references. Without this, the template may reference indices that don't
/// exist in the old component definition's consts array.
pub consts_js: Option<String>,
}
/// Compiled component information.
#[derive(Debug)]
pub struct CompiledComponent<'a> {
/// Component metadata.
pub metadata: ComponentMetadata<'a>,
/// Compiled template function.
pub template_fn: Option<FunctionExpr<'a>>,
/// Compiled template as JavaScript string.
pub template_js: Option<String>,
}
/// Map from imported identifier name to its source module path.
///
/// This is used to track where constructor dependency tokens come from,
/// enabling proper namespace aliasing in the compiled output.
///
/// Example:
/// ```typescript
/// import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
/// import { ServiceA, ServiceB } from "./services";
/// ```
/// Results in:
/// ```text
/// {
/// "AuthService" -> "@bitwarden/common/auth/abstractions/auth.service",
/// "ServiceA" -> "./services",
/// "ServiceB" -> "./services"
/// }
/// ```
/// Information about an imported symbol.
#[derive(Debug, Clone)]
pub struct ImportInfo<'a> {
/// The source module path (e.g., "@angular/core", "./services").
pub source_module: Ident<'a>,
/// Whether this is a named import that can be reused with bare name.
/// True for: `import { AuthService } from "module"`
/// False for: `import * as core from "module"` (namespace imports)
pub is_named_import: bool,
/// Whether this is a type-only import (`import type { X }` or `import { type X }`).
/// Type-only imports are erased at runtime and should not generate namespace
/// imports for `setClassMetadata()` type references.
pub is_type_only: bool,
}
/// Map from local identifier name to its import information.
///
/// Used to look up where a constructor dependency token was imported from
/// and whether it can be reused with a bare name or requires namespace prefix.
pub type ImportMap<'a> = FxHashMap<Ident<'a>, ImportInfo<'a>>;
/// Build an import map from the program's import declarations.
///
/// Extracts all imports and maps the local identifier name to the
/// source module path and import type. This enables:
/// - Looking up where a constructor dependency token was imported from
/// - Determining if the import can be reused with bare name (named import)
/// or requires namespace prefix (namespace import)
///
/// # Arguments
///
/// * `allocator` - Memory allocator for creating new Atoms
/// * `program_body` - The program's statement list
/// * `resolved_imports` - Optional map of identifier names to resolved module paths.
/// When provided, these paths override the source module from the import declaration.
/// This is used to resolve barrel exports to actual file paths.
///
/// Handles:
/// - Named imports: `import { AuthService } from "@angular/core"`
/// -> `is_named_import: true` (can use bare `AuthService`)
/// - Named imports with alias: `import { AuthService as Auth } from "@angular/core"`
/// -> `is_named_import: true` (can use bare `Auth`)
/// - Default imports: `import DefaultService from "@bitwarden/common"`
/// -> `is_named_import: true` (can use bare `DefaultService`)
/// - Namespace imports: `import * as core from "@angular/core"`
/// -> `is_named_import: false` (need namespace prefix)
pub fn build_import_map<'a>(
allocator: &'a Allocator,
program_body: &[Statement<'a>],
resolved_imports: Option<&HashMap<String, String>>,
) -> ImportMap<'a> {
let mut import_map = ImportMap::default();
for stmt in program_body {
let Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
let default_source_module = import_decl.source.value.clone();
// `import type { ... }` makes all specifiers type-only
let decl_is_type_only = import_decl.import_kind == ImportOrExportKind::Type;
// Process all specifiers
let Some(specifiers) = &import_decl.specifiers else {
// Side-effect import: `import 'foo'` - no identifiers to map
continue;
};
for specifier in specifiers {
match specifier {
ImportDeclarationSpecifier::ImportSpecifier(spec) => {
// Named import: `import { AuthService } from "module"`
// or aliased: `import { AuthService as Auth } from "module"`
// We use the local name as the key
// Named imports CAN be reused with bare name
let local_name: Ident<'a> = spec.local.name.clone().into();
// Type-only if the declaration is `import type { ... }` or the specifier
// is `import { type X }` (inline type specifier)
let is_type_only =
decl_is_type_only || spec.import_kind == ImportOrExportKind::Type;
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Ident::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone().into());
import_map.insert(
local_name,
ImportInfo { source_module, is_named_import: true, is_type_only },
);
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(spec) => {
// Default import: `import DefaultService from "module"`
// Default imports CAN be reused with bare name
let local_name: Ident<'a> = spec.local.name.clone().into();
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Ident::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone().into());
import_map.insert(
local_name,
ImportInfo {
source_module,
is_named_import: true,
is_type_only: decl_is_type_only,
},
);
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(spec) => {
// Namespace import: `import * as core from "module"`
// Namespace imports CANNOT be reused with bare name for individual symbols
let local_name: Ident<'a> = spec.local.name.clone().into();
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Ident::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone().into());
import_map.insert(
local_name,
ImportInfo {
source_module,
is_named_import: false,
is_type_only: decl_is_type_only,
},
);
}
}
}
}
import_map
}
/// Find the byte position (in the source) just after the last import statement.
///
/// Resolve namespace imports for factory dependency tokens.
///
/// The import elision phase removes type-only imports (e.g., `import { Store } from '@ngrx/store'`)
/// because constructor parameter types are considered type-only. However, the factory function
/// needs to reference these types at runtime (e.g., `i0.ɵɵinject(Store)`).
///
/// This function replaces bare `ReadVar` tokens with namespace-prefixed `ReadProp` references
/// (e.g., `Store` → `i1.Store`) for any token that has a corresponding import in the import map.
/// This ensures the factory works correctly even after import elision.
fn resolve_factory_dep_namespaces<'a>(
allocator: &'a Allocator,
deps: &mut oxc_allocator::Vec<'a, crate::factory::R3DependencyMetadata<'a>>,
import_map: &ImportMap<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) {
for dep in deps.iter_mut() {
let Some(ref token) = dep.token else { continue };
// Only process bare variable references (ReadVar)
let OutputExpression::ReadVar(var) = token else { continue };
let name = &var.name;
// Look up this identifier in the import map
let Some(import_info) = import_map.get(name) else { continue };
// Replace with namespace-prefixed reference: i1.Store instead of Store
let namespace = namespace_registry.get_or_assign(&import_info.source_module);
dep.token = Some(OutputExpression::ReadProp(oxc_allocator::Box::new_in(
ReadPropExpr {
receiver: oxc_allocator::Box::new_in(
OutputExpression::ReadVar(oxc_allocator::Box::new_in(
ReadVarExpr { name: namespace, source_span: None },
allocator,
)),
allocator,
),
name: name.clone(),
optional: false,
source_span: None,
},
allocator,
)));
}
}
/// Resolves namespace imports for host directive references in `R3HostDirectiveMetadata`.
///
/// Replaces bare `ReadVar("X")` references with namespace-prefixed `ReadProp(ReadVar("i1"), "X")`
/// for any host directive that has a corresponding import in the import map.
/// This ensures the compiled output works correctly even after import elision.
fn resolve_host_directive_namespaces<'a>(
allocator: &'a Allocator,
host_directives: &mut oxc_allocator::Vec<'a, crate::R3HostDirectiveMetadata<'a>>,
import_map: &ImportMap<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) {
for hd in host_directives.iter_mut() {
// Only process bare variable references (ReadVar)
let OutputExpression::ReadVar(ref var) = hd.directive else { continue };
let name = &var.name;
// Look up this identifier in the import map
let Some(import_info) = import_map.get(name) else { continue };
// Replace with namespace-prefixed reference: i1.BrnTooltipTrigger instead of BrnTooltipTrigger
let namespace = namespace_registry.get_or_assign(&import_info.source_module);
hd.directive = OutputExpression::ReadProp(oxc_allocator::Box::new_in(
ReadPropExpr {
receiver: oxc_allocator::Box::new_in(
OutputExpression::ReadVar(oxc_allocator::Box::new_in(
ReadVarExpr { name: namespace, source_span: None },
allocator,
)),
allocator,
),
name: name.clone(),
optional: false,
source_span: None,
},
allocator,
));
}
}
/// Compute the effective start position for a class statement in the original source.
///
/// This accounts for non-Angular decorators that remain on the class after Angular
/// decorator removal. The effective start is the minimum of `stmt_start` and the
/// earliest remaining (non-removed) decorator's start position.
fn compute_effective_start(
class: &oxc_ast::ast::Class,
decorator_spans_to_remove: &[Span],
stmt_start: u32,
) -> u32 {
class
.decorators
.iter()
.filter(|d| !decorator_spans_to_remove.contains(&d.span))
.map(|d| d.span.start)
.min()
.map_or(stmt_start, |dec_start| dec_start.min(stmt_start))
}
/// This is used to determine where to insert namespace imports so they appear
/// AFTER existing imports but BEFORE other code (like class declarations).
///
/// Returns `Some(position)` if imports were found, or `None` if no imports exist.
fn find_last_import_end(program_body: &[Statement<'_>]) -> Option<usize> {
let mut last_import_end: Option<u32> = None;
for stmt in program_body {
// Check for import declarations and import equals declarations
// These are the import statement types that Angular's TypeScript transform considers
// See: packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_typescript_transform.ts
let span_end = match stmt {
Statement::ImportDeclaration(import_decl) => Some(import_decl.span.end),
// Note: TypeScript import equals (import x = require()) are not common in Angular
// but we handle them for completeness
_ => None,
};
if let Some(end) = span_end {
last_import_end = Some(last_import_end.map_or(end, |prev| prev.max(end)));
}
}
last_import_end.map(|pos| pos as usize)
}
// ============================================================================
// JIT Compilation Transform
// ============================================================================
/// Identifies which Angular decorator type a class has.
#[derive(Debug, Clone, Copy)]
enum AngularDecoratorKind {
Component,
Directive,
Pipe,
Injectable,
NgModule,
}
/// Information about an Angular-decorated class for JIT transformation.
struct JitClassInfo {
/// The class name.
class_name: String,
/// Span of the decorator (including @).
decorator_span: Span,
/// Start of the statement (includes export keyword if present).
stmt_start: u32,
/// Start of the class keyword.
class_start: u32,
/// End of the class body (the closing `}`).
class_body_end: u32,
/// Whether the class is exported (not default).
is_exported: bool,
/// Whether the class is export default.
is_default_export: bool,
/// Whether the class is abstract.
is_abstract: bool,
/// Constructor parameter info for ctorParameters.
ctor_params: std::vec::Vec<JitCtorParam>,
/// Member decorator info for propDecorators.
member_decorators: std::vec::Vec<JitMemberDecorator>,
/// The modified decorator expression text for __decorate call.
decorator_text: String,
}
/// Constructor parameter info for JIT ctorParameters generation.
struct JitCtorParam {
/// The type name (if resolvable to a runtime value).
type_name: Option<String>,
/// Angular decorators on the parameter, as source text spans.
decorators: std::vec::Vec<JitParamDecorator>,
}
/// A single decorator on a constructor parameter.
struct JitParamDecorator {
/// The decorator name (e.g., "Optional", "Inject").
name: String,
/// The decorator arguments as source text (e.g., "TOKEN" for @Inject(TOKEN)).
args: Option<String>,
}
/// A member (property/method) with its Angular decorators for propDecorators.
struct JitMemberDecorator {
/// The property/member name.
member_name: String,
/// The Angular decorators on this member.
decorators: std::vec::Vec<JitParamDecorator>,
}
/// Find any Angular decorator on a class and return its kind and the decorator reference.
fn find_angular_decorator<'a>(
class: &'a oxc_ast::ast::Class<'a>,
) -> Option<(AngularDecoratorKind, &'a oxc_ast::ast::Decorator<'a>)> {
for decorator in &class.decorators {
if let Expression::CallExpression(call) = &decorator.expression {
let name = match &call.callee {
Expression::Identifier(id) => Some(id.name.as_str()),
Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
_ => None,
};
match name {
Some("Component") => return Some((AngularDecoratorKind::Component, decorator)),
Some("Directive") => return Some((AngularDecoratorKind::Directive, decorator)),
Some("Pipe") => return Some((AngularDecoratorKind::Pipe, decorator)),
Some("Injectable") => return Some((AngularDecoratorKind::Injectable, decorator)),
Some("NgModule") => return Some((AngularDecoratorKind::NgModule, decorator)),
_ => {}
}
}
}
None
}
/// Extract constructor parameter info for JIT ctorParameters generation.
fn extract_jit_ctor_params(
source: &str,
class: &oxc_ast::ast::Class<'_>,
) -> std::vec::Vec<JitCtorParam> {
use oxc_ast::ast::{ClassElement, MethodDefinitionKind};
let constructor = class.body.body.iter().find_map(|element| {
if let ClassElement::MethodDefinition(method) = element {
if method.kind == MethodDefinitionKind::Constructor {
return Some(method);
}
}
None
});
let Some(ctor) = constructor else {
return std::vec::Vec::new();
};
let mut params = std::vec::Vec::new();
for param in &ctor.value.params.items {
// Extract type name from type annotation (directly on FormalParameter)
let type_name = param
.type_annotation
.as_ref()
.and_then(|ann| extract_type_name_from_annotation(&ann.type_annotation));
// Extract Angular decorators
let mut decorators = std::vec::Vec::new();
for decorator in ¶m.decorators {
if let Expression::CallExpression(call) = &decorator.expression {
let dec_name = match &call.callee {
Expression::Identifier(id) => Some(id.name.to_string()),
_ => None,
};
if let Some(name) = dec_name {
match name.as_str() {
"Inject" | "Optional" | "SkipSelf" | "Self" | "Host" | "Attribute" => {
let args = if call.arguments.is_empty() {
None
} else {
// Extract args from source
let args_start = call.arguments.first().unwrap().span().start;
let args_end = call.arguments.last().unwrap().span().end;
Some(source[args_start as usize..args_end as usize].to_string())
};
decorators.push(JitParamDecorator { name, args });
}
_ => {}
}
}
} else if let Expression::Identifier(id) = &decorator.expression {
let name = id.name.to_string();
match name.as_str() {
"Optional" | "SkipSelf" | "Self" | "Host" => {
decorators.push(JitParamDecorator { name, args: None });
}
_ => {}
}
}
}
params.push(JitCtorParam { type_name, decorators });
}
params
}
/// Extract Angular member decorators for JIT propDecorators generation.
///
/// Collects all Angular-relevant decorators from class properties/methods
/// (excluding constructor) so they can be emitted as a `static propDecorators` property.
fn extract_jit_member_decorators(
source: &str,
class: &oxc_ast::ast::Class<'_>,
) -> std::vec::Vec<JitMemberDecorator> {
use oxc_ast::ast::{ClassElement, MethodDefinitionKind, PropertyKey};
const ANGULAR_MEMBER_DECORATORS: &[&str] = &[
"Input",
"Output",
"HostBinding",
"HostListener",
"ViewChild",
"ViewChildren",
"ContentChild",
"ContentChildren",
];
let mut result: std::vec::Vec<JitMemberDecorator> = std::vec::Vec::new();
for element in &class.body.body {
let (member_name, decorators) = match element {
ClassElement::PropertyDefinition(prop) => {
let name = match &prop.key {
PropertyKey::StaticIdentifier(id) => id.name.to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => continue,
};
(name, &prop.decorators)
}
ClassElement::MethodDefinition(method) => {
if method.kind == MethodDefinitionKind::Constructor {
continue;
}
let name = match &method.key {
PropertyKey::StaticIdentifier(id) => id.name.to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => continue,
};
(name, &method.decorators)
}
ClassElement::AccessorProperty(accessor) => {
let name = match &accessor.key {
PropertyKey::StaticIdentifier(id) => id.name.to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => continue,
};
(name, &accessor.decorators)
}
_ => continue,
};
let mut angular_decs: std::vec::Vec<JitParamDecorator> = std::vec::Vec::new();
for decorator in decorators {
let (dec_name, call_args) = match &decorator.expression {
Expression::CallExpression(call) => {
let name = match &call.callee {
Expression::Identifier(id) => id.name.to_string(),
Expression::StaticMemberExpression(m) => m.property.name.to_string(),
_ => continue,
};
let args = if call.arguments.is_empty() {
None
} else {
let start = call.arguments.first().unwrap().span().start;
let end = call.arguments.last().unwrap().span().end;
Some(source[start as usize..end as usize].to_string())
};
(name, args)
}
Expression::Identifier(id) => (id.name.to_string(), None),
_ => continue,
};
if ANGULAR_MEMBER_DECORATORS.contains(&dec_name.as_str()) {
angular_decs.push(JitParamDecorator { name: dec_name, args: call_args });
}
}
if !angular_decs.is_empty() {
result.push(JitMemberDecorator { member_name, decorators: angular_decs });
}
}
result
}
/// Build the propDecorators static property text for JIT member decorator metadata.
fn build_prop_decorators_text(members: &[JitMemberDecorator]) -> Option<String> {
if members.is_empty() {
return None;
}
let mut entries: std::vec::Vec<String> = std::vec::Vec::new();
for member in members {
let dec_strs: std::vec::Vec<String> = member
.decorators
.iter()
.map(|d| {
if let Some(ref args) = d.args {
format!("{{ type: {}, args: [{}] }}", d.name, args)
} else {
format!("{{ type: {} }}", d.name)
}
})
.collect();
entries.push(format!(" {}: [{}]", member.member_name, dec_strs.join(", ")));
}
Some(format!("static propDecorators = {{\n{}\n}}", entries.join(",\n")))
}
/// Extract a type name from a TypeScript type annotation for JIT ctorParameters.
fn extract_type_name_from_annotation(type_annotation: &oxc_ast::ast::TSType<'_>) -> Option<String> {
match type_annotation {
oxc_ast::ast::TSType::TSTypeReference(type_ref) => {
// Simple type reference: `SomeClass`
match &type_ref.type_name {
oxc_ast::ast::TSTypeName::IdentifierReference(id) => Some(id.name.to_string()),
oxc_ast::ast::TSTypeName::QualifiedName(qn) => {
// Qualified name: `ns.SomeClass`
Some(format!("{}.{}", extract_ts_type_name_left(&qn.left), qn.right.name))
}
_ => None,
}
}
oxc_ast::ast::TSType::TSUnionType(union) => {
// Match Angular's typeReferenceToExpression behavior:
// filter out only `null` literal types, and if exactly one type remains,
// resolve that type. Otherwise, return None (unresolvable).
// See: angular/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts
let non_null: std::vec::Vec<_> = union
.types
.iter()
.filter(|t| !matches!(t, oxc_ast::ast::TSType::TSNullKeyword(_)))
.collect();
if non_null.len() == 1 { extract_type_name_from_annotation(non_null[0]) } else { None }
}
_ => None,
}
}
/// Helper to extract the string from a TSTypeName (left side of qualified name).
fn extract_ts_type_name_left(name: &oxc_ast::ast::TSTypeName<'_>) -> String {
match name {
oxc_ast::ast::TSTypeName::IdentifierReference(id) => id.name.to_string(),
oxc_ast::ast::TSTypeName::QualifiedName(qn) => {
format!("{}.{}", extract_ts_type_name_left(&qn.left), qn.right.name)
}
_ => String::new(),
}
}
/// Build the ctorParameters static property text.
fn build_ctor_parameters_text(params: &[JitCtorParam]) -> Option<String> {
if params.is_empty() {
return None;
}
let mut entries = std::vec::Vec::new();
for param in params {
let mut parts = std::vec::Vec::new();
// type
if let Some(ref type_name) = param.type_name {
parts.push(format!("type: {}", type_name));
} else {
parts.push("type: undefined".to_string());
}