Skip to content

[sourcemaps] Ensure codeframe when calling Client Functions from Server #81918

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ impl EcmascriptClientReferenceModule {
writedoc!(
code,
r#"
// This file is generated by next-core EcmascriptClientReferenceModule.
import {{ registerClientReference }} from "react-server-dom-turbopack/server";
"#,
)?;
Expand Down Expand Up @@ -135,6 +136,7 @@ impl EcmascriptClientReferenceModule {
writedoc!(
code,
r#"
// This file is generated by next-core EcmascriptClientReferenceModule.
const {{ createClientModuleProxy }} = require("react-server-dom-turbopack/server");

{TURBOPACK_EXPORT_NAMESPACE}(createClientModuleProxy({server_module_path}));
Expand All @@ -149,11 +151,15 @@ impl EcmascriptClientReferenceModule {

let proxy_source = VirtualSource::new(
self.server_ident.path().await?.join(
// Depending on the original format, we call the file `proxy.mjs` or `proxy.cjs`.
// This is because we're placing the virtual module next to the original code, so
// its parsing will be affected by `type` fields in package.json --
// a bare `proxy.js` may end up being unexpectedly parsed as the wrong format.
&format!("proxy.{}", if is_esm { "mjs" } else { "cjs" }),
// We choose the extension based on the original file because we're placing the
// virtual module next to the original code, so its parsing will be
// affected by `type` fields in package.json -- a bare `proxy.js`
// may end up being unexpectedly parsed as the wrong format.
// The name special cased later to always ignore-list this module.
&format!(
"__nextjs-internal-proxy.{}",
if is_esm { "mjs" } else { "cjs" }
),
)?,
proxy_module_content,
);
Expand Down
2 changes: 2 additions & 0 deletions packages/next/src/build/webpack/config/blocks/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { getRspackCore } from '../../../../shared/lib/get-rspack'
function shouldIgnorePath(modulePath: string): boolean {
return (
modulePath.includes('node_modules') ||
modulePath.endsWith('__nextjs-internal-proxy.cjs') ||
modulePath.endsWith('__nextjs-internal-proxy.mjs') ||
// Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist')
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { NormalModule, webpack } from 'next/dist/compiled/webpack/webpack'
import type {
javascript,
LoaderContext,
NormalModule,
webpack,
} from 'next/dist/compiled/webpack/webpack'
import { RSC_MOD_REF_PROXY_ALIAS } from '../../../../lib/constants'
import {
BARREL_OPTIMIZATION_PREFIX,
Expand All @@ -8,10 +13,7 @@ import { warnOnce } from '../../../../shared/lib/utils/warn-once'
import { getRSCModuleInformation } from '../../../analysis/get-page-static-info'
import { formatBarrelOptimizedResource } from '../../utils'
import { getModuleBuildInfo } from '../get-module-build-info'
import type {
javascript,
LoaderContext,
} from 'next/dist/compiled/webpack/webpack'
import { ModuleFilenameHelpers } from 'next/dist/compiled/webpack/webpack'

type SourceType = javascript.JavascriptParser['sourceType'] | 'commonjs'

Expand Down Expand Up @@ -72,6 +74,7 @@ export default function transformSource(
prefix = `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\n`
source = prefix + source
}
prefix += `// This file is generated by the Webpack next-flight-loader.\n`

// Resource key is the unique identifier for the resource. When RSC renders
// a client module, that key is used to identify that module across all compiler
Expand Down Expand Up @@ -144,7 +147,28 @@ ${JSON.stringify(ref)},
}
}

return this.callback(null, esmSource, sourceMap)
const compilation = this._compilation!
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We completely replaced the original source so the original sourcemap can be discarded.

const originalSourceURL = ModuleFilenameHelpers.createFilename(
module,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, createFilename doesn't exist when using Rspack.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already informed the Rspack team but haven't heard back yet.

{
moduleFilenameTemplate:
'webpack://[namespace]/[resource-path]/__nextjs-internal-proxy.mjs',
namespace: '_N_E',
},
{
requestShortener: compilation.requestShortener,
chunkGraph: compilation.chunkGraph,
hashFunction: compilation.outputOptions.hashFunction,
}
)

return this.callback(null, esmSource, {
version: 3,
sources: [originalSourceURL],
// minimal, parseable mappings
mappings: 'AAAA',
Copy link
Member

@lubieowoce lubieowoce Jul 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe explain why we can get away with emitting no mappings? AFAIU the reasoning is sth like this

Suggested change
// minimal, parseable mappings
// proxy code is ignore-listed, so we don't need an actual sourcemap.
// emit one that's effectively empty, but still parseable.

Copy link
Member

@lubieowoce lubieowoce Jul 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(also personally i wouldn't mind moving this into a helper like createEmptySourceMap(sourceUrl, sourceContent) to have this explanation in one place, but i'm not gonna die on this hill)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not an empty sourcemap. It's just the minimal amount of mappings you need for it to be parseable by the sourcemap parsers we encounter. I need to think more about a sensible explainer to justify the abstraction. Until then I rather have it inline to avoid spreading an abstraction that may be incorrect.

sourcesContent: [esmSource],
})
} else if (assumedSourceType === 'commonjs') {
let cjsSource =
prefix +
Expand All @@ -153,7 +177,29 @@ const { createProxy } = require("${MODULE_PROXY_PATH}")

module.exports = createProxy(${stringifiedResourceKey})
`
return this.callback(null, cjsSource, sourceMap)

const compilation = this._compilation!
const originalSourceURL = ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate:
'webpack://[namespace]/[resource-path]/__nextjs-internal-proxy.cjs',
namespace: '_N_E',
},
{
requestShortener: compilation.requestShortener,
chunkGraph: compilation.chunkGraph,
hashFunction: compilation.outputOptions.hashFunction,
}
)

return this.callback(null, cjsSource, {
version: 3,
sources: [originalSourceURL],
// minimal, parseable mappings
mappings: 'AAAA',
sourcesContent: [cjsSource],
})
}
}

Expand Down
47 changes: 14 additions & 33 deletions test/development/app-dir/source-mapping/source-mapping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const isCacheComponentsEnabled =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'

describe('source-mapping', () => {
const { isTurbopack, next } = nextTestSetup({
const { next } = nextTestSetup({
files: __dirname,
})

Expand Down Expand Up @@ -172,37 +172,18 @@ describe('source-mapping', () => {
it('should show an error when client functions are called from server components', async () => {
const browser = await next.browser('/server-client')

// TODO(veil): Top stack should be ignore-listed
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "Attempted to call useClient() from the server but useClient is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.",
"environmentLabel": "${isCacheComponentsEnabled ? 'Prerender' : 'Server'}",
"label": "Runtime Error",
"source": "app/server-client/client.js/proxy.mjs (3:24) @ <anonymous>
> 3 | function() { throw new Error("Attempted to call useClient() from the server but useClient is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component."); },
| ^",
"stack": [
"<anonymous> app/server-client/client.js/proxy.mjs (3:24)",
"Component app/server-client/page.js (5:12)",
],
}
`)
} else {
await expect(browser).toDisplayRedbox(`
{
"description": "Attempted to call useClient() from the server but useClient is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.",
"environmentLabel": "${isCacheComponentsEnabled ? 'Prerender' : 'Server'}",
"label": "Runtime Error",
"source": "app/server-client/page.js (5:12) @ Component
> 5 | useClient()
| ^",
"stack": [
"<FIXME-file-protocol>",
"Component app/server-client/page.js (5:12)",
],
}
`)
}
await expect(browser).toDisplayRedbox(`
{
"description": "Attempted to call useClient() from the server but useClient is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.",
"environmentLabel": "${isCacheComponentsEnabled ? 'Prerender' : 'Server'}",
"label": "Runtime Error",
"source": "app/server-client/page.js (5:12) @ Component
> 5 | useClient()
| ^",
"stack": [
"Component app/server-client/page.js (5:12)",
],
}
`)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ describe('use-cache-errors', () => {
> 16 | return useStuff()
| ^",
"stack": [
"<FIXME-file-protocol>",
"useCachedStuff app/module-with-use-cache.ts (16:18)",
"Page app/page.tsx (22:10)",
],
Expand Down
2 changes: 2 additions & 0 deletions turbopack/crates/turbopack-core/src/source_map/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub fn add_default_ignore_list(map: &mut swc_sourcemap::SourceMap) {
if source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[next]"))
|| source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[turbopack]"))
|| source.contains("/node_modules/")
|| source.ends_with("__nextjs-internal-proxy.cjs")
|| source.ends_with("__nextjs-internal-proxy.mjs")
{
ignored_ids.insert(source_id);
}
Expand Down
Loading