Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
143 changes: 111 additions & 32 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,38 +34,41 @@ 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
}
// A leading `//` is a protocol-relative URL, not a rooted path; leave it for the
// resolver's own `starts_with("//")` external rule.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 +106,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 +172,77 @@ impl<'a> HTMLProcessorHandler for HTMLScanner<'a> {

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

/// Walks an HTML `srcset` attribute yielding `(url, descriptor)` per candidate,
/// per the WHATWG image-candidate-string grammar. The scan and rewrite passes
/// both drive this so their 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 comma.
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;
while desc_end < self.rest.len() && self.rest[desc_end] != b',' {
desc_end += 1;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
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
80 changes: 72 additions & 8 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
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,21 @@ 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
// A CSS importer will inline the file as a data: URI; any other
// importer (JS, HTML, ...) needs the asset emitted on disk, so
// treat every non-CSS reference as a copy-forcing context.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 @@ -4169,6 +4172,67 @@ pub mod bv2_impl {
}
}

// Distinct-content collisions on the same output path are last-writer-wins on
// disk; surface them as the same hard error the chunk pass emits. Identical
// content mapping to one path is benign and left alone.
Comment thread
robobun marked this conversation as resolved.
Resolved
{
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 _ = writeln!(
&mut msg,
" from input {}",
bstr::BStr::new(additional_output_files[j].src_path.text)
);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
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