Skip to main content

turbopack_ecmascript_runtime/
embed_js.rs

1use anyhow::Result;
2use turbo_rcstr::{RcStr, rcstr};
3use turbo_tasks::Vc;
4use turbo_tasks_fs::{FileContent, FileSystem, FileSystemPath, embed_directory};
5use turbopack_core::{
6    code_builder::Code,
7    context::AssetContext,
8    resolve::options::{ImportMap, ImportMapping},
9};
10use turbopack_ecmascript::StaticEcmascriptCode;
11
12#[turbo_tasks::function]
13pub fn embed_fs() -> Vc<Box<dyn FileSystem>> {
14    embed_directory!("turbopack", "$CARGO_MANIFEST_DIR/js/src")
15}
16
17#[turbo_tasks::function]
18pub async fn embed_file(path: RcStr) -> Result<Vc<FileContent>> {
19    Ok(embed_fs().root().await?.join(&path)?.read())
20}
21
22#[turbo_tasks::function]
23pub async fn embed_file_path(path: RcStr) -> Result<Vc<FileSystemPath>> {
24    Ok(embed_fs().root().await?.join(&path)?.cell())
25}
26
27#[turbo_tasks::function]
28pub async fn embed_static_code(
29    asset_context: Vc<Box<dyn AssetContext>>,
30    path: RcStr,
31    generate_source_map: bool,
32) -> Result<Vc<Code>> {
33    Ok(StaticEcmascriptCode::new(
34        asset_context,
35        embed_file_path(path).owned().await?,
36        generate_source_map,
37    )
38    .code())
39}
40
41/// Returns an [ImportMap] containing:
42/// - The `@vercel/turbopack-ecmascript-runtime/*` wildcard alias pointing to the embedded runtime
43///   filesystem.
44/// - All built-in `@turbopack/*` module aliases (e.g. `@turbopack/base64`).
45///
46/// This import map is injected automatically by
47/// [`ModuleAssetContext::resolve_options`] so that every Turbopack-processed
48/// module can resolve these paths without per-consumer configuration.
49///
50/// As more parts of the turbopack runtime are extracted into importable
51/// modules they should be added here.
52#[turbo_tasks::function]
53pub async fn turbopack_runtime_import_map() -> Result<Vc<ImportMap>> {
54    let embed_root = embed_fs().root().owned().await?;
55
56    let mut import_map = ImportMap::default();
57
58    // Wildcard alias: @vercel/turbopack-ecmascript-runtime/* -> embedded fs
59    import_map.insert_wildcard_alias(
60        rcstr!("@vercel/turbopack-ecmascript-runtime/"),
61        ImportMapping::PrimaryAlternative(rcstr!("./*"), Some(embed_root.clone())).resolved_cell(),
62    );
63
64    // Exact alias: @turbopack/base64
65    import_map.insert_exact_alias(
66        rcstr!("@turbopack/base64"),
67        ImportMapping::PrimaryAlternative(rcstr!("./shared/base64.ts"), Some(embed_root))
68            .resolved_cell(),
69    );
70
71    Ok(import_map.cell())
72}