Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 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
150 changes: 116 additions & 34 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,40 +32,40 @@ impl<'a> HTMLScanner<'a> {

impl<'a> HTMLScanner<'a> {
fn create_import_record(&mut self, input_path: &[u8], kind: ImportKind) -> Result<(), Error> {
// In HTML, sometimes people do /src/index.js
// In that case, we don't want to use the absolute filesystem path, we want to use the path relative to the project root
let path_to_use: &[u8] = if input_path.len() > 1 && input_path[0] == b'/' {
resolve_path::join_abs_string::<platform::Auto>(
fs::FileSystem::instance().top_level_dir,
&[&input_path[1..]],
)
}
// Check if imports to (e.g) "App.tsx" are actually relative imoprts w/o the "./"
else if input_path.len() > 2 && input_path[0] != b'.' && input_path[1] != b'/' {
'blk: {
let Some(index_of_dot) = input_path.iter().rposition(|&b| b == b'.') else {
break 'blk input_path;
};
let ext = &input_path[index_of_dot..];
if ext.len() > 4 {
break 'blk input_path;
}
// /foo/bar/index.html -> /foo/bar
let dirname = resolve_path::dirname::<platform::Auto>(self.source.path.text());
if dirname.is_empty() {
break 'blk input_path;
}
let resolved =
resolve_path::join_abs_string_z::<platform::Auto>(dirname, &[input_path]);
if sys::exists_z(resolved) {
resolved.as_bytes()
} else {
input_path
}
// `/src/x.js` is project-root-relative; `//host/x.js` is protocol-relative (external).
let path_to_use: &[u8] =
if input_path.len() > 1 && input_path[0] == b'/' && input_path[1] != b'/' {
resolve_path::join_abs_string::<platform::Auto>(
fs::FileSystem::instance().top_level_dir,
&[&input_path[1..]],
)
}
} else {
input_path
};
// Check if imports to (e.g) "App.tsx" are actually relative imoprts w/o the "./"
else if input_path.len() > 2 && input_path[0] != b'.' && input_path[1] != b'/' {
'blk: {
let Some(index_of_dot) = input_path.iter().rposition(|&b| b == b'.') else {
break 'blk input_path;
};
let ext = &input_path[index_of_dot..];
if ext.len() > 4 {
break 'blk input_path;
}
// /foo/bar/index.html -> /foo/bar
let dirname = resolve_path::dirname::<platform::Auto>(self.source.path.text());
if dirname.is_empty() {
break 'blk input_path;
}
let resolved =
resolve_path::join_abs_string_z::<platform::Auto>(dirname, &[input_path]);
if sys::exists_z(resolved) {
resolved.as_bytes()
} else {
input_path
}
}
} else {
input_path
};

let owned: &'static [u8] =
Box::leak(AstAlloc::vec_from_slice(path_to_use).into_boxed_slice());
Expand Down Expand Up @@ -103,7 +103,12 @@ impl<'a> HTMLScanner<'a> {
url_attribute: &[u8],
kind: ImportKind,
) {
let _ = url_attribute;
if url_attribute == b"srcset" {
for (url, _) in SrcSetIter::new(path) {
let _ = self.create_import_record(url, kind);
}
return;
}
let _ = self.create_import_record(path, kind);
}

Expand Down Expand Up @@ -164,6 +169,83 @@ impl<'a> HTMLProcessorHandler for HTMLScanner<'a> {

pub(crate) struct HTMLProcessor<T, const VISIT_DOCUMENT_TAGS: bool>(PhantomData<T>);

/// Yields `(url, descriptor)` per `srcset` candidate; scan and rewrite both
/// use this so their per-candidate import-record counts stay 1:1.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) struct SrcSetIter<'a> {
rest: &'a [u8],
}

impl<'a> SrcSetIter<'a> {
pub(crate) fn new(value: &'a [u8]) -> Self {
Self { rest: value }
}

#[inline]
fn is_ascii_ws(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0C)
}
}

impl<'a> Iterator for SrcSetIter<'a> {
/// `(url, descriptor)`; `descriptor` is `b""` when absent.
type Item = (&'a [u8], &'a [u8]);

fn next(&mut self) -> Option<Self::Item> {
// Skip leading whitespace and commas.
let mut i = 0;
while i < self.rest.len() && (Self::is_ascii_ws(self.rest[i]) || self.rest[i] == b',') {
i += 1;
}
self.rest = &self.rest[i..];
if self.rest.is_empty() {
return None;
}
// URL runs until whitespace.
let mut url_end = 0;
while url_end < self.rest.len() && !Self::is_ascii_ws(self.rest[url_end]) {
url_end += 1;
}
// Per spec, trailing commas terminate the candidate (they are not part of the URL).
let mut url_trim = url_end;
while url_trim > 0 && self.rest[url_trim - 1] == b',' {
url_trim -= 1;
}
let url = &self.rest[..url_trim];
// If the URL itself ended in a comma there is no descriptor.
if url_trim < url_end {
self.rest = &self.rest[url_end..];
return Some((url, b""));
}
// Descriptor runs until the next top-level comma (a comma inside `(...)` is part of the descriptor).
let mut desc_start = url_end;
while desc_start < self.rest.len() && Self::is_ascii_ws(self.rest[desc_start]) {
desc_start += 1;
}
let mut desc_end = desc_start;
let mut depth: u32 = 0;
while desc_end < self.rest.len() {
match self.rest[desc_end] {
b',' if depth == 0 => break,
b'(' => depth += 1,
b')' => depth = depth.saturating_sub(1),
_ => {}
}
desc_end += 1;
}
let mut desc_trim = desc_end;
while desc_trim > desc_start && Self::is_ascii_ws(self.rest[desc_trim - 1]) {
desc_trim -= 1;
}
let descriptor = &self.rest[desc_start..desc_trim];
self.rest = if desc_end < self.rest.len() {
&self.rest[desc_end + 1..]
} else {
&self.rest[desc_end..]
};
Some((url, descriptor))
}
}

#[derive(Clone, Copy)]
pub struct TagHandler {
/// CSS selector to match elements
Expand Down
86 changes: 75 additions & 11 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1643,7 +1643,7 @@ pub mod bv2_impl {
pub scb_bitset: Option<DynamicBitSetUnmanaged>,
pub scb_list: server_component_boundary::Slice<'a>,

/// Files which are imported by JS and inlined in CSS
/// Files inlined in CSS and also imported by a non-CSS source (JS, HTML)
pub additional_files_imported_by_js_and_inlined_in_css: &'a mut DynamicBitSetUnmanaged,
/// Files which are imported by CSS and inlined in CSS
pub additional_files_imported_by_css_and_inlined: &'a mut DynamicBitSetUnmanaged,
Expand Down Expand Up @@ -1744,7 +1744,6 @@ pub mod bv2_impl {
}
}

let is_js = self.all_loaders[source_index.get() as usize].is_javascript_like();
let is_css = self.all_loaders[source_index.get() as usize].is_css();

let import_record_list_id = source_index;
Expand Down Expand Up @@ -1795,17 +1794,19 @@ pub mod bv2_impl {
let import_record = &self.all_import_records
[import_record_list_id.get() as usize]
.as_slice()[ir_idx];
// Mark if the file is imported by JS and its URL is inlined for CSS
// CSS inlines as data:; any non-CSS importer (JS, HTML) forces on-disk emission.
let is_inlined = import_record.source_index.is_valid()
&& !self.all_urls_for_css
[import_record.source_index.get() as usize]
.is_empty();
if is_js && is_inlined {
self.additional_files_imported_by_js_and_inlined_in_css
.set(import_record.source_index.get() as usize);
} else if is_css && is_inlined {
self.additional_files_imported_by_css_and_inlined
.set(import_record.source_index.get() as usize);
if is_inlined {
if is_css {
self.additional_files_imported_by_css_and_inlined
.set(import_record.source_index.get() as usize);
} else {
self.additional_files_imported_by_js_and_inlined_in_css
.set(import_record.source_index.get() as usize);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

let next_source = import_record.source_index;
Expand Down Expand Up @@ -1976,8 +1977,7 @@ pub mod bv2_impl {
let content_hashes: &mut [u64] = input_files_cols.content_hash_for_additional_file;
for (index, url_for_css) in all_urls_for_css.iter().enumerate() {
if !url_for_css.is_empty() {
// We like to inline additional files in CSS if they fit a size threshold
// If we do inline a file in CSS, and it is not imported by JS, then we don't need to copy the additional file into the output directory
// A file inlined in CSS and not imported by any non-CSS source needn't be copied to the output directory.
if additional_files_imported_by_css_and_inlined.is_set(index)
&& !additional_files_imported_by_js_and_inlined_in_css.is_set(index)
{
Expand Down Expand Up @@ -4169,6 +4169,70 @@ pub mod bv2_impl {
}
}

// Distinct-content asset collisions on one output path are a hard error; identical content is benign.
{
let mut seen: bun_collections::StringHashMap<(u64, usize)> =
bun_collections::StringHashMap::default();
let mut duplicates: bun_collections::StringArrayHashMap<Vec<usize>> =
bun_collections::StringArrayHashMap::default();
for (i, out) in additional_output_files.iter().enumerate() {
let gop = seen.get_or_put(&out.dest_path)?;
if !gop.found_existing {
*gop.value_ptr = (out.hash, i);
continue;
}
let (prev_hash, prev_i) = *gop.value_ptr;
if prev_hash == out.hash {
continue;
}
let dup = duplicates.get_or_put(&out.dest_path)?;
if !dup.found_existing {
dup.value_ptr.push(prev_i);
}
dup.value_ptr.push(i);
}
if duplicates.count() > 0 {
let mut msg: Vec<u8> = Vec::new();
let _ = writeln!(&mut msg, "Multiple files share the same output path");
for (path, indices) in duplicates.keys().iter().zip(duplicates.values()) {
let _ = writeln!(&mut msg, " {}:", bstr::BStr::new(path));
for &j in indices {
let pretty: &[u8] = additional_output_files[j]
.source_index
.get()
.map(|i| sources[i.get() as usize].path.pretty)
.unwrap_or(additional_output_files[j].src_path.text);
let _ = writeln!(
&mut msg,
" from input {}",
bstr::BStr::new(pretty)
);
}
}
self.transpiler
.log_mut()
.add_error(None, bun_ast::Loc::EMPTY, msg);
let template = &self.transpiler.options.asset_naming;
if !template.is_empty() {
let mut note: Vec<u8> = Vec::new();
let _ = write!(
&mut note,
"asset naming is '{}', consider adding '[hash]' to make filenames unique",
bstr::BStr::new(template),
);
self.transpiler.log_mut().add_msg(bun_ast::Msg {
kind: bun_ast::Kind::Note,
data: bun_ast::Data {
text: std::borrow::Cow::Owned(note),
..Default::default()
},
..Default::default()
});
}
return Err(Error::DuplicateOutputPath);
}
}

self.graph.additional_output_files = additional_output_files;
}
Ok(())
Expand Down
Loading
Loading