Skip to content
Merged
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
85 changes: 80 additions & 5 deletions crates/rolldown_common/src/file_emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ pub struct FileEmitter {
options: Arc<NormalizedBundlerOptions>,
/// Mark the files that have been emitted to bundle.
emitted_files: FxDashSet<ArcStr>,
/// Source hashes of the files that have been flushed to a bundle, keyed by reference id.
/// The emitter is reused across dev-mode rebuilds, so a file that is re-emitted with
/// different content must be flushed again (see `insert_new_file`).
emitted_file_source_hashes: FxDashMap<ArcStr, ArcStr>,
emitted_chunks: FxDashMap<ArcStr, ArcStr>,
emitted_filenames: FxDashSet<ArcStr>,
/// Maps module IDs to their emitted file reference IDs.
Expand All @@ -109,6 +113,7 @@ impl FileEmitter {
is_build_phase: AtomicBool::new(false),
options,
emitted_files: DashSet::default(),
emitted_file_source_hashes: DashMap::default(),
emitted_filenames: FxDashSet::default(),
module_to_file_ref: DashMap::default(),
}
Expand Down Expand Up @@ -329,6 +334,16 @@ impl FileEmitter {
sanitized_file_name: Option<ArcStr>,
) -> anyhow::Result<()> {
self.generate_file_name(file, hash, asset_filename_template, sanitized_file_name)?;
// The emitter is reused across dev-mode rebuilds. If this asset was already flushed
// to a bundle but is now re-emitted with different content, mark it dirty so that
// `add_additional_files` flushes it again instead of dropping the update.
if self
.emitted_file_source_hashes
.get(&reference_id)
.is_some_and(|flushed_hash| &*flushed_hash != hash)
{
self.emitted_files.remove(&reference_id);
}
self.files.insert(
reference_id,
OutputAsset {
Expand All @@ -355,13 +370,24 @@ impl FileEmitter {
}
self.emitted_files.insert(key.clone());

// Follow rollup using lowercase filename to check conflicts
let lowercase_filename = value.filename.as_str().to_lowercase().into();
if !self.emitted_filenames.insert(lowercase_filename) {
warnings
.push(BuildDiagnostic::filename_conflict(value.filename.clone()).with_severity_warning());
// Follow rollup using lowercase filename to check conflicts. Only checked on the
// first flush: a re-flush after the content changed (dev-mode rebuild, see
// `insert_new_file`) reuses the same filename, which is not a conflict.
if !self.emitted_file_source_hashes.contains_key(key) {
let lowercase_filename = value.filename.as_str().to_lowercase().into();
if !self.emitted_filenames.insert(lowercase_filename) {
warnings.push(
BuildDiagnostic::filename_conflict(value.filename.clone()).with_severity_warning(),
);
}
}

// Record the hash of the flushed source, so that a re-emission with unchanged
// content stays deduplicated and a changed one is flushed again.
let source_hash: ArcStr =
xxhash_with_base(value.source.as_bytes(), self.options.hash_characters.base()).into();
self.emitted_file_source_hashes.insert(key.clone(), source_hash);

let mut names = std::mem::take(&mut value.names);
names.sort_unstable_by(|a, b| (a.len(), a).cmp(&(b.len(), b)));

Expand Down Expand Up @@ -451,6 +477,7 @@ impl FileEmitter {
self.base_reference_id.store(0, Ordering::Relaxed);
self.is_build_phase.store(false, Ordering::Relaxed);
self.emitted_files.clear();
self.emitted_file_source_hashes.clear();
self.emitted_chunks.clear();
self.emitted_filenames.clear();
self.module_to_file_ref.clear();
Expand Down Expand Up @@ -485,4 +512,52 @@ mod tests {
assert_eq!(emitter.assign_reference_id(Some(ArcStr::from(name))).len(), 22, "name={name:?}");
}
}

/// The emitter is reused across dev-mode rebuilds. An asset re-emitted with changed
/// content must be flushed again (previously it was silently dropped after the first
/// flush, which broke consumers serving emitted assets, e.g. Vite's bundled dev server).
#[test]
fn reemitted_asset_with_changed_content_is_flushed_again() {
let emitter = FileEmitter::new(Arc::new(NormalizedBundlerOptions::default()));
let emit = |source: &str| {
emitter
.emit_file(
EmittedAsset {
file_name: Some(ArcStr::from("entry.html")),
source: StrOrBytes::from(source.to_string()),
..Default::default()
},
None,
None,
)
.unwrap()
};
let flushed_source = |bundle: &[Output]| match &bundle[0] {
Output::Asset(asset) => String::from_utf8(asset.source.as_bytes().to_vec()).unwrap(),
Output::Chunk(_) => panic!("expected an asset"),
};

let mut bundle = Vec::new();
let mut warnings = Vec::new();

emit("v1");
emitter.add_additional_files(&mut bundle, &mut warnings);
assert_eq!(bundle.len(), 1);
assert_eq!(flushed_source(&bundle), "v1");
assert!(warnings.is_empty());
bundle.clear();

// Re-emitted with unchanged content: stays deduplicated.
emit("v1");
emitter.add_additional_files(&mut bundle, &mut warnings);
assert!(bundle.is_empty());
assert!(warnings.is_empty());

// Re-emitted with changed content: flushed again, without a filename conflict warning.
emit("v2");
emitter.add_additional_files(&mut bundle, &mut warnings);
assert_eq!(bundle.len(), 1);
assert_eq!(flushed_source(&bundle), "v2");
assert!(warnings.is_empty());
}
}
67 changes: 66 additions & 1 deletion packages/rolldown/tests/dev/dev-watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getDevWatchOptionsForCi } from '@rolldown/test-dev-server';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import type { InputOptions, OutputOptions } from 'rolldown';
import type { InputOptions, OutputOptions, RolldownOutput } from 'rolldown';
import type { DevEngine, DevOptions } from 'rolldown/experimental';
import { dev as _dev } from 'rolldown/experimental';
import { sleep } from 'rolldown-tests/utils';
Expand Down Expand Up @@ -353,6 +353,71 @@ function createTestInputAndOutput(testLabel: string, retryCount: number) {
return { input, outputDir, dir };
}

test.concurrent(
'dev re-emitted asset with changed content is included in rebuild output',
{ retry: TEST_RETRY, timeout: TEST_TIMEOUT },
async ({ task, expect, onTestFinished }) => {
const retryCount = task.result?.retryCount ?? 0;
const { input, outputDir, dir } = createTestInputAndOutput('dev-reemit-asset', retryCount);

const outputs: RolldownOutput[] = [];
const findAsset = (output: RolldownOutput) =>
output.output.find(
(o): o is Extract<typeof o, { type: 'asset' }> =>
o.type === 'asset' && o.fileName === 'extra.html',
);

const engine = await dev(
{
input,
experimental: { devMode: true },
plugins: [
{
name: 'emit-asset',
generateBundle() {
// Re-emit the same fileName on every build; its content changes
// whenever the input module is edited.
this.emitFile({
type: 'asset',
fileName: 'extra.html',
source: `<script>${fs.readFileSync(input, 'utf8')}</script>`,
});
},
},
],
},
{ dir: outputDir },
{
onOutput: (result) => {
if (!(result instanceof Error)) {
outputs.push(result);
}
},
},
);
onTestFinished(async () => {
await engine.close();
if (!process.env.CI) {
fs.rmSync(dir, { recursive: true, force: true });
}
});

await engine.run();
await expect.poll(() => outputs.length).toBeGreaterThan(0);
expect(findAsset(outputs.at(-1)!)?.source).toContain('console.log(1)');

outputs.length = 0;
await editFile(input, 'console.log(2)');
await expect
.poll(async () => {
await engine.ensureLatestBuildOutput();
const output = outputs.at(-1);
return output ? findAsset(output)?.source : undefined;
})
.toContain('console.log(2)');
},
);

function createTestWithMultiFiles(
testLabel: string,
retryCount: number,
Expand Down
Loading