oj_compiler 0.0.3

Fused per-file pipeline
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Raphael Amorim

//! The fused per-file compile pipeline.
//!
//! One arena, one parse, one fused transform pass-set, one codegen.
//! For TSX/TS/JSX: strip types, apply JSX (automatic runtime), then React
//! Fast Refresh instrumentation (dev), emitting JS plus sourcemap.
//!
//! Never re-parses between stages; keep it allocation-conscious.

pub mod bundle;
pub mod cjs;
pub mod glob;
pub mod json;

use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use memchr::memmem::Finder;
use oxc_allocator::Allocator;
use oxc_ast::ast::{Program, Statement, StringLiteral};
use oxc_codegen::{Codegen, CodegenOptions, CodegenReturn};
use oxc_parser::Parser;
use oxc_semantic::SemanticBuilder;
use oxc_span::SourceType;
use oxc_transformer::{JsxRuntime, ReactRefreshOptions, TransformOptions, Transformer};
use oxc_transformer_plugins::{ReplaceGlobalDefines, ReplaceGlobalDefinesConfig};

/// Maps an import specifier to a replacement (e.g. `./App` becomes
/// `/src/App.tsx`). Returning `None` leaves the specifier untouched.
pub type ImportRewriter<'r> = dyn FnMut(&str) -> Option<String> + 'r;

// SIMD substring finders for the per-module gating prescans. `str::contains`
// with a multi-byte needle is the scalar Two-Way algorithm; `memmem::Finder`
// is SIMD-accelerated and its shift table is built once here, not per call.
// Every compiled module runs these three scans over its full source/output.
static F_IMPORT_META_ENV: LazyLock<Finder<'static>> = LazyLock::new(|| Finder::new("import.meta.env"));
static F_IMPORT_META_GLOB: LazyLock<Finder<'static>> = LazyLock::new(|| Finder::new("import.meta.glob"));

/// Whether a transformed program contains a `$RefreshReg$(...)` registration
/// call — the semantic signal that Fast Refresh instrumented a component in this
/// module, so it can be an HMR boundary. Detected by walking the AST rather than
/// scanning the generated text, so a literal `$RefreshReg$(` inside a string or
/// comment can never produce a false boundary (and over-invalidate on edit).
pub(crate) fn detect_refresh_registrations(program: &Program) -> bool {
    use oxc_ast::ast::{CallExpression, Expression};
    use oxc_ast_visit::{Visit, walk};

    struct Detector {
        found: bool,
    }
    impl<'a> Visit<'a> for Detector {
        fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
            if self.found {
                return;
            }
            if let Expression::Identifier(id) = &call.callee {
                if id.name == "$RefreshReg$" {
                    self.found = true;
                    return;
                }
            }
            walk::walk_call_expression(self, call);
        }
    }
    let mut detector = Detector { found: false };
    detector.visit_program(program);
    detector.found
}

/// `import.meta.env.*` define pairs, set once at dev/build startup from the
/// app's `.env` files. Unset (e.g. in unit tests) falls back to built-ins.
static ENV_DEFINES: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();

/// Install the env defines for this process (call once, before compiling).
pub fn set_import_meta_env(defines: Vec<(String, String)>) {
    let _ = ENV_DEFINES.set(defines);
}

pub(crate) fn import_meta_env_defines(dev: bool) -> Vec<(String, String)> {
    if let Some(defines) = ENV_DEFINES.get() {
        return defines.clone();
    }
    // Built-in fallback: no .env loaded (unit tests, minimal usage).
    let mode = if dev { "development" } else { "production" };
    vec![
        ("import.meta.env.BASE_URL".into(), "\"/\"".into()),
        ("import.meta.env.MODE".into(), format!("\"{mode}\"")),
        ("import.meta.env.DEV".into(), dev.to_string()),
        ("import.meta.env.PROD".into(), (!dev).to_string()),
        ("import.meta.env.SSR".into(), "false".into()),
        (
            "import.meta.env".into(),
            format!(
                "({{\"BASE_URL\":\"/\",\"MODE\":\"{mode}\",\"DEV\":{dev},\"PROD\":{prod},\"SSR\":false}})",
                prod = !dev
            ),
        ),
    ]
}

#[derive(Debug, Clone)]
pub struct CompileOptions {
    /// Dev mode: jsxDEV runtime, no pure annotations needed for shaking yet.
    pub dev: bool,
    /// Instrument components for React Fast Refresh ($RefreshReg$/$RefreshSig$).
    /// Only meaningful in dev.
    pub refresh: bool,
    /// Emit a sourcemap alongside the code.
    pub sourcemap: bool,
}

impl CompileOptions {
    pub fn dev() -> Self {
        Self { dev: true, refresh: true, sourcemap: true }
    }

    pub fn prod() -> Self {
        Self { dev: false, refresh: false, sourcemap: true }
    }
}

#[derive(Debug)]
pub struct CompileOutput {
    pub code: String,
    /// Sourcemap as a `data:` URL, ready to append as `//# sourceMappingURL=`.
    pub map_data_url: Option<String>,
    /// Final specifiers of static imports and re-exports, post-rewrite.
    /// Type-only imports are already erased and never appear here.
    pub imports: Vec<String>,
    /// Final specifiers of dynamic `import("literal")` targets, post-rewrite.
    /// Kept separate from `imports` so the crawl and bundler can treat these as
    /// lazy boundaries (compiled on demand) rather than eager dependencies.
    pub dynamic_imports: Vec<String>,
    /// Whether the Fast Refresh transform emitted a `$RefreshReg$` registration.
    /// Detected on the transformed AST (see `detect_refresh_registrations`), not
    /// by scanning the generated text.
    pub is_refresh_boundary: bool,
}

impl CompileOutput {
    /// Code with the sourcemap inlined, for dev serving.
    pub fn code_with_inline_map(&self) -> String {
        match &self.map_data_url {
            Some(url) => format!("{}\n//# sourceMappingURL={}\n", self.code, url),
            None => self.code.clone(),
        }
    }

    /// Whether the Fast Refresh transform registered any components here.
    /// Modules where this is true are HMR boundary candidates.
    pub fn has_refresh_registrations(&self) -> bool {
        self.is_refresh_boundary
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CompileError {
    #[error("unsupported file type: {0}")]
    UnsupportedFileType(PathBuf),
    #[error("parse error in {path}:\n{message}")]
    Parse { path: PathBuf, message: String },
    #[error("transform error in {path}:\n{message}")]
    Transform { path: PathBuf, message: String },
}

pub fn compile(
    path: &Path,
    source_text: &str,
    opts: &CompileOptions,
) -> Result<CompileOutput, CompileError> {
    compile_module(path, source_text, opts, None)
}

/// The module's exported binding names: named exports, re-export specifiers
/// (`export { a } from "..."`), the namespace of an `export * as ns from "..."`,
/// and `default` when a default export is present. Used to generate client
/// stubs for server-only (`*.server.*`) modules. A bare `export * from "..."`
/// re-exports names that cannot be known without resolving the target module,
/// so it contributes none. Returns empty on a parse failure.
pub fn exports(source_text: &str, path: &Path) -> Vec<String> {
    let Ok(source_type) = SourceType::from_path(path) else { return Vec::new() };
    let allocator = Allocator::default();
    let parsed = Parser::new(&allocator, source_text, source_type).parse();
    if parsed.panicked {
        return Vec::new();
    }
    let mut names = Vec::new();
    for stmt in &parsed.program.body {
        match stmt {
            // `export const/function/class ...`
            Statement::ExportDeclaration(decl) => {
                names.extend(bundle::binding_names(&decl.declaration));
            }
            // `export { a, b as c }`
            Statement::ExportNamedDeclaration(decl) => {
                for spec in &decl.specifiers {
                    names.push(bundle::export_name(&spec.exported));
                }
            }
            // `export { a, b as c } from "./mod"`
            Statement::ExportFromDeclaration(decl) => {
                for spec in &decl.specifiers {
                    names.push(bundle::export_name(&spec.exported));
                }
            }
            // `export * as ns from "./mod"` binds `ns`; bare `export *` cannot
            // be enumerated statically, so it adds nothing.
            Statement::ExportAllDeclaration(decl) => {
                if let Some(exported) = &decl.exported {
                    names.push(bundle::export_name(exported));
                }
            }
            Statement::ExportDefaultDeclaration(_) => names.push("default".to_string()),
            _ => {}
        }
    }
    names
}

pub fn compile_module(
    path: &Path,
    source_text: &str,
    opts: &CompileOptions,
    mut rewriter: Option<&mut ImportRewriter>,
) -> Result<CompileOutput, CompileError> {
    let source_type = SourceType::from_path(path)
        .map_err(|_| CompileError::UnsupportedFileType(path.to_path_buf()))?;

    let allocator = Allocator::default();

    let parsed = Parser::new(&allocator, source_text, source_type).parse();
    if parsed.panicked || !parsed.diagnostics.is_empty() {
        let message = parsed
            .diagnostics
            .into_iter()
            .map(|d| format!("{:?}", d.with_source_code(source_text.to_string())))
            .collect::<Vec<_>>()
            .join("\n");
        return Err(CompileError::Parse { path: path.to_path_buf(), message });
    }
    let mut program = parsed.program;

    // Transformer needs scoping info; the transformer roughly triples scope counts.
    let semantic_ret = SemanticBuilder::new().with_excess_capacity(2.0).build(&program);
    let scoping = semantic_ret.semantic.into_scoping();

    let mut transform_options = TransformOptions::default();
    transform_options.jsx.jsx_plugin = true;
    transform_options.jsx.runtime = JsxRuntime::Automatic;
    transform_options.jsx.development = opts.dev;
    transform_options.jsx.jsx_self_plugin = opts.dev;
    transform_options.jsx.jsx_source_plugin = opts.dev;
    if opts.dev && opts.refresh {
        transform_options.jsx.refresh = Some(ReactRefreshOptions::default());
    }

    let transform_ret = Transformer::new(&allocator, path, &transform_options)
        .build_with_scoping(scoping, &mut program);
    if !transform_ret.diagnostics.is_empty() {
        let message = transform_ret
            .diagnostics
            .into_iter()
            .map(|d| format!("{:?}", d.with_source_code(source_text.to_string())))
            .collect::<Vec<_>>()
            .join("\n");
        return Err(CompileError::Transform { path: path.to_path_buf(), message });
    }

    // Static define replacement (import.meta.env plus config/env `define`),
    // gated on a substring test so modules without defines pay nothing.
    let defines = import_meta_env_defines(opts.dev);
    let needs_defines = F_IMPORT_META_ENV.find(source_text.as_bytes()).is_some()
        || defines
            .iter()
            .any(|(k, _)| !k.starts_with("import.meta") && source_text.contains(k.as_str()));
    if needs_defines {
        // Reuse the scoping the transformer already produced for the transformed
        // program, instead of running a second full SemanticBuilder pass over it.
        if let Ok(config) = ReplaceGlobalDefinesConfig::new(&defines) {
            let _ = ReplaceGlobalDefines::new(&allocator, config).build(transform_ret.scoping, &mut program);
        }
    }

    // Expand import.meta.glob before specifier rewriting, so the generated
    // import()/import statements get canonicalized to URLs by the rewriter.
    if F_IMPORT_META_GLOB.find(source_text.as_bytes()).is_some() {
        let dir = path.parent().unwrap_or(path);
        glob::expand(&allocator, dir, &mut program);
    }

    let (imports, dynamic_imports) = rewrite_module_specifiers(&allocator, &mut program, &mut rewriter);

    // Fast Refresh boundary, decided semantically on the transformed AST (only
    // when the refresh transform ran). Cheaper than it looks: no separate text
    // scan, and precise where a string scan would over-invalidate.
    let is_refresh_boundary = opts.refresh && detect_refresh_registrations(&program);

    let codegen_options = CodegenOptions {
        source_map_path: opts.sourcemap.then(|| path.to_path_buf()),
        ..CodegenOptions::default()
    };
    let CodegenReturn { code, map, .. } =
        Codegen::new().with_options(codegen_options).build(&program);

    Ok(CompileOutput {
        code,
        map_data_url: map.map(|m| m.to_data_url()),
        imports,
        dynamic_imports,
        is_refresh_boundary,
    })
}

/// Collect (and optionally rewrite) the source specifiers of all static
/// imports and re-exports. Runs after the transforms, so JSX-runtime imports
/// injected by the automatic runtime are included and type-only imports are
/// already gone.
///
/// TODO(M2): dynamic `import("...")` with literal arguments needs an AST
/// visitor pass; top-level statements are enough for milestone 1.
/// Exposed for bundle mode, which shares specifier canonicalization.
pub(crate) fn rewrite_module_specifiers_pub<'a>(
    allocator: &'a Allocator,
    program: &mut Program<'a>,
    rewriter: &mut ImportRewriter,
) -> (Vec<String>, Vec<String>) {
    let mut opt: Option<&mut ImportRewriter> = Some(rewriter);
    rewrite_module_specifiers(allocator, program, &mut opt)
}

fn rewrite_module_specifiers<'a>(
    allocator: &'a Allocator,
    program: &mut Program<'a>,
    rewriter: &mut Option<&mut ImportRewriter>,
) -> (Vec<String>, Vec<String>) {
    let mut imports = Vec::new();
    let mut dynamic_imports = Vec::new();
    for stmt in program.body.iter_mut() {
        let source: Option<&mut StringLiteral> = match stmt {
            Statement::ImportDeclaration(decl) => Some(&mut decl.source),
            Statement::ExportFromDeclaration(decl) => Some(&mut decl.source),
            Statement::ExportAllDeclaration(decl) => Some(&mut decl.source),
            _ => None,
        };
        let Some(lit) = source else { continue };

        if let Some(rewriter) = rewriter.as_deref_mut() {
            if let Some(new_spec) = rewriter(lit.value.as_str()) {
                lit.value = allocator.alloc_str(&new_spec).into();
                lit.raw = None;
            }
        }
        imports.push(lit.value.to_string());
    }
    // Dynamic import("literal") gets the same canonicalization (needed for
    // bare specifiers, which the browser cannot resolve), but is collected
    // separately: these are lazy boundaries, not eager dependencies.
    if let Some(rewriter) = rewriter.as_deref_mut() {
        let mut dyn_rewriter = DynamicImportRewriter { allocator, rewriter, dynamic: &mut dynamic_imports };
        use oxc_ast_visit::VisitMut;
        dyn_rewriter.visit_program(program);
    }
    (imports, dynamic_imports)
}

struct DynamicImportRewriter<'a, 'b> {
    allocator: &'a Allocator,
    rewriter: &'b mut ImportRewriter<'b>,
    dynamic: &'b mut Vec<String>,
}

impl<'a> oxc_ast_visit::VisitMut<'a> for DynamicImportRewriter<'a, '_> {
    fn visit_import_expression(&mut self, it: &mut oxc_ast::ast::ImportExpression<'a>) {
        if let oxc_ast::ast::Expression::StringLiteral(lit) = &mut it.source {
            if let Some(new_spec) = (self.rewriter)(lit.value.as_str()) {
                lit.value = self.allocator.alloc_str(&new_spec).into();
                lit.raw = None;
            }
            self.dynamic.push(lit.value.to_string());
        }
        oxc_ast_visit::walk_mut::walk_import_expression(self, it);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exports_lists_named_and_default() {
        let src = r#"
export const getUser = async (id) => ({ id });
export function listUsers() { return []; }
export class Thing {}
const x = 1;
export { x, x as y };
export default function () {}
"#;
        let mut names = exports(src, Path::new("api.server.ts"));
        names.sort();
        assert_eq!(names, ["Thing", "default", "getUser", "listUsers", "x", "y"]);
    }

    const APP_TSX: &str = r#"
interface Props { label: string }

export function Counter({ label }: Props) {
  const [n, setN] = React.useState<number>(0);
  return <button onClick={() => setN(n + 1)}>{label}: {n}</button>;
}

import React from "react";
"#;

    #[test]
    fn strips_types_and_uses_automatic_runtime_in_prod() {
        let out =
            compile(Path::new("App.tsx"), APP_TSX, &CompileOptions::prod()).unwrap();
        assert!(!out.code.contains("interface"), "types must be stripped");
        assert!(!out.code.contains("<button"), "JSX must be transformed");
        assert!(
            out.code.contains("react/jsx-runtime"),
            "prod uses the automatic runtime:\n{}",
            out.code
        );
        assert!(out.map_data_url.is_some());
    }

    #[test]
    fn dev_uses_jsx_dev_runtime_and_instruments_fast_refresh() {
        let out = compile(Path::new("App.tsx"), APP_TSX, &CompileOptions::dev()).unwrap();
        assert!(
            out.code.contains("react/jsx-dev-runtime"),
            "dev uses jsxDEV:\n{}",
            out.code
        );
        assert!(
            out.code.contains("$RefreshReg$"),
            "components must be registered for Fast Refresh:\n{}",
            out.code
        );
        assert!(
            out.code.contains("$RefreshSig$"),
            "hook users must be signed for Fast Refresh:\n{}",
            out.code
        );
    }

    #[test]
    fn rewrites_relative_specifiers_and_collects_imports() {
        let src = r#"
import { App } from "./App";
export { helper } from "../lib/helper";
import { useState } from "react";
export function Root() {
  const [n] = useState(0);
  return <App key={n} />;
}
"#;
        let mut rewrite = |spec: &str| -> Option<String> {
            spec.starts_with('.').then(|| format!("/resolved{}", spec.trim_start_matches('.')))
        };
        let out = compile_module(
            Path::new("Root.tsx"),
            src,
            &CompileOptions::prod(),
            Some(&mut rewrite),
        )
        .unwrap();
        assert!(out.code.contains("\"/resolved/App\""), "{}", out.code);
        assert!(out.code.contains("\"/resolved/lib/helper\""), "{}", out.code);
        assert!(out.code.contains("\"react\""), "bare imports stay untouched");
        assert!(out.imports.contains(&"/resolved/App".to_string()));
        assert!(out.imports.contains(&"react".to_string()));
        // the automatic runtime import injected by the JSX transform is visible
        assert!(out.imports.iter().any(|i| i.contains("jsx-runtime")), "{:?}", out.imports);
    }

    #[test]
    fn reports_parse_errors_instead_of_panicking() {
        let err = compile(Path::new("Broken.tsx"), "const = <div>;", &CompileOptions::dev())
            .unwrap_err();
        assert!(matches!(err, CompileError::Parse { .. }));
    }

    #[test]
    fn replaces_import_meta_env_flags_per_mode() {
        let src = "export const mode = import.meta.env.MODE;\n\
                   export const dev = import.meta.env.DEV;\n\
                   export const prod = import.meta.env.PROD;";
        let prod = compile(Path::new("env.ts"), src, &CompileOptions::prod()).unwrap();
        // every define is substituted, nothing left referencing import.meta.env
        assert!(!prod.code.contains("import.meta.env"), "defines must be replaced:\n{}", prod.code);
        assert!(prod.code.contains("\"production\""), "MODE is production:\n{}", prod.code);
        assert!(prod.code.contains("prod = true"), "PROD is true in prod:\n{}", prod.code);
        assert!(prod.code.contains("dev = false"), "DEV is false in prod:\n{}", prod.code);

        let dev = compile(Path::new("env.ts"), src, &CompileOptions::dev()).unwrap();
        assert!(dev.code.contains("\"development\""), "MODE is development:\n{}", dev.code);
        assert!(dev.code.contains("dev = true"), "DEV is true in dev:\n{}", dev.code);
        assert!(dev.code.contains("prod = false"), "PROD is false in dev:\n{}", dev.code);
    }

    #[test]
    fn erases_type_only_imports_from_code_and_collected_imports() {
        let src = r#"
import type { A } from "./types";
import { type B, c } from "./mixed";
import { d } from "./real";
export const used: A extends B ? number : number = c + d;
"#;
        let out = compile(Path::new("m.ts"), src, &CompileOptions::prod()).unwrap();
        // a fully type-only import is elided, so its specifier never surfaces
        assert!(!out.imports.iter().any(|i| i.contains("types")), "type-only import erased: {:?}", out.imports);
        assert!(!out.code.contains("./types"), "type-only source gone:\n{}", out.code);
        // an import with a value binding survives; the inline `type` specifier is dropped
        assert!(out.imports.iter().any(|i| i.contains("mixed")), "mixed import kept: {:?}", out.imports);
        assert!(!out.code.contains("type B"), "inline type specifier erased:\n{}", out.code);
        assert!(out.imports.iter().any(|i| i.contains("real")));
    }

    #[test]
    fn rewrites_dynamic_import_specifiers() {
        let src = r#"export async function load() { return import("./chunk"); }"#;
        let mut rewrite = |s: &str| -> Option<String> {
            s.starts_with('.').then(|| format!("/res{}", s.trim_start_matches('.')))
        };
        let out =
            compile_module(Path::new("d.ts"), src, &CompileOptions::prod(), Some(&mut rewrite)).unwrap();
        assert!(out.code.contains("import(\"/res/chunk\")"), "dynamic import rewritten:\n{}", out.code);
        // Dynamic targets are collected separately from static imports (lazy).
        assert!(
            out.dynamic_imports.contains(&"/res/chunk".to_string()),
            "dynamic spec collected: {:?}",
            out.dynamic_imports
        );
        assert!(!out.imports.contains(&"/res/chunk".to_string()), "dynamic not in static imports");
    }

    #[test]
    fn fast_refresh_only_in_dev_with_refresh_enabled() {
        // prod: never instrumented
        let prod = compile(Path::new("C.tsx"), APP_TSX, &CompileOptions::prod()).unwrap();
        assert!(!prod.has_refresh_registrations());
        // dev with refresh disabled: still the dev jsx runtime, but no instrumentation
        let dev_no_refresh = compile_module(
            Path::new("C.tsx"),
            APP_TSX,
            &CompileOptions { dev: true, refresh: false, sourcemap: false },
            None,
        )
        .unwrap();
        assert!(!dev_no_refresh.has_refresh_registrations());
        assert!(dev_no_refresh.code.contains("jsx-dev-runtime"), "dev runtime regardless of refresh");
    }

    #[test]
    fn rejects_unsupported_file_types() {
        let err = compile(Path::new("styles.css"), "body{}", &CompileOptions::prod()).unwrap_err();
        assert!(matches!(err, CompileError::UnsupportedFileType(_)), "got {err:?}");
    }

    #[test]
    fn sourcemap_toggle_and_inline_map_helper() {
        let no_map = compile_module(
            Path::new("a.ts"),
            "export const x = 1;",
            &CompileOptions { dev: false, refresh: false, sourcemap: false },
            None,
        )
        .unwrap();
        assert!(no_map.map_data_url.is_none());
        // with no map, the inline-map helper returns the code untouched
        assert_eq!(no_map.code_with_inline_map(), no_map.code);

        let with_map = compile(Path::new("a.ts"), "export const x = 1;", &CompileOptions::prod()).unwrap();
        assert!(with_map.map_data_url.is_some());
        assert!(with_map.code_with_inline_map().contains("sourceMappingURL="));
    }

    #[test]
    fn exports_handles_reexports_and_never_panics() {
        // local named exports (no `from`)
        let mut local = exports(r#"export const a = 1; export { a as b };"#, Path::new("m.ts"));
        local.sort();
        assert_eq!(local, ["a", "b"]);
        // a parse failure yields an empty list rather than a panic
        assert!(exports("export { = ;", Path::new("bad.ts")).is_empty());
        // an unsupported extension also yields empty, never an error
        assert!(exports("body{}", Path::new("x.css")).is_empty());
    }

    #[test]
    fn exports_captures_reexport_from_and_namespace_star() {
        // `export { a, b as c } from "./mod"` contributes the exported names
        let mut names = exports(r#"export { a, b as c } from "./mod";"#, Path::new("m.ts"));
        names.sort();
        assert_eq!(names, ["a", "c"]);
        // `export * as ns from "./mod"` binds the namespace name
        assert_eq!(exports(r#"export * as ns from "./mod";"#, Path::new("m.ts")), ["ns"]);
        // bare `export * from "./mod"` cannot be enumerated statically -> none
        assert!(exports(r#"export * from "./mod";"#, Path::new("m.ts")).is_empty());
        // a mix: local default + re-export-from are all present
        let mut mixed = exports(
            r#"export default function () {}
export { x } from "./a";
export * as z from "./b";"#,
            Path::new("m.ts"),
        );
        mixed.sort();
        assert_eq!(mixed, ["default", "x", "z"]);
    }
}