Unverified Commit 558caf1d authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] improve fragment handling in the resolver (#86888)

Improve the handling of fragments in the resolver

* ensure they are supported for dynamic matches
* ensure we accumulate matches only if they match the original pattern

Also add some unit tests for the resolver to demonstrate a number of existing issues that will be addressed in followups
parent 916f45d5
......@@ -9660,6 +9660,7 @@ dependencies = [
"smallvec",
"swc_core",
"swc_sourcemap",
"tempfile",
"tokio",
"tracing",
"turbo-bincode",
......
......@@ -57,6 +57,7 @@ rstest = { workspace = true }
tokio = { workspace = true }
turbo-tasks-testing = { workspace = true }
turbo-tasks-backend = { workspace = true }
tempfile = { workspace = true }
[features]
default = []
......@@ -290,19 +290,34 @@ impl Request {
Request::PackageInternal { path } => {
path.push(item);
}
Request::DataUri { .. } => {
result = Request::Dynamic;
}
Request::Uri { .. } => {
result = Request::Dynamic;
}
Request::Unknown { path } => {
path.push(item);
}
Request::Dynamic => {}
Request::DataUri { .. } | Request::Uri { .. } | Request::Dynamic => {
return Request::Dynamic;
}
Request::Alternatives { .. } => unreachable!(),
};
}
if let Request::Relative {
path,
fragment,
query,
..
} = &mut result
&& fragment.is_empty()
&& query.is_empty()
&& let Pattern::Concatenation(parts) = path
&& let Pattern::Constant(last_part) = parts.last().unwrap()
{
let (prefix, new_query, new_fragment) = split_off_query_fragment(last_part);
*parts.last_mut().unwrap() = prefix;
*query = new_query;
*fragment = new_fragment;
// now that we have composed the request try to find the query and fragment
path.normalize();
}
result
}
......
......@@ -48,14 +48,14 @@ interface ModuleContextEntry {
interface ModuleContext {
// require call
(moduleId: ModuleId): Exports | EsmNamespaceObject
(moduleId: string): Exports | EsmNamespaceObject
// async import call
import(moduleId: ModuleId): Promise<Exports | EsmNamespaceObject>
import(moduleId: string): Promise<Exports | EsmNamespaceObject>
keys(): ModuleId[]
resolve(moduleId: ModuleId): ModuleId
resolve(moduleId: string): ModuleId
}
type GetOrInstantiateModuleFromParent<M extends Module> = (
......@@ -390,11 +390,34 @@ function commonJsRequire(
}
contextPrototype.r = commonJsRequire
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/
function parseRequest(request: string): string {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
const hashIndex = request.indexOf('#')
if (hashIndex !== -1) {
request = request.substring(0, hashIndex)
}
const queryIndex = request.indexOf('?')
if (queryIndex !== -1) {
request = request.substring(0, queryIndex)
}
return request
}
/**
* `require.context` and require/import expression runtime.
*/
function moduleContext(map: ModuleContextMap): ModuleContext {
function moduleContext(id: ModuleId): Exports {
function moduleContext(id: string): Exports {
id = parseRequest(id)
if (hasOwnProperty.call(map, id)) {
return map[id].module()
}
......@@ -404,11 +427,12 @@ function moduleContext(map: ModuleContextMap): ModuleContext {
throw e
}
moduleContext.keys = (): ModuleId[] => {
moduleContext.keys = (): string[] => {
return Object.keys(map)
}
moduleContext.resolve = (id: ModuleId): ModuleId => {
moduleContext.resolve = (id: string): ModuleId => {
id = parseRequest(id)
if (hasOwnProperty.call(map, id)) {
return map[id].id()
}
......@@ -418,7 +442,7 @@ function moduleContext(map: ModuleContextMap): ModuleContext {
throw e
}
moduleContext.import = async (id: ModuleId) => {
moduleContext.import = async (id: string) => {
return await (moduleContext(id) as Promise<Exports>)
}
......
......@@ -18,3 +18,11 @@ it('should resolve to a file with a fragment and an extension', () => {
it('should resolve to a file without a fragment but with an extension', () => {
expect(nofrag2).toBe('nofrag')
})
it('dynamic with fragments', async () => {
const helper = async (p) => {
return (await import('./' + p + '#frag')).default
}
expect(await helper('nofrag.js')).toBe('nofrag')
expect(await helper('nofrag')).toBe('nofrag')
})
......@@ -4,6 +4,7 @@ import fileMts from './src/file-mts.mjs'
import fileCts from './src/file-cts.cjs'
import fileMjs from './src/file-mjs.mjs'
import fileCjs from './src/file-cjs.cjs'
import fooButton from 'foo/button'
it('should correctly resolve explicit extensions with nodenext', () => {
expect(foo).toBe('foo.ts')
......@@ -14,8 +15,6 @@ it('should correctly resolve explicit extensions with nodenext', () => {
expect(fileCjs).toBe('file-cjs')
})
// import fooButton from "foo/button";
// it("should correctly resolve explicit extensions with nodenext", () => {
// expect(fooButton).toBe("button");
// });
it('should correctly resolve explicit extensions with nodenext', () => {
expect(fooButton).toBe('button')
})
;!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]="c31d461b-8741-0731-04fb-322e2c81cdf1")}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]="daa7096d-88eb-4aef-8d70-6aae41560fce")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -260,10 +260,30 @@ function commonJsRequire(id) {
return getOrInstantiateModuleFromParent(id, this.m).exports;
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
const hashIndex = request.indexOf('#');
if (hashIndex !== -1) {
request = request.substring(0, hashIndex);
}
const queryIndex = request.indexOf('?');
if (queryIndex !== -1) {
request = request.substring(0, queryIndex);
}
return request;
}
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
......@@ -275,6 +295,7 @@ contextPrototype.r = commonJsRequire;
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
......@@ -1837,5 +1858,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=c31d461b-8741-0731-04fb-322e2c81cdf1
//# debugId=daa7096d-88eb-4aef-8d70-6aae41560fce
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -249,10 +249,30 @@ function commonJsRequire(id) {
return getOrInstantiateModuleFromParent(id, this.m).exports;
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
const hashIndex = request.indexOf('#');
if (hashIndex !== -1) {
request = request.substring(0, hashIndex);
}
const queryIndex = request.indexOf('?');
if (queryIndex !== -1) {
request = request.substring(0, queryIndex);
}
return request;
}
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
......@@ -264,6 +284,7 @@ contextPrototype.r = commonJsRequire;
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
......
......@@ -249,10 +249,30 @@ function commonJsRequire(id) {
return getOrInstantiateModuleFromParent(id, this.m).exports;
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
const hashIndex = request.indexOf('#');
if (hashIndex !== -1) {
request = request.substring(0, hashIndex);
}
const queryIndex = request.indexOf('?');
if (queryIndex !== -1) {
request = request.substring(0, queryIndex);
}
return request;
}
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
......@@ -264,6 +284,7 @@ contextPrototype.r = commonJsRequire;
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
......
......@@ -259,10 +259,30 @@ function commonJsRequire(id) {
return getOrInstantiateModuleFromParent(id, this.m).exports;
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
const hashIndex = request.indexOf('#');
if (hashIndex !== -1) {
request = request.substring(0, hashIndex);
}
const queryIndex = request.indexOf('?');
if (queryIndex !== -1) {
request = request.substring(0, queryIndex);
}
return request;
}
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
......@@ -274,6 +294,7 @@ contextPrototype.r = commonJsRequire;
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
......
......@@ -473,10 +473,30 @@ function commonJsRequire(id) {
return getOrInstantiateModuleFromParent(id, this.m).exports;
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
var hashIndex = request.indexOf('#');
if (hashIndex !== -1) {
request = request.substring(0, hashIndex);
}
var queryIndex = request.indexOf('?');
if (queryIndex !== -1) {
request = request.substring(0, queryIndex);
}
return request;
}
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
......@@ -488,6 +508,7 @@ contextPrototype.r = commonJsRequire;
return Object.keys(map);
};
moduleContext.resolve = function(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
......
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