Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion crates/nub-cache-key/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//! its `NUB_VERSION` / `CACHE_SCHEMA` / `BUILD_ID` consts.
//!
//! `filename` is in the preimage because the cached body carries a per-file
//! `//# sourceURL=<absolute path>` magic comment: two byte-identical sources in
//! `//# sourceURL=<file: URL>` magic comment: two byte-identical sources in
//! the same directory would otherwise collide on one entry and the second file
//! would be served the first's `sourceURL`, misattributing V8 stack frames and
//! debugger source mapping (issue #171).
Expand Down
132 changes: 132 additions & 0 deletions crates/nub-cli/tests/ts_source_url.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//! A transpiled TypeScript file's script identity is the `file:` URL Node's own
//! type-stripping reports, not a bare filesystem path.
//!
//! nub appends a `//# sourceURL` to every transpiled body, and that value is what
//! the inspector reports as `Debugger.scriptParsed`'s `url` — the key editors and
//! DevTools match breakpoints against. Node reports the module's URL there
//! (`pathToFileURL(filename).href`, via `convertCJSFilenameToURL`); emitting the
//! path instead gave every `.ts` file a different identity under nub than under
//! `node`. Upstream pins the same contract in
//! `test/parallel/test-inspector-strip-types.js`, including `hasSourceURL`.
//!
//! Deliberately NOT asserted here: the rendered stack frame. nub runs with
//! `--enable-source-maps`, and Node's source-map frame formatter strips the
//! `file://` scheme off the mapped source by design
//! (`prepare_stack_trace.js`, `originalSourceNoScheme`), so a mapped frame shows a
//! bare path whatever the sourceURL says. The inspector URL is the surface this
//! bug is actually about.
//!
//! The fixture supplies its OWN expectation — `pathToFileURL(__filename).href`
//! plus URLs resolved against it — so the assertion is a differential against
//! Node's URL for the same files rather than path arithmetic repeated in the
//! test. Each fixture directory is run TWICE against a private cache directory:
//! the sourceURL is baked into the cached body, so a cold transform and a warm
//! cache hit are separate claims.

use std::path::{Path, PathBuf};
use std::process::Command;

fn nub_binary() -> PathBuf {
PathBuf::from(env!("CARGO_BIN_EXE_nub"))
}

fn host_node_usable() -> bool {
Command::new("node")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
}

/// A `.ts` entry that pulls in one dependency per module format, so all three
/// load paths (entry, `require` of `.cts`, `import` of `.mts`) are covered by one
/// process. `Debugger.enable` is posted before either dependency loads, which is
/// what makes their `scriptParsed` notifications observable.
const PROBE: &str = r#"const inspector = require("node:inspector");
const { pathToFileURL } = require("node:url");

const session = new inspector.Session();
session.connect();
const seen: Record<string, boolean> = {};
session.on("Debugger.scriptParsed", ({ params }: any) => {
if (/\.[cm]?ts$/.test(params.url)) seen[params.url] = params.hasSourceURL;
});
session.post("Debugger.enable", async () => {
require("./dep.cts");
await import("./dep.mts");
const self: string = pathToFileURL(__filename).href;
const expected: string[] = [self, new URL("dep.cts", self).href, new URL("dep.mts", self).href];
console.log(JSON.stringify({ expected, seen }));
});
"#;

/// Write the fixture into `dir`, run it, and assert every TypeScript file in the
/// graph reported Node's own URL for itself as its script identity.
fn assert_script_urls(dir: &Path, cache: &Path) {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("package.json"), r#"{ "type": "commonjs" }"#).unwrap();
std::fs::write(dir.join("probe.ts"), PROBE).unwrap();
std::fs::write(
dir.join("dep.cts"),
"const y: number = 2;\nmodule.exports = y;\n",
)
.unwrap();
std::fs::write(dir.join("dep.mts"), "export const z: number = 3;\n").unwrap();

for pass in ["cold", "warm"] {
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
let output = Command::new(nub_binary())
.arg("probe.ts")
.current_dir(dir)
.env("XDG_CACHE_HOME", cache)
.output()
.expect("failed to spawn nub");
assert!(
output.status.success(),
"nub exited {:?} ({pass}) in {}\nstderr: {}",
output.status,
dir.display(),
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
let parsed: serde_json::Value = serde_json::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("fixture must emit JSON ({pass}), got {stdout:?}: {e}"));

for expected in parsed["expected"].as_array().unwrap() {
let href = expected.as_str().unwrap();
assert!(
href.starts_with("file:///"),
"({pass}) the fixture's own oracle must be a file: URL, got {href:?}"
);
assert_eq!(
parsed["seen"][href],
serde_json::json!(true),
"({pass}) {href} must reach the inspector under Node's own URL for it, \
with hasSourceURL set.\n reported: {}",
parsed["seen"]
);
}
}
}

/// The baseline contract, on a path with nothing to escape.
#[test]
fn transpiled_typescript_reports_its_file_url_to_the_inspector() {
if !host_node_usable() {
return;
}
let temp = tempfile::tempdir().unwrap();
assert_script_urls(&temp.path().join("plain"), &temp.path().join("cache"));
}

/// The percent-encoding has to match Node's `pathToFileURL` too, not merely carry
/// a `file://` prefix: the fixture's expectations come from Node, so a naive
/// `format!("file://{path}")` passes the test above and fails here. Unix-only —
/// `%`, `#` and `?` are not usable in a Windows filename.
#[cfg(unix)]
#[test]
fn percent_encoded_path_matches_node() {
if !host_node_usable() {
return;
}
let temp = tempfile::tempdir().unwrap();
assert_script_urls(&temp.path().join("a b%c#d?e"), &temp.path().join("cache"));
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}
111 changes: 103 additions & 8 deletions crates/nub-native/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
//! `NUB_VERSION \0 CACHE_SCHEMA \0 build_id \0 source \0 ext \0 tsconfig_hash \0 (pkg_type||"") \0 filename`
//! → blake3 → 64-hex lowercase → cache FILENAME. `filename` is in the key
//! because the cached body carries a per-file `//# sourceURL` comment (issue
//! #171). (SCHEMA "6" added `filename`; SCHEMA "5" = compile-time build-id era;
//! SCHEMA "4" folded a runtime exe-hash here, SCHEMA "3" / the old JS path used
//! SHA-256 and a key without that component.)
//! #171). (SCHEMA "7" = the `//# sourceURL` file-URL switch; SCHEMA "6" added
//! `filename`; SCHEMA "5" = compile-time build-id era; SCHEMA "4" folded a
//! runtime exe-hash here, SCHEMA "3" / the old JS path used SHA-256 and a key
//! without that component.)
//! On-disk entry: `[16-hex integrity = blake3(body)[..16]][body]`, where
//! `body = format_byte('c'|'m') + post_processed_code`.
//! Atomic write via a `*.tmp` sibling + rename (the `*.tmp` suffix is what
Expand All @@ -17,7 +18,7 @@
//! The post-processing that the old JS did in `loadTranspile` after `transform`
//! moves in here so the cached bytes are the FINAL bytes: drop oxc's empty
//! `export {};` marker for CJS, append the inline base64 sourceMap, append the
//! `//# sourceURL=<absolute path>` magic comment.
//! `//# sourceURL=<file: URL>` magic comment.

use std::sync::atomic::{AtomicU64, Ordering};

Expand All @@ -27,15 +28,18 @@ use oxc_napi::OxcError;

use crate::transform::{TransformOptions, transform};

/// On-disk entry format version. Bumped to "6" when `filename` was folded into
/// On-disk entry format version. Bumped to "7" when the `//# sourceURL` switched
/// from a bare filesystem path to the `file:` URL Node emits (see
/// [`source_url`]) — the sourceURL is baked into the stored body, so a "6"-era
/// entry would keep serving the old script identity. "6" folded `filename` into
/// the key (issue #171): a "5"-era entry was named without `filename` in the
/// preimage, so two byte-identical sources in a directory collided on one entry
/// and the second was served the first's `//# sourceURL`. "5" was the move from a
/// runtime exe-hash to the compile-time build-id const (see `BUILD_ID`). This
/// constant is hashed INTO the key, so the filenames are disjoint across schemas
/// — old entries are silently ignored (a miss), never mis-read. (SCHEMA "4" was
/// the blake3 + exe-hash era; "3" / the old JS path used SHA-256.)
const CACHE_SCHEMA: &str = "6";
const CACHE_SCHEMA: &str = "7";
const INTEGRITY_LEN: usize = 16;
/// Lockstep with `runtime/version.mjs` via `make version`; the sole version
/// component of the key (a new nub release ships any emit change + a rebuilt addon).
Expand Down Expand Up @@ -131,8 +135,11 @@ pub fn transform_cached(
"\n//# sourceMappingURL=data:application/json;base64,{b64}\n"
));
}
// sourceURL magic comment — absolute file path, as Node's strip-types does.
code.push_str(&format!("\n//# sourceURL={filename}\n"));
// sourceURL magic comment — the `file:` URL, as Node's strip-types does.
code.push_str(&format!(
"\n//# sourceURL={}\n",
source_url(&filename, cfg!(windows))
));

// Store: body = format_byte + code.
if let Some(dir) = cache_dir.as_deref() {
Expand Down Expand Up @@ -199,6 +206,94 @@ fn integrity(body: &[u8]) -> String {
blake3::hash(body).to_hex()[..INTEGRITY_LEN].to_string()
}

/// Whether a byte must be percent-encoded inside the path of a `file:` URL, as
/// Node's `pathToFileURL` spells it (Node 20+, where the conversion moved into
/// ada's `href_from_file`). Swept over the whole byte range against v26.7.0: the
/// set is WIDER than the WHATWG path percent-encode set — `[`, `]`, `^`, `|` and
/// `~` are escaped too — so deriving it from the URL spec instead of from Node
/// produces a string that differs on exactly the paths nobody tests.
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
fn must_percent_encode(b: u8) -> bool {
!b.is_ascii()
|| matches!(
b,
0x00..=0x20
| b'"'
| b'#'
| b'%'
| b'<'
| b'>'
| b'?'
| b'['
| b'\\'
| b']'
| b'^'
| b'`'
| b'{'
| b'|'
| b'}'
| b'~'
| 0x7f
)
}

fn push_encoded(out: &mut String, s: &str) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
for b in s.bytes() {
if must_percent_encode(b) {
out.push('%');
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
} else {
out.push(b as char);
}
}
}

/// The `//# sourceURL` a transpiled file carries: the `file:` URL spelling of
/// `path`, byte-identical to Node's `pathToFileURL(path).href`.
///
/// This is a compatibility contract, not a spelling preference. Node's own
/// type-stripping emits the module's URL (`convertCJSFilenameToURL`, i.e.
/// `pathToFileURL(...).href`) as the sourceURL, and the inspector reports it
/// verbatim as `Debugger.scriptParsed`'s `url` — the key editors and DevTools
/// match breakpoints against. A bare path silently gives a `.ts` file a different
/// script identity under nub than under `node`. (A RENDERED stack frame is a
/// weaker witness: nub runs with `--enable-source-maps`, and Node's frame
/// formatter strips the `file://` scheme off the mapped source, so a mapped frame
/// shows a bare path whatever this returns.) `path` always arrives absolute here
/// (the loader derives it with `fileURLToPath`); anything else is passed through
/// unconverted, matching Node's `convertCJSFilenameToURL` fallback.
fn source_url(path: &str, windows: bool) -> String {
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
let mut url = String::with_capacity(path.len() + 16);
if !windows {
if !path.starts_with('/') {
return path.to_string();
}
url.push_str("file://");
push_encoded(&mut url, path);
return url;
}
let forward = path.replace('\\', "/");
if let Some(rest) = forward.strip_prefix("//") {
// UNC `\\server\share\…` → `file://server/share/…`. The hostname is a URL
// authority rather than a path segment, so it is not percent-encoded.
let host_end = rest.find('/').unwrap_or(rest.len());
url.push_str("file://");
url.push_str(&rest[..host_end]);
push_encoded(&mut url, &rest[host_end..]);
return url;
}
let bytes = forward.as_bytes();
let drive_absolute =
bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/';
if !drive_absolute {
return path.to_string();
}
url.push_str("file:///");
push_encoded(&mut url, &forward);
url
}

/// Read a cache entry and return `(format_byte, code)` on a verified hit.
///
/// The integrity check is byte-identical to the on-disk format: the stored
Expand Down
Loading