nextjs_react_compiler_swc 0.1.5

Rust port of the React Compiler, vendored from facebook/react.
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
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

use react_compiler::entrypoint::plugin_options::CompilerTarget;
use react_compiler::entrypoint::plugin_options::PluginOptions;
use react_compiler_ast::scope::BindingKind;
use react_compiler_ast::scope::ScopeKind;
use react_compiler_ast::statements::Statement;
use react_compiler_swc::convert_ast::convert_module;
use react_compiler_swc::convert_ast_reverse::convert_program_to_swc;
use react_compiler_swc::convert_scope::build_scope_info;
use react_compiler_swc::lint_source;
use react_compiler_swc::prefilter::has_react_like_functions;
use react_compiler_swc::transform_source;
use swc_common::FileName;
use swc_common::SourceMap;
use swc_common::sync::Lrc;
use swc_ecma_ast::EsVersion;
use swc_ecma_parser::EsSyntax;
use swc_ecma_parser::Syntax;
use swc_ecma_parser::parse_file_as_module;

fn parse_module(source: &str) -> swc_ecma_ast::Module {
    let cm = Lrc::new(SourceMap::default());
    let fm = cm.new_source_file(Lrc::new(FileName::Anon), source.to_string());
    let mut errors = vec![];
    parse_file_as_module(
        &fm,
        Syntax::Es(EsSyntax {
            jsx: true,
            ..Default::default()
        }),
        EsVersion::latest(),
        None,
        &mut errors,
    )
    .expect("Failed to parse")
}

fn default_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: Default::default(),
        source_code: None,
        profiling: false,
        debug: false,
    }
}

// ── Prefilter tests ─────────────────────────────────────────────────────────

#[test]
fn prefilter_detects_function_component() {
    let module = parse_module("function MyComponent() { return <div />; }");
    assert!(has_react_like_functions(&module));
}

#[test]
fn prefilter_detects_arrow_component() {
    let module = parse_module("const MyComponent = () => <div />;");
    assert!(has_react_like_functions(&module));
}

#[test]
fn prefilter_detects_hook() {
    let module = parse_module("function useMyHook() { return 42; }");
    assert!(has_react_like_functions(&module));
}

#[test]
fn prefilter_detects_hook_assigned_to_variable() {
    let module = parse_module("const useMyHook = function() { return 42; };");
    assert!(has_react_like_functions(&module));
}

#[test]
fn prefilter_rejects_non_react_module() {
    let module = parse_module(
        r#"
        const x = 1;
        function helper() { return x + 2; }
        export { helper };
        "#,
    );
    assert!(!has_react_like_functions(&module));
}

#[test]
fn prefilter_rejects_lowercase_function() {
    let module = parse_module("function myFunction() { return 42; }");
    assert!(!has_react_like_functions(&module));
}

#[test]
fn prefilter_rejects_use_prefix_without_uppercase() {
    let module = parse_module("function useful() { return true; }");
    assert!(!has_react_like_functions(&module));
}

// ── AST round-trip tests ────────────────────────────────────────────────────

#[test]
fn convert_variable_declaration() {
    let source = "const x = 1;";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::VariableDeclaration(_)
    ));
}

#[test]
fn convert_function_declaration() {
    let source = "function foo() { return 42; }";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::FunctionDeclaration(_)
    ));
}

#[test]
fn convert_arrow_function_expression() {
    let source = "const f = (x) => x + 1;";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::VariableDeclaration(_)
    ));
}

#[test]
fn convert_jsx_element() {
    let source = "const el = <div className=\"test\">hello</div>;";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::VariableDeclaration(_)
    ));
}

#[test]
fn convert_import_declaration() {
    let source = "import { useState } from 'react';";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::ImportDeclaration(_)
    ));
}

#[test]
fn convert_export_named_declaration() {
    let source = "export const x = 1;";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::ExportNamedDeclaration(_)
    ));
}

#[test]
fn convert_export_default_declaration() {
    let source = "export default function App() { return <div />; }";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 1);
    assert!(matches!(
        &file.program.body[0],
        Statement::ExportDefaultDeclaration(_)
    ));
}

#[test]
fn convert_multiple_statements() {
    let source = r#"
        import React from 'react';
        const x = 1;
        function App() { return <div>{x}</div>; }
        export default App;
    "#;
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.body.len(), 4);
    assert!(matches!(
        &file.program.body[0],
        Statement::ImportDeclaration(_)
    ));
    assert!(matches!(
        &file.program.body[1],
        Statement::VariableDeclaration(_)
    ));
    assert!(matches!(
        &file.program.body[2],
        Statement::FunctionDeclaration(_)
    ));
    assert!(matches!(
        &file.program.body[3],
        Statement::ExportDefaultDeclaration(_)
    ));
}

#[test]
fn convert_directive() {
    let source = "'use strict';\nconst x = 1;";
    let module = parse_module(source);
    let file = convert_module(&module, source);
    assert_eq!(file.program.directives.len(), 1);
    assert_eq!(file.program.body.len(), 1);
}

// ── Scope analysis tests ────────────────────────────────────────────────────

#[test]
fn scope_program_scope_created() {
    let source = "const x = 1;";
    let module = parse_module(source);
    let info = build_scope_info(&module);
    assert!(!info.scopes.is_empty());
    assert!(matches!(info.scopes[0].kind, ScopeKind::Program));
    assert!(info.scopes[0].parent.is_none());
}

#[test]
fn scope_var_hoists_to_function() {
    let source = r#"
        function foo() {
            {
                var x = 1;
            }
        }
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    // Find the binding for x
    let x_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "x")
        .expect("should find binding x");
    assert!(matches!(x_binding.kind, BindingKind::Var));

    // x should be in a Function scope, not the Block scope
    let scope = &info.scopes[x_binding.scope.0 as usize];
    assert!(matches!(scope.kind, ScopeKind::Function));
}

#[test]
fn scope_let_const_block_scoped() {
    let source = r#"
        function foo() {
            {
                let x = 1;
                const y = 2;
            }
        }
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let x_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "x")
        .expect("should find binding x");
    assert!(matches!(x_binding.kind, BindingKind::Let));
    let x_scope = &info.scopes[x_binding.scope.0 as usize];
    assert!(matches!(x_scope.kind, ScopeKind::Block));

    let y_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "y")
        .expect("should find binding y");
    assert!(matches!(y_binding.kind, BindingKind::Const));
    let y_scope = &info.scopes[y_binding.scope.0 as usize];
    assert!(matches!(y_scope.kind, ScopeKind::Block));
}

#[test]
fn scope_function_declaration_hoists() {
    let source = r#"
        function outer() {
            {
                function inner() {}
            }
        }
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let inner_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "inner")
        .expect("should find binding inner");
    assert!(matches!(inner_binding.kind, BindingKind::Hoisted));
    // inner should be hoisted to the enclosing function scope (outer), not the block
    let scope = &info.scopes[inner_binding.scope.0 as usize];
    assert!(matches!(scope.kind, ScopeKind::Function));
}

#[test]
fn scope_import_bindings() {
    let source = r#"
        import React from 'react';
        import { useState, useEffect } from 'react';
        import * as Utils from './utils';
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let react_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "React")
        .expect("should find binding React");
    assert!(matches!(react_binding.kind, BindingKind::Module));
    assert!(react_binding.import.is_some());
    let import_data = react_binding.import.as_ref().unwrap();
    assert_eq!(import_data.source, "react");

    let use_state_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "useState")
        .expect("should find binding useState");
    assert!(matches!(use_state_binding.kind, BindingKind::Module));

    let utils_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "Utils")
        .expect("should find binding Utils");
    assert!(matches!(utils_binding.kind, BindingKind::Module));
}

#[test]
fn scope_nested_functions_create_scopes() {
    let source = r#"
        function outer(a) {
            function inner(b) {
                return a + b;
            }
        }
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let a_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "a")
        .expect("should find binding a");
    assert!(matches!(a_binding.kind, BindingKind::Param));

    let b_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "b")
        .expect("should find binding b");
    assert!(matches!(b_binding.kind, BindingKind::Param));

    // a and b should be in different function scopes
    assert!(a_binding.scope.0 != b_binding.scope.0);
}

#[test]
fn scope_catch_clause_creates_scope() {
    let source = r#"
        try {
            throw new Error();
        } catch (e) {
            console.log(e);
        }
    "#;
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let e_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "e")
        .expect("should find binding e");
    assert!(matches!(e_binding.kind, BindingKind::Let));
    let scope = &info.scopes[e_binding.scope.0 as usize];
    assert!(matches!(scope.kind, ScopeKind::Catch));
}

#[test]
fn scope_arrow_function_params() {
    let source = "const f = (x, y) => x + y;";
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let x_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "x")
        .expect("should find binding x");
    assert!(matches!(x_binding.kind, BindingKind::Param));
    let scope = &info.scopes[x_binding.scope.0 as usize];
    assert!(matches!(scope.kind, ScopeKind::Function));
}

#[test]
fn scope_for_loop_creates_scope() {
    let source = "for (let i = 0; i < 10; i++) { console.log(i); }";
    let module = parse_module(source);
    let info = build_scope_info(&module);

    let i_binding = info
        .bindings
        .iter()
        .find(|b| b.name == "i")
        .expect("should find binding i");
    assert!(matches!(i_binding.kind, BindingKind::Let));
    let scope = &info.scopes[i_binding.scope.0 as usize];
    assert!(matches!(scope.kind, ScopeKind::For));
}

// ── Full transform pipeline tests ───────────────────────────────────────────

#[test]
fn transform_simple_component_does_not_panic() {
    let source = r#"
        function App() {
            return <div>Hello</div>;
        }
    "#;
    let result = transform_source(source, default_options());
    // The transform should complete without panicking.
    // It may or may not produce output depending on compiler completeness.
    let _ = result.module;
    let _ = result.diagnostics;
}

#[test]
fn transform_component_with_hook_does_not_panic() {
    let source = r#"
        import { useState } from 'react';
        function Counter() {
            const [count, setCount] = useState(0);
            return <div>{count}</div>;
        }
    "#;
    let result = transform_source(source, default_options());
    let _ = result.module;
    let _ = result.diagnostics;
}

#[test]
fn transform_non_react_code_returns_none() {
    let source = "const x = 1 + 2;";
    let result = transform_source(source, default_options());
    // Non-React code with compilation_mode "infer" should be skipped (prefilter)
    assert!(result.module.is_none());
    assert!(result.diagnostics.is_empty());
}

#[test]
fn transform_compilation_mode_all_does_not_skip() {
    let source = "const x = 1 + 2;";
    let mut options = default_options();
    options.compilation_mode = "all".to_string();
    let result = transform_source(source, options);
    // With "all" mode, even non-React code should go through the compiler.
    // It may not produce output, but it should not be skipped by prefilter.
    let _ = result.module;
}

#[test]
fn lint_simple_component_does_not_panic() {
    let source = r#"
        function App() {
            return <div>Hello</div>;
        }
    "#;
    let result = lint_source(source, default_options());
    let _ = result.diagnostics;
}

#[test]
fn lint_non_react_code_returns_empty() {
    let source = "const x = 1;";
    let result = lint_source(source, default_options());
    assert!(result.diagnostics.is_empty());
}

// ── Reverse AST conversion tests ────────────────────────────────────────────

#[test]
fn reverse_convert_variable_declaration() {
    let source = "const x = 1;";
    let module = parse_module(source);
    let file = convert_module(&module, source);

    let swc_module = convert_program_to_swc(&file);
    assert_eq!(swc_module.module.body.len(), 1);
    assert!(matches!(
        &swc_module.module.body[0],
        swc_ecma_ast::ModuleItem::Stmt(swc_ecma_ast::Stmt::Decl(swc_ecma_ast::Decl::Var(_)))
    ));
}

#[test]
fn reverse_convert_function_declaration() {
    let source = "function foo() { return 42; }";
    let module = parse_module(source);
    let file = convert_module(&module, source);

    let swc_module = convert_program_to_swc(&file);
    assert_eq!(swc_module.module.body.len(), 1);
    assert!(matches!(
        &swc_module.module.body[0],
        swc_ecma_ast::ModuleItem::Stmt(swc_ecma_ast::Stmt::Decl(swc_ecma_ast::Decl::Fn(_)))
    ));
}

#[test]
fn reverse_convert_import_export() {
    let source = r#"
        import { useState } from 'react';
        export const x = 1;
    "#;
    let module = parse_module(source);
    let file = convert_module(&module, source);

    let swc_module = convert_program_to_swc(&file);
    assert_eq!(swc_module.module.body.len(), 2);
}

#[test]
fn reverse_convert_roundtrip_via_json() {
    let source = r#"
        const x = 1;
        function foo(a, b) { return a + b; }
    "#;
    let module = parse_module(source);
    let file = convert_module(&module, source);

    // Serialize to JSON and deserialize back
    let json = serde_json::to_value(&file).expect("serialize to JSON");
    let deserialized: react_compiler_ast::File =
        serde_json::from_value(json).expect("deserialize from JSON");

    // Convert the deserialized AST back to SWC
    let swc_module = convert_program_to_swc(&deserialized);
    assert_eq!(swc_module.module.body.len(), 2);
}

#[test]
fn reverse_convert_jsx_roundtrip() {
    let source = r#"const el = <div className="test">hello</div>;"#;
    let module = parse_module(source);
    let file = convert_module(&module, source);

    let json = serde_json::to_value(&file).expect("serialize to JSON");
    let deserialized: react_compiler_ast::File =
        serde_json::from_value(json).expect("deserialize from JSON");

    let swc_module = convert_program_to_swc(&deserialized);
    assert_eq!(swc_module.module.body.len(), 1);
}

#[test]
fn reverse_convert_multiple_statement_types() {
    let source = r#"
        import React from 'react';
        const x = 1;
        let y = 'hello';
        function App() { return <div>{x}{y}</div>; }
        export default App;
    "#;
    let module = parse_module(source);
    let file = convert_module(&module, source);

    let swc_module = convert_program_to_swc(&file);
    assert_eq!(swc_module.module.body.len(), 5);
}

// ── TS module interop statements ────────────────────────────────────────────

fn parse_ts_module(source: &str) -> swc_ecma_ast::Module {
    let cm = Lrc::new(SourceMap::default());
    let fm = cm.new_source_file(Lrc::new(FileName::Anon), source.to_string());
    let mut errors = vec![];
    parse_file_as_module(
        &fm,
        Syntax::Typescript(swc_ecma_parser::TsSyntax {
            tsx: true,
            ..Default::default()
        }),
        EsVersion::latest(),
        None,
        &mut errors,
    )
    .expect("Failed to parse")
}

/// The TS module-interop statements (`import x = require(...)`, `export = x`,
/// `export as namespace X`) flow through `Statement::Unknown` (carrying the
/// raw Babel shape), survive a JSON round trip like the real pipeline, get
/// rebuilt as SWC module declarations, and print back as the source
/// statements. The namespace export exercises the post-emit fixup for the
/// upstream swc_ecma_codegen bug that prints `TsNamespaceExportDecl` as
/// `export = X`.
#[test]
fn ts_module_interop_statements_round_trip() {
    let source =
        "import lib = require('shared-runtime');\nexport = lib;\nexport as namespace Foo;\n";
    let module = parse_ts_module(source);
    let file = convert_module(&module, source);

    let expected_types = [
        "TSImportEqualsDeclaration",
        "TSExportAssignment",
        "TSNamespaceExportDeclaration",
    ];
    assert_eq!(file.program.body.len(), 3);
    for (stmt, expected) in file.program.body.iter().zip(expected_types) {
        match stmt {
            Statement::Unknown(unknown) => assert_eq!(unknown.node_type(), expected),
            other => panic!("expected Unknown({expected}), got {other:?}"),
        }
    }

    // Round trip through JSON like the compiler pipeline does.
    let json = serde_json::to_value(&file).expect("serialize to JSON");
    let deserialized: react_compiler_ast::File =
        serde_json::from_value(json).expect("deserialize from JSON");

    let swc_module = convert_program_to_swc(&deserialized).module;
    assert_eq!(swc_module.body.len(), 3);
    assert!(matches!(
        &swc_module.body[0],
        swc_ecma_ast::ModuleItem::ModuleDecl(swc_ecma_ast::ModuleDecl::TsImportEquals(_))
    ));
    assert!(matches!(
        &swc_module.body[1],
        swc_ecma_ast::ModuleItem::ModuleDecl(swc_ecma_ast::ModuleDecl::TsExportAssignment(_))
    ));
    assert!(matches!(
        &swc_module.body[2],
        swc_ecma_ast::ModuleItem::ModuleDecl(swc_ecma_ast::ModuleDecl::TsNamespaceExport(_))
    ));

    let code = react_compiler_swc::emit_with_comments(&swc_module, None, &[]);
    assert!(
        code.contains("import lib = require(\"shared-runtime\");"),
        "missing import-equals in output: {code}"
    );
    assert!(
        code.contains("export = lib"),
        "missing export-assignment in output: {code}"
    );
    assert!(
        code.contains("export as namespace Foo;"),
        "missing namespace export in output: {code}"
    );
}

/// A qualified-name module reference (`import a = b.c.d`) round-trips
/// through the raw `TSQualifiedName` shape.
#[test]
fn ts_import_equals_qualified_name_round_trips() {
    let source = "import a = b.c.d;\n";
    let module = parse_ts_module(source);
    let file = convert_module(&module, source);

    let json = serde_json::to_value(&file).expect("serialize to JSON");
    let deserialized: react_compiler_ast::File =
        serde_json::from_value(json).expect("deserialize from JSON");

    let swc_module = convert_program_to_swc(&deserialized).module;
    let code = react_compiler_swc::emit_with_comments(&swc_module, None, &[]);
    assert!(
        code.contains("import a = b.c.d;"),
        "missing qualified import-equals in output: {code}"
    );
}

/// Round-trip a TS import-equals declaration source string and return the
/// rebuilt SWC declaration plus the emitted code.
fn round_trip_import_equals(source: &str) -> (swc_ecma_ast::TsImportEqualsDecl, String) {
    let module = parse_ts_module(source);
    let file = convert_module(&module, source);

    let json = serde_json::to_value(&file).expect("serialize to JSON");
    let deserialized: react_compiler_ast::File =
        serde_json::from_value(json).expect("deserialize from JSON");

    let swc_module = convert_program_to_swc(&deserialized).module;
    let decl = match &swc_module.body[0] {
        swc_ecma_ast::ModuleItem::ModuleDecl(swc_ecma_ast::ModuleDecl::TsImportEquals(d)) => {
            (**d).clone()
        }
        other => panic!("expected TsImportEquals, got {other:?}"),
    };
    let code = react_compiler_swc::emit_with_comments(&swc_module, None, &[]);
    (decl, code)
}

/// `import type x = require(...)` round-trips with `is_type_only`
/// preserved through the raw `importKind: "type"` field.
#[test]
fn ts_import_equals_type_only_round_trips() {
    let source = "import type x = require('shared-runtime');\n";
    let (decl, code) = round_trip_import_equals(source);
    assert!(decl.is_type_only, "is_type_only lost in round trip");
    assert!(!decl.is_export);
    assert!(
        code.contains("import type x = require(\"shared-runtime\");"),
        "missing type-only import-equals in output: {code}"
    );
}

/// `export import x = require(...)` round-trips with `is_export` preserved
/// through the raw `isExport: true` field.
#[test]
fn ts_import_equals_export_round_trips() {
    let source = "export import x = require('shared-runtime');\n";
    let (decl, code) = round_trip_import_equals(source);
    assert!(decl.is_export, "is_export lost in round trip");
    assert!(!decl.is_type_only);
    assert!(
        code.contains("export import x = require(\"shared-runtime\");"),
        "missing exported import-equals in output: {code}"
    );
}