Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
53 changes: 51 additions & 2 deletions src/bundler/transpiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,56 @@
}
Ok(())
}

/// Nearest tsconfig.json to `path` (as in `bun build`). Resolver lookup, so JS thread only.
pub fn tsconfig_for_file(&mut self, path: &[u8]) -> Option<&'static TSConfigJSON> {
let dir = Fs::PathName::init(path).dir;
if !bun_paths::is_absolute(dir) {
return None;
}
self.resolver
.read_dir_info(dir)
.ok()
.flatten()?
.enclosing_tsconfig_json

Check warning on line 846 in src/bundler/transpiler.rs

View check run for this annotation

Claude / Claude Code Review

Use read_dir_info_ignore_error helper

nit: `self.resolver.read_dir_info(dir).ok().flatten()?` can be `self.resolver.read_dir_info_ignore_error(dir)?` — the resolver already exposes that helper (resolver.rs:4162) and it's what bake/router use for the same lookup. No behavior difference.
Comment thread
robobun marked this conversation as resolved.
Resolved
}

/// Without a `tsconfig`, the cwd tsconfig values `configure_linker` put in `options` apply.
pub fn tsconfig_parse_options(&self, tsconfig: Option<&TSConfigJSON>) -> TSConfigParseOptions {
match tsconfig {
Some(tsconfig) => {
let mut jsx = tsconfig.merge_jsx(self.options.jsx.clone());
// Explicit NODE_ENV (already in `options.jsx`) outranks tsconfig's dev/prod jsx.
if self.options.production
|| self.options.force_node_env != options::ForceNodeEnv::Unspecified
{
jsx.development = self.options.jsx.development;
}
TSConfigParseOptions {
jsx,
emit_decorator_metadata: tsconfig.emit_decorator_metadata,
experimental_decorators: tsconfig.experimental_decorators,
use_define_for_class_fields: tsconfig
.use_define_for_class_fields
.unwrap_or(true),
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}
None => TSConfigParseOptions {
jsx: self.options.jsx.clone(),
emit_decorator_metadata: self.options.emit_decorator_metadata,
experimental_decorators: self.options.experimental_decorators,
use_define_for_class_fields: self.options.use_define_for_class_fields,
},
}
}
}

/// The [`ParseOptions`] fields a tsconfig.json controls.
pub struct TSConfigParseOptions {
pub jsx: crate::options_impl::jsx::Pragma,
pub emit_decorator_metadata: bool,
pub experimental_decorators: bool,
pub use_define_for_class_fields: bool,
}

// ══════════════════════════════════════════════════════════════════════════
Expand Down Expand Up @@ -976,8 +1026,7 @@

pub path: bun_paths::fs::Path<'static>,
pub loader: options::Loader,
/// `BundleOptions.jsx` — the file-backed `options_impl::jsx::Pragma`, NOT
/// the lib.rs shim. Callers pass `transpiler.options.jsx.clone()`.
/// File-backed `options_impl::jsx::Pragma` (NOT the lib.rs shim), tsconfig already merged in.
pub jsx: crate::options_impl::jsx::Pragma,
pub macro_remappings: MacroRemap,
pub macro_js_ctx: MacroJSCtx,
Expand Down
15 changes: 11 additions & 4 deletions src/jsc/RuntimeTranspilerStore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use bun_js_printer::{self as js_printer, BufferPrinter, BufferWriter};
use bun_paths;
use bun_ptr::BackRef;
use bun_resolve_builtins::{Alias as HardcodedAlias, Cfg as HardcodedAliasCfg};
use bun_resolver::TSConfigJSON;
use bun_resolver::fs as Fs;
use bun_resolver::node_fallbacks;
use bun_resolver::package_json::{MacroMap as MacroRemap, PackageJSON};
Expand Down Expand Up @@ -319,6 +320,7 @@ impl RuntimeTranspilerStore {
referrer: String,
loader: Loader,
package_json: Option<&PackageJSON>,
tsconfig: Option<&'static TSConfigJSON>,
) -> *mut c_void {
// The path text is heap-duplicated here and freed in `reset_for_pool` via
// heap::take on `path.text`.
Expand Down Expand Up @@ -360,6 +362,7 @@ impl RuntimeTranspilerStore {
ticket: None,
log: bun_ast::Log::init(),
loader,
tsconfig,
promise: StrongOptional::create(JSValue::from_cell(promise), global_object),
poll_ref: KeepAlive::default(),
resolved_source,
Expand Down Expand Up @@ -406,6 +409,8 @@ pub struct TranspilerJob {
pub(crate) non_threadsafe_input_specifier: bun_core::String,
pub(crate) non_threadsafe_referrer: bun_core::String,
pub(crate) loader: Loader,
/// Looked up on the JS thread: the worker's transpiler copy must not use the resolver.
pub(crate) tsconfig: Option<&'static TSConfigJSON>,
pub(crate) promise: StrongOptional,
// Note: struct is stored in a HiveArray and crosses to a worker thread;
// raw pointers/BackRefs are used (BACKREF — VM owns the
Expand Down Expand Up @@ -786,6 +791,8 @@ impl TranspilerJob {
_ => ModuleType::Unknown,
};

let tsconfig_options = transpiler.tsconfig_parse_options(self.tsconfig);

let mut parse_options = ParseOptions {
arena: &arena,
path,
Expand All @@ -798,10 +805,10 @@ impl TranspilerJob {
file_fd_ptr: Some(unsafe { &mut *ptr::addr_of_mut!(input_file_fd) }),
macro_remappings,
macro_js_ctx: transpiler::default_macro_js_value(),
jsx: transpiler.options.jsx.clone(),
emit_decorator_metadata: transpiler.options.emit_decorator_metadata,
experimental_decorators: transpiler.options.experimental_decorators,
use_define_for_class_fields: transpiler.options.use_define_for_class_fields,
jsx: tsconfig_options.jsx,
emit_decorator_metadata: tsconfig_options.emit_decorator_metadata,
experimental_decorators: tsconfig_options.experimental_decorators,
use_define_for_class_fields: tsconfig_options.use_define_for_class_fields,
virtual_source: None,
replace_exports: Default::default(),
dont_bundle_twice: true,
Expand Down
3 changes: 2 additions & 1 deletion src/resolver/dir_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ pub struct DirInfo {
// Borrows). Read sites use the `.package_json()` / `.tsconfig_json()` /
// `.package_json_for_dependencies()` accessors.
pub(crate) package_json_for_browser_field: Option<&'static PackageJSON>,
pub(crate) enclosing_tsconfig_json: Option<&'static TSConfigJSON>,
/// Nearest tsconfig.json at or above this directory; `tsconfig_json` is this directory's own.
pub enclosing_tsconfig_json: Option<&'static TSConfigJSON>,

/// package.json used for bundling
/// it's the deepest one in the hierarchy with a "name" field
Expand Down
36 changes: 22 additions & 14 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2475,6 +2475,15 @@ fn transpile_source_code_inner(
_ => ModuleType::Unknown,
};

let tsconfig = match loader {
// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM;
// no borrow of `vm.transpiler` is held across this call.
L::Js | L::Jsx | L::Ts | L::Tsx => unsafe {
(*jsc_vm).transpiler.tsconfig_for_file(path.text)
},
_ => None,
};

let mut input_file_fd = bun_sys::Fd::INVALID;
// The deferred fd close is independent of `give_back_arena`
// and must fire on every exit path: parse failure, JSON early
Expand Down Expand Up @@ -2550,6 +2559,10 @@ fn transpile_source_code_inner(
use bun_bundler::transpiler::{AlreadyBundled, ParseOptions, ParseResult};
use bun_jsc::resolved_source::Tag as ResolvedSourceTag;

// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
let tsconfig_options =
unsafe { &(*jsc_vm).transpiler }.tsconfig_parse_options(tsconfig);

// Keep the one-shot
// `set_break_point_on_first_line()` last so it is only
// consumed when the other conditions hold.
Expand Down Expand Up @@ -2633,20 +2646,10 @@ fn transpile_source_code_inner(
// fresh `&mut` (see Note on `_fd_guard`).
file_fd_ptr: Some(unsafe { &mut *input_file_fd_ptr }),
macro_remappings,
// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
jsx: unsafe { &*jsc_vm }.transpiler.options.jsx.clone(),
// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
emit_decorator_metadata: unsafe {
(*jsc_vm).transpiler.options.emit_decorator_metadata
},
// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
experimental_decorators: unsafe {
(*jsc_vm).transpiler.options.experimental_decorators
},
// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
use_define_for_class_fields: unsafe {
(*jsc_vm).transpiler.options.use_define_for_class_fields
},
jsx: tsconfig_options.jsx,
emit_decorator_metadata: tsconfig_options.emit_decorator_metadata,
experimental_decorators: tsconfig_options.experimental_decorators,
use_define_for_class_fields: tsconfig_options.use_define_for_class_fields,
virtual_source,
dont_bundle_twice: true,
allow_commonjs: true,
Expand Down Expand Up @@ -4327,6 +4330,10 @@ pub unsafe extern "C" fn Bun__transpileFile(
}
}

// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM and
// nothing borrows `vm.transpiler` across this call.
let tsconfig = unsafe { (*jsc_vm).transpiler.tsconfig_for_file(lr.path.text) };

// SAFETY: per fn contract — `jsc_vm` is the live per-thread VM.
// `lr.path` borrows `_specifier`, which the store immediately
// heap-duplicates inside `transpile()`.
Expand All @@ -4339,6 +4346,7 @@ pub unsafe extern "C" fn Bun__transpileFile(
referrer.clone(),
concurrent_loader,
lr.package_json,
tsconfig,
)
};
}
Expand Down
76 changes: 76 additions & 0 deletions test/bundler/transpiler/es-decorators.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import path from "node:path";

// ES standard decorators are used for .js files (always) and for .ts files
// when experimentalDecorators is NOT set in tsconfig.
Expand Down Expand Up @@ -678,6 +679,81 @@ describe("ES Decorators", () => {
expect(stdout).toBe("class Foo\n");
expect(exitCode).toBe(0);
});

// The mode of each file is decided by the tsconfig.json nearest to that
// file, not by the one in the directory bun was launched from. This is what
// tsc and `bun build` do; in a monorepo the packages commonly disagree.
describe("per-file tsconfig", () => {
// Reports how many arguments the method decorator received (legacy: 3,
// standard: 2) and which design:* metadata keys were emitted.
const probe = `
let arity = 0;
const metadata: string[] = [];
(Reflect as any).metadata = (key: string) => (metadata.push(key), () => {});
function dec(...args: unknown[]) {
arity = args.length;
}
class Foo {
@dec
method(a: string) {}
}
export const result = { arity, metadata };
`;
const designKeys = ["design:type", "design:paramtypes", "design:returntype"];
const expected = {
legacy: { arity: 3, metadata: [] },
standard: { arity: 2, metadata: [] },
inherited: { arity: 3, metadata: designKeys },
};
const files = {
"tsconfig.json": JSON.stringify({
compilerOptions: { experimentalDecorators: true, emitDecoratorMetadata: true },
}),
"packages/legacy/tsconfig.json": JSON.stringify({ compilerOptions: { experimentalDecorators: true } }),
"packages/legacy/index.ts": probe,
"packages/standard/tsconfig.json": JSON.stringify({ compilerOptions: {} }),
"packages/standard/index.ts": probe,
// No tsconfig of its own: governed by the root one.
"packages/inherited/index.ts": probe,
"static.ts": `
import { result as legacy } from "./packages/legacy/index.ts";
import { result as standard } from "./packages/standard/index.ts";
import { result as inherited } from "./packages/inherited/index.ts";
console.log(JSON.stringify({ legacy, standard, inherited }));
`,
// Modules imported after startup are transpiled on the thread pool,
// which is a separate code path from the entry point's static imports.
"dynamic.ts": `
await Promise.resolve();
const [legacy, standard, inherited] = await Promise.all(
["legacy", "standard", "inherited"].map(async name => (await import("./packages/" + name + "/index.ts")).result),
);
console.log(JSON.stringify({ legacy, standard, inherited }));
`,
};

for (const entry of ["static.ts", "dynamic.ts"]) {
for (const cwd of [".", "packages/legacy", "packages/standard", "packages/inherited"]) {
test.concurrent(`${entry} run from ${cwd}`, async () => {
using dir = tempDir("es-dec-per-file-tsconfig", files);
await using proc = Bun.spawn({
cmd: [bunExe(), path.join(String(dir), entry)],
env: bunEnv,
cwd: path.join(String(dir), cwd),
stderr: "pipe",
});
const [stdout, rawStderr, exitCode] = await Promise.all([
proc.stdout.text(),
proc.stderr.text(),
proc.exited,
]);
expect(filterStderr(rawStderr)).toBe("");
expect(JSON.parse(stdout)).toEqual(expected);
expect(exitCode).toBe(0);
});
}
}
});
});

describe("extends clause", () => {
Expand Down
Loading
Loading