Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
4 changes: 4 additions & 0 deletions src/ast/import_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ bitflags::bitflags! {
/// calling the "__reExport()" helper function
const CALLS_RUNTIME_RE_EXPORT_FN = 1 << 6;

/// Came from an HTML `<link rel=prefetch|modulepreload|preload as=script>`.
/// Fetch-only: emit as a raw asset, tolerate unresolved hrefs.
Comment thread
robobun marked this conversation as resolved.
Resolved
const WAS_HTML_RESOURCE_HINT = 1 << 7;
Comment thread
robobun marked this conversation as resolved.
Resolved

/// If true, this was originally written as a bare "import 'file'" statement
const WAS_ORIGINALLY_BARE_IMPORT = 1 << 8;

Expand Down
76 changes: 43 additions & 33 deletions src/bundler/HTMLScanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ impl<'a> HTMLScanner<'a> {
}

impl<'a> HTMLScanner<'a> {
fn create_import_record(&mut self, input_path: &[u8], kind: ImportKind) -> Result<(), Error> {
fn create_import_record(
&mut self,
input_path: &[u8],
kind: ImportKind,
is_resource_hint: bool,
) -> Result<(), Error> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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'/' {
Expand Down Expand Up @@ -69,6 +74,11 @@ impl<'a> HTMLScanner<'a> {

let owned: &'static [u8] =
Box::leak(AstAlloc::vec_from_slice(path_to_use).into_boxed_slice());
let mut flags = ImportRecordFlags::default();
if is_resource_hint {
flags.insert(ImportRecordFlags::WAS_HTML_RESOURCE_HINT);
flags.insert(ImportRecordFlags::HANDLES_IMPORT_ERRORS);
}
let record = ImportRecord {
path: FsPath::init(owned),
kind,
Expand All @@ -77,7 +87,7 @@ impl<'a> HTMLScanner<'a> {
loader: None,
source_index: AstIndex::default(),
original_path: b"",
flags: ImportRecordFlags::default(),
flags,
};

self.import_records.push(record);
Expand All @@ -96,15 +106,8 @@ impl<'a> HTMLScanner<'a> {
.add_error(Some(self.source), Loc::EMPTY, message.to_vec());
}

pub(crate) fn on_tag(
&mut self,
_element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
) {
let _ = url_attribute;
let _ = self.create_import_record(path, kind);
pub(crate) fn on_tag(&mut self, _element: &mut Element<'_, '_>, path: &[u8], tag: TagHandler) {
let _ = self.create_import_record(path, tag.kind, tag.is_resource_hint);
}

pub(crate) fn scan(&mut self, input: &[u8]) -> Result<(), Error> {
Expand All @@ -120,13 +123,7 @@ type Processor<'a> = HTMLProcessor<HTMLScanner<'a>, false>;

/// Trait capturing the methods `HTMLProcessor` calls on `T`.
pub(crate) trait HTMLProcessorHandler {
fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
);
fn on_tag(&mut self, element: &mut Element<'_, '_>, path: &[u8], tag: TagHandler);
fn on_write_html(&mut self, bytes: &[u8]);
fn on_html_parse_error(&mut self, message: &[u8]);

Expand All @@ -145,14 +142,8 @@ pub(crate) trait HTMLProcessorHandler {
}

impl<'a> HTMLProcessorHandler for HTMLScanner<'a> {
fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
path: &[u8],
url_attribute: &[u8],
kind: ImportKind,
) {
HTMLScanner::on_tag(self, element, path, url_attribute, kind)
fn on_tag(&mut self, element: &mut Element<'_, '_>, path: &[u8], tag: TagHandler) {
HTMLScanner::on_tag(self, element, path, tag)
}
fn on_write_html(&mut self, bytes: &[u8]) {
HTMLScanner::on_write_html(self, bytes)
Expand All @@ -172,6 +163,8 @@ pub struct TagHandler {
pub url_attribute: &'static str,
/// The kind of import to create
pub kind: ImportKind,
/// Sets `ImportRecordFlags::WAS_HTML_RESOURCE_HINT` on the record.
pub is_resource_hint: bool,
}

impl TagHandler {
Expand All @@ -180,11 +173,21 @@ impl TagHandler {
selector,
url_attribute,
kind,
is_resource_hint: false,
}
}

const fn hint(selector: &'static str, url_attribute: &'static str, kind: ImportKind) -> Self {
Self {
selector,
url_attribute,
kind,
is_resource_hint: true,
}
}
}

pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
pub(crate) const TAG_HANDLERS: [TagHandler; 20] = [
// Module scripts with src
TagHandler::new("script[src]", "src", ImportKind::Stmt),
// CSS Stylesheets
Expand Down Expand Up @@ -215,6 +218,18 @@ pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [
"href",
ImportKind::Url,
),
// Generic preload targets (fetch/track/document/embed/object)
TagHandler::hint(
"link[as='fetch'][href], link[as='track'][href], link[as='document'][href], link[as='embed'][href], link[as='object'][href]",
"href",
ImportKind::Url,
),
// Preloaded scripts (<link rel="preload" as="script">)
TagHandler::hint("link[as='script'][href]", "href", ImportKind::Url),
// Module preloads (<link rel="modulepreload">)
TagHandler::hint("link[rel='modulepreload'][href]", "href", ImportKind::Url),
// Prefetch hints (<link rel="prefetch">)
TagHandler::hint("link[rel='prefetch'][href]", "href", ImportKind::Url),
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
// Images with src
TagHandler::new("img[src]", "src", ImportKind::Url),
// Images with srcset
Expand Down Expand Up @@ -289,12 +304,7 @@ impl<T: HTMLProcessorHandler, const VISIT_DOCUMENT_TAGS: bool>
// which is not reborrowed while the rewriter — the only
// holder of these closures — is alive.
unsafe {
(*this_ptr).on_tag(
element,
value.as_bytes(),
tag_info.url_attribute.as_bytes(),
tag_info.kind,
);
(*this_ptr).on_tag(element, value.as_bytes(), tag_info);
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6273,6 +6273,15 @@
&& (import_record.loader.is_none()
|| import_record.loader.unwrap() == Loader::Html)
{
if import_record
.flags
.contains(bun_ast::ImportRecordFlags::WAS_HTML_RESOURCE_HINT)
{
// <link rel="prefetch" href="./page2.html"> and similar
// hints are fetch-only; leave the href untouched.
Comment thread
robobun marked this conversation as resolved.
Resolved
import_record.path.is_disabled = true;
continue 'outer;
}

Check failure on line 6284 in src/bundler/bundle_v2.rs

View check run for this annotation

Claude / Claude Code Review

Dev-server hint carve-outs (bundle_v2.rs:6276-6284, generateCompileResultForHtmlChunk.rs:167-168) ship without any automated test

The two dev-server hunks added in 20de21f — the `WAS_HTML_RESOURCE_HINT` carve-out at `bundle_v2.rs:6276-6284` and the `is_resource_hint && path.is_disabled` pass-through at `generateCompileResultForHtmlChunk.rs:167-168` — are both gated on `dev_server.is_some()` and are unreachable from `itBundled`, so neither is exercised by any test in this PR (deleting either keeps the whole suite green). Per REVIEW.md, every behavioral change ships an automated test in the same PR and each load-bearing clau
Comment thread
robobun marked this conversation as resolved.
Resolved
// This use case is currently not supported. This error
// blocks an assertion failure because the DevServer
// reserves the HTML file's spot in IncrementalGraph for the
Expand Down
19 changes: 10 additions & 9 deletions src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use crate::mal_prelude::*;
use bstr::BStr;

use bun_ast::Log;
use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags};
use bun_ast::{ImportRecord, ImportRecordFlags};
use bun_core::strings;
use bun_threading::thread_pool::Task as ThreadPoolLibTask;
use lol_html::HandlerResult;
use lol_html::html_content::{ContentType, Element, EndTag};

use crate::HTMLScanner::{HTMLProcessor, HTMLProcessorHandler};
use crate::HTMLScanner::{HTMLProcessor, HTMLProcessorHandler, TagHandler};
use crate::linker_context_mod::{GenerateChunkCtx, LinkerContext, debug};
use crate::options::Loader;
use crate::{Chunk, CompileResult};
Expand Down Expand Up @@ -118,13 +118,8 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
));
}

fn on_tag(
&mut self,
element: &mut Element<'_, '_>,
_path: &[u8],
url_attribute: &[u8],
_kind: ImportKind,
) {
fn on_tag(&mut self, element: &mut Element<'_, '_>, _path: &[u8], tag: TagHandler) {
let url_attribute = tag.url_attribute.as_bytes();
if self.current_import_record_index as usize >= self.import_records.len() {
bun_core::Output::panic(format_args!(
"Assertion failure in HTMLLoader.onTag: current_import_record_index ({}) >= import_records.len ({})",
Expand Down Expand Up @@ -162,9 +157,15 @@ impl<'a> HTMLProcessorHandler for HTMLLoader<'a> {
return;
}

let is_resource_hint = import_record
.flags
.contains(ImportRecordFlags::WAS_HTML_RESOURCE_HINT);

if self.linker.dev_server.is_some() {
if !unique_key_for_additional_files.is_empty() {
set_attribute(element, url_attribute, unique_key_for_additional_files);
} else if is_resource_hint && import_record.path.is_disabled {
// Unresolved hint href: pass through untouched.
} else if import_record.path.is_disabled
|| loader.is_javascript_like()
|| loader.is_css()
Expand Down
100 changes: 100 additions & 0 deletions test/bundler/bundler_html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1011,4 +1011,104 @@ body {
expect(htmlContent).toMatch(/href=".*\.webmanifest"/);
},
});

// <link rel="prefetch">, <link rel="modulepreload"> and <link rel="preload"> with
// as={script,fetch,track,document,embed,object} must not ship dangling source-path
// hrefs. Non-code targets are emitted + hashed; JS/CSS targets are bundled and
// the hint tag is dropped (nothing separate to preload once bundled).
itBundled("html/link-preload-prefetch", {
outdir: "out/",
files: {
"/index.html": `
<!DOCTYPE html>
<html>
<head>
<link rel="prefetch" href="./hero.png">
<link rel="modulepreload" href="./dep.js">
<link rel="preload" as="script" href="./preloaded.js">
<link rel="preload" as="fetch" href="./data.json" crossorigin>
<link rel="preload" as="track" href="./captions.vtt">
</head>
<body>
<img src="./hero.png">
<script type="module" src="./main.js"></script>
</body>
</html>`,
"/main.js": `import { x } from "./dep.js"; console.log("main", x);`,
"/dep.js": `export const x = 42; console.log("dep");`,
"/preloaded.js": `console.log("preloaded");`,
"/hero.png": "PNG",
"/data.json": `{"k":1}`,
"/captions.vtt": "WEBVTT",
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
entryPoints: ["/index.html"],
onAfterBundle(api) {
const html = api.readFile("out/index.html");

// No raw source paths should survive in the output; every one of these
// would have been a guaranteed 404 before.
expect(html).not.toContain('href="./hero.png"');
expect(html).not.toContain('href="./dep.js"');
expect(html).not.toContain('href="./preloaded.js"');
expect(html).not.toContain('href="./data.json"');
expect(html).not.toContain('href="./captions.vtt"');

// prefetch / preload of non-code assets: copied + hashed and href rewritten.
expect(html).toMatch(/<link rel="prefetch" href="[^"]*hero-[a-z0-9]+\.png">/);
expect(html).toMatch(/<link rel="preload" as="fetch" href="[^"]*data-[a-z0-9]+\.json" crossorigin>/);
expect(html).toMatch(/<link rel="preload" as="track" href="[^"]*captions-[a-z0-9]+\.vtt">/);

// JS hints are bundled and the hint tag is dropped.
expect(html).not.toMatch(/rel="modulepreload"/);
expect(html).not.toMatch(/as="script"/);

const hero = html.match(/href="(?:\.\/|\/)?(hero-[a-z0-9]+\.png)"/);
const data = html.match(/href="(?:\.\/|\/)?(data-[a-z0-9]+\.json)"/);
const vtt = html.match(/href="(?:\.\/|\/)?(captions-[a-z0-9]+\.vtt)"/);
expect(hero).not.toBeNull();
expect(data).not.toBeNull();
expect(vtt).not.toBeNull();
api.expectFile("out/" + hero![1]).toBe("PNG");
api.expectFile("out/" + data![1]).toBe(`{"k":1}`);
api.expectFile("out/" + vtt![1]).toBe("WEBVTT");

// modulepreload of a transitive dep: dep.js is reached via both the hint
// and main.js's import. It must be bundled as JS (not pinned to a file
// loader), so `import { x } from "./dep.js"` resolves.
const js = html.match(/src="(?:\.\/|\/)?(index-[a-z0-9]+\.js)"/);
expect(js).not.toBeNull();
const jsContent = api.readFile("out/" + js![1]);
expect(jsContent).toContain('"main"');
expect(jsContent).toContain('"dep"');
expect(jsContent).toContain('"preloaded"');
},
});

// Resource-hint hrefs that do not resolve to a local file (navigation routes,
// API endpoints, external URLs) pass through untouched instead of failing the
// build.
itBundled("html/link-hint-unresolved", {
outdir: "out/",
files: {
"/index.html": `
<!DOCTYPE html>
<html>
<head>
<link rel="prefetch" href="/dashboard">
<link rel="preload" as="fetch" href="/api/user" crossorigin>
<link rel="preload" as="document" href="/settings">
<link rel="modulepreload" href="https://cdn.example.com/lib.js">
</head>
<body></body>
</html>`,
},
entryPoints: ["/index.html"],
onAfterBundle(api) {
const html = api.readFile("out/index.html");
expect(html).toContain('<link rel="prefetch" href="/dashboard">');
expect(html).toContain('<link rel="preload" as="fetch" href="/api/user" crossorigin>');
expect(html).toContain('<link rel="preload" as="document" href="/settings">');
expect(html).toContain('<link rel="modulepreload" href="https://cdn.example.com/lib.js">');
},
});
});
Loading