Commit ce6731ea authored by Luke Sandberg's avatar Luke Sandberg Committed by Luke Sandberg

support edge as well, why not

be more aggressive with the patch
parent 48d0172a
...@@ -4035,29 +4035,10 @@ ...@@ -4035,29 +4035,10 @@
} }
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for ( for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var chunks = metadata[1], promises = [], i = 0; globalThis.__next_chunk_load__(chunks[i]);
i < chunks.length; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
i++ }
) {
var thenable = globalThis.__next_chunk_load__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
}
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
if (4 === metadata.length && "function" === typeof moduleExports.then) if (4 === metadata.length && "function" === typeof moduleExports.then)
......
...@@ -2284,24 +2284,9 @@ var instrumentedChunks = new WeakSet(), ...@@ -2284,24 +2284,9 @@ var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet(); loadedChunks = new WeakSet();
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) { for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var thenable = globalThis.__next_chunk_load__(chunks[i]); globalThis.__next_chunk_load__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable); return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
} }
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
......
...@@ -4496,30 +4496,10 @@ ...@@ -4496,30 +4496,10 @@
} }
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for ( for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var chunks = metadata[1], promises = [], i = 0; globalThis.__next_chunk_load__(chunks[i]);
i < chunks.length; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
i++ }
) {
var thenable = globalThis.__next_chunk_load__(chunks[i]);
if (!thenable) continue;
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
}
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
if (4 === metadata.length && "function" === typeof moduleExports.then) if (4 === metadata.length && "function" === typeof moduleExports.then)
......
...@@ -2314,25 +2314,9 @@ var instrumentedChunks = new WeakSet(), ...@@ -2314,25 +2314,9 @@ var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet(); loadedChunks = new WeakSet();
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) { for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var thenable = globalThis.__next_chunk_load__(chunks[i]); globalThis.__next_chunk_load__(chunks[i]);
if (!thenable) continue; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
} }
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
......
...@@ -3989,29 +3989,10 @@ ...@@ -3989,29 +3989,10 @@
} }
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for ( for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var chunks = metadata[1], promises = [], i = 0; globalThis.__next_chunk_load__(chunks[i]);
i < chunks.length; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
i++ }
) {
var thenable = globalThis.__next_chunk_load__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
}
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
if (4 === metadata.length && "function" === typeof moduleExports.then) if (4 === metadata.length && "function" === typeof moduleExports.then)
......
...@@ -2235,24 +2235,9 @@ var instrumentedChunks = new WeakSet(), ...@@ -2235,24 +2235,9 @@ var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet(); loadedChunks = new WeakSet();
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) { for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var thenable = globalThis.__next_chunk_load__(chunks[i]); globalThis.__next_chunk_load__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable); return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
} }
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
......
...@@ -4450,30 +4450,10 @@ ...@@ -4450,30 +4450,10 @@
} }
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for ( for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var chunks = metadata[1], promises = [], i = 0; globalThis.__next_chunk_load__(chunks[i]);
i < chunks.length; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
i++ }
) {
var thenable = globalThis.__next_chunk_load__(chunks[i]);
if (!thenable) continue;
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
}
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
if (4 === metadata.length && "function" === typeof moduleExports.then) if (4 === metadata.length && "function" === typeof moduleExports.then)
......
...@@ -2265,25 +2265,9 @@ var instrumentedChunks = new WeakSet(), ...@@ -2265,25 +2265,9 @@ var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet(); loadedChunks = new WeakSet();
function ignoreReject() {} function ignoreReject() {}
function preloadModule(metadata) { function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) { for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
var thenable = globalThis.__next_chunk_load__(chunks[i]); globalThis.__next_chunk_load__(chunks[i]);
if (!thenable) continue; return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
thenable.then(resolve, ignoreReject);
instrumentedChunks.add(thenable);
}
}
return 4 === metadata.length
? 0 === promises.length
? requireAsyncModule(metadata[0])
: Promise.all(promises).then(function () {
return requireAsyncModule(metadata[0]);
})
: 0 < promises.length
? Promise.all(promises)
: null;
} }
function requireModule(metadata) { function requireModule(metadata) {
var moduleExports = globalThis.__next_require__(metadata[0]); var moduleExports = globalThis.__next_require__(metadata[0]);
......
...@@ -1567,6 +1567,42 @@ export async function copy_vendor_react(task_) { ...@@ -1567,6 +1567,42 @@ export async function copy_vendor_react(task_) {
}) })
.target(`src/compiled/react-dom${packageSuffix}/cjs`) .target(`src/compiled/react-dom${packageSuffix}/cjs`)
/**
* Replaces the body of a named function declaration/expression.
* Finds `function <name>(` and uses brace counting to locate the
* full body, then replaces it with the provided code.
*/
function replaceFunctionBody(
/** @type {string} */ code,
/** @type {string} */ name,
/** @type {string} */ newBody
) {
const needle = `function ${name}(`
const funcStart = code.indexOf(needle)
if (funcStart === -1) {
throw new Error(`replaceFunctionBody: "${name}" not found`)
}
// Find the opening brace of the function body
const openBrace = code.indexOf('{', funcStart + needle.length)
if (openBrace === -1) {
throw new Error(
`replaceFunctionBody: opening brace not found for "${name}"`
)
}
// Count braces to find the matching close
let depth = 1
let pos = openBrace + 1
while (depth > 0 && pos < code.length) {
if (code[pos] === '{') depth++
else if (code[pos] === '}') depth--
pos++
}
// pos is now one past the closing brace
const before = code.slice(0, openBrace + 1)
const after = code.slice(pos - 1) // includes the closing brace
return `${before}\n ${newBody}\n${after}`
}
function replaceIdentifiersInAst( function replaceIdentifiersInAst(
/** @type {recast.types.namedTypes.File} */ ast, /** @type {recast.types.namedTypes.File} */ ast,
/** @type {Map<string, ExpressionKind>} */ replacements /** @type {Map<string, ExpressionKind>} */ replacements
...@@ -1740,17 +1776,22 @@ export async function copy_vendor_react(task_) { ...@@ -1740,17 +1776,22 @@ export async function copy_vendor_react(task_) {
let code = recast.print(ast).code let code = recast.print(ast).code
// In Node.js builds, __next_chunk_load__ may return void when chunk // In Node.js and Edge builds, __next_chunk_load__ returns void
// loading is synchronous (Turbopack on Node.js uses require()). Patch // because chunk loading is synchronous (require() on Node.js,
// preloadModule to skip promise tracking for sync loads so we avoid // pre-bundled on Edge). Replace the entire preloadModule function
// calling .then() on undefined. // to eliminate all promise tracking overhead — the chunks are
// already loaded synchronously, so we just need to call
// __next_chunk_load__ for side effects and handle async modules.
if ( if (
file.base.startsWith('react-server-dom-turbopack-server') && file.base.startsWith('react-server-dom-turbopack-server') &&
file.base.includes('.node.') (file.base.includes('.node.') || file.base.includes('.edge.'))
) { ) {
code = code.replace( code = replaceFunctionBody(
/^([ \t]*)(var thenable = globalThis\.__next_chunk_load__\(chunks\[i\]\);)/gm, code,
'$1$2\n$1if (!thenable) continue;' 'preloadModule',
`for (var chunks = metadata[1], i = 0; i < chunks.length; i++)
globalThis.__next_chunk_load__(chunks[i]);
return 4 === metadata.length ? requireAsyncModule(metadata[0]) : null;`
) )
} }
......
...@@ -17,6 +17,22 @@ type ChunkRunner = { ...@@ -17,6 +17,22 @@ type ChunkRunner = {
runtimeModuleIds: ModuleId[] runtimeModuleIds: ModuleId[]
} }
// Override the shared asyncLoader with an async version for Edge.
// In the Edge runtime, chunk loading is synchronous (all chunks are pre-bundled),
// so the loader may return a plain value or throw. Since dynamic import() must
// always return a Promise per the spec, wrapping in async ensures both success
// values and errors are properly wrapped in a Promise.
async function asyncLoaderEdge(
this: TurbopackBaseContext<Module>,
moduleId: ModuleId
): Promise<Exports> {
const loader = this.r(moduleId) as (
importFunction: EsmImport
) => Exports | Promise<Exports>
return loader(esmImport.bind(this))
}
contextPrototype.A = asyncLoaderEdge
let BACKEND: RuntimeBackend let BACKEND: RuntimeBackend
;(() => { ;(() => {
BACKEND = { BACKEND = {
......
...@@ -197,12 +197,12 @@ impl EcmascriptChunkPlaceable for AsyncLoaderModule { ...@@ -197,12 +197,12 @@ impl EcmascriptChunkPlaceable for AsyncLoaderModule {
let is_sync = matches!( let is_sync = matches!(
*chunking_context.environment().chunk_loading().await?, *chunking_context.environment().chunk_loading().await?,
ChunkLoading::NodeJs ChunkLoading::NodeJs | ChunkLoading::Edge
); );
let code = if is_sync { let code = if is_sync {
// Node.js: chunk loading is synchronous (require()), so we can avoid // Node.js/Edge: chunk loading is synchronous (require() on Node.js,
// all promise overhead. The loader returns the result directly. // pre-bundled on Edge), so we can avoid all promise overhead.
match (id, chunks_data.is_empty()) { match (id, chunks_data.is_empty()) {
(Some(id), true) => { (Some(id), true) => {
formatdoc! { formatdoc! {
...@@ -245,7 +245,7 @@ impl EcmascriptChunkPlaceable for AsyncLoaderModule { ...@@ -245,7 +245,7 @@ impl EcmascriptChunkPlaceable for AsyncLoaderModule {
} }
} }
} else { } else {
// Browser/Edge: chunk loading is async, use promises. // Browser (DOM): chunk loading is async, use promises.
// Single-chunk case avoids Promise.all + map overhead. // Single-chunk case avoids Promise.all + map overhead.
match (id, chunks_data.len()) { match (id, chunks_data.len()) {
(Some(id), 0) => { (Some(id), 0) => {
......
...@@ -162,13 +162,14 @@ impl EcmascriptChunkPlaceable for ManifestLoaderModule { ...@@ -162,13 +162,14 @@ impl EcmascriptChunkPlaceable for ManifestLoaderModule {
let is_sync = matches!( let is_sync = matches!(
*chunking_context.environment().chunk_loading().await?, *chunking_context.environment().chunk_loading().await?,
ChunkLoading::NodeJs ChunkLoading::NodeJs | ChunkLoading::Edge
); );
if is_sync { if is_sync {
// Node.js: all chunk loading is synchronous (require()), so we can // Node.js/Edge: all chunk loading is synchronous (require() on Node.js,
// avoid all promise overhead. Load chunks, require manifest, load // pre-bundled on Edge), so we can avoid all promise overhead. Load
// dynamic chunks, import target — all synchronous. // chunks, require manifest, load dynamic chunks, import target — all
// synchronous.
writedoc!( writedoc!(
code, code,
r#" r#"
...@@ -186,7 +187,7 @@ impl EcmascriptChunkPlaceable for ManifestLoaderModule { ...@@ -186,7 +187,7 @@ impl EcmascriptChunkPlaceable for ManifestLoaderModule {
dynamic_id = StringifyModuleId(&dynamic_id), dynamic_id = StringifyModuleId(&dynamic_id),
)?; )?;
} else { } else {
// Browser/Edge: chunk loading is async, use promises. // Browser (DOM): chunk loading is async, use promises.
// The second stage chunks come from TURBOPACK_REQUIRE at runtime so we // The second stage chunks come from TURBOPACK_REQUIRE at runtime so we
// cannot know their count at codegen time. // cannot know their count at codegen time.
let load_dynamic = formatdoc! { let load_dynamic = formatdoc! {
......
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