Skip to main content

amber_transpile/
lib.rs

1// TypeScript 支持模块
2//
3// Default product path: oxc transpile (TypeScript 6.0 syntax, transpile-only).
4// The historical self-hosted compiler remains for its own unit tests.
5pub mod cache;
6pub mod compiler;
7pub mod detect;
8pub mod oxc_backend;
9
10pub use compiler::{
11    CompilationOutput, ErrorSeverity, TypeScriptCompiler, TypeScriptCompilerConfig,
12    TypeScriptError, TypeScriptModule, TypeScriptTarget,
13};
14pub use detect::{looks_like_jsx_source, looks_like_typescript_source};
15
16/// `//# sourceMappingURL=data:...` comment so V8 can attribute stacks to `.ts`.
17pub fn source_mapping_url_comment(map_json: &str) -> String {
18    use base64::Engine;
19    format!(
20        "\n//# sourceMappingURL=data:application/json;base64,{}",
21        base64::engine::general_purpose::STANDARD.encode(map_json.as_bytes())
22    )
23}
24
25/// 快速编译 TypeScript 源代码(oxc 后端,带内容哈希缓存)
26pub fn compile_typescript(source: &str, file_name: &str) -> Result<CompilationOutput, String> {
27    if let Some(hit) = cache::get_cached(source, file_name) {
28        return Ok(hit);
29    }
30    let output = oxc_backend::transpile(source, file_name)?;
31    cache::put_cached(source, file_name, &output);
32    Ok(output)
33}
34
35/// 快速编译 TypeScript 文件
36pub fn compile_typescript_file(file_path: &std::path::Path) -> Result<CompilationOutput, String> {
37    let source = std::fs::read_to_string(file_path).map_err(|e| e.to_string())?;
38    let file_name = file_path.to_string_lossy().to_string();
39    compile_typescript(&source, &file_name)
40}