turbopack_ecmascript/chunk/
item.rs

1use std::io::Write;
2
3use anyhow::{Result, bail};
4use serde::{Deserialize, Serialize};
5use smallvec::SmallVec;
6use turbo_rcstr::{RcStr, rcstr};
7use turbo_tasks::{
8    NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Upcast, ValueToString, Vc,
9    trace::TraceRawVcs,
10};
11use turbo_tasks_fs::{FileSystemPath, rope::Rope};
12use turbopack_core::{
13    chunk::{
14        AsyncModuleInfo, ChunkItem, ChunkItemWithAsyncModuleInfo, ChunkingContext,
15        ChunkingContextExt, ModuleId, SourceMapSourceType,
16    },
17    code_builder::{Code, CodeBuilder},
18    error::PrettyPrintError,
19    issue::{IssueExt, IssueSeverity, StyledString, code_gen::CodeGenerationIssue},
20    source_map::utils::{absolute_fileify_source_map, relative_fileify_source_map},
21};
22
23use crate::{
24    EcmascriptModuleContent,
25    references::async_module::{AsyncModuleOptions, OptionAsyncModuleOptions},
26    runtime_functions::TURBOPACK_ASYNC_MODULE,
27    utils::StringifyJs,
28};
29
30#[derive(
31    Debug,
32    Clone,
33    PartialEq,
34    Eq,
35    Hash,
36    Serialize,
37    Deserialize,
38    TraceRawVcs,
39    TaskInput,
40    NonLocalValue,
41    Default,
42)]
43pub enum RewriteSourcePath {
44    AbsoluteFilePath(FileSystemPath),
45    RelativeFilePath(FileSystemPath, RcStr),
46    #[default]
47    None,
48}
49
50#[turbo_tasks::value(shared)]
51#[derive(Default, Clone)]
52pub struct EcmascriptChunkItemContent {
53    pub inner_code: Rope,
54    pub source_map: Option<Rope>,
55    pub additional_ids: SmallVec<[ResolvedVc<ModuleId>; 1]>,
56    pub options: EcmascriptChunkItemOptions,
57    pub rewrite_source_path: RewriteSourcePath,
58    pub placeholder_for_future_extensions: (),
59}
60
61#[turbo_tasks::value_impl]
62impl EcmascriptChunkItemContent {
63    #[turbo_tasks::function]
64    pub async fn new(
65        content: Vc<EcmascriptModuleContent>,
66        chunking_context: Vc<Box<dyn ChunkingContext>>,
67        async_module_options: Vc<OptionAsyncModuleOptions>,
68    ) -> Result<Vc<Self>> {
69        let externals = *chunking_context
70            .environment()
71            .supports_commonjs_externals()
72            .await?;
73
74        let content = content.await?;
75        let async_module = async_module_options.owned().await?;
76        let strict = content.strict;
77
78        Ok(EcmascriptChunkItemContent {
79            rewrite_source_path: match *chunking_context.source_map_source_type().await? {
80                SourceMapSourceType::AbsoluteFileUri => {
81                    RewriteSourcePath::AbsoluteFilePath(chunking_context.root_path().owned().await?)
82                }
83                SourceMapSourceType::RelativeUri => RewriteSourcePath::RelativeFilePath(
84                    chunking_context.root_path().owned().await?,
85                    chunking_context
86                        .relative_path_from_chunk_root_to_project_root()
87                        .owned()
88                        .await?,
89                ),
90                SourceMapSourceType::TurbopackUri => RewriteSourcePath::None,
91            },
92            inner_code: content.inner_code.clone(),
93            source_map: content.source_map.clone(),
94            additional_ids: content.additional_ids.clone(),
95            options: if content.is_esm {
96                EcmascriptChunkItemOptions {
97                    strict: true,
98                    externals,
99                    async_module,
100                    ..Default::default()
101                }
102            } else {
103                if async_module.is_some() {
104                    bail!("CJS module can't be async.");
105                }
106
107                EcmascriptChunkItemOptions {
108                    strict,
109                    externals,
110                    // These things are not available in ESM
111                    module_and_exports: true,
112                    ..Default::default()
113                }
114            },
115            ..Default::default()
116        }
117        .cell())
118    }
119}
120
121impl EcmascriptChunkItemContent {
122    async fn module_factory(&self) -> Result<ResolvedVc<Code>> {
123        let mut code = CodeBuilder::default();
124        for additional_id in self.additional_ids.iter().try_join().await? {
125            writeln!(code, "{}, ", StringifyJs(&*additional_id))?;
126        }
127        if self.options.module_and_exports {
128            code += "((__turbopack_context__, module, exports) => {\n";
129        } else {
130            code += "((__turbopack_context__) => {\n";
131        }
132        if self.options.strict {
133            code += "\"use strict\";\n\n";
134        } else {
135            code += "\n";
136        }
137
138        if self.options.async_module.is_some() {
139            writeln!(
140                code,
141                "return {TURBOPACK_ASYNC_MODULE}(async (__turbopack_handle_async_dependencies__, \
142                 __turbopack_async_result__) => {{ try {{\n"
143            )?;
144        }
145
146        let source_map = match &self.rewrite_source_path {
147            RewriteSourcePath::AbsoluteFilePath(path) => {
148                absolute_fileify_source_map(self.source_map.as_ref(), path.clone()).await?
149            }
150            RewriteSourcePath::RelativeFilePath(path, relative_path) => {
151                relative_fileify_source_map(
152                    self.source_map.as_ref(),
153                    path.clone(),
154                    relative_path.clone(),
155                )
156                .await?
157            }
158            RewriteSourcePath::None => self.source_map.clone(),
159        };
160
161        code.push_source(&self.inner_code, source_map);
162
163        if let Some(opts) = &self.options.async_module {
164            write!(
165                code,
166                "__turbopack_async_result__();\n}} catch(e) {{ __turbopack_async_result__(e); }} \
167                 }}, {});",
168                opts.has_top_level_await
169            )?;
170        }
171
172        code += "})";
173
174        Ok(code.build().resolved_cell())
175    }
176}
177
178#[derive(
179    PartialEq, Eq, Default, Debug, Clone, Serialize, Deserialize, TraceRawVcs, NonLocalValue,
180)]
181pub struct EcmascriptChunkItemOptions {
182    /// Whether this chunk item should be in "use strict" mode.
183    pub strict: bool,
184    /// Whether this chunk item's module factory should include a `module` and
185    /// `exports` argument.
186    pub module_and_exports: bool,
187    /// Whether this chunk item's module factory should include a
188    /// `__turbopack_external_require__` argument.
189    pub externals: bool,
190    /// Whether this chunk item's module is async (either has a top level await
191    /// or is importing async modules).
192    pub async_module: Option<AsyncModuleOptions>,
193    pub placeholder_for_future_extensions: (),
194}
195
196#[derive(
197    Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, TraceRawVcs, TaskInput, NonLocalValue,
198)]
199pub struct EcmascriptChunkItemWithAsyncInfo {
200    pub chunk_item: ResolvedVc<Box<dyn EcmascriptChunkItem>>,
201    pub async_info: Option<ResolvedVc<AsyncModuleInfo>>,
202}
203
204impl EcmascriptChunkItemWithAsyncInfo {
205    pub fn from_chunk_item(
206        chunk_item: &ChunkItemWithAsyncModuleInfo,
207    ) -> Result<EcmascriptChunkItemWithAsyncInfo> {
208        let ChunkItemWithAsyncModuleInfo {
209            chunk_item,
210            module: _,
211            async_info,
212        } = chunk_item;
213        let Some(chunk_item) =
214            ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkItem>>(*chunk_item)
215        else {
216            bail!("Chunk item is not an ecmascript chunk item but reporting chunk type ecmascript");
217        };
218        Ok(EcmascriptChunkItemWithAsyncInfo {
219            chunk_item,
220            async_info: *async_info,
221        })
222    }
223}
224
225#[turbo_tasks::value_trait]
226pub trait EcmascriptChunkItem: ChunkItem {
227    #[turbo_tasks::function]
228    fn content(self: Vc<Self>) -> Vc<EcmascriptChunkItemContent>;
229    #[turbo_tasks::function]
230    fn content_with_async_module_info(
231        self: Vc<Self>,
232        _async_module_info: Option<Vc<AsyncModuleInfo>>,
233    ) -> Vc<EcmascriptChunkItemContent> {
234        self.content()
235    }
236
237    /// Specifies which availability information the chunk item needs for code
238    /// generation
239    #[turbo_tasks::function]
240    fn need_async_module_info(self: Vc<Self>) -> Vc<bool> {
241        Vc::cell(false)
242    }
243}
244
245pub trait EcmascriptChunkItemExt {
246    /// Generates the module factory for this chunk item.
247    fn code(self: Vc<Self>, async_module_info: Option<Vc<AsyncModuleInfo>>) -> Vc<Code>;
248}
249
250impl<T> EcmascriptChunkItemExt for T
251where
252    T: Upcast<Box<dyn EcmascriptChunkItem>>,
253{
254    /// Generates the module factory for this chunk item.
255    fn code(self: Vc<Self>, async_module_info: Option<Vc<AsyncModuleInfo>>) -> Vc<Code> {
256        module_factory_with_code_generation_issue(Vc::upcast_non_strict(self), async_module_info)
257    }
258}
259
260#[turbo_tasks::function]
261async fn module_factory_with_code_generation_issue(
262    chunk_item: Vc<Box<dyn EcmascriptChunkItem>>,
263    async_module_info: Option<Vc<AsyncModuleInfo>>,
264) -> Result<Vc<Code>> {
265    let content = match chunk_item
266        .content_with_async_module_info(async_module_info)
267        .await
268    {
269        Ok(item) => item.module_factory().await,
270        Err(err) => Err(err),
271    };
272    Ok(match content {
273        Ok(factory) => *factory,
274        Err(error) => {
275            let id = chunk_item.asset_ident().to_string().await;
276            let id = id.as_ref().map_or_else(|_| "unknown", |id| &**id);
277            let error = error.context(format!(
278                "An error occurred while generating the chunk item {id}"
279            ));
280            let error_message = format!("{}", PrettyPrintError(&error)).into();
281            let js_error_message = serde_json::to_string(&error_message)?;
282            CodeGenerationIssue {
283                severity: IssueSeverity::Error,
284                path: chunk_item.asset_ident().path().owned().await?,
285                title: StyledString::Text(rcstr!("Code generation for chunk item errored"))
286                    .resolved_cell(),
287                message: StyledString::Text(error_message).resolved_cell(),
288            }
289            .resolved_cell()
290            .emit();
291            let mut code = CodeBuilder::default();
292            code += "(() => {{\n\n";
293            writeln!(code, "throw new Error({error});", error = &js_error_message)?;
294            code += "\n}})";
295            code.build().cell()
296        }
297    })
298}