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26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use std::{fmt::Write, sync::Arc};

use anyhow::{Context, Result, bail};
use indoc::formatdoc;
use lightningcss::css_modules::CssModuleReference;
use swc_core::common::{BytePos, FileName, LineCol, SourceMap};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, IntoTraitRef, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{FileSystemPath, rope::Rope};
use turbopack_core::{
    asset::{Asset, AssetContent},
    chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt},
    context::{AssetContext, ProcessResult},
    ident::AssetIdent,
    issue::{
        Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource,
        OptionStyledString, StyledString,
    },
    module::Module,
    module_graph::ModuleGraph,
    reference::{ModuleReference, ModuleReferences},
    reference_type::{CssReferenceSubType, ReferenceType},
    resolve::{origin::ResolveOrigin, parse::Request},
    source::Source,
};
use turbopack_ecmascript::{
    chunk::{
        EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
        EcmascriptChunkType, EcmascriptExports,
    },
    parse::generate_js_source_map,
    runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_IMPORT},
    utils::StringifyJs,
};

use crate::{
    process::{CssWithPlaceholderResult, ProcessCss},
    references::{compose::CssModuleComposeReference, internal::InternalCssAssetReference},
};

#[turbo_tasks::value]
#[derive(Clone)]
/// A CSS Module asset, as in `.module.css`. For a global CSS module, see [`CssModuleAsset`].
pub struct ModuleCssAsset {
    pub source: ResolvedVc<Box<dyn Source>>,
    pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
}

#[turbo_tasks::value_impl]
impl ModuleCssAsset {
    #[turbo_tasks::function]
    pub fn new(
        source: ResolvedVc<Box<dyn Source>>,
        asset_context: ResolvedVc<Box<dyn AssetContext>>,
    ) -> Vc<Self> {
        Self::cell(ModuleCssAsset {
            source,
            asset_context,
        })
    }
}

#[turbo_tasks::value_impl]
impl Module for ModuleCssAsset {
    #[turbo_tasks::function]
    async fn ident(&self) -> Result<Vc<AssetIdent>> {
        Ok(self
            .source
            .ident()
            .with_modifier(rcstr!("css module"))
            .with_layer(self.asset_context.into_trait_ref().await?.layer()))
    }

    #[turbo_tasks::function]
    async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> {
        // The inner reference must come last so it is loaded as the last in the
        // resulting css. @import or composes references must be loaded first so
        // that the css style rules in them are overridable from the local css.

        // This affects the order in which the resulting CSS chunks will be loaded:
        // 1. @import or composes references are loaded first
        // 2. The local CSS is loaded last

        let references = self
            .module_references()
            .await?
            .iter()
            .copied()
            .chain(
                match *self
                    .inner(ReferenceType::Css(CssReferenceSubType::Internal))
                    .try_into_module()
                    .await?
                {
                    Some(inner) => Some(
                        InternalCssAssetReference::new(*inner)
                            .to_resolved()
                            .await
                            .map(ResolvedVc::upcast)?,
                    ),
                    None => None,
                },
            )
            .collect();

        Ok(Vc::cell(references))
    }
}

#[turbo_tasks::value_impl]
impl Asset for ModuleCssAsset {
    #[turbo_tasks::function]
    fn content(&self) -> Result<Vc<AssetContent>> {
        bail!("CSS module asset has no contents")
    }
}

/// A CSS class that is exported from a CSS module.
///
/// See [`ModuleCssClasses`] for more information.
#[turbo_tasks::value]
#[derive(Debug, Clone)]
enum ModuleCssClass {
    Local {
        name: String,
    },
    Global {
        name: String,
    },
    Import {
        original: String,
        from: ResolvedVc<CssModuleComposeReference>,
    },
}

/// A map of CSS classes exported from a CSS module.
///
/// ## Example
///
/// ```css
/// :global(.class1) {
///    color: red;
/// }
///
/// .class2 {
///   color: blue;
/// }
///
/// .class3 {
///   composes: class4 from "./other.module.css";
/// }
/// ```
///
/// The above CSS module would have the following exports:
/// 1. class1: [Global("exported_class1")]
/// 2. class2: [Local("exported_class2")]
/// 3. class3: [Local("exported_class3), Import("class4", "./other.module.css")]
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
struct ModuleCssClasses(FxIndexMap<String, Vec<ModuleCssClass>>);

#[turbo_tasks::value_impl]
impl ModuleCssAsset {
    #[turbo_tasks::function]
    pub fn inner(&self, ty: ReferenceType) -> Vc<ProcessResult> {
        self.asset_context.process(*self.source, ty)
    }

    #[turbo_tasks::function]
    async fn classes(self: Vc<Self>) -> Result<Vc<ModuleCssClasses>> {
        let inner = self
            .inner(ReferenceType::Css(CssReferenceSubType::Analyze))
            .module();

        let inner = Vc::try_resolve_sidecast::<Box<dyn ProcessCss>>(inner)
            .await?
            .context("inner asset should be CSS processable")?;

        let result = inner.get_css_with_placeholder().await?;
        let mut classes = FxIndexMap::default();

        // TODO(alexkirsz) Should we report an error on parse error here?
        if let CssWithPlaceholderResult::Ok {
            exports: Some(exports),
            ..
        } = &*result
        {
            for (class_name, export_class_names) in exports {
                let mut export = Vec::default();

                export.push(ModuleCssClass::Local {
                    name: export_class_names.name.clone(),
                });

                for export_class_name in &export_class_names.composes {
                    export.push(match export_class_name {
                        CssModuleReference::Dependency { specifier, name } => {
                            ModuleCssClass::Import {
                                original: name.to_string(),
                                from: CssModuleComposeReference::new(
                                    Vc::upcast(self),
                                    Request::parse(RcStr::from(specifier.clone()).into()),
                                )
                                .to_resolved()
                                .await?,
                            }
                        }
                        CssModuleReference::Local { name } => ModuleCssClass::Local {
                            name: name.to_string(),
                        },
                        CssModuleReference::Global { name } => ModuleCssClass::Global {
                            name: name.to_string(),
                        },
                    })
                }

                classes.insert(class_name.to_string(), export);
            }
        }

        Ok(Vc::cell(classes))
    }

    #[turbo_tasks::function]
    async fn module_references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> {
        let mut references = vec![];

        for (_, class_names) in &*self.classes().await? {
            for class_name in class_names {
                match class_name {
                    ModuleCssClass::Import { from, .. } => {
                        references.push(ResolvedVc::upcast(*from));
                    }
                    ModuleCssClass::Local { .. } | ModuleCssClass::Global { .. } => {}
                }
            }
        }

        Ok(Vc::cell(references))
    }
}

#[turbo_tasks::value_impl]
impl ChunkableModule for ModuleCssAsset {
    #[turbo_tasks::function]
    fn as_chunk_item(
        self: ResolvedVc<Self>,
        module_graph: ResolvedVc<ModuleGraph>,
        chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
    ) -> Vc<Box<dyn turbopack_core::chunk::ChunkItem>> {
        Vc::upcast(
            ModuleChunkItem {
                chunking_context,
                module_graph,
                module: self,
            }
            .cell(),
        )
    }
}

#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for ModuleCssAsset {
    #[turbo_tasks::function]
    fn get_exports(&self) -> Vc<EcmascriptExports> {
        EcmascriptExports::Value.cell()
    }
}

#[turbo_tasks::value_impl]
impl ResolveOrigin for ModuleCssAsset {
    #[turbo_tasks::function]
    fn origin_path(&self) -> Vc<FileSystemPath> {
        self.source.ident().path()
    }

    #[turbo_tasks::function]
    fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
        *self.asset_context
    }
}

#[turbo_tasks::value]
struct ModuleChunkItem {
    module: ResolvedVc<ModuleCssAsset>,
    module_graph: ResolvedVc<ModuleGraph>,
    chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
}

#[turbo_tasks::value_impl]
impl ChunkItem for ModuleChunkItem {
    #[turbo_tasks::function]
    fn asset_ident(&self) -> Vc<AssetIdent> {
        self.module.ident()
    }

    #[turbo_tasks::function]
    fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
        Vc::upcast(*self.chunking_context)
    }

    #[turbo_tasks::function]
    async fn ty(&self) -> Result<Vc<Box<dyn ChunkType>>> {
        Ok(Vc::upcast(
            Vc::<EcmascriptChunkType>::default().resolve().await?,
        ))
    }

    #[turbo_tasks::function]
    fn module(&self) -> Vc<Box<dyn Module>> {
        Vc::upcast(*self.module)
    }
}

#[turbo_tasks::value_impl]
impl EcmascriptChunkItem for ModuleChunkItem {
    #[turbo_tasks::function]
    async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
        let classes = self.module.classes().await?;

        let mut code = format!("{TURBOPACK_EXPORT_VALUE}({{\n");
        for (export_name, class_names) in &*classes {
            let mut exported_class_names = Vec::with_capacity(class_names.len());

            for class_name in class_names {
                match class_name {
                    ModuleCssClass::Import {
                        original: original_name,
                        from,
                    } => {
                        let resolved_module = from.resolve_reference().first_module().await?;

                        let Some(resolved_module) = &*resolved_module else {
                            CssModuleComposesIssue {
                                severity: IssueSeverity::Error,
                                // TODO(PACK-4879): this should include detailed location information
                                source: IssueSource::from_source_only(self.module.await?.source),
                                message: formatdoc! {
                                    r#"
                                        Module {from} referenced in `composes: ... from {from};` can't be resolved.
                                    "#,
                                    from = &*from.await?.request.to_string().await?
                                }.into(),
                            }.resolved_cell().emit();
                            continue;
                        };

                        let Some(css_module) =
                            ResolvedVc::try_downcast_type::<ModuleCssAsset>(*resolved_module)
                        else {
                            CssModuleComposesIssue {
                                severity: IssueSeverity::Error,
                                // TODO(PACK-4879): this should include detailed location information
                                source: IssueSource::from_source_only(self.module.await?.source),
                                message: formatdoc! {
                                    r#"
                                        Module {from} referenced in `composes: ... from {from};` is not a CSS module.
                                    "#,
                                    from = &*from.await?.request.to_string().await?
                                }.into(),
                            }.resolved_cell().emit();
                            continue;
                        };

                        // TODO(alexkirsz) We should also warn if `original_name` can't be found in
                        // the target module.

                        let placeable: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>> =
                            ResolvedVc::upcast(css_module);

                        let module_id = placeable
                            .chunk_item_id(Vc::upcast(*self.chunking_context))
                            .await?;
                        let module_id = StringifyJs(&*module_id);
                        let original_name = StringifyJs(&original_name);
                        exported_class_names
                            .push(format!("{TURBOPACK_IMPORT}({module_id})[{original_name}]"));
                    }
                    ModuleCssClass::Local { name: class_name }
                    | ModuleCssClass::Global { name: class_name } => {
                        exported_class_names.push(StringifyJs(&class_name).to_string());
                    }
                }
            }

            writeln!(
                code,
                "  {}: {},",
                StringifyJs(export_name),
                exported_class_names.join(" + \" \" + ")
            )?;
        }
        code += "});\n";
        let source_map = *self
            .chunking_context
            .reference_module_source_maps(*ResolvedVc::upcast(self.module))
            .await?;
        Ok(EcmascriptChunkItemContent {
            inner_code: code.clone().into(),
            // We generate a minimal map for runtime code so that the filename is
            // displayed in dev tools.
            source_map: if source_map {
                Some(generate_minimal_source_map(
                    self.module.ident().to_string().await?.to_string(),
                    code,
                )?)
            } else {
                None
            },
            ..Default::default()
        }
        .cell())
    }
}

fn generate_minimal_source_map(filename: String, source: String) -> Result<Rope> {
    let mut mappings = vec![];
    // Start from 1 because 0 is reserved for dummy spans in SWC.
    let mut pos = 1;
    for (index, line) in source.split_inclusive('\n').enumerate() {
        mappings.push((
            BytePos(pos),
            LineCol {
                line: index as u32,
                col: 0,
            },
        ));
        pos += line.len() as u32;
    }
    let sm: Arc<SourceMap> = Default::default();
    sm.new_source_file(FileName::Custom(filename).into(), source);
    let map = generate_js_source_map(&*sm, mappings, None, true, true)?;
    Ok(map)
}

#[turbo_tasks::value(shared)]
struct CssModuleComposesIssue {
    severity: IssueSeverity,
    source: IssueSource,
    message: RcStr,
}

#[turbo_tasks::value_impl]
impl Issue for CssModuleComposesIssue {
    fn severity(&self) -> IssueSeverity {
        self.severity
    }

    #[turbo_tasks::function]
    fn title(&self) -> Vc<StyledString> {
        StyledString::Text(rcstr!(
            "An issue occurred while resolving a CSS module `composes:` rule"
        ))
        .cell()
    }

    #[turbo_tasks::function]
    fn stage(&self) -> Vc<IssueStage> {
        IssueStage::CodeGen.cell()
    }

    #[turbo_tasks::function]
    fn file_path(&self) -> Vc<FileSystemPath> {
        self.source.file_path()
    }

    #[turbo_tasks::function]
    fn description(&self) -> Vc<OptionStyledString> {
        Vc::cell(Some(
            StyledString::Text(self.message.clone()).resolved_cell(),
        ))
    }

    #[turbo_tasks::function]
    fn source(&self) -> Vc<OptionIssueSource> {
        Vc::cell(Some(self.source))
    }
}