Skip to main content

turbopack_ecmascript/text/
mod.rs

1use anyhow::Result;
2use turbo_rcstr::{RcStr, rcstr};
3use turbo_tasks::{ResolvedVc, Vc};
4use turbo_tasks_fs::FileContent;
5use turbopack_core::{
6    asset::{Asset, AssetContent},
7    ident::AssetIdent,
8    source::Source,
9};
10
11use crate::utils::StringifyJs;
12
13/// A source asset that exports the string content of an asset as the default
14/// export of a JS module.
15#[turbo_tasks::value]
16pub struct TextContentFileSource {
17    pub source: ResolvedVc<Box<dyn Source>>,
18}
19
20#[turbo_tasks::value_impl]
21impl TextContentFileSource {
22    #[turbo_tasks::function]
23    pub fn new(source: ResolvedVc<Box<dyn Source>>) -> Vc<Self> {
24        TextContentFileSource { source }.cell()
25    }
26}
27
28#[turbo_tasks::value_impl]
29impl Source for TextContentFileSource {
30    #[turbo_tasks::function]
31    async fn ident(&self) -> Result<Vc<AssetIdent>> {
32        Ok(self
33            .source
34            .ident()
35            .owned()
36            .await?
37            .with_modifier(rcstr!("text content"))
38            .rename_as("*.mjs")
39            .into_vc())
40    }
41
42    #[turbo_tasks::function]
43    async fn description(&self) -> Result<Vc<RcStr>> {
44        let inner = self.source.description().await?;
45        Ok(Vc::cell(format!("text content of {}", inner).into()))
46    }
47}
48
49#[turbo_tasks::value_impl]
50impl Asset for TextContentFileSource {
51    #[turbo_tasks::function]
52    async fn content(&self) -> Result<Vc<AssetContent>> {
53        let source = self.source.content().file_content();
54        let FileContent::Content(content) = &*source.await? else {
55            return Ok(AssetContent::file(FileContent::NotFound.cell()));
56        };
57        let text = content.content().to_str()?;
58        let code: RcStr = format!("export default {};", StringifyJs(&text)).into();
59        let content = FileContent::Content(code.into()).cell();
60        Ok(AssetContent::file(content))
61    }
62}