Unverified Commit 859c4edc authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Produce valid file URLs for `import.meta.url` on Windows in Turbopack (#94179)

### What?

`import.meta.url` evaluated in a Turbopack-compiled module on Windows
produced
an invalid file URI: the path portion contained backslashes (`\`) and
was not
URL-encoded, e.g.

```
file://C:\Users\me\project\apps\web\app\page.tsx
```

This affects any code that hands the value to `URL`, `fileURLToPath`,
source
maps, dev tools, or anything else that expects a [valid file
URI](https://en.wikipedia.org/wiki/File_URI_scheme).

This PR makes `import.meta.url` return a correct, percent-encoded file
URI on
all platforms, e.g. `file:///C:/Users/me/project/apps/web/app/page.tsx`.

### Why?

The existing codegen in `references/esm/meta.rs` emitted

```js
`file://${__turbopack_context__.P("<rel/path>")}`
```

where `__turbopack_context__.P` is the runtime helper
`resolveAbsolutePath`.
On the Node-side runtime (`shared-node/node-externals-utils.ts`) that
helper
returns `path.join(ABSOLUTE_ROOT, modulePath)`, which is OS-native — so
on
Windows it returns a backslash-separated path with no percent-encoding.
The
result was then concatenated into a `file://...` template literal,
producing
an invalid URI.

The initial hint that `turbopack-core/src/source_map/utils.rs` was the
culprit
turned out to be a false lead: that code path uses
`FileSystemPath::try_join`, which already normalizes `\` to `/` on
Windows.
The bug is in the codegen + runtime helper for `import.meta.url`, not in
source-map handling.

### How?

- Introduce a new runtime function `__turbopack_resolve_file_url__`
(shortcut `F`) whose contract is to return a complete `file://` URI for
a
  given relative module path.
  - Node implementation (`shared-node/node-externals-utils.ts`): uses
`url.pathToFileURL(resolveAbsolutePath(modulePath)).href`.
`pathToFileURL`
    handles drive letters (`file:///C:/...`), normalizes slashes, and
    percent-encodes path segments.
- Browser implementation (`browser/runtime/base/runtime-base.ts`):
returns
    `` `file:///ROOT/${modulePath ?? ''}` `` — the browser runtime
intentionally does not expose the real filesystem path, so it returns
the
same stable placeholder as before, just with a valid `file:///` prefix
    instead of having callers concatenate one.
- Change the `import.meta.url` codegen in `references/esm/meta.rs` to
call
  `__turbopack_resolve_file_url__($formatted)` directly instead of
concatenating a `file://` prefix to the absolute path. The pre-existing
  `encode_path` is kept only to keep the embedded JS string literal safe
  (the runtime helper is responsible for the URI-level encoding).
- Update `TurbopackBaseContext` and add a `ResolveFileUrl` type alias in
  `runtime-types.d.ts` so the new shortcut is typed.
- Register the new shortcut in `TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS` so
user
code can also reference `__turbopack_resolve_file_url__` (mirroring the
existing `__turbopack_resolve_absolute_path__`). `P` is left in place
and
  unchanged because it's still used elsewhere.
- Regenerate the affected Turbopack snapshot fixtures (`import-meta/*`,
`comptime/typeof`, `runtime/default_*_runtime`, `workers/*`,
`debug-ids/*`,
  etc.). The functional change in the generated code is uniform:
  `` `file://${__turbopack_context__.P(<rel>)}` `` →
  `__turbopack_context__.F(<rel>)`.
- Drop the `// TODO: These file URIs are wrong on turbopack+windows`
comment
  and the `.replaceAll('\\', '/')` workarounds from

`test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts`,
so the assertion now verifies that the URI is correctly slashed and
encoded
  on all platforms.

### Verification

- `cargo clippy --workspace --all-targets` — clean
- `cargo fmt --check` — clean
- `cargo test -p turbopack-tests --test snapshot` — 87/87 pass
- `cargo test -p turbopack-tests --test execution` — 219/219 pass (1
ignored)
- `pnpm test-dev-turbo
test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts`
— 9/9 pass
- `pnpm test-start-turbo
test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts`
— 6/6 pass
- `pnpm test-dev-webpack
test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts`
— 9/9 pass (verifying webpack path still works)

Windows itself can't be exercised in the sandbox, but the new code path
no
longer depends on `path.sep` or any OS-native string manipulation for
the
URI: `url.pathToFileURL` is the canonical Node API for producing a file
URI
from any OS-native path, and the test assertion has been tightened so
that a
regression on Windows would fail in CI rather than be papered over.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarv-work-app[bot] <262237222+v-work-app[bot]@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
parent 41829385
import { text } from './with space'
export default function Page() {
return <p>{text}</p>
}
'use client'
import { text } from './with space'
export default function Page() {
return <p>{text}</p>
}
...@@ -48,20 +48,17 @@ describe('non-root-project-monorepo', () => { ...@@ -48,20 +48,17 @@ describe('non-root-project-monorepo', () => {
}) })
}) })
// TODO: These file URIs are wrong on turbopack+windows:
// https://en.wikipedia.org/wiki/File_URI_scheme
// The URIs should always use forward slashes, but use backslashes on windows.
describe('import.meta.url', () => { describe('import.meta.url', () => {
it('should work during RSC', async () => { it('should work during RSC', async () => {
const $ = await next.render$('/import-meta-url-rsc') const $ = await next.render$('/import-meta-url-rsc')
expect($('p').text().replaceAll('\\', '/')).toMatch( expect($('p').text()).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-rsc\/page.tsx$/ /^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-rsc\/page.tsx$/
) )
}) })
it('should work during SSR', async () => { it('should work during SSR', async () => {
const $ = await next.render$('/import-meta-url-ssr') const $ = await next.render$('/import-meta-url-ssr')
expect($('p').text().replaceAll('\\', '/')).toMatch( expect($('p').text()).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-ssr\/page.tsx$/ /^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-ssr\/page.tsx$/
) )
}) })
...@@ -71,18 +68,50 @@ describe('non-root-project-monorepo', () => { ...@@ -71,18 +68,50 @@ describe('non-root-project-monorepo', () => {
await waitForNoRedbox(browser) await waitForNoRedbox(browser)
if (isTurbopack) { if (isTurbopack) {
// Turbopack intentionally doesn't expose the full path to the browser bundles // Turbopack intentionally doesn't expose the full path to the browser bundles
expect( expect(await browser.elementByCss('p').text()).toBe(
(await browser.elementByCss('p').text()).replaceAll('\\', '/') 'file:///ROOT/apps/web/app/import-meta-url-ssr/page.tsx'
).toBe('file:///ROOT/apps/web/app/import-meta-url-ssr/page.tsx') )
} else { } else {
expect( expect(await browser.elementByCss('p').text()).toMatch(
(await browser.elementByCss('p').text()).replaceAll('\\', '/')
).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-ssr\/page.tsx$/ /^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-ssr\/page.tsx$/
) )
} }
await browser.close() await browser.close()
}) })
// Verifies that non-URL-safe characters in file paths (here: a literal
// space) are correctly percent-encoded in the resulting `file://` URI.
describe('non-url-safe characters', () => {
it('should encode special chars during RSC', async () => {
const $ = await next.render$('/import-meta-url-encoded-rsc')
expect($('p').text()).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-encoded-rsc\/with%20space.ts$/
)
})
it('should encode special chars during SSR', async () => {
const $ = await next.render$('/import-meta-url-encoded-ssr')
expect($('p').text()).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-encoded-ssr\/with%20space.ts$/
)
})
it('should encode special chars on client-side', async () => {
const browser = await next.browser('/import-meta-url-encoded-ssr')
await waitForNoRedbox(browser)
if (isTurbopack) {
// Turbopack intentionally doesn't expose the full path to the browser bundles
expect(await browser.elementByCss('p').text()).toBe(
'file:///ROOT/apps/web/app/import-meta-url-encoded-ssr/with%20space.ts'
)
} else {
expect(await browser.elementByCss('p').text()).toMatch(
/^file:\/\/.*\/next-install-[^/]+\/apps\/web\/app\/import-meta-url-encoded-ssr\/with%20space.ts$/
)
}
await browser.close()
})
})
}) })
if (isNextDev) { if (isNextDev) {
......
...@@ -289,6 +289,20 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -289,6 +289,20 @@ function resolveAbsolutePath(modulePath?: string): string {
} }
browserContextPrototype.P = resolveAbsolutePath browserContextPrototype.P = resolveAbsolutePath
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/
function resolveFileUrl(modulePath?: string): string {
if (!modulePath) return 'file:///ROOT/'
return `file:///ROOT/${modulePath
.split('/')
.map(encodeURIComponent)
.join('/')}`
}
browserContextPrototype.F = resolveFileUrl
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ */
......
...@@ -31,3 +31,15 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -31,3 +31,15 @@ function resolveAbsolutePath(modulePath?: string): string {
return ABSOLUTE_ROOT return ABSOLUTE_ROOT
} }
Context.prototype.P = resolveAbsolutePath Context.prototype.P = resolveAbsolutePath
/**
* Returns an absolute `file://` URL for the given module path.
*
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded).
*/
function resolveFileUrl(modulePath?: string): string {
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href
}
Context.prototype.F = resolveFileUrl
...@@ -97,6 +97,7 @@ type AsyncModule = ( ...@@ -97,6 +97,7 @@ type AsyncModule = (
) => void ) => void
type ResolveAbsolutePath = (modulePath?: string) => string type ResolveAbsolutePath = (modulePath?: string) => string
type ResolveFileUrl = (modulePath?: string) => string
type GetWorkerURL = ( type GetWorkerURL = (
entrypoint: ChunkPath, entrypoint: ChunkPath,
moduleChunks: ChunkPath[], moduleChunks: ChunkPath[],
...@@ -148,6 +149,7 @@ interface TurbopackBaseContext<M> { ...@@ -148,6 +149,7 @@ interface TurbopackBaseContext<M> {
w: LoadWebAssembly w: LoadWebAssembly
u: LoadWebAssemblyModule u: LoadWebAssemblyModule
P: ResolveAbsolutePath P: ResolveAbsolutePath
F: ResolveFileUrl
U: RelativeURL U: RelativeURL
b: GetWorkerURL b: GetWorkerURL
x: ExternalRequire x: ExternalRequire
......
...@@ -16,7 +16,7 @@ use crate::{ ...@@ -16,7 +16,7 @@ use crate::{
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath, references::AstPath,
runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_ABSOLUTE_PATH}, runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_FILE_URL},
}; };
/// Responsible for initializing the `import.meta` object binding, so that it /// Responsible for initializing the `import.meta` object binding, so that it
...@@ -55,10 +55,13 @@ impl ImportMetaBinding { ...@@ -55,10 +55,13 @@ impl ImportMetaBinding {
) )
}, },
|path| { |path| {
// `encode_path` only escapes characters that would break the JS string literal
// we embed `formatted` into. The runtime helper (`TURBOPACK_RESOLVE_FILE_URL`)
// is responsible for producing the final, properly URL-encoded `file://` URI.
let formatted = encode_path(path.trim_start_matches("./")).to_string(); let formatted = encode_path(path.trim_start_matches("./")).to_string();
quote!( quote!(
"`file://${$turbopack_resolve_absolute_path($formatted)}`" as Expr, "$turbopack_resolve_file_url($formatted)" as Expr,
turbopack_resolve_absolute_path: Expr = TURBOPACK_RESOLVE_ABSOLUTE_PATH.into(), turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(),
formatted: Expr = formatted.into() formatted: Expr = formatted.into()
) )
}, },
......
...@@ -81,6 +81,7 @@ pub const TURBOPACK_LOAD_BY_URL: &TurbopackRuntimeFunctionShortcut = make_shortc ...@@ -81,6 +81,7 @@ pub const TURBOPACK_LOAD_BY_URL: &TurbopackRuntimeFunctionShortcut = make_shortc
pub const TURBOPACK_CLEAR_CHUNK_CACHE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("C"); pub const TURBOPACK_CLEAR_CHUNK_CACHE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("C");
pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!("j"); pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!("j");
pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P"); pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P");
pub const TURBOPACK_RESOLVE_FILE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("F");
pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U"); pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R"); pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_CREATE_WORKER: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b"); pub const TURBOPACK_CREATE_WORKER: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
...@@ -96,7 +97,7 @@ pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!(" ...@@ -96,7 +97,7 @@ pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("
/// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called /// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called
/// from user code (by inserting a replacement into free_var_references) /// from user code (by inserting a replacement into free_var_references)
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 23] = [ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 24] = [
("__turbopack_require__", TURBOPACK_REQUIRE), ("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT), ("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT), ("__turbopack_import__", TURBOPACK_IMPORT),
...@@ -112,6 +113,7 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -112,6 +113,7 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
"__turbopack_resolve_absolute_path__", "__turbopack_resolve_absolute_path__",
TURBOPACK_RESOLVE_ABSOLUTE_PATH, TURBOPACK_RESOLVE_ABSOLUTE_PATH,
), ),
("__turbopack_resolve_file_url__", TURBOPACK_RESOLVE_FILE_URL),
("__turbopack_relative_url__", TURBOPACK_RELATIVE_URL), ("__turbopack_relative_url__", TURBOPACK_RELATIVE_URL),
( (
"__turbopack_resolve_module_id_path__", "__turbopack_resolve_module_id_path__",
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js");
} }
}; };
console.log('typeof require', ("TURBOPACK compile-time value", "function")); console.log('typeof require', ("TURBOPACK compile-time value", "function"));
...@@ -24,7 +24,7 @@ __turbopack_context__.s([]); ...@@ -24,7 +24,7 @@ __turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$dep$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$dep$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)");
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js");
} }
}; };
; ;
...@@ -42,7 +42,7 @@ console.log(/*TURBOPACK member replacement*/ __turbopack_context__.z); ...@@ -42,7 +42,7 @@ console.log(/*TURBOPACK member replacement*/ __turbopack_context__.z);
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs");
} }
}; };
console.log('typeof require', ("TURBOPACK compile-time value", "function")); console.log('typeof require', ("TURBOPACK compile-time value", "function"));
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="63d3116b-6e4c-29e3-253a-989477151583")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="c62d338f-1706-8257-26fe-07dd3a11b4a5")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js",
{"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -727,6 +727,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -727,6 +727,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
...@@ -2253,5 +2262,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2253,5 +2262,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=63d3116b-6e4c-29e3-253a-989477151583 //# debugId=c62d338f-1706-8257-26fe-07dd3a11b4a5
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map
\ No newline at end of file
...@@ -640,6 +640,16 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -640,6 +640,16 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
return ABSOLUTE_ROOT; return ABSOLUTE_ROOT;
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/**
* Returns an absolute `file://` URL for the given module path.
*
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded).
*/ function resolveFileUrl(modulePath) {
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href;
}
Context.prototype.F = resolveFileUrl;
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" />
function readWebAssemblyAsResponse(path) { function readWebAssemblyAsResponse(path) {
const { createReadStream } = require('fs'); const { createReadStream } = require('fs');
......
...@@ -7,7 +7,7 @@ var __TURBOPACK__url__external__node$3a$child_process__ = __turbopack_context__. ...@@ -7,7 +7,7 @@ var __TURBOPACK__url__external__node$3a$child_process__ = __turbopack_context__.
var __TURBOPACK__url__external__node$3a$fs__ = __turbopack_context__.x("node:fs", ()=>require("node:fs"), true); var __TURBOPACK__url__external__node$3a$fs__ = __turbopack_context__.x("node:fs", ()=>require("node:fs"), true);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/dynamic-request/very-dynamic/input/index.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/dynamic-request/very-dynamic/input/index.js");
} }
}; };
; ;
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs");
} }
}; };
console.log(__TURBOPACK__import$2e$meta__.url); console.log(__TURBOPACK__import$2e$meta__.url);
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-multiple/input/mod.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-multiple/input/mod.mjs");
} }
}; };
function foo() { function foo() {
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-mutable/input/mod.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-mutable/input/mod.mjs");
} }
}; };
__TURBOPACK__import$2e$meta__.foo = 1; __TURBOPACK__import$2e$meta__.foo = 1;
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-object/input/mod.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-object/input/mod.mjs");
} }
}; };
console.log(__TURBOPACK__import$2e$meta__); console.log(__TURBOPACK__import$2e$meta__);
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm/input/mod.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm/input/mod.mjs");
} }
}; };
console.log(__TURBOPACK__import$2e$meta__.url); console.log(__TURBOPACK__import$2e$meta__.url);
......
...@@ -8,7 +8,7 @@ __turbopack_context__.q("/static/asset.1z1abqqd69ldl.txt");}), ...@@ -8,7 +8,7 @@ __turbopack_context__.q("/static/asset.1z1abqqd69ldl.txt");}),
__turbopack_context__.s([]); __turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/mod.mjs")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/mod.mjs");
} }
}; };
const assetUrl = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/asset.txt (static in ecmascript)")); const assetUrl = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/asset.txt (static in ecmascript)"));
......
...@@ -24,7 +24,7 @@ __turbopack_context__.s([ ...@@ -24,7 +24,7 @@ __turbopack_context__.s([
]); ]);
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js");
} }
}; };
__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)").then(console.log); __turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)").then(console.log);
......
...@@ -640,6 +640,16 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -640,6 +640,16 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
return ABSOLUTE_ROOT; return ABSOLUTE_ROOT;
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/**
* Returns an absolute `file://` URL for the given module path.
*
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded).
*/ function resolveFileUrl(modulePath) {
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href;
}
Context.prototype.F = resolveFileUrl;
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" />
function readWebAssemblyAsResponse(path) { function readWebAssemblyAsResponse(path) {
const { createReadStream } = require('fs'); const { createReadStream } = require('fs');
......
...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -1276,6 +1276,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1276,6 +1276,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath !== null && modulePath !== void 0 ? modulePath : ''}`; return `/ROOT/${modulePath !== null && modulePath !== void 0 ? modulePath : ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -12,7 +12,7 @@ __turbopack_context__.v(function(Ctor, opts) { ...@@ -12,7 +12,7 @@ __turbopack_context__.v(function(Ctor, opts) {
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js");
} }
}; };
console.log('index.js'); console.log('index.js');
......
...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -726,6 +726,15 @@ browserContextPrototype.R = resolvePathFromModule;
return `/ROOT/${modulePath ?? ''}`; return `/ROOT/${modulePath ?? ''}`;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/**
* Returns a placeholder `file://` URL for the given module path. The browser
* runtime intentionally does not expose the real filesystem path. Path
* segments are percent-encoded so the result is always a valid file URI.
*/ function resolveFileUrl(modulePath) {
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -12,7 +12,7 @@ __turbopack_context__.v(function(Ctor, opts) { ...@@ -12,7 +12,7 @@ __turbopack_context__.v(function(Ctor, opts) {
var __TURBOPACK__import$2e$meta__ = { var __TURBOPACK__import$2e$meta__ = {
get url () { get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js")}`; return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js");
} }
}; };
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)")); const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)"));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment