turbopack_browser/ecmascript/
content.rs

1use std::io::Write;
2
3use anyhow::{Result, bail};
4use either::Either;
5use turbo_rcstr::RcStr;
6use turbo_tasks::{ResolvedVc, Vc};
7use turbo_tasks_fs::{File, FileContent};
8use turbopack_core::{
9    asset::AssetContent,
10    chunk::{ChunkingContext, MinifyType, ModuleId},
11    code_builder::{Code, CodeBuilder},
12    output::OutputAsset,
13    source_map::{GenerateSourceMap, SourceMapAsset},
14    version::{MergeableVersionedContent, Version, VersionedContent, VersionedContentMerger},
15};
16use turbopack_ecmascript::{chunk::EcmascriptChunkContent, minify::minify, utils::StringifyJs};
17
18use super::{
19    chunk::EcmascriptBrowserChunk, content_entry::EcmascriptBrowserChunkContentEntries,
20    merged::merger::EcmascriptBrowserChunkContentMerger, version::EcmascriptBrowserChunkVersion,
21};
22use crate::{
23    BrowserChunkingContext,
24    chunking_context::{CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR, CurrentChunkMethod},
25};
26
27#[turbo_tasks::value(serialization = "none")]
28pub struct EcmascriptBrowserChunkContent {
29    pub(super) chunking_context: ResolvedVc<BrowserChunkingContext>,
30    pub(super) chunk: ResolvedVc<EcmascriptBrowserChunk>,
31    pub(super) content: ResolvedVc<EcmascriptChunkContent>,
32    pub(super) source_map: ResolvedVc<SourceMapAsset>,
33}
34
35#[turbo_tasks::value_impl]
36impl EcmascriptBrowserChunkContent {
37    #[turbo_tasks::function]
38    pub(crate) fn new(
39        chunking_context: ResolvedVc<BrowserChunkingContext>,
40        chunk: ResolvedVc<EcmascriptBrowserChunk>,
41        content: ResolvedVc<EcmascriptChunkContent>,
42        source_map: ResolvedVc<SourceMapAsset>,
43    ) -> Result<Vc<Self>> {
44        Ok(EcmascriptBrowserChunkContent {
45            chunking_context,
46            chunk,
47            content,
48            source_map,
49        }
50        .cell())
51    }
52
53    #[turbo_tasks::function]
54    pub fn entries(&self) -> Vc<EcmascriptBrowserChunkContentEntries> {
55        EcmascriptBrowserChunkContentEntries::new(*self.content)
56    }
57}
58
59#[turbo_tasks::value_impl]
60impl EcmascriptBrowserChunkContent {
61    #[turbo_tasks::function]
62    pub(crate) async fn own_version(&self) -> Result<Vc<EcmascriptBrowserChunkVersion>> {
63        Ok(EcmascriptBrowserChunkVersion::new(
64            self.chunking_context.output_root().owned().await?,
65            self.chunk.path().owned().await?,
66            *self.content,
67        ))
68    }
69
70    #[turbo_tasks::function]
71    async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
72        let this = self.await?;
73        let source_maps = *this
74            .chunking_context
75            .reference_chunk_source_maps(*ResolvedVc::upcast(this.chunk))
76            .await?;
77        // Lifetime hack to pull out the var into this scope
78        let chunk_path;
79        let script_or_path = match *this.chunking_context.current_chunk_method().await? {
80            CurrentChunkMethod::StringLiteral => {
81                let output_root = this.chunking_context.output_root().await?;
82                let chunk_path_vc = this.chunk.path();
83                chunk_path = chunk_path_vc.await?;
84                let chunk_server_path = if let Some(path) = output_root.get_path_to(&chunk_path) {
85                    path
86                } else {
87                    bail!("chunk path {chunk_path} is not in output root {output_root}");
88                };
89                Either::Left(StringifyJs(chunk_server_path))
90            }
91            CurrentChunkMethod::DocumentCurrentScript => {
92                Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
93            }
94        };
95        let mut code = CodeBuilder::new(
96            source_maps,
97            *this.chunking_context.debug_ids_enabled().await?,
98        );
99
100        // When a chunk is executed, it will either register itself with the current
101        // instance of the runtime, or it will push itself onto the list of pending
102        // chunks (`self.TURBOPACK`).
103        //
104        // When the runtime executes (see the `evaluate` module), it will pick up and
105        // register all pending chunks, and replace the list of pending chunks
106        // with itself so later chunks can register directly with it.
107        write!(
108            code,
109            // `||=` would be better but we need to be es2020 compatible
110            //`x || (x = default)` is better than `x = x || default` simply because we avoid _writing_ the property in the common case.
111            "(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([{script_or_path},"
112        )?;
113
114        let content = this.content.await?;
115        let chunk_items = content.chunk_item_code_and_ids().await?;
116        for item in chunk_items {
117            for (id, item_code) in item {
118                write!(code, "\n{}, ", StringifyJs(&id))?;
119                code.push_code(item_code);
120                write!(code, ",")?;
121            }
122        }
123
124        write!(code, "\n]);")?;
125
126        let mut code = code.build();
127
128        if let MinifyType::Minify { mangle } = *this.chunking_context.minify_type().await? {
129            code = minify(code, source_maps, mangle)?;
130        }
131
132        Ok(code.cell())
133    }
134}
135
136#[turbo_tasks::value_impl]
137impl VersionedContent for EcmascriptBrowserChunkContent {
138    #[turbo_tasks::function]
139    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
140        let this = self.await?;
141
142        Ok(AssetContent::file(
143            FileContent::Content(File::from(
144                self.code()
145                    .to_rope_with_magic_comments(|| *this.source_map)
146                    .await?,
147            ))
148            .cell(),
149        ))
150    }
151
152    #[turbo_tasks::function]
153    fn version(self: Vc<Self>) -> Vc<Box<dyn Version>> {
154        Vc::upcast(self.own_version())
155    }
156}
157
158#[turbo_tasks::value_impl]
159impl MergeableVersionedContent for EcmascriptBrowserChunkContent {
160    #[turbo_tasks::function]
161    fn get_merger(&self) -> Vc<Box<dyn VersionedContentMerger>> {
162        Vc::upcast(EcmascriptBrowserChunkContentMerger::new())
163    }
164}
165
166#[turbo_tasks::value_impl]
167impl GenerateSourceMap for EcmascriptBrowserChunkContent {
168    #[turbo_tasks::function]
169    fn generate_source_map(self: Vc<Self>) -> Vc<FileContent> {
170        self.code().generate_source_map()
171    }
172
173    #[turbo_tasks::function]
174    async fn by_section(self: Vc<Self>, section: RcStr) -> Result<Vc<FileContent>> {
175        // Weirdly, the ContentSource will have already URL decoded the ModuleId, and we
176        // can't reparse that via serde.
177        if let Ok(id) = ModuleId::parse(&section) {
178            let entries = self.entries().await?;
179            for (entry_id, entry) in entries.iter() {
180                if id == **entry_id {
181                    let sm = entry.code.generate_source_map();
182                    return Ok(sm);
183                }
184            }
185        }
186
187        Ok(FileContent::NotFound.cell())
188    }
189}