Skip to content
Closed
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
6 changes: 1 addition & 5 deletions src/base64/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -943,11 +943,7 @@ pub mod zig_base64 {
}

// ──────────────────────────────────────────────────────────────────────────
// LAYERING: hoisted from `bun_css::css_modules::hash` so `bun_bundler` can
// call the *same* implementation without taking a hard dep on `bun_css` (and
// without re-implementing the hash, which would diverge — see review of
// `LinkerContext.rs::css_modules_hash_shim`). `bun_css` re-exports this as
// `css_modules::hash` for its in-crate callers.
// The hash behind CSS module names; `bun_css` wraps it as `css_modules::hash`.
//
// Behavior: wyhash(u64) of the formatted args,
// truncated to u32, url-safe-base64-encoded into a bump-allocated slice. If
Expand Down
29 changes: 7 additions & 22 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2375,30 +2375,15 @@ impl<'a> LinkerContext<'a> {

let source = &all_sources[r#ref.source_index() as usize];

// SAFETY: `Symbol.original_name` is a `*const [u8]` arena
// pointer; valid for the link step.
let original_name: &[u8] = symbol.original_name.slice();
// The hash itself is short-lived; use a scratch bump.
let scratch = ::bun_alloc::Arena::new();
let path_hash = ::bun_base64::wyhash_url_safe(
&scratch,
// use path relative to cwd for determinism
format_args!("{}", bstr::BStr::new(&source.path.pretty)),
false,
);

let mut final_generated_name = Vec::<u8>::new();
use std::io::Write;
write!(
&mut final_generated_name,
"{}_{}",
bstr::BStr::new(original_name),
bstr::BStr::new(path_hash)
)
.expect("infallible: in-memory write");
// The map owns its boxed values (freed with `mangled_props`).
self.mangled_props
.put(r#ref, final_generated_name.into_boxed_slice())
.put(
r#ref,
crate::bun_css::css_modules::local_name(
symbol.original_name.slice(),
source.path.pretty,
),
)
.expect("OOM");
}
}
Expand Down
19 changes: 15 additions & 4 deletions src/bundler/transpiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2856,8 +2856,14 @@ impl<'a> Transpiler<'a> {

let mut file_path = Fs::Path::init(file_path_text);

// Computed the way the bundler computes `Source.path.pretty` (see
// `generic_path_with_pretty_initialized`: forward slashes on every
// platform), because CSS module names are hashed from it.
Comment on lines +2859 to +2861

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

let top_level_dir = self.fs().top_level_dir;
let rel = bun_paths::resolve_path::relative(top_level_dir, file_path_text);
let rel = bun_paths::resolve_path::relative_platform::<
bun_paths::resolve_path::platform::Loose,
false,
>(top_level_dir, file_path_text);
file_path.pretty = crate::linker::dupe(rel);

let mut output_file = options::OutputFile::zero_value();
Expand Down Expand Up @@ -3067,12 +3073,16 @@ impl<'a> Transpiler<'a> {
// `'bump`-threading note).
let alloc: &'static Arena = unsafe { bun_ptr::detach_lifetime_ref::<Arena>(self.arena) };

// Every class/id selector of a CSS module becomes a `LocalCss` symbol
// `Ref` carrying this source index; the printer resolves those through
// the symbol map and local names built below, so the three must agree.
Comment on lines +3076 to +3078

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

let source_index = bun_ast::Index::RUNTIME;
let (mut sheet, extra) = match bun_css::StyleSheet::<bun_css::DefaultAtRule>::parse(
alloc,
entry.contents(),
opts,
None,
bun_ast::Index::INVALID,
source_index,
) {
Ok(v) => v,
Err(e) => {
Expand All @@ -3092,7 +3102,8 @@ impl<'a> Transpiler<'a> {
);
return None;
}
let symbols = bun_ast::symbol::Map::init_list(Default::default());
let local_names = sheet.local_names(source_index, file_path_pretty);
let symbols = bun_ast::symbol::Map::init_with_one_list(extra.symbols);
let result = match sheet.to_css(
alloc,
&bun_css::PrinterOptions {
Expand All @@ -3101,7 +3112,7 @@ impl<'a> Transpiler<'a> {
..bun_css::PrinterOptions::default()
},
None,
None,
Some(&local_names),
&symbols,
) {
Ok(v) => v,
Expand Down
13 changes: 8 additions & 5 deletions src/css/css_modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,12 +453,15 @@ impl<'a> CssModuleReference<'a> {
}
}

/// LAYERING: canonical implementation lives in `bun_base64::wyhash_url_safe`
/// (a leaf crate) so `bun_bundler::LinkerContext::mangle_local_css` can call
/// the *same* hasher without depending on `bun_css`. Re-export here so
/// in-crate callers (`dependencies.rs`, `rules/import.rs`) keep the
/// `css_modules::hash` path.
#[inline]
pub(crate) fn hash<'a>(bump: &'a Bump, args: Arguments<'_>, at_start: bool) -> &'a [u8] {
bun_base64::wyhash_url_safe(bump, args, at_start)
}

/// The printed name of a CSS module's local (class or id): `<local>_<hash of path>`,
/// `path` being the sheet's project-relative path (`Source.path.pretty` in the bundler).
Comment on lines +461 to +462

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub fn local_name(local: &[u8], path: &[u8]) -> Box<[u8]> {
let scratch = Bump::new();
let path_hash = hash(&scratch, format_args!("{}", bstr::BStr::new(path)), false);
[local, b"_", path_hash].concat().into_boxed_slice()
}
14 changes: 14 additions & 0 deletions src/css/css_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2555,6 +2555,20 @@ mod stylesheet_impl {
return Ok(ToCssResult { code: dest });
}

/// The `local_names` for printing this sheet outside a bundle (the bundler
/// builds the whole graph's in `LinkerContext::mangle_local_css`).
/// `source_index` must be the one the sheet was parsed with: the refs embed it.
Comment on lines +2558 to +2560

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub fn local_names(&self, source_index: SrcIndex, path: &[u8]) -> LocalsResultsMap {
let mut local_names = LocalsResultsMap::default();
for (local, entry) in self.local_scope.iter() {
local_names.insert(
entry.ref_.to_real_ref(source_index.get()),
css_modules::local_name(local, path),
);
}
local_names
}

pub fn parse(
arena: &'static Bump,
code: &[u8],
Expand Down
36 changes: 21 additions & 15 deletions src/css_jsc/css_internals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ pub(crate) enum TestCategory {
ParserOptions,
}

/// The path `css_modules` test sheets are named as if they were read from.
const CSS_MODULE_FILENAME: &[u8] = b"test.module.css";

// These test-only wrappers are consumed as plain safe fns through
// `dispatch_js2native.rs` re-exports, so they don't use the
// `#[bun_jsc::host_fn]` C-ABI shim.
Expand Down Expand Up @@ -92,8 +95,8 @@ fn testing_impl(
) -> JsResult<JSValue> {
use bun_ast::ImportRecord;
use bun_css::{
DefaultAtRule, ImportRecordHandler, LocalsResultsMap, MinifyOptions, ParserOptions,
PrinterOptions, StyleSheet,
DefaultAtRule, ImportRecordHandler, MinifyOptions, ParserOptions, PrinterOptions,
StyleSheet,
};
use bun_jsc::{LogJsc as _, StringJsc as _};

Expand Down Expand Up @@ -167,12 +170,14 @@ fn testing_impl(
};

let mut import_records = Vec::<ImportRecord>::default();
// Index 0, where `init_with_one_list` below puts the symbols.
let source_index = bun_ast::Index::RUNTIME;
match StyleSheet::<DefaultAtRule>::parse(
alloc,
source.slice(),
parser_options,
Some(&mut import_records),
bun_ast::Index::INVALID,
source_index,
) {
Ok(ret) => {
let (mut stylesheet, extra) = ret;
Expand All @@ -187,8 +192,8 @@ fn testing_impl(
}
}

let symbols = bun_ast::symbol::Map::init_list(Default::default());
let local_names = LocalsResultsMap::default();
let local_names = stylesheet.local_names(source_index, CSS_MODULE_FILENAME);
let symbols = bun_ast::symbol::Map::init_with_one_list(extra.symbols);
let result = match stylesheet.to_css(
alloc,
&PrinterOptions {
Expand Down Expand Up @@ -255,16 +260,17 @@ fn parser_options_from_js(
}
}

// if (try jsobj.getTruthy(globalThis, "css_modules")) |val| {
// opts.css_modules = bun.css.css_modules.Config{
//
// };
// if (val.isObject()) {
// if (try val.getTruthy(globalThis, "pure")) |pure_val| {
// opts.css_modules.pure = pure_val.toBoolean();
// }
// }
// }
if let Some(val) = jsobj
.get_truthy(global, b"css_modules")?
.filter(|val| val.to_boolean())
{
// Bun has no `pure` mode; a test asking for it must not silently run without it.
if val.is_object() && val.get_boolean_loose(global, b"pure")? == Some(true) {
return Err(global.throw(format_args!("css_modules.pure is not supported")));
}
opts.filename = CSS_MODULE_FILENAME;
opts.css_modules = Some(bun_css::css_modules::Config::default());
}

Ok(())
}
Expand Down
83 changes: 83 additions & 0 deletions test/bundler/css/css-modules.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import { itBundled } from "../expectBundled";

describe("css", () => {
Expand Down Expand Up @@ -213,3 +215,84 @@ describe("css", () => {
},
});
});

// `bun build --no-bundle` prints each entry point on its own without going
// through the linker, so it has to scope the locals of a `.module.css` file
// itself. It used to crash on the first class or id selector instead.
describe.concurrent("css-module --no-bundle", () => {
const stylesheet = /* css */ `
.foo { color: red }
#bar { color: blue }
.foo .baz { color: green }
:global(.keep) .foo { color: green }
.btn { composes: foo; padding: 0 }
@keyframes spin { to { opacity: 1 } }
.spinner { animation: spin 1s }
`;

async function build(cwd: string, ...args: string[]) {
await using proc = Bun.spawn({
cmd: [bunExe(), "build", ...args],
env: bunEnv,
cwd,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
return stdout;
}

test("scopes classes, ids and keyframes", async () => {
using dir = tempDir("css-module-no-bundle", { "styles.module.css": stylesheet });

expect(await build(String(dir), "--no-bundle", "styles.module.css")).toMatchInlineSnapshot(`
".foo_-MSaAA {
color: red;
}

#bar_-MSaAA {
color: #00f;
}

.foo_-MSaAA .baz_-MSaAA {
color: green;
}

.keep .foo_-MSaAA {
color: green;
}

.btn_-MSaAA {
padding: 0;
}

@keyframes spin_-MSaAA {
to {
opacity: 1;
}
}

.spinner_-MSaAA {
animation: 1s spin_-MSaAA;
}
"
`);
});

// The class and id names hash the file's path relative to the cwd, so a
// file in a subdirectory gets different names than one at the top level,
// and `bun build --no-bundle` has to agree with `bun build` on both.
test.each(["styles.module.css", "nested/deep.module.css"])(
"prints the same names as bun build for %s",
async entry => {
using dir = tempDir("css-module-no-bundle-parity", { [entry]: stylesheet });

const bundled = await build(String(dir), entry);
const header = `/* ${entry} */\n`;
expect(bundled).toStartWith(header);
expect(await build(String(dir), "--no-bundle", entry)).toBe(bundled.slice(header.length));
},
);
});
Loading
Loading