File size: 27,987 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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 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 | use std::{collections::BTreeMap, fmt::Display};
use once_cell::sync::Lazy;
use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{
common::{BytePos, Span, Spanned, SyntaxContext, comments::Comments, source_map::SmallPos},
ecma::{
ast::*,
atoms::{Atom, atom},
utils::{IsDirective, find_pat_ids},
visit::{Visit, VisitWith},
},
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc};
use turbopack_core::{issue::IssueSource, source::Source};
use super::{JsValue, ModuleValue, top_level_await::has_top_level_await};
use crate::{
SpecifiedModuleType,
analyzer::{ConstantValue, ObjectPart},
magic_identifier,
tree_shake::{PartId, find_turbopack_part_id_in_asserts},
};
#[turbo_tasks::value]
#[derive(Default, Debug, Clone, Hash)]
pub struct ImportAnnotations {
// TODO store this in more structured way
#[turbo_tasks(trace_ignore)]
map: BTreeMap<Atom, Atom>,
}
/// Enables a specified transition for the annotated import
static ANNOTATION_TRANSITION: Lazy<Atom> =
Lazy::new(|| crate::annotations::ANNOTATION_TRANSITION.into());
/// Changes the chunking type for the annotated import
static ANNOTATION_CHUNKING_TYPE: Lazy<Atom> =
Lazy::new(|| crate::annotations::ANNOTATION_CHUNKING_TYPE.into());
/// Changes the type of the resolved module (only "json" is supported currently)
static ATTRIBUTE_MODULE_TYPE: Lazy<Atom> = Lazy::new(|| "type".into());
impl ImportAnnotations {
pub fn parse(with: Option<&ObjectLit>) -> ImportAnnotations {
let Some(with) = with else {
return ImportAnnotations::default();
};
let mut map = BTreeMap::new();
// The `with` clause is way more restrictive than `ObjectLit`, it only allows
// string -> value and value can only be a string.
// We just ignore everything else here till the SWC ast is more restrictive.
for (key, value) in with.props.iter().filter_map(|prop| {
let kv = prop.as_prop()?.as_key_value()?;
let Lit::Str(str) = kv.value.as_lit()? else {
return None;
};
Some((&kv.key, str))
}) {
let key = match key {
PropName::Ident(ident) => ident.sym.as_str(),
PropName::Str(str) => str.value.as_str(),
// the rest are invalid, ignore for now till SWC ast is correct
_ => continue,
};
map.insert(key.into(), value.value.as_str().into());
}
ImportAnnotations { map }
}
pub fn parse_dynamic(with: &JsValue) -> Option<ImportAnnotations> {
let mut map = BTreeMap::new();
let JsValue::Object { parts, .. } = with else {
return None;
};
for part in parts.iter() {
let ObjectPart::KeyValue(key, value) = part else {
continue;
};
let (
JsValue::Constant(ConstantValue::Str(key)),
JsValue::Constant(ConstantValue::Str(value)),
) = (key, value)
else {
continue;
};
map.insert(key.as_str().into(), value.as_str().into());
}
Some(ImportAnnotations { map })
}
/// Returns the content on the transition annotation
pub fn transition(&self) -> Option<&str> {
self.get(&ANNOTATION_TRANSITION)
}
/// Returns the content on the chunking-type annotation
pub fn chunking_type(&self) -> Option<&str> {
self.get(&ANNOTATION_CHUNKING_TYPE)
}
/// Returns the content on the type attribute
pub fn module_type(&self) -> Option<&str> {
self.get(&ATTRIBUTE_MODULE_TYPE)
}
pub fn get(&self, key: &Atom) -> Option<&str> {
self.map.get(key).map(|w| w.as_str())
}
}
impl Display for ImportAnnotations {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut it = self.map.iter();
if let Some((k, v)) = it.next() {
write!(f, "{{ {k}: {v}")?
} else {
return f.write_str("{}");
};
for (k, v) in it {
write!(f, ", {k}: {v}")?
}
f.write_str(" }")
}
}
#[derive(Debug)]
pub(crate) enum Reexport {
Star,
Namespace { exported: Atom },
Named { imported: Atom, exported: Atom },
}
/// The storage for all kinds of imports.
///
/// Note that when it's initialized by calling `analyze`, it only contains ESM
/// import/exports.
#[derive(Default, Debug)]
pub(crate) struct ImportMap {
/// Map from identifier to (index in references, exported symbol)
imports: FxIndexMap<Id, (usize, Atom)>,
/// Map from identifier to index in references
namespace_imports: FxIndexMap<Id, usize>,
/// List of (index in references, imported symbol, exported symbol)
reexports: Vec<(usize, Reexport)>,
/// Ordered list of imported symbols
references: FxIndexSet<ImportMapReference>,
/// True, when the module has imports
has_imports: bool,
/// True, when the module has exports
has_exports: bool,
/// True if the module is an ESM module due to top-level await.
has_top_level_await: bool,
/// True if the module has "use strict"
pub(crate) strict: bool,
/// Locations of [webpack-style "magic comments"][magic] that override import behaviors.
///
/// Most commonly, these are `/* webpackIgnore: true */` comments. See [ImportAttributes] for
/// full details.
///
/// [magic]: https://webpack.js.org/api/module-methods/#magic-comments
attributes: FxHashMap<BytePos, ImportAttributes>,
/// The module specifiers of star imports that are accessed dynamically and should be imported
/// as a whole.
full_star_imports: FxHashSet<Atom>,
pub(crate) exports: FxHashMap<RcStr, Id>,
}
/// Represents a collection of [webpack-style "magic comments"][magic] that override import
/// behaviors.
///
/// [magic]: https://webpack.js.org/api/module-methods/#magic-comments
#[derive(Debug)]
pub struct ImportAttributes {
/// Should we ignore this import expression when bundling? If so, the import expression will be
/// left as-is in Turbopack's output.
///
/// This is set by using either a `webpackIgnore` or `turbopackIgnore` comment.
///
/// Example:
/// ```js
/// const a = import(/* webpackIgnore: true */ "a");
/// const b = import(/* turbopackIgnore: true */ "b");
/// ```
pub ignore: bool,
}
impl ImportAttributes {
pub const fn empty() -> Self {
ImportAttributes { ignore: false }
}
pub fn empty_ref() -> &'static Self {
// use `Self::empty` here as `Default::default` isn't const
static DEFAULT_VALUE: ImportAttributes = ImportAttributes::empty();
&DEFAULT_VALUE
}
}
impl Default for ImportAttributes {
fn default() -> Self {
ImportAttributes::empty()
}
}
impl Default for &ImportAttributes {
fn default() -> Self {
ImportAttributes::empty_ref()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum ImportedSymbol {
ModuleEvaluation,
Symbol(Atom),
Exports,
Part(u32),
PartEvaluation(u32),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ImportMapReference {
pub module_path: Atom,
pub imported_symbol: ImportedSymbol,
pub annotations: ImportAnnotations,
pub issue_source: Option<IssueSource>,
}
impl ImportMap {
pub fn is_esm(&self, specified_type: SpecifiedModuleType) -> bool {
if self.has_exports {
return true;
}
match specified_type {
SpecifiedModuleType::Automatic => {
self.has_exports || self.has_imports || self.has_top_level_await
}
SpecifiedModuleType::CommonJs => false,
SpecifiedModuleType::EcmaScript => true,
}
}
pub fn get_import(&self, id: &Id) -> Option<JsValue> {
if let Some((i, i_sym)) = self.imports.get(id) {
let r = &self.references[*i];
return Some(JsValue::member(
Box::new(JsValue::Module(ModuleValue {
module: r.module_path.clone(),
annotations: r.annotations.clone(),
})),
Box::new(i_sym.clone().into()),
));
}
if let Some(i) = self.namespace_imports.get(id) {
let r = &self.references[*i];
return Some(JsValue::Module(ModuleValue {
module: r.module_path.clone(),
annotations: r.annotations.clone(),
}));
}
None
}
pub fn get_attributes(&self, span: Span) -> &ImportAttributes {
self.attributes.get(&span.lo).unwrap_or_default()
}
// TODO this could return &str instead of String to avoid cloning
pub fn get_binding(&self, id: &Id) -> Option<(usize, Option<RcStr>)> {
if let Some((i, i_sym)) = self.imports.get(id) {
return Some((*i, Some(i_sym.as_str().into())));
}
if let Some(i) = self.namespace_imports.get(id) {
return Some((*i, None));
}
None
}
pub fn references(&self) -> impl ExactSizeIterator<Item = &ImportMapReference> {
self.references.iter()
}
pub fn reexports(&self) -> impl ExactSizeIterator<Item = (usize, &Reexport)> {
self.reexports.iter().map(|(i, r)| (*i, r))
}
/// Analyze ES import
pub(super) fn analyze(
m: &Program,
source: Option<ResolvedVc<Box<dyn Source>>>,
comments: Option<&dyn Comments>,
) -> Self {
let mut data = ImportMap::default();
// We have to analyze imports first to determine if a star import is dynamic.
// We can't do this in the visitor because import may (and likely) comes before usages, and
// a method invoked after visitor will not work because we need to preserve the import
// order.
if let Program::Module(m) = m {
let mut candidates = FxIndexMap::default();
// Imports are hoisted to the top of the module.
// So we have to collect all imports first.
m.body.iter().for_each(|stmt| {
if let ModuleItem::ModuleDecl(ModuleDecl::Import(import)) = stmt {
for s in &import.specifiers {
if let ImportSpecifier::Namespace(s) = s {
candidates.insert(s.local.to_id(), import.src.value.clone());
}
}
}
});
let mut analyzer = StarImportAnalyzer {
candidates,
full_star_imports: &mut data.full_star_imports,
};
m.visit_with(&mut analyzer);
}
let mut analyzer = Analyzer {
data: &mut data,
source,
comments,
};
m.visit_with(&mut analyzer);
data
}
pub(crate) fn should_import_all(&self, esm_reference_index: usize) -> bool {
let r = &self.references[esm_reference_index];
self.full_star_imports.contains(&r.module_path)
}
}
struct StarImportAnalyzer<'a> {
/// The local identifiers of the star imports
candidates: FxIndexMap<Id, Atom>,
full_star_imports: &'a mut FxHashSet<Atom>,
}
impl Visit for StarImportAnalyzer<'_> {
fn visit_expr(&mut self, node: &Expr) {
if let Expr::Ident(i) = node
&& let Some(module_path) = self.candidates.get(&i.to_id())
{
self.full_star_imports.insert(module_path.clone());
return;
}
node.visit_children_with(self);
}
fn visit_import_decl(&mut self, _: &ImportDecl) {}
fn visit_member_expr(&mut self, node: &MemberExpr) {
match &node.prop {
MemberProp::Ident(..) | MemberProp::PrivateName(..) => {
if node.obj.is_ident() {
return;
}
// We can skip `visit_expr(obj)` because it's not a dynamic access
node.obj.visit_children_with(self);
}
MemberProp::Computed(..) => {
node.obj.visit_with(self);
node.prop.visit_with(self);
}
}
}
fn visit_pat(&mut self, pat: &Pat) {
if let Pat::Ident(i) = pat
&& let Some(module_path) = self.candidates.get(&i.to_id())
{
self.full_star_imports.insert(module_path.clone());
return;
}
pat.visit_children_with(self);
}
fn visit_simple_assign_target(&mut self, node: &SimpleAssignTarget) {
if let SimpleAssignTarget::Ident(i) = node
&& let Some(module_path) = self.candidates.get(&i.to_id())
{
self.full_star_imports.insert(module_path.clone());
return;
}
node.visit_children_with(self);
}
}
struct Analyzer<'a> {
data: &'a mut ImportMap,
source: Option<ResolvedVc<Box<dyn Source>>>,
comments: Option<&'a dyn Comments>,
}
impl Analyzer<'_> {
fn ensure_reference(
&mut self,
span: Span,
module_path: Atom,
imported_symbol: ImportedSymbol,
annotations: ImportAnnotations,
) -> Option<usize> {
let issue_source = self
.source
.map(|s| IssueSource::from_swc_offsets(s, span.lo.to_u32(), span.hi.to_u32()));
let r = ImportMapReference {
module_path,
imported_symbol,
issue_source,
annotations,
};
if let Some(i) = self.data.references.get_index_of(&r) {
Some(i)
} else {
let i = self.data.references.len();
self.data.references.insert(r);
Some(i)
}
}
}
fn export_as_atom(name: &ModuleExportName) -> &Atom {
match name {
ModuleExportName::Ident(ident) => &ident.sym,
ModuleExportName::Str(s) => &s.value,
}
}
impl Visit for Analyzer<'_> {
fn visit_import_decl(&mut self, import: &ImportDecl) {
self.data.has_imports = true;
let annotations = ImportAnnotations::parse(import.with.as_deref());
let internal_symbol = parse_with(import.with.as_deref());
if internal_symbol.is_none() {
self.ensure_reference(
import.span,
import.src.value.clone(),
ImportedSymbol::ModuleEvaluation,
annotations.clone(),
);
}
for s in &import.specifiers {
let symbol = internal_symbol
.clone()
.unwrap_or_else(|| get_import_symbol_from_import(s));
let i = self.ensure_reference(
import.span,
import.src.value.clone(),
symbol,
annotations.clone(),
);
let i = match i {
Some(v) => v,
None => continue,
};
let (local, orig_sym) = match s {
ImportSpecifier::Named(ImportNamedSpecifier {
local, imported, ..
}) => match imported {
Some(imported) => (local.to_id(), orig_name(imported)),
_ => (local.to_id(), local.sym.clone()),
},
ImportSpecifier::Default(s) => (s.local.to_id(), "default".into()),
ImportSpecifier::Namespace(s) => {
self.data.namespace_imports.insert(s.local.to_id(), i);
continue;
}
};
self.data.imports.insert(local, (i, orig_sym));
}
if import.specifiers.is_empty()
&& let Some(internal_symbol) = internal_symbol
{
self.ensure_reference(
import.span,
import.src.value.clone(),
internal_symbol,
annotations,
);
}
}
fn visit_export_all(&mut self, export: &ExportAll) {
self.data.has_exports = true;
let annotations = ImportAnnotations::parse(export.with.as_deref());
self.ensure_reference(
export.span,
export.src.value.clone(),
ImportedSymbol::ModuleEvaluation,
annotations.clone(),
);
let symbol = parse_with(export.with.as_deref());
let i = self.ensure_reference(
export.span,
export.src.value.clone(),
symbol.unwrap_or(ImportedSymbol::Exports),
annotations,
);
if let Some(i) = i {
self.data.reexports.push((i, Reexport::Star));
}
}
fn visit_named_export(&mut self, export: &NamedExport) {
self.data.has_exports = true;
let Some(ref src) = export.src else {
export.visit_children_with(self);
return;
};
let annotations = ImportAnnotations::parse(export.with.as_deref());
let internal_symbol = parse_with(export.with.as_deref());
if internal_symbol.is_none() || export.specifiers.is_empty() {
self.ensure_reference(
export.span,
src.value.clone(),
ImportedSymbol::ModuleEvaluation,
annotations.clone(),
);
}
for spec in export.specifiers.iter() {
let symbol = internal_symbol
.clone()
.unwrap_or_else(|| get_import_symbol_from_export(spec));
let i =
self.ensure_reference(export.span, src.value.clone(), symbol, annotations.clone());
let i = match i {
Some(v) => v,
None => continue,
};
match spec {
ExportSpecifier::Namespace(n) => {
self.data.reexports.push((
i,
Reexport::Namespace {
exported: export_as_atom(&n.name).clone(),
},
));
}
ExportSpecifier::Default(d) => {
self.data.reexports.push((
i,
Reexport::Named {
imported: atom!("default"),
exported: d.exported.sym.clone(),
},
));
}
ExportSpecifier::Named(n) => {
self.data.reexports.push((
i,
Reexport::Named {
imported: export_as_atom(&n.orig).clone(),
exported: export_as_atom(n.exported.as_ref().unwrap_or(&n.orig))
.clone(),
},
));
}
}
}
}
fn visit_export_decl(&mut self, n: &ExportDecl) {
self.data.has_exports = true;
if self.comments.is_some() {
// only visit children if we potentially need to mark import / requires
n.visit_children_with(self);
}
match &n.decl {
Decl::Class(n) => {
self.data
.exports
.insert(n.ident.sym.as_str().into(), n.ident.to_id());
}
Decl::Fn(n) => {
self.data
.exports
.insert(n.ident.sym.as_str().into(), n.ident.to_id());
}
Decl::Var(..) | Decl::Using(..) => {
let ids: Vec<Id> = find_pat_ids(&n.decl);
for id in ids {
self.data.exports.insert(id.0.as_str().into(), id);
}
}
_ => {}
}
}
fn visit_export_default_decl(&mut self, n: &ExportDefaultDecl) {
self.data.has_exports = true;
if self.comments.is_some() {
// only visit children if we potentially need to mark import / requires
n.visit_children_with(self);
}
self.data.exports.insert(
rcstr!("default"),
// Mirror what `EsmModuleItem::code_generation` does, these are live bindings if the
// class/function has an identifier.
match &n.decl {
DefaultDecl::Class(ClassExpr { ident, .. })
| DefaultDecl::Fn(FnExpr { ident, .. }) => ident.as_ref().map_or_else(
|| {
(
magic_identifier::mangle("default export").into(),
SyntaxContext::empty(),
)
},
|ident| (ident.to_id()),
),
DefaultDecl::TsInterfaceDecl(_) => {
// not matching, might happen due to eventual consistency
(
magic_identifier::mangle("default export").into(),
SyntaxContext::empty(),
)
}
},
);
}
fn visit_export_default_expr(&mut self, n: &ExportDefaultExpr) {
self.data.has_exports = true;
if self.comments.is_some() {
// only visit children if we potentially need to mark import / requires
n.visit_children_with(self);
}
self.data.exports.insert(
rcstr!("default"),
(
// `EsmModuleItem::code_generation` inserts this variable.
magic_identifier::mangle("default export").into(),
SyntaxContext::empty(),
),
);
}
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
let ModuleExportName::Ident(local) = &n.orig else {
// This is only possible for re-exports, but they are already handled earlier in
// visit_named_export.
unreachable!("string reexports should have been already handled in visit_named_export");
};
let exported = n.exported.as_ref().unwrap_or(&n.orig);
self.data
.exports
.insert(export_as_atom(exported).as_str().into(), local.to_id());
}
fn visit_export_default_specifier(&mut self, n: &ExportDefaultSpecifier) {
self.data
.exports
.insert(rcstr!("default"), n.exported.to_id());
}
fn visit_program(&mut self, m: &Program) {
self.data.has_top_level_await = has_top_level_await(m).is_some();
self.data.strict = match m {
Program::Module(module) => module
.body
.iter()
.take_while(|s| s.directive_continue())
.any(IsDirective::is_use_strict),
Program::Script(script) => script
.body
.iter()
.take_while(|s| s.directive_continue())
.any(IsDirective::is_use_strict),
};
m.visit_children_with(self);
}
fn visit_stmt(&mut self, n: &Stmt) {
if self.comments.is_some() {
// only visit children if we potentially need to mark import / requires
n.visit_children_with(self);
}
}
/// check if import or require contains an ignore comment
///
/// We are checking for the following cases:
/// - import(/* webpackIgnore: true */ "a")
/// - require(/* webpackIgnore: true */ "a")
///
/// We can do this by checking if any of the comment spans are between the
/// callee and the first argument.
//
// potentially support more webpack magic comments in the future:
// https://webpack.js.org/api/module-methods/#magic-comments
fn visit_call_expr(&mut self, n: &CallExpr) {
// we could actually unwrap thanks to the optimisation above but it can't hurt to be safe...
if let Some(comments) = self.comments {
let callee_span = match &n.callee {
Callee::Import(Import { span, .. }) => Some(*span),
Callee::Expr(e) => Some(e.span()),
_ => None,
};
let ignore_directive = parse_ignore_directive(comments, n.args.first());
if let Some((callee_span, ignore_directive)) = callee_span.zip(ignore_directive) {
self.data.attributes.insert(
callee_span.lo,
ImportAttributes {
ignore: ignore_directive,
},
);
};
}
n.visit_children_with(self);
}
fn visit_new_expr(&mut self, n: &NewExpr) {
// we could actually unwrap thanks to the optimisation above but it can't hurt to be safe...
if let Some(comments) = self.comments {
let callee_span = match &n.callee {
box Expr::Ident(Ident { sym, .. }) if sym == "Worker" => Some(n.span),
_ => None,
};
let ignore_directive = parse_ignore_directive(comments, n.args.iter().flatten().next());
if let Some((callee_span, ignore_directive)) = callee_span.zip(ignore_directive) {
self.data.attributes.insert(
callee_span.lo,
ImportAttributes {
ignore: ignore_directive,
},
);
};
}
n.visit_children_with(self);
}
}
fn parse_ignore_directive(comments: &dyn Comments, value: Option<&ExprOrSpread>) -> Option<bool> {
// we are interested here in the last comment with a valid directive
value
.map(|arg| arg.span_lo())
.and_then(|comment_pos| comments.get_leading(comment_pos))
.iter()
.flatten()
.rev()
.filter_map(|comment| {
let (directive, value) = comment.text.trim().split_once(':')?;
// support whitespace between the colon
match (directive.trim(), value.trim()) {
("webpackIgnore" | "turbopackIgnore", "true") => Some(true),
("webpackIgnore" | "turbopackIgnore", "false") => Some(false),
_ => None, // ignore anything else
}
})
.next()
}
pub(crate) fn orig_name(n: &ModuleExportName) -> Atom {
match n {
ModuleExportName::Ident(v) => v.sym.clone(),
ModuleExportName::Str(v) => v.value.clone(),
}
}
fn parse_with(with: Option<&ObjectLit>) -> Option<ImportedSymbol> {
find_turbopack_part_id_in_asserts(with?).map(|v| match v {
PartId::Internal(index, true) => ImportedSymbol::PartEvaluation(index),
PartId::Internal(index, false) => ImportedSymbol::Part(index),
PartId::ModuleEvaluation => ImportedSymbol::ModuleEvaluation,
PartId::Export(e) => ImportedSymbol::Symbol(e.as_str().into()),
PartId::Exports => ImportedSymbol::Exports,
})
}
fn get_import_symbol_from_import(specifier: &ImportSpecifier) -> ImportedSymbol {
match specifier {
ImportSpecifier::Named(ImportNamedSpecifier {
local, imported, ..
}) => ImportedSymbol::Symbol(match imported {
Some(imported) => orig_name(imported),
_ => local.sym.clone(),
}),
ImportSpecifier::Default(..) => ImportedSymbol::Symbol(atom!("default")),
ImportSpecifier::Namespace(..) => ImportedSymbol::Exports,
}
}
fn get_import_symbol_from_export(specifier: &ExportSpecifier) -> ImportedSymbol {
match specifier {
ExportSpecifier::Named(ExportNamedSpecifier { orig, .. }) => {
ImportedSymbol::Symbol(orig_name(orig))
}
ExportSpecifier::Default(..) => ImportedSymbol::Symbol(atom!("default")),
ExportSpecifier::Namespace(..) => ImportedSymbol::Exports,
}
}
|