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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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
use anyhow::{Result, anyhow, bail};
use either::Either;
use strsim::jaro;
use swc_core::{
    common::{BytePos, DUMMY_SP, Span, SyntaxContext, source_map::PURE_SP},
    ecma::ast::{
        ComputedPropName, Decl, Expr, ExprStmt, Ident, Lit, MemberExpr, MemberProp, Number,
        SeqExpr, Stmt, Str,
    },
    quote,
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
    chunk::{
        ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkingTypeOption,
        ModuleChunkItemIdExt,
    },
    context::AssetContext,
    issue::{
        Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource,
        OptionStyledString, StyledString,
    },
    module::Module,
    module_graph::export_usage::ModuleExportUsageInfo,
    reference::ModuleReference,
    reference_type::{EcmaScriptModulesReferenceSubType, ImportWithType},
    resolve::{
        ExportUsage, ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem,
        RequestKey,
        origin::{ResolveOrigin, ResolveOriginExt},
        parse::Request,
    },
};
use turbopack_resolve::ecmascript::esm_resolve;

use super::export::{all_known_export_names, is_export_missing};
use crate::{
    ScopeHoistingContext, TreeShakingMode,
    analyzer::imports::ImportAnnotations,
    chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
    code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
    magic_identifier,
    references::{
        esm::EsmExport,
        util::{request_to_string, throw_module_not_found_expr},
    },
    runtime_functions::{TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, TURBOPACK_IMPORT},
    tree_shake::{TURBOPACK_PART_IMPORT_SOURCE, asset::EcmascriptModulePartAsset},
    utils::module_id_to_lit,
};

#[turbo_tasks::value]
pub enum ReferencedAsset {
    Some(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>),
    External(RcStr, ExternalType),
    None,
    Unresolvable,
}

#[derive(Debug)]
pub enum ReferencedAssetIdent {
    /// The given export (or namespace) is a local binding in the current scope hoisting group.
    LocalBinding { ident: RcStr, ctxt: SyntaxContext },
    /// The given export (or namespace) should be imported and will be assigned to a new variable.
    Module {
        namespace_ident: String,
        ctxt: Option<SyntaxContext>,
        export: Option<RcStr>,
    },
}

impl ReferencedAssetIdent {
    pub fn into_module_namespace_ident(self) -> Option<(String, Option<SyntaxContext>)> {
        match self {
            ReferencedAssetIdent::Module {
                namespace_ident,
                ctxt,
                ..
            } => Some((namespace_ident, ctxt)),
            ReferencedAssetIdent::LocalBinding { .. } => None,
        }
    }

    pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> {
        match self {
            ReferencedAssetIdent::LocalBinding { ident, ctxt } => {
                Either::Left(Ident::new(ident.as_str().into(), span, *ctxt))
            }
            ReferencedAssetIdent::Module {
                namespace_ident,
                ctxt,
                export,
            } => {
                if let Some(export) = export {
                    Either::Right(MemberExpr {
                        span,
                        obj: Box::new(Expr::Ident(Ident::new(
                            namespace_ident.as_str().into(),
                            DUMMY_SP,
                            ctxt.unwrap_or_default(),
                        ))),
                        prop: MemberProp::Computed(ComputedPropName {
                            span: DUMMY_SP,
                            expr: Box::new(Expr::Lit(Lit::Str(Str {
                                span: DUMMY_SP,
                                value: export.as_str().into(),
                                raw: None,
                            }))),
                        }),
                    })
                } else {
                    Either::Left(Ident::new(
                        namespace_ident.as_str().into(),
                        span,
                        ctxt.unwrap_or_default(),
                    ))
                }
            }
        }
    }
    pub fn as_expr(&self, span: Span, is_callee: bool) -> Expr {
        match self.as_expr_individual(span) {
            Either::Left(ident) => ident.into(),
            Either::Right(member) => {
                if is_callee {
                    Expr::Seq(SeqExpr {
                        exprs: vec![
                            Box::new(Expr::Lit(Lit::Num(Number {
                                span: DUMMY_SP,
                                value: 0.0,
                                raw: None,
                            }))),
                            Box::new(member.into()),
                        ],
                        span: DUMMY_SP,
                    })
                } else {
                    member.into()
                }
            }
        }
    }
}

impl ReferencedAsset {
    pub async fn get_ident(
        &self,
        chunking_context: Vc<Box<dyn ChunkingContext>>,
        export: Option<RcStr>,
        scope_hoisting_context: ScopeHoistingContext<'_>,
    ) -> Result<Option<ReferencedAssetIdent>> {
        self.get_ident_inner(chunking_context, export, scope_hoisting_context, None)
            .await
    }

    async fn get_ident_inner(
        &self,
        chunking_context: Vc<Box<dyn ChunkingContext>>,
        export: Option<RcStr>,
        scope_hoisting_context: ScopeHoistingContext<'_>,
        initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,
    ) -> Result<Option<ReferencedAssetIdent>> {
        Ok(match self {
            ReferencedAsset::Some(asset) => {
                if let Some(ctxt) =
                    scope_hoisting_context.get_module_syntax_context(ResolvedVc::upcast(*asset))
                    && let Some(export) = &export
                    && let EcmascriptExports::EsmExports(exports) = *asset.get_exports().await?
                {
                    let exports = exports.expand_exports(ModuleExportUsageInfo::all()).await?;
                    let esm_export = exports.exports.get(export);
                    match esm_export {
                        Some(EsmExport::LocalBinding(_, _)) => {
                            // A local binding in a module that is merged in the same group. Use the
                            // export name as identifier, it will be replaced with the actual
                            // variable name during AST merging.
                            return Ok(Some(ReferencedAssetIdent::LocalBinding {
                                ident: export.clone(),
                                ctxt,
                            }));
                        }
                        Some(b @ EsmExport::ImportedBinding(esm_ref, _, _))
                        | Some(b @ EsmExport::ImportedNamespace(esm_ref)) => {
                            let imported = if let EsmExport::ImportedBinding(_, export, _) = b {
                                Some(export.clone())
                            } else {
                                None
                            };

                            let referenced_asset =
                                ReferencedAsset::from_resolve_result(esm_ref.resolve_reference())
                                    .await?;

                            if let Some(&initial) = initial
                                && *referenced_asset == ReferencedAsset::Some(initial)
                            {
                                // `initial` reexports from `asset` reexports from
                                // `referenced_asset` (which is `initial`)
                                CircularReExport {
                                    export: export.clone(),
                                    import: imported.clone(),
                                    module: *asset,
                                    module_cycle: initial,
                                }
                                .resolved_cell()
                                .emit();
                                return Ok(None);
                            }

                            // If the target module is still in the same group, we can
                            // refer it locally, otherwise it will be imported
                            return Ok(
                                match Box::pin(referenced_asset.get_ident_inner(
                                    chunking_context,
                                    imported,
                                    scope_hoisting_context,
                                    Some(asset),
                                ))
                                .await?
                                {
                                    Some(ReferencedAssetIdent::Module {
                                        namespace_ident,
                                        // Overwrite the context. This import isn't
                                        // inserted in the module that uses the import,
                                        // but in the module containing the reexport
                                        ctxt: None,
                                        export,
                                    }) => Some(ReferencedAssetIdent::Module {
                                        namespace_ident,
                                        ctxt: Some(ctxt),
                                        export,
                                    }),
                                    ident => ident,
                                },
                            );
                        }
                        Some(EsmExport::Error) | None => {
                            // Export not found, either there was already an error, or
                            // this is some dynamic (CJS) (re)export situation.
                        }
                    }
                }

                Some(ReferencedAssetIdent::Module {
                    namespace_ident: Self::get_ident_from_placeable(asset, chunking_context)
                        .await?,
                    ctxt: None,
                    export,
                })
            }
            ReferencedAsset::External(request, ty) => Some(ReferencedAssetIdent::Module {
                namespace_ident: magic_identifier::mangle(&format!("{ty} external {request}")),
                ctxt: None,
                export,
            }),
            ReferencedAsset::None | ReferencedAsset::Unresolvable => None,
        })
    }

    pub(crate) async fn get_ident_from_placeable(
        asset: &Vc<Box<dyn EcmascriptChunkPlaceable>>,
        chunking_context: Vc<Box<dyn ChunkingContext>>,
    ) -> Result<String> {
        let id = asset.chunk_item_id(Vc::upcast(chunking_context)).await?;
        Ok(magic_identifier::mangle(&format!("imported module {id}")))
    }
}

#[turbo_tasks::value_impl]
impl ReferencedAsset {
    #[turbo_tasks::function]
    pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Vc<Self>> {
        // TODO handle multiple keyed results
        let result = resolve_result.await?;
        if result.is_unresolvable_ref() {
            return Ok(ReferencedAsset::Unresolvable.cell());
        }
        for (_, result) in result.primary.iter() {
            match result {
                ModuleResolveResultItem::External {
                    name: request, ty, ..
                } => {
                    return Ok(ReferencedAsset::External(request.clone(), *ty).cell());
                }
                &ModuleResolveResultItem::Module(module) => {
                    if let Some(placeable) =
                        ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(module)
                    {
                        return Ok(ReferencedAsset::Some(placeable).cell());
                    }
                }
                // TODO ignore should probably be handled differently
                _ => {}
            }
        }
        Ok(ReferencedAsset::None.cell())
    }
}

#[turbo_tasks::value(transparent)]
pub struct EsmAssetReferences(Vec<ResolvedVc<EsmAssetReference>>);

#[turbo_tasks::value_impl]
impl EsmAssetReferences {
    #[turbo_tasks::function]
    pub fn empty() -> Vc<Self> {
        Vc::cell(Vec::new())
    }
}

#[turbo_tasks::value(shared)]
#[derive(Hash, Debug)]
pub struct EsmAssetReference {
    pub origin: ResolvedVc<Box<dyn ResolveOrigin>>,
    pub request: ResolvedVc<Request>,
    pub annotations: ImportAnnotations,
    pub issue_source: IssueSource,
    pub export_name: Option<ModulePart>,
    pub import_externals: bool,
    pub is_pure_import: bool,
}

impl EsmAssetReference {
    fn get_origin(&self) -> Vc<Box<dyn ResolveOrigin>> {
        if let Some(transition) = self.annotations.transition() {
            self.origin.with_transition(transition.into())
        } else {
            *self.origin
        }
    }
}

impl EsmAssetReference {
    pub fn new(
        origin: ResolvedVc<Box<dyn ResolveOrigin>>,
        request: ResolvedVc<Request>,
        issue_source: IssueSource,
        annotations: ImportAnnotations,
        export_name: Option<ModulePart>,
        import_externals: bool,
    ) -> Self {
        EsmAssetReference {
            origin,
            request,
            issue_source,
            annotations,
            export_name,
            import_externals,
            is_pure_import: false,
        }
    }

    pub fn new_pure(
        origin: ResolvedVc<Box<dyn ResolveOrigin>>,
        request: ResolvedVc<Request>,
        issue_source: IssueSource,
        annotations: ImportAnnotations,
        export_name: Option<ModulePart>,
        import_externals: bool,
    ) -> Self {
        EsmAssetReference {
            origin,
            request,
            issue_source,
            annotations,
            export_name,
            import_externals,
            is_pure_import: true,
        }
    }
}

#[turbo_tasks::value_impl]
impl EsmAssetReference {
    #[turbo_tasks::function]
    pub(crate) fn get_referenced_asset(self: Vc<Self>) -> Vc<ReferencedAsset> {
        ReferencedAsset::from_resolve_result(self.resolve_reference())
    }
}

#[turbo_tasks::value_impl]
impl ModuleReference for EsmAssetReference {
    #[turbo_tasks::function]
    async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
        let ty = if matches!(self.annotations.module_type(), Some("json")) {
            EcmaScriptModulesReferenceSubType::ImportWithType(ImportWithType::Json)
        } else if let Some(part) = &self.export_name {
            EcmaScriptModulesReferenceSubType::ImportPart(part.clone())
        } else {
            EcmaScriptModulesReferenceSubType::Import
        };

        if let Some(ModulePart::Evaluation) = &self.export_name {
            let module: ResolvedVc<crate::EcmascriptModuleAsset> =
                ResolvedVc::try_downcast_type(self.origin)
                    .expect("EsmAssetReference origin should be a EcmascriptModuleAsset");

            let tree_shaking_mode = module.options().await?.tree_shaking_mode;

            if let Some(TreeShakingMode::ModuleFragments) = tree_shaking_mode {
                let side_effect_free_packages = module.asset_context().side_effect_free_packages();

                if *module
                    .is_marked_as_side_effect_free(side_effect_free_packages)
                    .await?
                {
                    return Ok(ModuleResolveResult {
                        primary: Box::new([(
                            RequestKey::default(),
                            ModuleResolveResultItem::Ignore,
                        )]),
                        affecting_sources: Default::default(),
                    }
                    .cell());
                }
            }
        }

        if let Request::Module { module, .. } = &*self.request.await?
            && module == TURBOPACK_PART_IMPORT_SOURCE
        {
            if let Some(part) = &self.export_name {
                let module: ResolvedVc<crate::EcmascriptModuleAsset> =
                    ResolvedVc::try_downcast_type(self.origin)
                        .expect("EsmAssetReference origin should be a EcmascriptModuleAsset");

                return Ok(*ModuleResolveResult::module(ResolvedVc::upcast(
                    EcmascriptModulePartAsset::select_part(*module, part.clone())
                        .to_resolved()
                        .await?,
                )));
            }

            bail!("export_name is required for part import")
        }

        let result = esm_resolve(
            self.get_origin().resolve().await?,
            *self.request,
            ty,
            false,
            Some(self.issue_source),
        )
        .await?;

        if let Some(ModulePart::Export(export_name)) = &self.export_name {
            for &module in result.primary_modules().await? {
                if let Some(module) = ResolvedVc::try_downcast(module)
                    && *is_export_missing(*module, export_name.clone()).await?
                {
                    InvalidExport {
                        export: export_name.clone(),
                        module,
                        source: self.issue_source,
                    }
                    .resolved_cell()
                    .emit();
                }
            }
        }

        Ok(result)
    }
}

#[turbo_tasks::value_impl]
impl ValueToString for EsmAssetReference {
    #[turbo_tasks::function]
    async fn to_string(&self) -> Result<Vc<RcStr>> {
        Ok(Vc::cell(
            format!(
                "import {} with {}",
                self.request.to_string().await?,
                self.annotations
            )
            .into(),
        ))
    }
}

#[turbo_tasks::value_impl]
impl ChunkableModuleReference for EsmAssetReference {
    #[turbo_tasks::function]
    fn chunking_type(&self) -> Result<Vc<ChunkingTypeOption>> {
        Ok(Vc::cell(
            if let Some(chunking_type) = self.annotations.chunking_type() {
                match chunking_type {
                    "parallel" => Some(ChunkingType::Parallel {
                        inherit_async: true,
                        hoisted: true,
                    }),
                    "none" => None,
                    _ => return Err(anyhow!("unknown chunking_type: {}", chunking_type)),
                }
            } else {
                Some(ChunkingType::Parallel {
                    inherit_async: true,
                    hoisted: true,
                })
            },
        ))
    }

    #[turbo_tasks::function]
    fn export_usage(&self) -> Vc<ExportUsage> {
        match &self.export_name {
            Some(ModulePart::Export(export_name)) => ExportUsage::named(export_name.clone()),
            Some(ModulePart::Evaluation) => ExportUsage::evaluation(),
            _ => ExportUsage::all(),
        }
    }
}

impl EsmAssetReference {
    pub async fn code_generation(
        self: Vc<Self>,
        chunking_context: Vc<Box<dyn ChunkingContext>>,
        scope_hoisting_context: ScopeHoistingContext<'_>,
    ) -> Result<CodeGeneration> {
        let this = &*self.await?;

        // only chunked references can be imported
        if this.annotations.chunking_type() != Some("none") {
            let import_externals = this.import_externals;
            let referenced_asset = self.get_referenced_asset().await?;

            match &*referenced_asset {
                ReferencedAsset::Unresolvable => {
                    // Insert code that throws immediately at time of import if a request is
                    // unresolvable
                    let request = request_to_string(*this.request).await?.to_string();
                    let stmt = Stmt::Expr(ExprStmt {
                        expr: Box::new(throw_module_not_found_expr(&request)),
                        span: DUMMY_SP,
                    });
                    return Ok(CodeGeneration::hoisted_stmt(
                        format!("throw {request}").into(),
                        stmt,
                    ));
                }
                ReferencedAsset::None => {}
                _ => {
                    let mut result = vec![];

                    let merged_index = if let ReferencedAsset::Some(asset) = &*referenced_asset {
                        scope_hoisting_context.get_module_index(*asset)
                    } else {
                        None
                    };

                    if let Some(merged_index) = merged_index {
                        // Insert a placeholder to inline the merged module at the right place
                        // relative to the other references (so to keep reference order).
                        result.push(CodeGenerationHoistedStmt::new(
                            format!("hoisted {merged_index}").into(),
                            quote!(
                                "__turbopack_merged_esm__($id);" as Stmt,
                                id: Expr = Lit::Num(merged_index.into()).into(),
                            ),
                        ));
                    }

                    if merged_index.is_some()
                        && matches!(*self.export_usage().await?, ExportUsage::Evaluation)
                    {
                        // No need to import, the module was already executed and is available in
                        // the same scope hoisting group (unless it's a
                        // namespace import)
                    } else {
                        let ident = referenced_asset
                            .get_ident(
                                chunking_context,
                                this.export_name.as_ref().and_then(|e| match e {
                                    ModulePart::Export(export_name) => Some(export_name.clone()),
                                    _ => None,
                                }),
                                scope_hoisting_context,
                            )
                            .await?;
                        match ident {
                            Some(ReferencedAssetIdent::LocalBinding { .. }) => {
                                // no need to import
                            }
                            Some(ident @ ReferencedAssetIdent::Module { .. }) => {
                                let span = this
                                    .issue_source
                                    .to_swc_offsets()
                                    .await?
                                    .map_or(DUMMY_SP, |(start, end)| {
                                        Span::new(BytePos(start), BytePos(end))
                                    });
                                match &*referenced_asset {
                                    ReferencedAsset::Unresolvable => {
                                        unreachable!();
                                    }
                                    ReferencedAsset::Some(asset) => {
                                        let id = asset
                                            .chunk_item_id(Vc::upcast(chunking_context))
                                            .await?;
                                        let (sym, ctxt) =
                                            ident.into_module_namespace_ident().unwrap();
                                        let name = Ident::new(
                                            sym.into(),
                                            DUMMY_SP,
                                            ctxt.unwrap_or_default(),
                                        );
                                        let mut call_expr = quote!(
                                            "$turbopack_import($id)" as Expr,
                                            turbopack_import: Expr = TURBOPACK_IMPORT.into(),
                                            id: Expr = module_id_to_lit(&id),
                                        );
                                        if this.is_pure_import {
                                            call_expr.set_span(PURE_SP);
                                        }
                                        result.push(CodeGenerationHoistedStmt::new(
                                            id.to_string().into(),
                                            var_decl_with_span(
                                                quote!(
                                                    "var $name = $call;" as Stmt,
                                                    name = name,
                                                    call: Expr = call_expr
                                                ),
                                                span,
                                            ),
                                        ));
                                    }
                                    ReferencedAsset::External(
                                        request,
                                        ExternalType::EcmaScriptModule,
                                    ) => {
                                        if !*chunking_context
                                            .environment()
                                            .supports_esm_externals()
                                            .await?
                                        {
                                            bail!(
                                                "the chunking context ({}) does not support \
                                                 external modules (esm request: {})",
                                                chunking_context.name().await?,
                                                request
                                            );
                                        }
                                        let (sym, ctxt) =
                                            ident.into_module_namespace_ident().unwrap();
                                        let name = Ident::new(
                                            sym.into(),
                                            DUMMY_SP,
                                            ctxt.unwrap_or_default(),
                                        );
                                        let mut call_expr = if import_externals {
                                            quote!(
                                                "$turbopack_external_import($id)" as Expr,
                                                turbopack_external_import: Expr = TURBOPACK_EXTERNAL_IMPORT.into(),
                                                id: Expr = Expr::Lit(request.clone().to_string().into())
                                            )
                                        } else {
                                            quote!(
                                                "$turbopack_external_require($id, () => require($id), true)" as Expr,
                                                turbopack_external_require: Expr = TURBOPACK_EXTERNAL_REQUIRE.into(),
                                                id: Expr = Expr::Lit(request.clone().to_string().into())
                                            )
                                        };
                                        if this.is_pure_import {
                                            call_expr.set_span(PURE_SP);
                                        }
                                        result.push(CodeGenerationHoistedStmt::new(
                                            name.sym.as_str().into(),
                                            var_decl_with_span(
                                                quote!(
                                                    "var $name = $call;" as Stmt,
                                                    name = name,
                                                    call: Expr = call_expr,
                                                ),
                                                span,
                                            ),
                                        ));
                                    }
                                    ReferencedAsset::External(
                                        request,
                                        ExternalType::CommonJs | ExternalType::Url,
                                    ) => {
                                        if !*chunking_context
                                            .environment()
                                            .supports_commonjs_externals()
                                            .await?
                                        {
                                            bail!(
                                                "the chunking context ({}) does not support \
                                                 external modules (request: {})",
                                                chunking_context.name().await?,
                                                request
                                            );
                                        }
                                        let (sym, ctxt) =
                                            ident.into_module_namespace_ident().unwrap();
                                        let name = Ident::new(
                                            sym.into(),
                                            DUMMY_SP,
                                            ctxt.unwrap_or_default(),
                                        );
                                        let mut call_expr = quote!(
                                            "$turbopack_external_require($id, () => require($id), true)" as Expr,
                                            turbopack_external_require: Expr = TURBOPACK_EXTERNAL_REQUIRE.into(),
                                            id: Expr = Expr::Lit(request.clone().to_string().into())
                                        );
                                        if this.is_pure_import {
                                            call_expr.set_span(PURE_SP);
                                        }
                                        result.push(CodeGenerationHoistedStmt::new(
                                            name.sym.as_str().into(),
                                            var_decl_with_span(
                                                quote!(
                                                    "var $name = $call;" as Stmt,
                                                    name = name,
                                                    call: Expr = call_expr,
                                                ),
                                                span,
                                            ),
                                        ));
                                    }
                                    // fallback in case we introduce a new `ExternalType`
                                    #[allow(unreachable_patterns)]
                                    ReferencedAsset::External(request, ty) => {
                                        bail!(
                                            "Unsupported external type {:?} for ESM reference \
                                             with request: {:?}",
                                            ty,
                                            request
                                        )
                                    }
                                    ReferencedAsset::None => {}
                                };
                            }
                            None => {
                                // Nothing to import.
                            }
                        }
                    }
                    return Ok(CodeGeneration::hoisted_stmts(result));
                }
            }
        };

        Ok(CodeGeneration::empty())
    }
}

fn var_decl_with_span(mut decl: Stmt, span: Span) -> Stmt {
    match &mut decl {
        Stmt::Decl(Decl::Var(decl)) => decl.span = span,
        _ => panic!("Expected Stmt::Decl::Var"),
    };
    decl
}

#[turbo_tasks::value(shared)]
pub struct InvalidExport {
    export: RcStr,
    module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
    source: IssueSource,
}

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

    #[turbo_tasks::function]
    fn title(&self) -> Result<Vc<StyledString>> {
        Ok(StyledString::Line(vec![
            StyledString::Text(rcstr!("Export ")),
            StyledString::Code(self.export.clone()),
            StyledString::Text(rcstr!(" doesn't exist in target module")),
        ])
        .cell())
    }

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

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

    #[turbo_tasks::function]
    async fn description(&self) -> Result<Vc<OptionStyledString>> {
        let export_names = all_known_export_names(*self.module).await?;
        let did_you_mean = export_names
            .iter()
            .map(|s| (s, jaro(self.export.as_str(), s.as_str())))
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
            .map(|(s, _)| s);
        Ok(Vc::cell(Some(
            StyledString::Stack(vec![
                StyledString::Line(vec![
                    StyledString::Text(rcstr!("The export ")),
                    StyledString::Code(self.export.clone()),
                    StyledString::Text(rcstr!(" was not found in module ")),
                    StyledString::Strong(self.module.ident().to_string().owned().await?),
                    StyledString::Text(rcstr!(".")),
                ]),
                if let Some(did_you_mean) = did_you_mean {
                    StyledString::Line(vec![
                        StyledString::Text(rcstr!("Did you mean to import ")),
                        StyledString::Code(did_you_mean.clone()),
                        StyledString::Text(rcstr!("?")),
                    ])
                } else {
                    StyledString::Strong(rcstr!("The module has no exports at all."))
                },
                StyledString::Text(
                    "All exports of the module are statically known (It doesn't have dynamic \
                     exports). So it's known statically that the requested export doesn't exist."
                        .into(),
                ),
            ])
            .resolved_cell(),
        )))
    }

    #[turbo_tasks::function]
    async fn detail(&self) -> Result<Vc<OptionStyledString>> {
        let export_names = all_known_export_names(*self.module).await?;
        Ok(Vc::cell(Some(
            StyledString::Line(vec![
                StyledString::Text(rcstr!("These are the exports of the module:\n")),
                StyledString::Code(
                    export_names
                        .iter()
                        .map(|s| s.as_str())
                        .intersperse(", ")
                        .collect::<String>()
                        .into(),
                ),
            ])
            .resolved_cell(),
        )))
    }

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

#[turbo_tasks::value(shared)]
pub struct CircularReExport {
    export: RcStr,
    import: Option<RcStr>,
    module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
    module_cycle: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
}

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

    #[turbo_tasks::function]
    async fn title(&self) -> Result<Vc<StyledString>> {
        Ok(StyledString::Line(vec![
            StyledString::Text("Export ".into()),
            StyledString::Code(self.export.clone()),
            StyledString::Text(" is a circular re-export".into()),
        ])
        .cell())
    }

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

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

    #[turbo_tasks::function]
    async fn description(&self) -> Result<Vc<OptionStyledString>> {
        Ok(Vc::cell(Some(
            StyledString::Stack(vec![
                StyledString::Line(vec![StyledString::Text("The export".into())]),
                StyledString::Line(vec![
                    StyledString::Code(self.export.clone()),
                    StyledString::Text(" of module ".into()),
                    StyledString::Strong(self.module.ident().to_string().owned().await?),
                ]),
                StyledString::Line(vec![StyledString::Text(
                    "is a re-export of the export".into(),
                )]),
                StyledString::Line(vec![
                    StyledString::Code(self.import.clone().unwrap_or_else(|| "*".into())),
                    StyledString::Text(" of module ".into()),
                    StyledString::Strong(self.module_cycle.ident().to_string().owned().await?),
                    StyledString::Text(".".into()),
                ]),
            ])
            .resolved_cell(),
        )))
    }

    #[turbo_tasks::function]
    fn source(&self) -> Vc<OptionIssueSource> {
        // TODO(PACK-4879): This should point at the buggy export by querying for the source
        // location
        Vc::cell(None)
    }
}