Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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>` hint.
/// Unresolved hrefs pass through untouched.
Comment thread
robobun marked this conversation as resolved.
Resolved
const WAS_HTML_RESOURCE_HINT = 1 << 7;

/// 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
14 changes: 13 additions & 1 deletion src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6273,6 +6273,15 @@ pub mod bv2_impl {
&& (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;
}
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 Expand Up @@ -6359,7 +6368,10 @@ pub mod bv2_impl {
&& !resolved_loader.should_copy_for_bundling()
&& !resolved_loader.is_javascript_like()
&& !resolved_loader.is_css()
&& resolved_loader != Loader::Html
&& (resolved_loader != Loader::Html
|| import_record
.flags
.contains(bun_ast::ImportRecordFlags::WAS_HTML_RESOURCE_HINT))
Comment on lines 6368 to +6374

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The new as='fetch' / rel='prefetch' selectors feed .json/.toml/.txt targets into the pre-existing ImportKind::Url → Loader::File override, and because the HTML entry's records are resolved first, the target is registered in path_to_source_index_map with loader=File before any JS module's imports are seen. A later import data from './data.json' in bundled JS then reuses that slot and gets the emitted path string instead of the parsed object — a silent runtime regression vs main, where these tags weren't matched at all. The PR already handled this exact class for .js (2bd81d6, covered by the "not pinned to a file loader" assertion in html/link-preload-prefetch) and for .html (5d17bb2); JSON/TOML/text is the remaining sibling.

Extended reasoning...

What the bug is

The four new TagHandler::hint selectors (link[as='fetch'|'track'|'document'|'embed'|'object'], link[as='script'], link[rel='modulepreload'], link[rel='prefetch']) all use ImportKind::Url. When such a hint targets a file whose extension maps to a non-JS/CSS/HTML/should-copy loader — .json→Json, .toml→Toml, .txt→Text, etc. — the pre-existing override at bundle_v2.rs:6366-6377 fires (loader == Html && kind == Url && !should_copy && !is_js && !is_css) and forces import_record_loader = Loader::File. That forced loader flows into resolve_task.loader at line 6434, and process_resolve_queue then registers the path in path_to_source_index_map (line 6499) with new_input_file.loader = File (line 6527) — first-wins.

If a bundled JS module later does import data from './data.json', its import-record resolution hits the already-populated map entry at line 6386, sets source_index to the File-loaded slot at line 6391, and continues. The File loader's default export is the emitted path string, so data is "./data-<hash>.json" instead of the parsed {k:1} object.

Why it's a regression introduced by this PR

The override at 6366-6377 itself is unchanged from main (only the Html clause at 6371-6374 changed). What's new is that this PR adds selectors that feed it: on main, no TAG_HANDLERS entry matches as='fetch' or rel='prefetch', so a ./data.json referenced by such a hint is never scanned, and the file is reached only via main.js's import → Loader::Json → parsed object. After this PR the hint record is created during index.html's scan, resolved and enqueued in the same synchronous process_resolve_queue pass that schedules main.js's ParseTask, so it always wins the map slot.

The pre-existing rel='manifest' selector could technically hit the same override, but overlapping a manifest with a JS static import is implausible. as='fetch' and rel='prefetch' are specifically intended for data files, which developers do sometimes also statically import (e.g. <link rel="prefetch" href="./config.json"> for a future page + a lazy chunk that does import cfg from './config.json').

Step-by-step proof

<!-- index.html -->
<head>
  <link rel="preload" as="fetch" href="./data.json" crossorigin>
</head>
<body><script type="module" src="./main.js"></script></body>
// main.js
import data from "./data.json";
console.log(data.k);
// data.json
{"k":1}
  1. Scan — HTMLScanner matches link[as='fetch'][href] → import record with kind=Url, loader=None, WAS_HTML_RESOURCE_HINT|HANDLES_IMPORT_ERRORS. Separately matches script[src] → record for ./main.js.
  2. Resolve index.html's records (bundle_v2.rs:6356): for ./data.json, resolved_loader = Loader::Json (from extension). Json.should_copy_for_bundling() is false (loader.rs:114-123), Json.is_javascript_like() is false, Json.is_css() is false, Json != Html → override fires → import_record_loader = Loader::File. Line 6434: resolve_task.loader = Some(File).
  3. process_resolve_queue (same synchronous drain): line 6483 reads value.loader = Some(File); line 6499 map.get_or_put("…/data.json") inserts; line 6527 new_input_file.loader = File; line 6534 writes source_index into the map; line 6569 schedules the File ParseTask. In the same loop iteration, ./main.js is scheduled with Loader::Js — its own import records won't be resolved until its ParseTask completes on a later drain.
  4. Resolve main.js's records (later): for ./data.json, line 6386 path_to_source_index_map.get(path) returns the existing id → line 6391 import_record.source_index = existing → continue. The record's loader is set to Json at line 6380, but that's on the record; the input-file slot's loader stays File and the already-scheduled File ParseTask has emitted the path-string default export.
  5. Runtime: console.log(data.k) logs undefined (data is the string "./data-<hash>.json"). On main it logs 1.

Why existing code doesn't prevent it

  • The is_javascript_like() exclusion at line 6369 (which lets 2bd81d6's fix work for modulepreloaded .js) doesn't cover Loader::Json/Toml/Text.
  • The WAS_HTML_RESOURCE_HINT clause added at line 6374 only affects resolved_loader == Html.
  • path_to_source_index_map is first-wins by design; there's no reconciliation when a later import wants a different loader.
  • None of the three new tests cover a hint target that is also statically imported from JS with a data loader — html/link-preload-prefetch's data.json is reached only via the hint, and its dep.js overlap case exercises the .js sibling that 2bd81d6 already fixed.

Impact

Silent behavioral change: a JSON/TOML/text import that returned a parsed value on main now returns a path string, with no build error or warning. Per REVIEW.md's whole-class rule, the PR already fixed two siblings of this exact first-wins interaction (.js targets in 2bd81d6 — the test even comments "It must be bundled as JS (not pinned to a file loader), so `import { x } from './dep.js'` resolves" — and .html targets in 5d17bb2); JSON/TOML/text is the remaining member of the class the new selectors expose.

How to fix

Either exclude data loaders from the override the same way JS/CSS are excluded (but then a hint-only .json wouldn't be emitted as a raw asset, so that's wrong on its own), or — more targeted — when WAS_HTML_RESOURCE_HINT is set and the target already exists in path_to_source_index_map with a non-File loader, reuse that slot instead of forcing File; conversely, if the JS import arrives second, the fix needs the hint record to not pin the input-file loader. The simplest correct shape is probably: for hint records whose resolved_loader is a data loader (Json/Toml/Text/etc.), keep the native loader on the input_file slot (so a JS import gets the parsed object) and separately emit the raw bytes as an additional file for the href rewrite — mirroring what should_copy_for_bundling loaders already do. A regression test in html/link-preload-prefetch adding import data from './data.json' to main.js and asserting jsContent contains the JSON's value would pin it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified. This is the JSON/TOML/text sibling of the first-wins loader-pinning interaction the PR already documents under Trade-off for JS targets, and it is triggered by the pre-existing Url->File override (unchanged from main except for the Html clause). Fixing it correctly (so a hint-only .json is emitted as a raw asset AND a hint-plus-JS-import .json gives a parsed object) requires deferring hint-only ParseTasks until the graph is complete, same as the JS case. I have added it to the Trade-off section in the PR description rather than expanding the loader-pinning workarounds further. The trigger (both <link rel=preload as=fetch href=./data.json> and import data from './data.json' for the same file) is unusual: preload-as-fetch is for fetch() calls, and a static import is bundled so there is nothing to preload.

Comment thread
robobun marked this conversation as resolved.
Resolved
{
break 'brk Loader::File;
}
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
137 changes: 137 additions & 0 deletions test/bundler/bundler_html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1011,4 +1011,141 @@ 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"');
},
});

// A resource hint targeting a local .html file must be emitted as a raw asset,
// not parsed as a nested HTML entry (which would pull its scripts into the
// entry chunk).
itBundled("html/link-hint-local-html", {
outdir: "out/",
files: {
"/index.html": `
<!DOCTYPE html>
<html>
<head>
<link rel="prefetch" href="./page2.html">
<link rel="preload" as="document" href="./frame.html">
</head>
<body><h1>Index</h1></body>
</html>`,
"/page2.html": `<!doctype html><script src="./page2-script.js"></script><h1>Page 2</h1>`,
"/frame.html": `<!doctype html><h1>Frame</h1>`,
"/page2-script.js": `console.log("PAGE2_SCRIPT");`,
},
entryPoints: ["/index.html"],
onAfterBundle(api) {
const html = api.readFile("out/index.html");
expect(html).not.toContain('href="./page2.html"');
expect(html).not.toContain('href="./frame.html"');
expect(html).toMatch(/<link rel="prefetch" href="[^"]*page2-[a-z0-9]+\.html">/);
expect(html).toMatch(/<link rel="preload" as="document" href="[^"]*frame-[a-z0-9]+\.html">/);

// page2.html's <script> must not leak into index.html's entry chunk.
const js = html.match(/src="(?:\.\/|\/)?(index-[a-z0-9]+\.js)"/);
if (js) expect(api.readFile("out/" + js[1])).not.toContain("PAGE2_SCRIPT");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const page2 = html.match(/href="(?:\.\/|\/)?(page2-[a-z0-9]+\.html)"/);
expect(page2).not.toBeNull();
api.expectFile("out/" + page2![1]).toContain("<h1>Page 2</h1>");
},
});

// 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