Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 41 additions & 16 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,21 +928,11 @@ impl<'a> LinkerContext<'a> {
// Size the per-file part-liveness bitsets now that `scan_imports_and_exports`
// has finished pushing wrapper / entry-point parts.
{
let loaders = self.parse_graph().input_files.items_loader();
let parts_col = self.graph.ast.items_parts();
let mut parts_live: Vec<bun_collections::AutoBitSet> =
Vec::with_capacity(parts_col.len());
for (i, parts) in parts_col.iter().enumerate() {
let mut bits = bun_collections::AutoBitSet::init_empty(parts.len())?;
// The HTML loader's `ParseTask` builds its synthetic part 1 already
// live (so the JS-chunk visitor follows every embedded import record).
// `mark_file_live_for_tree_shaking` short-circuits for HTML and never
// walks its parts, so seed the bit here to preserve the old
// `Part::is_live = true` initializer.
if loaders.get(i).is_some_and(|l| *l == Loader::Html) && parts.len() > 1 {
bits.set(1);
}
parts_live.push(bits);
for parts in parts_col.iter() {
parts_live.push(bun_collections::AutoBitSet::init_empty(parts.len())?);
}
self.graph.parts_live = parts_live;
}
Expand Down Expand Up @@ -2185,6 +2175,7 @@ impl<'a> LinkerContext<'a> {
loc: Loc,
namespace_ref: Ref,
import_record_index: u32,
source_index: u32,
alloc: &Bump,
ast: &JSAst<'_>,
) -> Result<bool, BunError> {
Expand All @@ -2193,8 +2184,14 @@ impl<'a> LinkerContext<'a> {
if record.flags.contains(bun_ast::ImportRecordFlags::IS_UNUSED) {
return Ok(true);
}
let is_html_script =
self.parse_graph().input_files.items_loader()[source_index as usize] == Loader::Html;
// Is this an external import?
if !record.source_index.is_valid() {
// An external `<script src>` stays a tag in the HTML file.
if is_html_script {
return Ok(true);
}
// Keep the "import" statement if import statements are supported
if self.options.output_format.keep_es6_import_export_syntax() {
return Ok(false);
Expand Down Expand Up @@ -2244,6 +2241,19 @@ impl<'a> LinkerContext<'a> {
let other_flags = self.graph.meta.items_flags()[record.source_index.get() as usize];
match other_flags.wrap {
WrapKind::None => {}
// A `<script src>` only runs the module, in document order with the
// page's other scripts: "require_foo();"
WrapKind::Cjs if is_html_script => {
stmts
.inside_wrapper_prefix
.append_sync_dependency(Expr::init(
E::RequireString {
import_record_index,
..Default::default()
},
loc,
))?;
}
WrapKind::Cjs => {
// Replace the statement with a call to "require()" since the other module is CJS-wrapped
stmts
Expand Down Expand Up @@ -2298,7 +2308,10 @@ impl<'a> LinkerContext<'a> {
loc,
);

if other_flags.is_async_or_has_async_dependency {
// An HTML file starts an async script where its tag was and lets the
// scripts after it run meanwhile, like the browser does for separate
// module scripts. `generate_entry_point_tail_js` awaits it at the end.
if other_flags.is_async_or_has_async_dependency && !is_html_script {
stmts
.inside_wrapper_prefix
.append_async_dependency(init_call, self.promise_all_runtime_ref)?;
Expand Down Expand Up @@ -3092,9 +3105,12 @@ impl<'a> LinkerContext<'a> {
return;
}

// HTML files can reference non-JS/CSS assets (favicons, images, etc.)
// via .url kind import records. Follow all import records for HTML files
// so these assets are marked live and included in the manifest.
// Everything an HTML file references is live: every script runs, and
// non-JS/CSS assets (favicons, images, etc.) referenced via .url kind
// import records must be included in the manifest. Its parts (one
// `import` per `<script src>`) are all live too, so that the wrapper
// and runtime dependencies `scan_imports_and_exports` attached to them
// are followed.
if self.parse_graph().input_files.items_loader()[source_index as usize] == Loader::Html {
for record in ctx.import_records[source_index as usize].iter() {
if record.source_index.is_valid() {
Expand All @@ -3104,6 +3120,15 @@ impl<'a> LinkerContext<'a> {
}
}
}
let parts_len = ctx.parts[source_index as usize].len();
for part_index in (bun_ast::NAMESPACE_EXPORT_PART_INDEX as usize + 1)..parts_len {
if !ctx.parts_live[source_index as usize].is_set(part_index) {
ctx.worklist.push(TreeShakeWork::Part {
part_index: u32::try_from(part_index).expect("int cast"),
source_index,
});
}
}
return;
}

Expand Down
113 changes: 93 additions & 20 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,96 @@ pub enum Step {
Resolve,
}

/// Builds the parts of an HTML file's JavaScript module: every `<script src>`
/// becomes `import "./script"` in a part of its own, in document order. The
/// linker then treats the tag like an import statement: it orders the script
/// after the files before it, and it calls the script's wrapper where the tag
/// was when the script is wrapped (CommonJS, lazily initialized ESM, or a
/// script with a top-level await that must not hold back the scripts after
/// it). The other records (stylesheets, images) join the part of the next
/// script, so `find_imported_css_files_in_js_order` still sees document order.
fn html_module_parts(
ast: &mut ast::Ast<'static>,
import_records: &mut [ImportRecord],
bump: &'static Bump,
source: &Source,
) -> core::result::Result<(), bun_alloc::AllocError> {
use bun_ast::base::{RefInt, RefTag};
use bun_ast::{DeclaredSymbol, DeclaredSymbolList, ImportKind, ImportRecordFlags, Ref, S};

// Keep the namespace export part, drop the lazy export statement.
ast.parts.truncate(1);
let mut record_indices = ast::PartImportRecordIndices::new_in(bun_alloc::AstAlloc);
for (import_record_index, record) in import_records.iter_mut().enumerate() {
let import_record_index = u32::try_from(import_record_index).expect("int cast");
record_indices.push(import_record_index);
if record.kind != ImportKind::Stmt {
continue;
}
record
.flags
.insert(ImportRecordFlags::WAS_ORIGINALLY_BARE_IMPORT);

let name: &'static [u8] = bun_alloc::arena_format!(
in bump,
"import_{}",
bun_core::fmt::fmt_identifier(
bun_paths::fs::PathName::init(record.path.text).non_unique_name_string_base()
)
)
.into_bump_str()
.as_bytes();
let namespace_ref = Ref::new(
RefInt::try_from(ast.symbols.len()).expect("int cast"),
source.index.0,
RefTag::Symbol,
);
ast.symbols.push(ast::Symbol {
kind: ast::symbol::Kind::Other,
original_name: ast::StoreStr::new(name),
..Default::default()
});
ast.module_scope.generated.push(namespace_ref);
let part_index = u32::try_from(ast.parts.len()).expect("int cast");
ast.top_level_symbols_to_parts
.entry(namespace_ref)
.or_insert_with(bun_alloc::AstAlloc::vec)
.push(part_index);

let stmts: &mut [ast::Stmt] = bump.alloc_slice_copy(&[ast::Stmt::alloc(
S::Import {
namespace_ref,
import_record_index,
is_single_line: true,
..Default::default()
},
Loc::EMPTY,
)]);
ast.parts.push(Part {
stmts: ast::StoreSlice::new_mut(stmts),
declared_symbols: DeclaredSymbolList::from_slice(&[DeclaredSymbol {
ref_: namespace_ref,
is_top_level: true,
}])?,
import_record_indices: core::mem::replace(
&mut record_indices,
ast::PartImportRecordIndices::new_in(bun_alloc::AstAlloc),
),
..Default::default()
});
}
if ast.parts.len() == 1 {
ast.parts.push(Part {
import_record_indices: record_indices,
..Default::default()
});
} else if let Some(last) = ast.parts.last_mut() {
last.import_record_indices
.extend(record_indices.iter().copied());
}
Ok(())
}

// ───────────────────────────────────────────────────────────────────────────
// init
// ───────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -1198,7 +1288,7 @@ pub mod parse_worker {
Loader::Html => {
// scope the scanner so its `&mut log` / `&source`
// borrows release before `new_lazy_export_ast` re-borrows them.
let import_records = {
let mut import_records = {
let mut scanner = HTMLScanner::init(log, source);
scanner.scan(&source.contents)?;
scanner.import_records
Expand All @@ -1207,7 +1297,6 @@ pub mod parse_worker {
// Reuse existing code for creating the AST
// because it handles the various Ref and other structs we
// need in order to print code later.
let import_records_len = import_records.len();
let output_format = opts.output_format;
let mut ast = js_parser::new_lazy_export_ast(
bump,
Expand All @@ -1219,7 +1308,6 @@ pub mod parse_worker {
b"",
)?
.ok_or(AnyError::ParserError)?;
ast.import_records = bun_alloc::vec_from_iter_in(import_records, bump);

// We're banning import default of html loader files for now.
//
Expand All @@ -1231,23 +1319,8 @@ pub mod parse_worker {
// gave up on figuring out how to fix it so that
// this feature could ship.
ast.has_lazy_export = false;
// Liveness for this synthetic part is seeded in
// `tree_shaking_and_code_splitting` (the per-part bitset
// does not exist at parse time).
ast.parts.as_mut_slice()[1] = Part {
stmts: ast::StoreSlice::EMPTY,
import_record_indices: {
// Generate a single part that depends on all the import records.
// This is to ensure that we generate a JavaScript bundle containing all the user's code.
let mut import_record_indices = ast::PartImportRecordIndices::init_capacity(
import_records_len as usize,
);
import_record_indices
.extend(0..u32::try_from(import_records_len).expect("int cast"));
import_record_indices
},
..Default::default()
};
html_module_parts(&mut ast, &mut import_records, bump, source)?;
ast.import_records = bun_alloc::vec_from_iter_in(import_records, bump);

// Try to avoid generating unnecessary ESM <> CJS wrapper code.
if output_format == js_parser::options::Format::Esm
Expand Down
3 changes: 3 additions & 0 deletions src/bundler/linker_context/convertStmtsForChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ pub(crate) fn convert_stmts_for_chunk(
stmt.loc,
s.namespace_ref,
s.import_record_index,
source_index,
bump,
ast,
)? {
Expand All @@ -122,6 +123,7 @@ pub(crate) fn convert_stmts_for_chunk(
stmt.loc,
s.namespace_ref,
s.import_record_index,
source_index,
bump,
ast,
)? {
Expand Down Expand Up @@ -405,6 +407,7 @@ pub(crate) fn convert_stmts_for_chunk(
stmt.loc,
s.namespace_ref,
s.import_record_index,
source_index,
bump,
ast,
)? {
Expand Down
48 changes: 48 additions & 0 deletions src/bundler/linker_context/postProcessJSChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,54 @@ pub(crate) fn generate_entry_point_tail_js<'a>(
}
}

// An HTML file starts its async scripts where their tags were, without
// awaiting them (`should_remove_import_export_stmt`). The chunk still
// finishes evaluating only once they settle: "await init_foo();"
if c.parse_graph().input_files.items_loader()[source_index as usize]
== options::Loader::Html
{
let meta_flags = c.graph.meta.items_flags();
let wrapper_refs = c.graph.ast.items_wrapper_ref();
for record in ast.import_records.as_slice() {
if record.kind != bun_ast::ImportKind::Stmt
|| !record.source_index.is_valid()
{
continue;
}
let other = record.source_index.get() as usize;
let other_flags = meta_flags[other];
let wrapper_ref = wrapper_refs[other];
if other_flags.wrap != crate::WrapKind::Esm
|| !other_flags.is_async_or_has_async_dependency
|| !c.graph.files_live.is_set(other)
|| wrapper_ref.is_empty()
{
continue;
}
stmts.push(Stmt::alloc(
S::SExpr {
value: Expr::init(
E::Await {
value: Expr::init(
E::Call {
target: Expr::init_identifier(
wrapper_ref,
bun_ast::Loc::EMPTY,
),
..Default::default()
},
bun_ast::Loc::EMPTY,
),
},
bun_ast::Loc::EMPTY,
),
..Default::default()
},
bun_ast::Loc::EMPTY,
));
}
}

let sorted_and_filtered_export_aliases =
&c.graph.meta.items_sorted_and_filtered_export_aliases()
[source_index as usize];
Expand Down
Loading
Loading