You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
bun build --dts: write index.aot.ts without the // @bun line of its bundle - #48425
bun run --aot fails on a package from bun build --dts --target=bun: SyntaxError: Unexpected token ':'. Expected a ')' or a ',' after a parameter declaration. at dist/index.aot.ts:3.
Transfer::finish (src/sema/driver/typed_files.rs:3981) copies the bundle's first line, // @bun, into index.aot.ts. With it the runtime runs TypeScript as written (src/js_parser/parse/parse_entry.rs:942).
Fix
Transfer::finish, which writes every .aot.ts file, leaves // @bun out and keeps the line break. The line also meant "ES module", so a bundle with no export ends with export {};.
If export {}; adds a type error, Bun writes the files without it, unless they pass only with it.
On Windows the type check saw no file: a native path join broke its keys.
// @bun starts a bundle for Bun. The runtime skips the transpiler, for .ts files too (bun-pragma/fail/ts-with-pragma.ts).
index.aot.ts is index.js with its types put back. bun run --aot reads it through the "aot" condition.
Bun type checks the .aot.ts files of a build. export {}; makes what a file with no import or export declares local.
Considered: a reader rule for aot packages keeps the false line. Three rules that predict where export {}; is safe failed.
Downsides
bun compile and bun test --aot compile a target-bun .aot.ts file as transpiled TypeScript. A class used above its declaration works there and throws in index.js.
On Windows too, .aot.ts files with a type error are now left out. Without export {};, a .aot.ts file in a "type": "commonjs" package loads as CommonJS.
Release text of the two bun_sema crates: +1,766 bytes. A two-file build whose check runs twice executes 32% more instructions (debug build).
Notes
Repro
# lib/src/index.ts: export function add(a: number, b: number): number { return a + b; }cd lib && bun build ./src/index.ts --dts --target=bun --outdir dist
# copy dist to app/node_modules/pkg/dist, with this package.json:# {"name":"pkg","type":"module","exports":{".":{"aot":"./dist/index.aot.ts","types":"./dist/index.d.ts","default":"./dist/index.js"}}}# app/main.ts: import { add } from "pkg"; console.log(add(1, 2));cd ../app && bun run --aot ./main.ts
Command
main
this branch
bun run ./main.ts
3
3
bun run --aot ./main.ts
SyntaxError, exit 1
3
bun --aot ./main.ts
SyntaxError, exit 1
3
bun --conditions=aot run ./main.ts
SyntaxError, exit 1
3
bun test --aot, bun check --aot, bun build --compile --aot
pass
pass
No issue reports this. It was found by a probe of --dts with --target=bun.
The failure can be silent. On main, a typed file whose only TypeScript is new Set<Point>([new Point]).size runs as JavaScript under bun run --aot. It prints count = false with exit code 0, where bun run prints count = 1.
The file, before and after
// @bun (empty line)
// src/index.ts // src/index.ts
function add(a: number, b: number): number { function add(a: number, b: number): number {
The line break stays, so the second line of the bundle does not become the first line of the typed file. That second line can be a banner or the path comment of a source. Both readers take a first line that only begins with // @bun for the line.
The line arrives in four ways.--target=bun, target: "bun" in Bun.build, an entry point that starts with #!/usr/bin/env bun with any target (src/bundler/ParseTask.rs:2396), and a banner that is the line itself (--banner="// @bun") with any target. With a hashbang the line is the second line. The typed file keeps the hashbang.
When export {}; is added
The two conditions are: the bundle starts with the line, and the bundle has no export statement. An import does not count as an export. A file that names module and has an import is CommonJS for the runtime, and an export makes it an ES module. The line decides, not the target: a build without the line gives the bytes of main.
The clause has two effects.
Run time. In a package with "type": "commonjs", a typed file with no export loads as CommonJS. Its index.js is an ES module because of the line.
The type check of the build. --dts type checks the .aot.ts files before it writes them. A file with no import and no export is a script there, and its top-level names are global. The clause makes them local. For a name from a module that is what the source says. For a name from a script it is not: interface Window { greeter: string } then declares a second interface, and a var is no longer a property of window.
Where export {}; adds an error
If the first pass of the check reports an error with the clause, typed_files_for_build (src/runtime/cli/check_command/typed_files.rs) runs the writer again without the clause, and checks that text too. It is the text of main without the seven bytes. The two texts are the same up to the last line, so the build compares their errors by file, offset and code.
The clause adds no error: the clause stays. The check of the typed files does not read the declaration files of the project. A console or a BUILD that a .d.ts file declares is a missing name with and without the clause, and such an error does not count here (row 12). If the text with the clause fails, the warning names its first error. That is not always the error that main names: the clause can remove an earlier one. With a top-level await in front of an error that both texts have, main names TS1375 and this branch names the other error.
The clause adds an error, and the text without it passes: that text is written. It is the text of main (rows 1, 2 and 10).
The clause adds an error, and only the text with it passes: the clause stays (row 11).
The clause adds an error, and both texts fail: the warning names the first error of the text without the clause, as on main.
"An error" is any error of the first pass, also one that does not count against the files. Two kinds do not count. The verdict drops some (TS7017, TS2304). And the check repairs a parameter that has no type: it writes : any and runs again (TS7006). With the clause, globalThis.list.map((n) => n + 1) on a script's var list has both kinds, and the second commit wrote that file with (n: any) and the clause. Now it has the text of main.
The second run is for the whole build: the typed files are one program for the check, and an error does not say which file the clause is wrong in.
The check on Windows
On Windows the check of the typed files saw none of them, on main too. The build said nothing where the other platforms warn, and test/cli/compile/compile-library.test.ts had its --splitting test of that check set aside there. So the second run of this PR never started on Windows.
typed_files_for_build gave the texts to the checker through already_read. That function is for paths of the bundler: it joins each one to the working directory as a native path. The paths of the typed files are in the checker's format, /C:/dir/out/index.aot.ts, and the Windows join makes C:\C:\dir\out\index.aot.ts of that. The checker then found no typed file and reported TS6053 for each, which the verdict drops. The two calls in typed_files_for_build now key the texts by their checker paths. On the other platforms the keys are the same as before.
The --splitting test runs on Windows again. This machine has no Windows, so CI is the proof of this part. At ec34547208, on Windows x64 and on Windows aarch64, test/bundler/bun-build-api-dts.test.ts has 19 pass and test/cli/compile/compile-library.test.ts passes.
Builds with --dts. The bundle in each row has no export:
Sources
main, every target
this branch, with the line
1. An entry point that is a script with interface Window { greeter: string } and window.greeter = "hi"
.aot.ts written
written, no clause
2. A module entry point that imports that script
written
written, no clause
3. A module with top-level await
left out, TS1375
written, with the clause
4. Two modules that bundle the same ./join
left out, TS2393
written, with the clause
5. A module with top-level const name
left out, TS2451
written, with the clause
6. A module that imports a module with declare global
left out, TS2669
written, with the clause
7. A JavaScript entry point beside a TypeScript one
written
written, with the clause
8. A chunk of --splitting with no export
written
written, with the clause
9. A module that imports a script with var order, which no code reads as a global
written
written, with the clause
10. A script with var list and globalThis.list.map((n) => n + 1)
written
written, no clause, the text of main
11. A module with top-level await that imports the script of row 10
left out, TS1375
written, with the clause and (n: any)
12. A module that reads a name from a .d.ts file of the project: console.log(BUILD.length)
written
written, with the clause
Without the line this branch gives the column "main" in every row. Rows 3 to 6 are a fault of the typed file check that exists for every build. This change does not repair it for a bundle without the line, because the output of such a build must stay byte for byte the same here.
The clause had three other forms in this PR. The first commit tied it to the entry point: a module entry point that bundles the script of row 2 lost every .aot.ts file (TS2339), and the files of rows 7 and 8 loaded as CommonJS. The next two forms tied it to the scripts among the sources. A self-review and an independent check of the PR found a counterexample to each rule for what a script declares. Now the type check decides.
The model changes for a target-bun typed file
The ahead-of-time compiler reads the line too (find_transpiled_mark, src/sema/hir/runtime_syntax.rs:283). With the line it compiles the file as the engine runs it. Without the line it compiles the file as Bun transpiles it. One difference is that Bun moves a class with no side effects to the start of a file that it transpiles.
A library whose top-level code makes an instance of a class that is declared below, built with bun compile --library --target=bun:
Reader
main
this branch
bun run (index.js)
ReferenceError
ReferenceError
bun run --aot
SyntaxError
prints the value
bun test --aot
ReferenceError
prints the value
bun build --compile --aot executable
ReferenceError
prints the value
The same library built with the default target prints the value in all four rows on main. So the three --aot readers now agree with each other and with the other targets.
An entry point with a hashbang for Bun, no export, in a "type": "commonjs" package: cli.js and cli.aot.ts are both ES modules under all four readers on this branch. On main bun run --aot fails with the SyntaxError.
Costs, measured
What
main
this branch
Release objects of bun_sema and bun_sema_driver, text column of size (main af566a38e5)
9,780,467
9,782,233 (+1,766)
Release bun, text column of size, at the first commit (main 2596ac5d39)
137,930,427
137,931,195 (+768)
has_bun_pragma (nm -S, release)
353 bytes
353 bytes
Lines changed in src/js_parser, src/bundler, src/resolver, src/jsc, src/aot
0
Lines changed in src/runtime
45 added and 19 removed, in the --dts command (cli/check_command/typed_files.rs)
index.aot.ts of the repro, --target=bun
105 bytes
98 bytes
index.js and index.d.ts of the repro, both targets
identical
Calls of find_transpiled_mark for each typed file
0
1
Allocator calls in Transfer::finish, repro
2 allocations, 5 frees
the same
Instructions in Transfer::finish, debug build, no line
65,385
67,546
The same, --target=bun
65,391
71,959
The same, --target=bun, module entry point with no export
63,298
74,373
Instructions in add_types, release build, no line, 5 runs
268,351 to 269,478
268,499 to 269,413
The same, --target=bun
269,164 to 270,210
269,234 to 270,354
Runs of the writer and of the check, where the first pass of the check reports no error
the same as main
Runs of the writer and of the check, where the first pass reports an error, also one that does not count, and a typed file has export {};
1 more of each
User-mode instructions of bun build --dts for a package of two small files with such an error, debug build, median of 15 runs
22.49 billion (one check: this branch with --target=node, which has no line)
29.83 billion (+32.7%)
The first row is cargo build --release -p bun_sema_driver at both commits, with no link step. It does not have the lines in bun_runtime: that crate builds only in a full build. The check of the binary size in CI reported +0.0 KB for each Linux and macOS target at the first commit, +0.5 KB for Windows x64 and -2.5 KB for Windows aarch64. The instruction counts are from the first commit. The later commits change one condition in Transfer::finish.
Instructions are user-mode instructions of the calling thread between entry and return (perf_event_open, read under gdb). In the release build the difference is below the spread of the runs. A build without --dts does not reach these functions.
The last row counts every thread of the process (perf_event_open with inherit). Its sources have the error of row 12, so the clause stays and the check runs two times. The runs of one build spread by about 4%: 21.77 to 23.55 billion with one check, 28.40 to 30.93 billion with two. The same sources without the error cost 22.20 billion with --target=bun and 22.11 billion with --target=node (median of 5), so the target alone makes no difference. No release build with --dts was at hand, so the number is from a debug build.
A typed file that the runtime loads under the "aot" condition is now transpiled like any TypeScript file. Against the file with the line, which the runtime handed to the engine as it was: +28 allocator calls, +29 arena calls and +8 to +21 system calls for each load (gdb, entry to return of TranspilerJob::run, debug build). A typed file of 121 KB gets one entry in the transpiler cache on the first run and uses it on the second. The file with the line got none.
Builds that never had the line
6 fixtures, 4 sets of flags (none, --minify-syntax, --minify-whitespace, --splitting) and 3 targets: 72 builds on main and 72 on this branch, at the first commit.
40 builds have no line. Every output file is byte for byte the same.
32 builds have the line. index.js and the .d.ts files are the same. 41 .aot.ts files are the text of main without the seven bytes, and 12 of them also end with export {};.
The second commit changes only which typed files of a bundle with the line end with export {};. A test now pins that a bundle without the line gets nothing.
Tests run on a debug build
test/bundler/bun-build-api-dts.test.ts (21 pass) and test/aot/library-typed-file.test.ts (8 pass). 15 of them are new. Two of the 15 pin what does not change: a bundle without the line, and the warning for files that have one error with export {}; and another without it. The 8 tests of the first commit were run against a debug build of main and failed there.
The two outcomes of the second check that a review asked tests for, each with the condition changed in a debug build. Without the exception for files that pass only with export {};, the test of row 11 fails: the build warns with TS1375. With the text without export {}; taken only where it passes, the test of the two errors fails: the warning names TS2339.
cargo test -p bun_sema --lib the_mark_alone: the table test of find_transpiled_mark_alone passes.
test/cli/compile/compile-library.test.ts: 56 pass, with the --splitting test of the check among them. The test that runs tsc two times needs 57 to 60 seconds of its 60 on a debug build, on main too.
test/aot/library-from-npm.test.ts (39 pass) and test/cli/compile/compile-library-ecosystem.test.ts (51 pass). In each, one test that compiles a CommonJS package with --aot fails in some runs: the debug build aborts there under the address sanitizer, inside the ahead-of-time compiler. It did that on a debug build of main too, and those packages have no // @bun line.
Not run here: Windows. The fix of the check on Windows is from the code and from a run of the Windows path join on Linux, which gives C:\C:\dir\out\index.aot.ts for /C:/dir/out/index.aot.ts. CI ran it on Windows (see "The check on Windows").
cargo clippy -p bun_sema -p bun_sema_driver: clean at the second commit. The later commits change bun_runtime only, and cargo clippy -p bun_runtime is clean.
The new tests of the writer are in the Bun.build file, where a build runs in the test process. The tests with bun run --aot use bun compile --library --target=bun, which runs the same build as bun build --dts.
Not fixed here
A first line that only begins with // @bun, for example a banner // @bundled by acme or the path comment // @bunx/index.ts, with no line above it. Both readers test a bare prefix (parse_entry.rs:2704, runtime_syntax.rs:293), so a typed file and a hand-written .ts file with such a first line both fail, with any target. The readers own this. js_parser: stop the // @bun keyword scan at the end of the pragma line #46122 names it as not done, and a review comment on fix(lexer): do not treat '#bun' in a url as a pragma #15888 says that the match needs a space or a tab after the word.
Where the clause stays, what a script among the sources declares is local to the typed file. The check of the build sees the typed files only. A file outside the build that reads such a name as a global finds it no longer. To declare a global in a module, use declare global { } (row 6).
Where only the clause lets the files pass, they are written with what the clause costs (row 11).
Where the second run writes the files, they have no export {};. With "type": "commonjs" in the package they load as CommonJS, and their index.js is an ES module. With "type": "module" and with no "type" both are ES modules.
A bundle with no export and without the line: the .aot.ts files are left out as on main (rows 3 to 6 of the table).
With --sourcemap=linked the typed file still ends with the //# debugId= and //# sourceMappingURL=index.js.map lines of the bundle.
A file with the line that an older build wrote fails with the SyntaxError and two notes about source maps. The notes name the wrong cause. The remedy is a new build of the package. No release has --dts.
Reviews
A self-review of the first form of this change found three faults. The clause was tied to the line alone, so a script entry point that adds to a global interface lost every .aot.ts file of the build (TS2339). An import stopped the clause, but an import does not make a file an ES module where the file names module. An empty line in front of a first line that only begins like the line worked around the readers for one writer, and its test pinned that.
A code review of the PR found that a JavaScript entry point got no clause. A second self-review weighed the rules for the clause, found a counterexample to each of the three, and named a second run of the check as the sound form. This form has no rule and has the second run.
A code review of the second commit found that the second run never started on Windows. An independent check of that commit found the (n: any) of row 10. The next form started the second run on any error and then wrote the text without the clause. A code review and an independent check found that a name from a declaration file of the project then cost the clause (row 12). This form compares the errors of the two texts. A code review of this form asked for a test of each of its two other outcomes, and an independent check found that this text named the wrong error for one case of the warning. Both are in.
Not taken, with the reason:
export {}; for every target. It changes the output of builds that never had the line, and it is a fix for a different fault (rows 3 to 6 of the table).
declare global { } around what a script declares, in the typed file. It changes the typed text of script sources for every target, so it is a change of its own in the same writer.
A second run that keeps the clause in some files of the build. An error of the check does not say which file the clause is wrong in.
A signal for the ahead-of-time compiler that a typed file has the text of a bundle that ran as written. bun run --aot transpiles the same file, so the compiler would then differ from it.
allowUmdGlobalAccess for the check of the typed files. A read of a UMD global fails with the clause (TS2686), and the second run already writes those files.
The cut of the inherited source map comments. A separate change in the same writer.
A check of the typed text with the runtime's own test of the line. It belongs with the word-end rule of the readers.
Other open PRs in these files
A trial merge of this head (09940276b3) with the head of each open PR that changes these files gives this:
#33859 stops the line for a hashbang entry point with another target. The hashbang test here passes target: "bun", so it holds with and without that change.
no test proof · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/aot/library-typed-file.test.ts
…bundle
A bundle for Bun starts with the line `// @bun`. The runtime then runs
the file as it is written, as an ES module. The .aot.ts file is that
bundle with its types put back, so it carried the line too, and
`bun run --aot` handed TypeScript to the engine.
The writer now leaves the seven bytes out and keeps the line break, so
the line below does not move up. Where the entry point is a module and
the bundle has no export statement, the .aot.ts file ends with
`export {};`: it is then an ES module for the runtime and for the type
check of the build, as the line made the bundle one.
Status: ready for review. No CI failure is in code that this PR changes. A maintainer has to review and merge it.
How it was reproduced (debug build of main 2596ac5d39, because no release has --dts):
bun build ./src/index.ts --dts --target=bun --outdir dist writes dist/index.aot.ts. Its first line is // @bun.
An app imports the package through the "aot" condition of exports.
bun run --aot ./main.ts fails with SyntaxError: Unexpected token ':'. Expected a ')' or a ',' after a parameter declaration. at dist/index.aot.ts:3.
On this branch the same commands print 3.
CI:
Build 139974 at e52f68652a, an empty commit that ran CI again: 184 jobs passed. The four darwin x64 - test-bun jobs got no agent and expired. They are in the queue again.
Build 139880 at 09940276b3, the same code: 187 jobs passed, three of them on darwin x64. The fourth darwin x64 job failed on test/aot/parallel/node-http/the-handle-of-a-response-is-deleted-behind-a-write.cjs. The compiled program did not print client ECONNRESET where plain Bun printed it. This PR does not change that code.
test/bundler/bun-build-api-dts.test.ts has 21 pass on Windows x64, Windows aarch64, Linux x64, Linux aarch64 and the Linux ASAN build (build 139880).
The other tests that failed in the two builds passed on a retry. None is in a file that this PR changes.
No actionable comments were generated in the recent review.
Walkthrough
Typed-file generation removes an isolated // @bun mark from .aot.ts output. It can append export {}; when requested and no export declaration exists. The CLI retries typed-file checking without empty exports under specified conditions. Tests cover output variants and AOT execution.
Typed-file generation removes an isolated // @bun mark and can append export {}; when requested and the output has no export declaration. Tests and documentation cover the output behavior.
Retry checking without empty exports src/runtime/cli/check_command/typed_files.rs
The CLI requests empty exports for typed-file builds. If the initial check is not clean and the build added empty exports, it retries without them and can adopt the rebuilt result based on the check reports.
Tests cover AOT execution across run modes and a TypeScript file with a later-declared class. The incompatible .aot.ts compile test now runs on Windows as well as other platforms.
Possibly related PRs
oven-sh/bun#47627: Both changes update source-text inputs used to check generated .aot.ts files.
Suggested reviewers: jarred-sumner
Merge Risk: Minimal · up to e52f6
Merge Risk:⚪ Minimal · up to e52f6
No concrete issue remains that should block merging after normal checks.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title clearly identifies the main change: bun build --dts writes index.aot.ts without the bundle’s // @bun line.
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description clearly explains the problem, the implementation, the trade-offs, and extensive verification results. It does not use the template headings exactly, but it contains the required inform…
Full details: Description check
Explanation
The description clearly explains the problem, the implementation, the trade-offs, and extensive verification results. It does not use the template headings exactly, but it contains the required information for what the PR does and how it was verified.
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Reviewing files that changed from the base of the PR and between 362819b and 0994027.
Files selected for processing: 4
docs/bundler/index.mdx
src/runtime/cli/check_command/typed_files.rs
test/bundler/bun-build-api-dts.test.ts
test/cli/compile/compile-library.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline findings, I also checked the Insertions::apply -> apply_without refactor for the existing 0..0 call: the empty prefix append adds no separator byte (text is still empty) and offset.max(0) is a no-op, so non-bun output is byte-identical; the clamp only matters for an insertion offset inside the cut mark, where the old at..offset slice would have panicked. find_transpiled_mark_alone correctly leaves // @ bun @ bun-cjs, // @ bun @ bytecode and // @ bundled-style banners alone. No tests were run in this review.
Extended reasoning...
The change touches the typed-file writer in src/sema/driver/typed_files.rs, a new mark helper in src/sema/hir/runtime_syntax.rs, and bundler/aot tests; it touches no security-sensitive surface. The refactor and the mark matcher were checked by reading and found behavior-preserving for existing paths.
…xport {}`
A bundle that starts with `// @bun` and has no export gets `export {}`
at the end of its .aot.ts file, so that Bun still takes the file for an
ES module. The entry point decided that: a module entry point got it.
- A JavaScript entry point and a chunk without an export got none. In a
package with "type": "commonjs" their .aot.ts files loaded as
CommonJS, and their bundles are ES modules.
- A module entry point that bundles a file without imports and exports
got one. `export {}` makes what such a file declares local, so
`interface Window { greeter: string }` no longer added to the global
interface, and the build left out every .aot.ts file (TS2339).
Now every such file gets `export {}`. If the .aot.ts files have type
errors with it, the build writes and judges them without it. That text
is the text without the line only, so the build writes every .aot.ts
file that it wrote before.
- `build_typed_files` takes a flag for `export {}` and counts the files
that got one, so the second run happens only where it can differ.
- `ModuleTypes.is_module` is gone.
- `find_transpiled_mark_alone` has a table test.
- The tests of the runs compare stderr too.
- Docs: a JavaScript entry point gets an .aot.ts file beside a
TypeScript entry point.
JavaScript entry point (typed_files.rs:2182): confirmed and fixed. The clause no longer depends on the entry point: a bundle with the line and no export gets export {};, and if the .aot.ts files then fail the type check, the build writes them without it. This also repairs a loss that the old key caused, where a module entry point that bundles a script with interface Window { ... } lost every .aot.ts file (TS2339).
Test assertions (library-typed-file.test.ts:162): done.
Model of a target-bun typed file (typed_files.rs:4006) and look-alike first line (runtime_syntax.rs:317): no code change. The reasons are in the threads.
The PR body describes the rule as it is now, and its limits.
…es on Windows
On Windows the type check of the .aot.ts files reports no error, so the
build never writes them again without `export {}`. The `--splitting`
test of that check in compile-library.test.ts is set aside on Windows
for the same reason.
The reason will be displayed to describe this comment to others. Learn more.
Beyond the inline finding, I also checked: apply_without's offset clamp for insertions inside the cut (none can land there: Transfer inserts at statement offsets, all after the mark); find_transpiled_mark_alone returning None for // @ bun @ bytecode (bytecode needs format: "cjs", which already drops the .aot.ts files); and is_export_declaration covering export default, export * and modifier-flagged declarations, so a bundle with any export never gets export {};.
Not run here: the Rust unit test and the new bun tests, and rust:check-all.
Extended reasoning...
Since my last review, one commit (362819b) landed that only wraps the script-globals test in test.skipIf(isWindows); the inline finding covers that. This note records the other paths of the // @ bun cut and export {}; append in Transfer::finish that I read and found consistent with the intended behavior.
…without `export {}` on any error
The type check of the .aot.ts files saw none of them on Windows. The
build gave their texts to the checker through `already_read`, which
joins each path to the working directory as a native path. The paths are
in the checker's format, `/C:/dir/out/index.aot.ts`, and the Windows
join makes `C:\C:\dir\out\index.aot.ts` of that. The checker then
reported TS6053 for each file, which the verdict drops, so the build
said nothing about a type error there. The texts are now keyed by their
checker paths. The `--splitting` test of that check runs on Windows
again, and so does the test of the second check.
The second check, without `export {}`, now starts on any error of the
first pass, also on one that does not count against the files: TS7017
is dropped, and TS7006 is repaired with `: any`. With `export {}`,
`globalThis.list.map((n) => n + 1)` on a script's `var list` had both,
and the file was written with `(n: any)`. The text without `export {}`
is written, unless it fails the check and the text with it passes.
The check of the .aot.ts files saw none of them on Windows, on main too. Their texts were keyed through a native path join, which turns /C:/dir/out/index.aot.ts into C:\C:\dir\out\index.aot.ts. The texts are now keyed by their checker paths. The details are in the thread.
The test of the second check runs on Windows again, and so does the --splitting test of that check that main had set aside there.
The same commit starts the second check on any error of the first pass, also on one that does not count against the files. With export {};, globalThis.list.map((n) => n + 1) on a script's var list was written with (n: any). It now keeps the text that main writes.
Not run here: Windows. CI has to confirm that part.
369-379: Trivial · Maintainability & Code Quality · Low value
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Document or fail visibly when the retry rebuild fails.
The let Ok(..) pattern silently discards the error from build_typed_files(..., false). The code then keeps the original files, which contain export {}. This is a safe fallback, but a learning requires a comment explaining why a silent fallback is safe. Add a short comment on this point.
Reviewing files that changed from the base of the PR and between 362819b and d41a58e.
Files selected for processing: 3
src/runtime/cli/check_command/typed_files.rs
test/bundler/bun-build-api-dts.test.ts
test/cli/compile/compile-library.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
…re it adds an error
The second check, without `export {}`, started on any error of the first
pass, and its text was then written if it passed. The check of the
.aot.ts files does not read the declaration files of the project, so a
name that one of them declares is a missing name there, with and without
`export {}`. A file that calls `console.log` under a lib without DOM
lost `export {}` for that.
The errors of the first pass of the two texts are now compared by file,
offset and code. The text without `export {}` is written where
`export {}` adds an error, unless only the text with it passes.
- A warning that counts against the files is an error here too.
- A report that is incomplete does not pass.
ec34547 answers the optional finding about dropped error classes.
The text without export {}; is now written only where export {}; adds an error. The first-pass errors of the two texts are compared by file, offset and code. An error that both texts have no longer costs the clause. That covers a name from a declaration file of the project, which the check of the .aot.ts files cannot see: a file that calls console.log under a lib without DOM keeps export {}; again.
The CodeRabbit note on the let Ok(..) of the second run: that call has the inputs of the first run, which succeeded. If it fails, the files of the first run stay, as before this PR.
292-310: Trivial · Maintainability & Code Quality · Low value
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Error positions are compared across two different texts.
first_errors stores (path, start, code). The plain build omits export {}; from the end of the file. A trailing statement therefore does not shift earlier offsets, so this works only because the clause is appended last. If a later change inserts the clause earlier, every offset changes and each error looks new. Keep the append-only invariant documented next to the comparison.
Reviewing files that changed from the base of the PR and between 362819b and ec34547.
Files selected for processing: 4
docs/bundler/index.mdx
src/runtime/cli/check_command/typed_files.rs
test/bundler/bun-build-api-dts.test.ts
test/cli/compile/compile-library.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
…he .aot.ts files
- The files pass only with `export {}`: the clause stays.
- The files fail with and without it: the warning names the error of the text without it.
The sentence in the docs gets the exception, and a comment names what the comparison of the errors relies on.
The reason will be displayed to describe this comment to others. Learn more.
I reviewed the latest push and found no new issues; because it changes the bytes of every target-bun .aot.ts file and adds a second type-check pass with its own adoption rule, a human look is still worthwhile.
What was reviewed:
The two tests added in the last commit cover the passes_alone and both-fail outcomes raised earlier (exact trailing lines with (n: any) and export {};; the TS1375 warning text and no .aot.ts written).
Insertions::apply routing through apply_without(0..0) is behavior-preserving (empty prefix, clamping is a no-op at 0); all three build_typed_files call sites pass the new flag; the already_read helper still has callers in check_command.rs and declarations.rs, so nothing is orphaned.
The Windows fix (checker-format keys for Provided::already_read instead of a native join) and the un-skipped --splitting test were checked by reading only; no tests were run here, so Windows CI is the evidence for that part.
Extended reasoning...
The change touches the typed-file writer in src/sema/driver/typed_files.rs (cuts the // @ bun mark via a new apply_without, appends export {}; when the bundle has the mark and no export), the type-check fallback in src/runtime/cli/check_command/typed_files.rs (a second build-and-check without export {} that is adopted when the clause adds a first-pass error unless the files pass only with it), a small helper in src/sema/hir/runtime_syntax.rs with unit tests, docs, and three test files. It touches no security-sensitive surface. The bug hunt ran dry with no findings, the last commit added the tests my prior inline comment asked for, and no CODEOWNERS entry covers these paths. Defer rather than approve because the adoption heuristic and the second check pass are design choices in user-facing output, and the Windows path change could only be verified by reading.
0994027 answers the review of ec34547 and the independent check of it.
Tests of the second check (typed_files.rs:388): two tests added. One is for files that pass only with export {};, and one is for files that fail with and without it. Each fails when its condition is changed in a debug build. The details are in the thread.
Which error a warning names: no code change. The PR body said that the warning names the error of the text without export {}; where both texts fail. That holds only where export {}; adds an error. Where it adds none, the text with export {}; stays, and the warning names its first error. Example: a top-level await in front of [1, 2].last(), with last declared in a .d.ts file of the project. Main names TS1375. This branch names TS2339, because export {}; removes TS1375. The body now says this.
Docs: the sentence in docs/bundler/index.mdx now has the exception, "unless they type check only with it".
CodeRabbit note on the compared offsets: a comment beside the comparison now states that export {}; is the last line of its file. The test of an error that both texts have (... export {} stays) exercises that comparison.
Windows: CI ran it at ec34547. On Windows x64 and on Windows aarch64, test/bundler/bun-build-api-dts.test.ts has 19 pass. test/cli/compile/compile-library.test.ts passes there with the --splitting test that main had set aside.
Cost in time: measured. A build whose check runs two times executes 32.7% more user-mode instructions than the same build with one check: 29.83 against 22.49 billion, for two small files on a debug build, median of 15 runs. The cost table in the Notes has the method.
CodeRabbit names #47627 as a related PR. I ran a trial merge of this head (0994027) with each open PR that changes these files. The full list is in the PR body, under "Other open PRs in these files". The important results:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
bun run --aotfails on a package frombun build --dts --target=bun:SyntaxError: Unexpected token ':'. Expected a ')' or a ',' after a parameter declaration.atdist/index.aot.ts:3.Transfer::finish(src/sema/driver/typed_files.rs:3981) copies the bundle's first line,// @bun, intoindex.aot.ts. With it the runtime runs TypeScript as written (src/js_parser/parse/parse_entry.rs:942).Fix
Transfer::finish, which writes every.aot.tsfile, leaves// @bunout and keeps the line break. The line also meant "ES module", so a bundle with noexportends withexport {};.export {};adds a type error, Bun writes the files without it, unless they pass only with it.test/bundler/bun-build-api-dts.test.ts,test/aot/library-typed-file.test.ts). Self-reviewed: 44 concerns raised, 36 addressed (Notes).Background
// @bunstarts a bundle for Bun. The runtime skips the transpiler, for.tsfiles too (bun-pragma/fail/ts-with-pragma.ts).index.aot.tsisindex.jswith its types put back.bun run --aotreads it through the"aot"condition..aot.tsfiles of a build.export {};makes what a file with noimportorexportdeclares local.export {};is safe failed.Downsides
bun compileandbun test --aotcompile a target-bun.aot.tsfile as transpiled TypeScript. A class used above its declaration works there and throws inindex.js..aot.tsfiles with a type error are now left out. Withoutexport {};, a.aot.tsfile in a"type": "commonjs"package loads as CommonJS.bun_semacrates: +1,766 bytes. A two-file build whose check runs twice executes 32% more instructions (debug build).Notes
Repro
bun run ./main.tsbun run --aot ./main.tsbun --aot ./main.tsbun --conditions=aot run ./main.tsbun test --aot,bun check --aot,bun build --compile --aotNo issue reports this. It was found by a probe of
--dtswith--target=bun.The failure can be silent. On main, a typed file whose only TypeScript is
new Set<Point>([new Point]).sizeruns as JavaScript underbun run --aot. It printscount = falsewith exit code 0, wherebun runprintscount = 1.The file, before and after
The line break stays, so the second line of the bundle does not become the first line of the typed file. That second line can be a banner or the path comment of a source. Both readers take a first line that only begins with
// @bunfor the line.The line arrives in four ways.
--target=bun,target: "bun"inBun.build, an entry point that starts with#!/usr/bin/env bunwith any target (src/bundler/ParseTask.rs:2396), and a banner that is the line itself (--banner="// @bun") with any target. With a hashbang the line is the second line. The typed file keeps the hashbang.When
export {};is addedThe two conditions are: the bundle starts with the line, and the bundle has no
exportstatement. Animportdoes not count as anexport. A file that namesmoduleand has animportis CommonJS for the runtime, and anexportmakes it an ES module. The line decides, not the target: a build without the line gives the bytes of main.The clause has two effects.
"type": "commonjs", a typed file with noexportloads as CommonJS. Itsindex.jsis an ES module because of the line.--dtstype checks the.aot.tsfiles before it writes them. A file with noimportand noexportis a script there, and its top-level names are global. The clause makes them local. For a name from a module that is what the source says. For a name from a script it is not:interface Window { greeter: string }then declares a second interface, and avaris no longer a property ofwindow.Where
export {};adds an errorIf the first pass of the check reports an error with the clause,
typed_files_for_build(src/runtime/cli/check_command/typed_files.rs) runs the writer again without the clause, and checks that text too. It is the text of main without the seven bytes. The two texts are the same up to the last line, so the build compares their errors by file, offset and code.consoleor aBUILDthat a.d.tsfile declares is a missing name with and without the clause, and such an error does not count here (row 12). If the text with the clause fails, the warning names its first error. That is not always the error that main names: the clause can remove an earlier one. With a top-levelawaitin front of an error that both texts have, main names TS1375 and this branch names the other error."An error" is any error of the first pass, also one that does not count against the files. Two kinds do not count. The verdict drops some (TS7017, TS2304). And the check repairs a parameter that has no type: it writes
: anyand runs again (TS7006). With the clause,globalThis.list.map((n) => n + 1)on a script'svar listhas both kinds, and the second commit wrote that file with(n: any)and the clause. Now it has the text of main.The second run is for the whole build: the typed files are one program for the check, and an error does not say which file the clause is wrong in.
The check on Windows
On Windows the check of the typed files saw none of them, on main too. The build said nothing where the other platforms warn, and
test/cli/compile/compile-library.test.tshad its--splittingtest of that check set aside there. So the second run of this PR never started on Windows.typed_files_for_buildgave the texts to the checker throughalready_read. That function is for paths of the bundler: it joins each one to the working directory as a native path. The paths of the typed files are in the checker's format,/C:/dir/out/index.aot.ts, and the Windows join makesC:\C:\dir\out\index.aot.tsof that. The checker then found no typed file and reported TS6053 for each, which the verdict drops. The two calls intyped_files_for_buildnow key the texts by their checker paths. On the other platforms the keys are the same as before.The
--splittingtest runs on Windows again. This machine has no Windows, so CI is the proof of this part. Atec34547208, on Windows x64 and on Windows aarch64,test/bundler/bun-build-api-dts.test.tshas 19 pass andtest/cli/compile/compile-library.test.tspasses.Builds with
--dts. The bundle in each row has noexport:interface Window { greeter: string }andwindow.greeter = "hi".aot.tswrittenawait./joinconst namedeclare global--splittingwith noexportvar order, which no code reads as a globalvar listandglobalThis.list.map((n) => n + 1)awaitthat imports the script of row 10(n: any).d.tsfile of the project:console.log(BUILD.length)Without the line this branch gives the column "main" in every row. Rows 3 to 6 are a fault of the typed file check that exists for every build. This change does not repair it for a bundle without the line, because the output of such a build must stay byte for byte the same here.
The clause had three other forms in this PR. The first commit tied it to the entry point: a module entry point that bundles the script of row 2 lost every
.aot.tsfile (TS2339), and the files of rows 7 and 8 loaded as CommonJS. The next two forms tied it to the scripts among the sources. A self-review and an independent check of the PR found a counterexample to each rule for what a script declares. Now the type check decides.The model changes for a target-bun typed file
The ahead-of-time compiler reads the line too (
find_transpiled_mark,src/sema/hir/runtime_syntax.rs:283). With the line it compiles the file as the engine runs it. Without the line it compiles the file as Bun transpiles it. One difference is that Bun moves a class with no side effects to the start of a file that it transpiles.A library whose top-level code makes an instance of a class that is declared below, built with
bun compile --library --target=bun:bun run(index.js)bun run --aotbun test --aotbun build --compile --aotexecutableThe same library built with the default target prints the value in all four rows on main. So the three
--aotreaders now agree with each other and with the other targets.An entry point with a hashbang for Bun, no
export, in a"type": "commonjs"package:cli.jsandcli.aot.tsare both ES modules under all four readers on this branch. On mainbun run --aotfails with the SyntaxError.Costs, measured
bun_semaandbun_sema_driver,textcolumn ofsize(mainaf566a38e5)bun,textcolumn ofsize, at the first commit (main2596ac5d39)has_bun_pragma(nm -S, release)src/js_parser,src/bundler,src/resolver,src/jsc,src/aotsrc/runtime--dtscommand (cli/check_command/typed_files.rs)index.aot.tsof the repro,--target=bunindex.jsandindex.d.tsof the repro, both targetsfind_transpiled_markfor each typed fileTransfer::finish, reproTransfer::finish, debug build, no line--target=bun--target=bun, module entry point with noexportadd_types, release build, no line, 5 runs--target=bunexport {};bun build --dtsfor a package of two small files with such an error, debug build, median of 15 runs--target=node, which has no line)The first row is
cargo build --release -p bun_sema_driverat both commits, with no link step. It does not have the lines inbun_runtime: that crate builds only in a full build. The check of the binary size in CI reported +0.0 KB for each Linux and macOS target at the first commit, +0.5 KB for Windows x64 and -2.5 KB for Windows aarch64. The instruction counts are from the first commit. The later commits change one condition inTransfer::finish.Instructions are user-mode instructions of the calling thread between entry and return (
perf_event_open, read under gdb). In the release build the difference is below the spread of the runs. A build without--dtsdoes not reach these functions.The last row counts every thread of the process (
perf_event_openwithinherit). Its sources have the error of row 12, so the clause stays and the check runs two times. The runs of one build spread by about 4%: 21.77 to 23.55 billion with one check, 28.40 to 30.93 billion with two. The same sources without the error cost 22.20 billion with--target=bunand 22.11 billion with--target=node(median of 5), so the target alone makes no difference. No release build with--dtswas at hand, so the number is from a debug build.A typed file that the runtime loads under the
"aot"condition is now transpiled like any TypeScript file. Against the file with the line, which the runtime handed to the engine as it was: +28 allocator calls, +29 arena calls and +8 to +21 system calls for each load (gdb, entry to return ofTranspilerJob::run, debug build). A typed file of 121 KB gets one entry in the transpiler cache on the first run and uses it on the second. The file with the line got none.Builds that never had the line
6 fixtures, 4 sets of flags (none,
--minify-syntax,--minify-whitespace,--splitting) and 3 targets: 72 builds on main and 72 on this branch, at the first commit.index.jsand the.d.tsfiles are the same. 41.aot.tsfiles are the text of main without the seven bytes, and 12 of them also end withexport {};.The second commit changes only which typed files of a bundle with the line end with
export {};. A test now pins that a bundle without the line gets nothing.Tests run on a debug build
test/bundler/bun-build-api-dts.test.ts(21 pass) andtest/aot/library-typed-file.test.ts(8 pass). 15 of them are new. Two of the 15 pin what does not change: a bundle without the line, and the warning for files that have one error withexport {};and another without it. The 8 tests of the first commit were run against a debug build of main and failed there.export {};, the test of row 11 fails: the build warns with TS1375. With the text withoutexport {};taken only where it passes, the test of the two errors fails: the warning names TS2339.cargo test -p bun_sema --lib the_mark_alone: the table test offind_transpiled_mark_alonepasses.--timeout 300000:test/bundler/bun-build-dts.test.ts(11 pass),test/cli/compile/compile-library-aot-condition.test.ts(13),test/aot/aot-condition.test.ts(10),test/cli/compile/compile-library-javascript.test.ts(3),test/cli/check/specifiers-in-declarations.test.ts(3).test/cli/compile/compile-library.test.ts: 56 pass, with the--splittingtest of the check among them. The test that runstsctwo times needs 57 to 60 seconds of its 60 on a debug build, on main too.test/aot/library-from-npm.test.ts(39 pass) andtest/cli/compile/compile-library-ecosystem.test.ts(51 pass). In each, one test that compiles a CommonJS package with--aotfails in some runs: the debug build aborts there under the address sanitizer, inside the ahead-of-time compiler. It did that on a debug build of main too, and those packages have no// @bunline.C:\C:\dir\out\index.aot.tsfor/C:/dir/out/index.aot.ts. CI ran it on Windows (see "The check on Windows").cargo clippy -p bun_sema -p bun_sema_driver: clean at the second commit. The later commits changebun_runtimeonly, andcargo clippy -p bun_runtimeis clean.The new tests of the writer are in the
Bun.buildfile, where a build runs in the test process. The tests withbun run --aotusebun compile --library --target=bun, which runs the same build asbun build --dts.Not fixed here
// @bun, for example a banner// @bundled by acmeor the path comment// @bunx/index.ts, with no line above it. Both readers test a bare prefix (parse_entry.rs:2704,runtime_syntax.rs:293), so a typed file and a hand-written.tsfile with such a first line both fail, with any target. The readers own this. js_parser: stop the// @bunkeyword scan at the end of the pragma line #46122 names it as not done, and a review comment on fix(lexer): do not treat '#bun' in a url as a pragma #15888 says that the match needs a space or a tab after the word.declare global { }(row 6).export {};. With"type": "commonjs"in the package they load as CommonJS, and theirindex.jsis an ES module. With"type": "module"and with no"type"both are ES modules.exportand without the line: the.aot.tsfiles are left out as on main (rows 3 to 6 of the table).--sourcemap=linkedthe typed file still ends with the//# debugId=and//# sourceMappingURL=index.js.maplines of the bundle.--dts.Reviews
A self-review of the first form of this change found three faults. The clause was tied to the line alone, so a script entry point that adds to a global interface lost every
.aot.tsfile of the build (TS2339). Animportstopped the clause, but animportdoes not make a file an ES module where the file namesmodule. An empty line in front of a first line that only begins like the line worked around the readers for one writer, and its test pinned that.A code review of the PR found that a JavaScript entry point got no clause. A second self-review weighed the rules for the clause, found a counterexample to each of the three, and named a second run of the check as the sound form. This form has no rule and has the second run.
A code review of the second commit found that the second run never started on Windows. An independent check of that commit found the
(n: any)of row 10. The next form started the second run on any error and then wrote the text without the clause. A code review and an independent check found that a name from a declaration file of the project then cost the clause (row 12). This form compares the errors of the two texts. A code review of this form asked for a test of each of its two other outcomes, and an independent check found that this text named the wrong error for one case of the warning. Both are in.Not taken, with the reason:
export {};for every target. It changes the output of builds that never had the line, and it is a fix for a different fault (rows 3 to 6 of the table).declare global { }around what a script declares, in the typed file. It changes the typed text of script sources for every target, so it is a change of its own in the same writer.bun run --aottranspiles the same file, so the compiler would then differ from it.allowUmdGlobalAccessfor the check of the typed files. A read of a UMD global fails with the clause (TS2686), and the second run already writes those files.Other open PRs in these files
A trial merge of this head (
09940276b3) with the head of each open PR that changes these files gives this:.aot.tswhere the React Compiler moved its default value #48267,--dts,--aot: make a type predicate follow its parameter when the build renames it #48275, bun build --dts: write no!on a static or declared class field in.aot.ts#48392, js_parser, aot: an undecoratedaccessor #xis a getter and setter from the first initializer on #42643 and bun build --dts: declare a constant that is not finite asnumberin.aot.ts, and an alias oftrue | falseasboolean#48485. The helperinstallinlibrary-typed-file.test.tshas the same new signature here as in bun build --dts: make a parameter optional in.aot.tswhere the React Compiler moved its default value #48267 and--dts,--aot: make a type predicate follow its parameter when the build renames it #48275.undefined,trueandfalseunder --minify-syntax #48282 and bun build --dts: keep the.aot.tsfiles when Bun's types clear the type error #48512 each add a second check of their own totyped_files_for_build, at the statement where this PR adds its second run. bun build --dts: keep the cast ofundefined,trueandfalseunder --minify-syntax #48282 also adds a flag and a count at the places where this PR addsadds_empty_exportandempty_exports. The PR that lands later has to put the checks in an order..aot.tsfiles when Bun's types clear the type error #48512 rewrites the call that gives the texts to the checker, and keeps the native path join there. After a merge that call needs the checker paths of this PR. Without them the check sees no file on Windows again, and the Windows tests of this PR fail..aot.tsfiles from checker facts #48466: the last fields ofBundle, where both PRs add fields.sourcesof its source map #47627: oneuseline ofcheck_command/typed_files.rs, and the end of thedescribeblock inbun-build-api-dts.test.ts, where both PRs add tests..aot.ts#48488: the helperinstallinlibrary-typed-file.test.ts, which gets another signature there.#33859 stops the line for a hashbang entry point with another target. The hashbang test here passes
target: "bun", so it holds with and without that change.no test proof · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/aot/library-typed-file.test.ts