Unverified Commit 702eb176 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix client references extraction of CJS exports analysis (#50059)

client refs are not correctly extracted as we're using regex to get the exports names from cjs file. The regex was extracting some bad names from the code source, this PR fixes the regex to make sure they extract the correct content

Fixes NEXT-1213
parent d381d581
...@@ -4,6 +4,26 @@ import type { ...@@ -4,6 +4,26 @@ import type {
} from '../../analysis/get-page-static-info' } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
export function extractCjsExports(source: string) {
// In case the client entry is a CJS module, we need to parse all the exports
// to make sure that the flight manifest plugin can correctly generate the
// manifest.
// TODO: Currently SWC wraps CJS exports with `_export(exports, { ... })`,
// which is tricky to statically analyze. But since the shape is known, we
// use a regex to extract the exports as a workaround. See:
// https://github.com/swc-project/swc/blob/5629e6b5291b416c8316587b67b5e83d011a8c22/crates/swc_ecma_transforms_module/src/util.rs#L295
const matchExportObject = source.match(
/(?<=_export\(exports, {)(.*?)(?=}\);)/gs
)
if (matchExportObject) {
// Match the property name with format <property>: function() ...
return matchExportObject[0].match(/\b\w+(?=:)/g)
}
return null
}
/** /**
* A getter for module build info that casts to the type it should have. * A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it. * We also expose here types to make easier to use it.
......
import { getRSCModuleInformation } from '../../analysis/get-page-static-info' import { getRSCModuleInformation } from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo, extractCjsExports } from './get-module-build-info'
export default async function transformSource( export default async function transformSource(
this: any, this: any,
...@@ -18,22 +18,8 @@ export default async function transformSource( ...@@ -18,22 +18,8 @@ export default async function transformSource(
buildInfo.rsc = getRSCModuleInformation(source, false) buildInfo.rsc = getRSCModuleInformation(source, false)
if (buildInfo.rsc.isClientRef) { if (buildInfo.rsc.isClientRef) {
// In case the client entry is a CJS module, we need to parse all the exports const exportNames = extractCjsExports(source)
// to make sure that the flight manifest plugin can correctly generate the if (exportNames) buildInfo.rsc.clientRefs = exportNames
// manifest.
// TODO: Currently SWC wraps CJS exports with `_export(exports, { ... })`,
// which is tricky to statically analyze. But since the shape is known, we
// use a regex to extract the exports as a workaround. See:
// https://github.com/swc-project/swc/blob/5629e6b5291b416c8316587b67b5e83d011a8c22/crates/swc_ecma_transforms_module/src/util.rs#L295
const matchExportObject = source.match(/\n_export\(exports, {([.\s\S]+)}/m)
if (matchExportObject) {
const matches: string[] = []
const matchExports = matchExportObject[1].matchAll(/([^\s]+):/g)
for (const match of matchExports) {
matches.push(match[1])
}
buildInfo.rsc.clientRefs = matches
}
} }
// This is a server action entry module in the client layer. We need to attach // This is a server action entry module in the client layer. We need to attach
......
...@@ -340,7 +340,7 @@ export class ClientReferenceManifestPlugin { ...@@ -340,7 +340,7 @@ export class ClientReferenceManifestPlugin {
].filter((name) => name !== null) ].filter((name) => name !== null)
moduleExportedKeys.forEach((name) => { moduleExportedKeys.forEach((name) => {
const key = resource + '#' + name const key = getClientReferenceModuleKey(resource, name)
// If the chunk is from `app/` chunkGroup, use it first. // If the chunk is from `app/` chunkGroup, use it first.
// This make sure not to load the overlapped chunk from `pages/` chunkGroup // This make sure not to load the overlapped chunk from `pages/` chunkGroup
......
...@@ -34,6 +34,23 @@ createNextDescribe( ...@@ -34,6 +34,23 @@ createNextDescribe(
buildCommand: 'yarn build', buildCommand: 'yarn build',
}, },
({ next, isNextDev, isNextStart }) => { ({ next, isNextDev, isNextStart }) => {
if (isNextDev) {
it('should have correct client references keys in manifest', async () => {
await next.render('/')
// Check that the client-side manifest is correct before any requests
const clientReferenceManifest = JSON.parse(
await next.readFile('.next/server/client-reference-manifest.json')
)
const clientModulesNames = Object.keys(
clientReferenceManifest.clientModules
)
clientModulesNames.every((name) => {
const [, key] = name.split('#')
return key === undefined || key === '' || key === 'default'
})
})
}
it('should correctly render page returning null', async () => { it('should correctly render page returning null', async () => {
const homeHTML = await next.render('/return-null/page') const homeHTML = await next.render('/return-null/page')
const $ = cheerio.load(homeHTML) const $ = cheerio.load(homeHTML)
......
import { extractCjsExports } from 'next/dist/build/webpack/loaders/get-module-build-info'
describe('extractCjsExports', () => {
it('should extract exports', () => {
const exportNames = extractCjsExports(`
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getServerActionDispatcher: function() {
return getServerActionDispatcher;
},
urlToUrlWithoutFlightMarker: function() {
return urlToUrlWithoutFlightMarker;
},
default: function() {
return AppRouter;
}
});
`)
expect(exportNames).toEqual([
'getServerActionDispatcher',
'urlToUrlWithoutFlightMarker',
'default',
])
})
})
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