oxc_react_compiler 0.135.0

oxc integration for the Rust port of React Compiler
Documentation
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
pub mod apply_renames;
pub mod convert_ast;
pub mod convert_ast_reverse;
pub mod convert_scope;
pub mod diagnostics;
pub mod prefilter;

use apply_renames::build_rename_plan;
use convert_ast::convert_program;
use convert_scope::convert_scope_info;
use diagnostics::compile_result_to_diagnostics;
use prefilter::{has_react_like_functions, has_resource_management_declarations};
use react_compiler::entrypoint::compile_result::LoggerEvent;
use react_compiler_hir::environment_config::EnvironmentConfig;
use rustc_hash::FxHashSet;
// Re-exported so integrations needn't depend on the upstream `react_compiler` crate.
pub use react_compiler::entrypoint::plugin_options::{
    CompilerTarget, DynamicGatingConfig, GatingConfig, PluginOptions,
};

/// [`PluginOptions`] with the compiler's standard defaults (it has no `Default`).
/// Override fields with struct-update syntax: `PluginOptions { ..default_plugin_options() }`.
pub fn default_plugin_options() -> PluginOptions {
    PluginOptions {
        should_compile: true,
        enable_reanimated: false,
        is_dev: false,
        filename: None,
        compilation_mode: "infer".to_string(),
        panic_threshold: "none".to_string(),
        target: CompilerTarget::Version("19".to_string()),
        gating: None,
        dynamic_gating: None,
        no_emit: false,
        output_mode: None,
        eslint_suppression_rules: None,
        flow_suppressions: true,
        ignore_use_no_forget: false,
        custom_opt_out_directives: None,
        environment: EnvironmentConfig::default(),
        source_code: None,
        profiling: false,
        debug: false,
    }
}

pub struct TransformResult<'a> {
    /// Compiled, ready-to-codegen OXC AST; `None` if the compiler made no changes.
    pub program: Option<oxc_ast::ast::Program<'a>>,
    pub diagnostics: Vec<oxc_diagnostics::OxcDiagnostic>,
    pub events: Vec<LoggerEvent>,
}

pub struct LintResult {
    pub diagnostics: Vec<oxc_diagnostics::OxcDiagnostic>,
}

/// Transform a pre-parsed program. `program` is `None` when nothing was compiled.
pub fn transform<'a>(
    program: &oxc_ast::ast::Program<'a>,
    semantic: &oxc_semantic::Semantic,
    allocator: &'a oxc_allocator::Allocator,
    options: PluginOptions,
) -> TransformResult<'a> {
    let source_text = program.source_text;

    // Skip files with no React-like functions, unless the mode compiles everything.
    if !matches!(options.compilation_mode.as_str(), "all" | "annotation")
        && !has_react_like_functions(program)
    {
        return TransformResult { program: None, diagnostics: vec![], events: vec![] };
    }

    // `using`/`await using` disposal semantics aren't preserved yet — skip the file.
    if has_resource_management_declarations(program) {
        return TransformResult { program: None, diagnostics: vec![], events: vec![] };
    }

    let file = convert_program(program, source_text);
    let scope_info = convert_scope_info(semantic, program);
    let result =
        react_compiler::entrypoint::program::compile_program(file, scope_info.clone(), options);

    let diagnostics = compile_result_to_diagnostics(&result);
    let (program_ast, events, renames) = match result {
        react_compiler::entrypoint::compile_result::CompileResult::Success {
            ast,
            events,
            renames,
            ..
        } => (ast, events, renames),
        react_compiler::entrypoint::compile_result::CompileResult::Error { events, .. } => {
            (None, events, Vec::new())
        }
    };

    // Rename plan maps source positions of uncompiled references to new names.
    let rename_plan = build_rename_plan(&scope_info, &renames);

    let compiled_program = program_ast.map(|file: react_compiler_ast::File| {
        let mut compiled =
            convert_ast_reverse::convert_program_to_oxc_with_source(&file, allocator, source_text);
        compiled.source_type = program.source_type;
        apply_renames::apply_renames(&mut compiled, &rename_plan, allocator);
        preserve_comments(&mut compiled, source_text, allocator);
        compiled
    });

    TransformResult { program: compiled_program, diagnostics, events }
}

/// Re-parse the source for comments and keep those attached to top-level
/// statements of the compiled program, so codegen can re-emit them.
fn preserve_comments<'a>(
    program: &mut oxc_ast::ast::Program<'a>,
    source_text: &str,
    allocator: &'a oxc_allocator::Allocator,
) {
    let comment_allocator = oxc_allocator::Allocator::default();
    let source_type = oxc_span::SourceType::tsx();
    let parsed = oxc_parser::Parser::new(&comment_allocator, source_text, source_type).parse();

    // Keep only comments attached to a top-level statement; inner comments have
    // `attached_to` positions that match no top-level statement.
    let mut top_level_starts = FxHashSet::default();
    top_level_starts.insert(0u32);
    for stmt in &program.body {
        use oxc_span::GetSpan;
        let start = stmt.span().start;
        if start > 0 {
            top_level_starts.insert(start);
        }
    }

    // Copy only comments attached to top-level statements.
    let mut comments =
        oxc_allocator::Vec::with_capacity_in(parsed.program.comments.len(), allocator);
    for comment in &parsed.program.comments {
        if top_level_starts.contains(&comment.attached_to) {
            comments.push(*comment);
        }
    }
    program.comments = comments;

    // Copy the source into `allocator` so codegen can read comment content from spans.
    let source_in_alloc = oxc_allocator::StringBuilder::from_str_in(source_text, allocator);
    program.source_text = source_in_alloc.into_str();
}

/// Convenience wrapper — parses source text, runs semantic analysis, then transforms.
pub fn transform_source<'a>(
    source_text: &'a str,
    source_type: oxc_span::SourceType,
    allocator: &'a oxc_allocator::Allocator,
    options: PluginOptions,
) -> TransformResult<'a> {
    let parsed = oxc_parser::Parser::new(allocator, source_text, source_type).parse();

    let semantic =
        oxc_semantic::SemanticBuilder::new().with_enum_eval(true).build(&parsed.program).semantic;

    transform(&parsed.program, &semantic, allocator, options)
}

/// Lint a pre-parsed program — like [`transform`] but only collects diagnostics.
pub fn lint(
    program: &oxc_ast::ast::Program,
    semantic: &oxc_semantic::Semantic,
    options: PluginOptions,
) -> LintResult {
    let mut opts = options;
    opts.no_emit = true;

    // `no_emit` yields `program: None`; a local arena for the conversion suffices.
    let allocator = oxc_allocator::Allocator::default();
    let result = transform(program, semantic, &allocator, opts);
    LintResult { diagnostics: result.diagnostics }
}

/// Convenience wrapper — parses source text, runs semantic analysis, then lints.
pub fn lint_source(
    source_text: &str,
    source_type: oxc_span::SourceType,
    options: PluginOptions,
) -> LintResult {
    let allocator = oxc_allocator::Allocator::default();
    let parsed = oxc_parser::Parser::new(&allocator, source_text, source_type).parse();

    let semantic =
        oxc_semantic::SemanticBuilder::new().with_enum_eval(true).build(&parsed.program).semantic;

    lint(&parsed.program, &semantic, options)
}

/// Run the React Compiler as a standalone pass, returning the `Scoping` for the
/// rest of the pipeline (rebuilt if the program changed). Must run **first**, on
/// the pristine AST, before any other transform.
pub fn run<'a>(
    program: &mut oxc_ast::ast::Program<'a>,
    allocator: &'a oxc_allocator::Allocator,
    scoping: oxc_semantic::Scoping,
    options: &PluginOptions,
    errors: &mut std::vec::Vec<oxc_diagnostics::OxcDiagnostic>,
) -> oxc_semantic::Scoping {
    // `compiled` lives in `allocator`, not borrowed from `*program`, so the
    // reassignment below is sound.
    let result = {
        let semantic =
            oxc_semantic::SemanticBuilder::new().with_enum_eval(true).build(program).semantic;
        transform(program, &semantic, allocator, options.clone())
    };
    errors.extend(result.diagnostics);

    let Some(compiled) = result.program else {
        return scoping;
    };
    *program = compiled;

    // Rebuild scoping for downstream transforms.
    oxc_semantic::SemanticBuilder::new().with_enum_eval(true).build(program).semantic.into_scoping()
}

// End-to-end smoke tests: oxc parse + semantic -> convert -> compile -> convert
// back -> codegen.
#[cfg(test)]
mod tests {
    use react_compiler::entrypoint::plugin_options::PluginOptions;

    use super::transform_source;

    fn options() -> PluginOptions {
        // Only the non-`#[serde(default)]` fields are required; the rest default.
        serde_json::from_value(serde_json::json!({
            "shouldCompile": true,
            "enableReanimated": false,
            "isDev": false,
            "filename": "Component.jsx",
        }))
        .unwrap()
    }

    #[test]
    fn memoizes_a_component_end_to_end() {
        let source = "function Component(props) {\n  \
            return <div onClick={() => props.onClick()}>{props.text}</div>;\n}\n";

        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());

        assert!(result.diagnostics.is_empty(), "unexpected diagnostics: {:?}", result.diagnostics);
        let program = result.program.expect("React Compiler should have transformed the component");

        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(
            output.contains("react/compiler-runtime"),
            "expected the compiler-runtime cache import in output:\n{output}"
        );
        assert!(
            output.contains("_c("),
            "expected memo cache reads (`_c(...)`) in output:\n{output}"
        );
    }

    #[test]
    fn skips_non_react_code() {
        let source = "function add(a, b) {\n  return a + b;\n}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        assert!(result.program.is_none(), "non-React code must not be transformed");
    }

    /// TypeScript-only constructs (`declare global`, `import =`, `export =`,
    /// overload signatures, `#field in obj`) round-trip without panicking while the
    /// component still compiles.
    #[test]
    fn typescript_only_constructs_round_trip() {
        let source = "\
import legacy = require('legacy');\n\
declare global {\n  interface Window { __APP__: number; }\n}\n\
declare function ambient(x: number): void;\n\
function overloaded(x: number): number;\n\
function overloaded(x: string): string;\n\
function overloaded(x: unknown): unknown { return x; }\n\
class Brand {\n  #brand = 1;\n  static isBrand(obj: object) { return #brand in obj; }\n}\n\
function Component(props) {\n  return <div>{props.text}</div>;\n}\n\
export = legacy;\n";

        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.unwrap_or_else(|| {
            panic!("component should be compiled; diagnostics: {:?}", result.diagnostics)
        });
        let output = oxc_codegen::Codegen::new().build(&program).code;
        assert!(
            output.contains("react/compiler-runtime"),
            "expected compiler-runtime import in output:\n{output}"
        );
        assert!(output.contains("declare global"), "`declare global` lost:\n{output}");
        assert!(output.contains("import legacy"), "`import =` lost:\n{output}");
        assert!(
            output.contains("function overloaded(x: number): number;"),
            "overload signature lost:\n{output}"
        );
        assert!(
            !output.contains("function overloaded(x: number): number {}"),
            "overload signature gained an empty body:\n{output}"
        );
        assert!(output.contains("export = legacy"), "`export =` lost:\n{output}");
    }

    /// TS wrappers in assignment-target / for-head positions must not crash the
    /// converter (the compiler may still decline to compile them).
    #[test]
    fn ts_wrapped_assignment_targets_do_not_panic() {
        let cases = [
            "function Component(props) {\n  let x = 0;\n  (x as number) = props.x;\n  return <div>{x}</div>;\n}\n",
            "function Component(props) {\n  let x = 0;\n  x! = props.x;\n  return <div>{x}</div>;\n}\n",
            "function Component(props) {\n  const o = props.o;\n  for ((o.k as string) in props.src) {}\n  return <div />;\n}\n",
            "function Component(props) {\n  const o = props.o;\n  for (o.k! of props.src) {}\n  return <div />;\n}\n",
            "function Component(props) {\n  let [a] = props.p;\n  ([a!] = props.q);\n  return <div>{a}</div>;\n}\n",
        ];
        let opts = options();
        for source in cases {
            let allocator = oxc_allocator::Allocator::default();
            let _ = transform_source(source, oxc_span::SourceType::tsx(), &allocator, opts.clone());
        }
    }

    /// Class bodies are stubbed by the converter and re-parsed from source on the
    /// way back, so members survive.
    #[test]
    fn class_body_is_preserved() {
        let source = "\
class Store {\n  count = 0;\n  increment() {\n    this.count++;\n  }\n}\n\
function Component(props) {\n  return <div>{props.text}</div>;\n}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("component should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;
        assert!(output.contains("react/compiler-runtime"), "component should memoize:\n{output}");
        assert!(output.contains("count = 0"), "class field lost:\n{output}");
        assert!(output.contains("increment("), "class method lost:\n{output}");
    }

    #[test]
    fn unsupported_sibling_ast_forms_are_preserved() {
        let source = "\
import './style.css';\n\
export * as ns from './mod';\n\
function helper() {\n\
  const C = class {\n\
    method() {\n\
      return 1;\n\
    }\n\
  };\n\
  return 123n + BigInt(new C().method());\n\
}\n\
function Component(props) {\n\
  return <div>{props.text}</div>;\n\
}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("component should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(output.contains("react/compiler-runtime"), "component should memoize:\n{output}");
        assert!(output.contains("import \"./style.css\";"), "bare import changed:\n{output}");
        assert!(
            !output.contains("import {} from \"./style.css\""),
            "bare import became an empty named import:\n{output}"
        );
        assert!(
            output.contains("export * as ns from \"./mod\";"),
            "namespace export lost:\n{output}"
        );
        assert!(output.contains("method() {"), "class expression method lost:\n{output}");
        assert!(output.contains("return 1;"), "class expression body lost:\n{output}");
        assert!(output.contains("123n"), "BigInt literal lost:\n{output}");
        assert!(!output.contains("123nn"), "BigInt literal gained an extra suffix:\n{output}");
    }

    #[test]
    fn typescript_surface_syntax_is_preserved_around_compiled_code() {
        let source = "\
import { createContext, forwardRef } from 'react';\n\
type Props = { text: string };\n\
declare const Generic: React.FC<Props>;\n\
declare const tag: <T>(strings: TemplateStringsArray) => string;\n\
class Box<T> {}\n\
const settings = { mode: 'dark' } as const;\n\
const Context = createContext<Props | undefined>(undefined);\n\
const typedValue: string = settings.mode as string;\n\
const checked = settings.mode satisfies string;\n\
const boxed = new Box<Props>();\n\
const tagged = tag<Props>`value`;\n\
const Wrapped = forwardRef<HTMLDivElement, Props>(({ text }: Props, ref): JSX.Element => {\n\
  const label: string = text satisfies string;\n\
  return <div ref={ref}>{label}</div>;\n\
});\n\
function renderGeneric(props: Props): JSX.Element {\n\
  'use no memo';\n\
  try {\n\
    return <Generic<Props> text={props.text} />;\n\
  } catch (error: unknown) {\n\
    return <Generic<Props> text={String(error)} />;\n\
  }\n\
}\n\
function Component(props: Props): JSX.Element {\n\
  return <Context.Provider value={{ text: props.text } as Props}>\n\
    <Wrapped text={props.text} />\n\
  </Context.Provider>;\n\
}\n";

        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.unwrap_or_else(|| {
            panic!("component should compile; diagnostics: {:?}", result.diagnostics)
        });
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(output.contains("react/compiler-runtime"), "component should memoize:\n{output}");
        assert!(output.contains("as const"), "`as const` lost:\n{output}");
        assert!(
            output.contains("declare const Generic: React.FC<Props>"),
            "declared variable type annotation lost:\n{output}"
        );
        assert!(
            output.contains("createContext<Props | undefined>"),
            "call type arguments lost:\n{output}"
        );
        assert!(output.contains("typedValue: string"), "variable type annotation lost:\n{output}");
        assert!(output.contains("as string"), "`as` expression lost:\n{output}");
        assert!(output.contains("satisfies string"), "`satisfies` expression lost:\n{output}");
        assert!(output.contains("new Box<Props>()"), "`new` type arguments lost:\n{output}");
        assert!(
            output.contains("tag<Props>`value`"),
            "tagged template type arguments lost:\n{output}"
        );
        assert!(
            output.contains("forwardRef<HTMLDivElement, Props>"),
            "generic forwardRef call lost type arguments:\n{output}"
        );
        assert!(output.contains(": Props"), "parameter type lost:\n{output}");
        assert!(output.contains(": JSX.Element"), "return type lost:\n{output}");
        assert!(output.contains("catch (error: unknown)"), "catch type lost:\n{output}");
        assert!(output.contains("<Generic<Props>"), "generic JSX type arguments lost:\n{output}");
    }

    #[test]
    fn type_query_casts_are_renamed_with_value_bindings() {
        let source = "\
type Field = { value?: string; optionsInputs?: Record<string, string> };\n\
function Component({ fields }: { fields: Field[] }) {\n\
  const field = { value: 'outer', optionsInputs: {} };\n\
  const nodes = fields.map((field, index) => {\n\
    const options = [{ value: field.value }];\n\
    const firstOptionInput = field.optionsInputs?.[options?.[0]?.value as keyof typeof field.optionsInputs];\n\
    return <div key={index}>{firstOptionInput}{field.value}</div>;\n\
  });\n\
  return <>{nodes}{field.value}</>;\n\
}\n";

        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("component should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(output.contains("react/compiler-runtime"), "component should memoize:\n{output}");
        assert!(
            !output.contains("typeof field.optionsInputs"),
            "stale type query source was restored:\n{output}"
        );
        assert!(
            output.contains("typeof field_0.optionsInputs"),
            "type query binding was not renamed with the value binding:\n{output}"
        );
    }

    fn rename_collision_source_and_offset() -> (&'static str, usize) {
        let rename_source = "\
function makeResults(items, names) {\n\
  const results = [...items.map((x) => use(x.value)), ...names.map((x) => use(x))];\n\
  return results;\n\
}\n";
        let collision_offset = rename_source
            .find("use(x))")
            .map(|index| index + "use(".len())
            .expect("test source should contain the renamed reference");
        (rename_source, collision_offset)
    }

    fn assert_has_rename_collision_setup(output: &str) {
        assert!(
            output.contains("function _temp2(x_0)") || output.contains("function _temp(x_0)"),
            "test setup did not produce a compiler rename:\n{output}"
        );
    }

    #[test]
    fn source_extracted_class_spans_do_not_collide_with_rename_plan() {
        let (rename_source, collision_offset) = rename_collision_source_and_offset();

        let class_prefix = "export class C {\n  m() {\n    ";
        let declarator_prefix = "const [octokit, ";
        let padding_len = collision_offset
            .checked_sub(class_prefix.len() + declarator_prefix.len())
            .expect("class binding should be padded to the earlier rename position");
        let source = format!(
            "{rename_source}{class_prefix}{}{declarator_prefix}ghRepository] = foo();\n    return ghRepository.full_name;\n  }}\n}}\n",
            " ".repeat(padding_len)
        );

        let allocator = oxc_allocator::Allocator::default();
        let mut opts = options();
        opts.compilation_mode = "all".to_string();
        let result = transform_source(&source, oxc_span::SourceType::tsx(), &allocator, opts);
        let program = result.program.expect("file should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert_has_rename_collision_setup(&output);
        assert!(
            output.contains("const [octokit, ghRepository] = foo()"),
            "source-preserved class binding was renamed by an unrelated plan entry:\n{output}"
        );
        assert!(!output.contains("const [octokit, x_0]"), "class binding was corrupted:\n{output}");
    }

    #[test]
    fn jsx_attribute_string_entities_are_decoded() {
        let source = "\
function Component(props) {\n\
  return <TemplateLinkSection label={props.label} piiWarning='Use the iframe&apos;s payload.' />;\n\
}\n";

        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("component should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(output.contains("react/compiler-runtime"), "component should memoize:\n{output}");
        assert!(
            output.contains("iframe's payload"),
            "JSX string attribute entity was not decoded:\n{output}"
        );
        assert!(
            !output.contains("iframe&apos;s payload"),
            "JSX string attribute entity leaked into runtime string:\n{output}"
        );
    }

    #[test]
    fn resource_management_declarations_bail_out() {
        let cases = [
            "\
function Component(props) {\n  using x = sideEffect();\n  return <div>{props.text}</div>;\n}\n",
            "\
async function Component(props) {\n  await using x = sideEffect();\n  return <div>{props.text}</div>;\n}\n",
        ];

        for source in cases {
            let allocator = oxc_allocator::Allocator::default();
            let result =
                transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());

            assert!(result.program.is_none(), "resource management should skip React Compiler");
            assert!(
                result.diagnostics.is_empty(),
                "unexpected diagnostics: {:?}",
                result.diagnostics
            );
        }
    }

    #[test]
    fn exported_typescript_runtime_declarations_are_preserved() {
        let source = "\
export enum E { A }\n\
export namespace N {\n  export const value = E.A;\n}\n\
function Component(props) {\n  return <div>{E.A}{N.value}{props.text}</div>;\n}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("component should be compiled");
        let output = oxc_codegen::Codegen::new().build(&program).code;

        assert!(output.contains("export enum E"), "exported enum lost:\n{output}");
        assert!(output.contains("A"), "enum member lost:\n{output}");
        assert!(output.contains("export namespace N"), "exported namespace lost:\n{output}");
        assert!(output.contains("value = E.A"), "namespace body lost:\n{output}");
        assert!(
            !output.contains("declare const"),
            "exported TS declaration became a placeholder:\n{output}"
        );
    }

    /// A `React.memo(...)` component is anonymous; the prefilter must still see it.
    #[test]
    fn memo_wrapped_component_compiles() {
        let source = "React.memo((props) => {\n  return <div>{props.text}</div>;\n});\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        let program = result.program.expect("memo-wrapped component should compile");
        let output = oxc_codegen::Codegen::new().build(&program).code;
        assert!(output.contains("react/compiler-runtime"), "should memoize:\n{output}");
        assert!(output.contains("_c("), "expected memo cache reads:\n{output}");
    }

    /// Diagnostics are surfaced at the compiler's own severity, not flattened.
    #[test]
    fn diagnostics_preserve_compiler_severity() {
        use oxc_diagnostics::Severity;

        // A Rules of Hooks violation is an `Error`-severity diagnostic.
        let source = "function Component(props) {\n  if (props.cond) {\n    useState(0);\n  }\n  return <div>{props.text}</div>;\n}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        assert!(
            result.diagnostics.iter().any(|d| d.severity == Severity::Error),
            "Rules of Hooks violation should be reported as an error: {:?}",
            result.diagnostics
        );

        // A local named `fbt` is an unsupported-syntax bail-out — a warning, not an error.
        let source = "function Component() {\n  const fbt = \"span\";\n  return <fbt desc=\"label\">Hello</fbt>;\n}\n";
        let allocator = oxc_allocator::Allocator::default();
        let result = transform_source(source, oxc_span::SourceType::tsx(), &allocator, options());
        assert!(
            result.diagnostics.iter().any(|d| d.severity == Severity::Warning),
            "fbt bail-out should be reported as a warning: {:?}",
            result.diagnostics
        );
        assert!(
            result.diagnostics.iter().all(|d| d.severity != Severity::Error),
            "fbt warning must not be reported as an error: {:?}",
            result.diagnostics
        );
    }
}