@modern-js/builder 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cjs/createBuilder.js +3 -8
  2. package/dist/cjs/plugins/environmentDefaults.js +4 -4
  3. package/dist/cjs/plugins/rscConfig.js +159 -0
  4. package/dist/cjs/{rsc/rsc-css-loader.js → shared/rsc/rsc-server-entry-loader.js} +6 -7
  5. package/dist/esm/createBuilder.mjs +3 -8
  6. package/dist/esm/plugins/environmentDefaults.mjs +4 -4
  7. package/dist/esm/plugins/rscConfig.mjs +112 -0
  8. package/dist/esm/shared/rsc/rsc-server-entry-loader.mjs +7 -0
  9. package/dist/esm-node/createBuilder.mjs +3 -8
  10. package/dist/esm-node/plugins/environmentDefaults.mjs +4 -4
  11. package/dist/esm-node/plugins/rscConfig.mjs +117 -0
  12. package/dist/esm-node/shared/rsc/rsc-server-entry-loader.mjs +8 -0
  13. package/dist/types/plugins/rscConfig.d.ts +18 -0
  14. package/dist/types/shared/rsc/rsc-server-entry-loader.d.ts +5 -0
  15. package/package.json +7 -7
  16. package/dist/cjs/rsc/common.js +0 -157
  17. package/dist/cjs/rsc/plugins/rsbuild-rsc-plugin.js +0 -169
  18. package/dist/cjs/rsc/plugins/rspack-rsc-client-plugin.js +0 -187
  19. package/dist/cjs/rsc/plugins/rspack-rsc-server-plugin.js +0 -245
  20. package/dist/cjs/rsc/rsc-client-loader.js +0 -71
  21. package/dist/cjs/rsc/rsc-server-loader.js +0 -102
  22. package/dist/cjs/rsc/rsc-ssr-loader.js +0 -60
  23. package/dist/esm/rsc/common.mjs +0 -87
  24. package/dist/esm/rsc/plugins/rsbuild-rsc-plugin.mjs +0 -124
  25. package/dist/esm/rsc/plugins/rspack-rsc-client-plugin.mjs +0 -143
  26. package/dist/esm/rsc/plugins/rspack-rsc-server-plugin.mjs +0 -211
  27. package/dist/esm/rsc/rsc-client-loader.mjs +0 -37
  28. package/dist/esm/rsc/rsc-css-loader.mjs +0 -8
  29. package/dist/esm/rsc/rsc-server-loader.mjs +0 -58
  30. package/dist/esm/rsc/rsc-ssr-loader.mjs +0 -26
  31. package/dist/esm-node/rsc/common.mjs +0 -88
  32. package/dist/esm-node/rsc/plugins/rsbuild-rsc-plugin.mjs +0 -126
  33. package/dist/esm-node/rsc/plugins/rspack-rsc-client-plugin.mjs +0 -144
  34. package/dist/esm-node/rsc/plugins/rspack-rsc-server-plugin.mjs +0 -212
  35. package/dist/esm-node/rsc/rsc-client-loader.mjs +0 -38
  36. package/dist/esm-node/rsc/rsc-css-loader.mjs +0 -9
  37. package/dist/esm-node/rsc/rsc-server-loader.mjs +0 -60
  38. package/dist/esm-node/rsc/rsc-ssr-loader.mjs +0 -27
  39. package/dist/types/rsc/common.d.ts +0 -22
  40. package/dist/types/rsc/plugins/rsbuild-rsc-plugin.d.ts +0 -7
  41. package/dist/types/rsc/plugins/rspack-rsc-client-plugin.d.ts +0 -14
  42. package/dist/types/rsc/plugins/rspack-rsc-server-plugin.d.ts +0 -32
  43. package/dist/types/rsc/rsc-client-loader.d.ts +0 -7
  44. package/dist/types/rsc/rsc-css-loader.d.ts +0 -2
  45. package/dist/types/rsc/rsc-server-loader.d.ts +0 -6
  46. package/dist/types/rsc/rsc-ssr-loader.d.ts +0 -6
@@ -1,124 +0,0 @@
1
- import node_path from "node:path";
2
- import fs_extra from "@modern-js/utils/fs-extra";
3
- import { logger } from "@rsbuild/core";
4
- import { rspackRscLayerName } from "../common.mjs";
5
- import { RspackRscClientPlugin } from "./rspack-rsc-client-plugin.mjs";
6
- import { RscServerPlugin } from "./rspack-rsc-server-plugin.mjs";
7
- const CSS_RULE_NAMES = [
8
- 'less',
9
- 'css',
10
- 'scss',
11
- 'sass'
12
- ];
13
- const createVirtualModule = (content)=>`data:text/javascript,${encodeURIComponent(content)}`;
14
- const checkReactVersionAtLeast19 = async (appDir)=>{
15
- const packageJsonPath = node_path.resolve(appDir, 'package.json');
16
- const packageJson = await fs_extra.readJSON(packageJsonPath);
17
- if (!packageJson.dependencies) return false;
18
- const { dependencies } = packageJson;
19
- const reactVersion = dependencies.react;
20
- const reactDomVersion = dependencies['react-dom'];
21
- if (!reactVersion || !reactDomVersion) return false;
22
- const cleanVersion = (version)=>version.replace(/[\^~]/g, '');
23
- const reactVersionParts = cleanVersion(reactVersion).split('.');
24
- const reactDomVersionParts = cleanVersion(reactDomVersion).split('.');
25
- const reactMajor = parseInt(reactVersionParts[0], 10);
26
- const reactDomMajor = parseInt(reactDomVersionParts[0], 10);
27
- if (Number.isNaN(reactMajor) || Number.isNaN(reactDomMajor)) return false;
28
- return reactMajor >= 19 && reactDomMajor >= 19;
29
- };
30
- const rsbuildRscPlugin = ({ appDir, rscClientRuntimePath, rscServerRuntimePath, internalDirectory })=>({
31
- name: 'builder:rsc-rsbuild-plugin',
32
- setup (api) {
33
- api.modifyBundlerChain({
34
- handler: async (chain, { isServer, CHAIN_ID, isWebWorker })=>{
35
- if (!await checkReactVersionAtLeast19(appDir)) {
36
- logger.error('Enable react server component, please make sure the react and react-dom versions are greater than or equal to 19.0.0');
37
- process.exit(1);
38
- }
39
- const entryPath2Name = new Map();
40
- for (const [name, entry] of Object.entries(chain.entryPoints.entries()))entry.values().forEach((value)=>{
41
- entryPath2Name.set(value, name);
42
- });
43
- const jsHandler = ()=>{
44
- const originalJsRule = chain.module.rules.get(CHAIN_ID.RULE.JS);
45
- if (!originalJsRule) throw new Error('Original JS rule not found when setup RSC plugin.');
46
- const originalJsMainRule = originalJsRule.oneOfs.get(CHAIN_ID.ONE_OF.JS_MAIN);
47
- if (!originalJsMainRule) throw new Error('Original JS main rule not found when setup RSC plugin.');
48
- const useBabel = originalJsMainRule.uses.has(CHAIN_ID.USE.BABEL);
49
- const jsLoader = useBabel ? CHAIN_ID.USE.BABEL : CHAIN_ID.USE.SWC;
50
- const jsLoaderOptions = originalJsMainRule.use(jsLoader).get('options');
51
- const jsLoaderPath = originalJsMainRule.use(jsLoader).get('loader');
52
- originalJsRule.oneOfs.delete(CHAIN_ID.ONE_OF.JS_MAIN);
53
- chain.module.rule(CHAIN_ID.RULE.JS).oneOf('rsc-server').issuerLayer(rspackRscLayerName).exclude.add(/universal[/\\]async_storage/).end().use('rsc-server-loader').loader(require.resolve('../rsc-server-loader')).options({
54
- entryPath2Name,
55
- appDir,
56
- runtimePath: rscServerRuntimePath,
57
- internalDirectory
58
- }).end().use(jsLoader).loader(jsLoaderPath).options(jsLoaderOptions).end().end().oneOf('rsc-ssr').exclude.add(/universal[/\\]async_storage/).end().use('rsc-ssr-loader').loader(require.resolve('../rsc-ssr-loader')).options({
59
- entryPath2Name,
60
- internalDirectory
61
- }).end().use(jsLoader).loader(jsLoaderPath).options(jsLoaderOptions).end().end();
62
- };
63
- const layerHandler = ()=>{
64
- const routesFileReg = new RegExp(`${internalDirectory.replace(/[/\\]/g, '[/\\\\]')}[/\\\\][^/\\\\]*[/\\\\]routes`);
65
- chain.module.rule('server-module').resource([
66
- /render[/\\].*[/\\]server[/\\]rsc/,
67
- /AppProxy/,
68
- routesFileReg
69
- ]).layer(rspackRscLayerName).end();
70
- chain.module.rule(rspackRscLayerName).issuerLayer(rspackRscLayerName).resolve.conditionNames.add(rspackRscLayerName).add('...');
71
- chain.module.rule('rsc-common').resource([
72
- /universal[/\\]async_storage/
73
- ]).layer('rsc-common');
74
- };
75
- const flightCssHandler = ()=>{
76
- CSS_RULE_NAMES.forEach((ruleName)=>{
77
- const rule = chain.module.rules.get(ruleName);
78
- if (rule) chain.module.rule(ruleName).use('custom-loader').before('ignore-css').loader(require.resolve('../rsc-css-loader'));
79
- });
80
- };
81
- const addServerRscPlugin = ()=>{
82
- const ServerPlugin = RscServerPlugin;
83
- chain.plugin('rsc-server-plugin').use(ServerPlugin, [
84
- {
85
- entryPath2Name
86
- }
87
- ]);
88
- };
89
- const addRscClientLoader = ()=>{
90
- chain.module.rule('js').use('rsc-client-loader').loader(require.resolve('../rsc-client-loader')).before('babel').options({
91
- callServerImport: rscClientRuntimePath,
92
- registerImport: rscClientRuntimePath
93
- }).end();
94
- };
95
- const addRscClientPlugin = ()=>{
96
- const ClientPlugin = RspackRscClientPlugin;
97
- chain.plugin('rsc-client-plugin').use(ClientPlugin);
98
- };
99
- if (isServer) {
100
- chain.name('server');
101
- layerHandler();
102
- flightCssHandler();
103
- jsHandler();
104
- addServerRscPlugin();
105
- } else if (!isWebWorker) {
106
- chain.name('client');
107
- chain.dependencies([
108
- 'server'
109
- ]);
110
- const entries = chain.entryPoints.entries();
111
- for (const entryName of Object.keys(entries)){
112
- const entryPoint = chain.entry(entryName);
113
- const code = `window.__MODERN_JS_ENTRY_NAME="${entryName}";`;
114
- entryPoint.add(createVirtualModule(code));
115
- }
116
- addRscClientLoader();
117
- addRscClientPlugin();
118
- }
119
- },
120
- order: 'post'
121
- });
122
- }
123
- });
124
- export { rsbuildRscPlugin };
@@ -1,143 +0,0 @@
1
- import path from "path";
2
- import { sharedData } from "../common.mjs";
3
- const hasExtension = (filePath)=>'' !== path.extname(filePath);
4
- class RspackRscClientPlugin {
5
- apply(compiler) {
6
- const { EntryPlugin, RuntimeGlobals, WebpackError, sources: { RawSource } } = compiler.rspack;
7
- const ssrManifest = {
8
- moduleMap: {},
9
- moduleLoading: null,
10
- styles: []
11
- };
12
- const getEntryModule = (compilation)=>{
13
- const entryModules = [];
14
- for (const [, entryValue] of compilation.entries.entries()){
15
- const entryDependency = entryValue.dependencies[0];
16
- if (!entryDependency) {
17
- compilation.errors.push(new WebpackError("Could not find an entry dependency."));
18
- continue;
19
- }
20
- const resolvedModule = compilation.moduleGraph.getModule(entryDependency);
21
- if (resolvedModule) entryModules.push(resolvedModule);
22
- }
23
- if (0 === entryModules.length) {
24
- compilation.errors.push(new WebpackError("Could not find any entries in the compilation."));
25
- return [];
26
- }
27
- return entryModules;
28
- };
29
- const addClientReferencesChunks = (compilation, callback)=>{
30
- const promises = [];
31
- [
32
- ...this.clientReferencesMap.keys()
33
- ].forEach((resourcePath)=>{
34
- const entries = compilation.entries.entries();
35
- for (const [entryName, entry] of entries){
36
- const runtimeName = entry.options.runtime || entryName;
37
- if (hasExtension(entryName)) continue;
38
- const dependency = EntryPlugin.createDependency(resourcePath);
39
- promises.push(new Promise((resolve, reject)=>{
40
- compilation.addInclude(compiler.context, dependency, {
41
- name: entryName
42
- }, (error, module)=>{
43
- if (error) reject(error);
44
- else {
45
- compilation.moduleGraph.getExportsInfo(module).setUsedInUnknownWay(runtimeName);
46
- this.dependencies.push(dependency);
47
- resolve(void 0);
48
- }
49
- });
50
- }));
51
- }
52
- });
53
- if (this.styles && this.styles.size > 0) for (const style of this.styles){
54
- const dependency = EntryPlugin.createDependency(style);
55
- promises.push(new Promise((resolve, reject)=>{
56
- compilation.addInclude(compiler.context, dependency, {
57
- name: void 0
58
- }, (error, module)=>{
59
- if (error) reject(error);
60
- else {
61
- compilation.moduleGraph.getExportsInfo(module).setUsedInUnknownWay(void 0);
62
- this.dependencies.push(dependency);
63
- resolve(void 0);
64
- }
65
- });
66
- }));
67
- }
68
- Promise.all(promises).then(()=>callback(null)).catch((error)=>callback(error));
69
- };
70
- compiler.hooks.finishMake.tapAsync(RspackRscClientPlugin.name, (compilation, callback)=>{
71
- const entryModules = getEntryModule(compilation);
72
- for (const entryModule of entryModules)if (entryModule) addClientReferencesChunks(compilation, callback);
73
- });
74
- compiler.hooks.thisCompilation.tap(RspackRscClientPlugin.name, (compilation)=>{
75
- this.styles = sharedData.get('styles');
76
- this.clientReferencesMap = sharedData.get('clientReferencesMap');
77
- compilation.hooks.additionalTreeRuntimeRequirements.tap(RspackRscClientPlugin.name, (_chunk, runtimeRequirements)=>{
78
- runtimeRequirements.add(RuntimeGlobals.ensureChunkHandlers);
79
- runtimeRequirements.add(RuntimeGlobals.ensureChunk);
80
- runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
81
- });
82
- compilation.hooks.processAssets.tap(RspackRscClientPlugin.name, ()=>{
83
- const clientManifest = {};
84
- const { chunkGraph, moduleGraph } = compilation;
85
- for (const dependency of this.dependencies){
86
- const module = moduleGraph.getModule(dependency);
87
- if (!module) continue;
88
- const resourcePath = module.nameForCondition();
89
- const clientReferences = resourcePath ? this.clientReferencesMap.get(resourcePath) : void 0;
90
- if (clientReferences) {
91
- const moduleId = chunkGraph.getModuleId(module);
92
- const ssrModuleMetaData = {};
93
- for (const { id, exportName, ssrId } of clientReferences){
94
- const clientExportName = exportName;
95
- const ssrExportName = exportName;
96
- const chunksSet = new Set();
97
- for (const chunk of chunkGraph.getModuleChunksIterable(module))chunksSet.add(chunk);
98
- for (const connection of moduleGraph.getOutgoingConnections(module))for (const chunk of chunkGraph.getModuleChunksIterable(connection.module))chunksSet.add(chunk);
99
- const chunks = [];
100
- const styles = [];
101
- for (const chunk of chunksSet)if (chunk.id) {
102
- for (const file of chunk.files)if (file.endsWith('.js')) chunks.push(chunk.id, file);
103
- }
104
- clientManifest[id] = {
105
- id: moduleId,
106
- name: clientExportName,
107
- chunks,
108
- styles
109
- };
110
- if (ssrId) ssrModuleMetaData[clientExportName] = {
111
- id: ssrId,
112
- name: ssrExportName,
113
- chunks: []
114
- };
115
- }
116
- ssrManifest.moduleMap[moduleId] = ssrModuleMetaData;
117
- }
118
- }
119
- compilation.emitAsset(this.clientManifestFilename, new RawSource(JSON.stringify(clientManifest, null, 2), false));
120
- const { crossOriginLoading, publicPath = "" } = compilation.outputOptions;
121
- ssrManifest.moduleLoading = {
122
- prefix: compilation.getPath(publicPath, {
123
- hash: compilation.hash ?? "XXXX"
124
- }),
125
- crossOrigin: crossOriginLoading ? "use-credentials" === crossOriginLoading ? crossOriginLoading : "" : void 0
126
- };
127
- if (this.styles && this.styles.size > 0) {
128
- const assets = compilation.getAssets();
129
- const cssAsset = assets.find((asset)=>asset.name.endsWith('.css'));
130
- if (cssAsset) ssrManifest.styles.push(cssAsset.name);
131
- }
132
- compilation.emitAsset(this.ssrManifestFilename, new RawSource(JSON.stringify(ssrManifest, null, 2), false));
133
- });
134
- });
135
- }
136
- constructor(options){
137
- this.clientReferencesMap = new Map();
138
- this.dependencies = [];
139
- this.clientManifestFilename = options?.clientManifestFilename || "react-client-manifest.json";
140
- this.ssrManifestFilename = options?.ssrManifestFilename || "react-ssr-manifest.json";
141
- }
142
- }
143
- export { RspackRscClientPlugin };
@@ -1,211 +0,0 @@
1
- import { findRootIssuer, getRscBuildInfo, isCssModule, rspackRscLayerName, setRscBuildInfo, sharedData } from "../common.mjs";
2
- const rspack_rsc_server_plugin_resourcePath2Entries = new Map();
3
- class RscServerPlugin {
4
- isValidModule(module) {
5
- return Boolean(module?.resource);
6
- }
7
- hasValidEntries(entries) {
8
- return Boolean(entries && entries.length > 0);
9
- }
10
- getEntryNameFromIssuer(issuer) {
11
- return issuer.resource ? this.entryPath2Name.get(issuer.resource) : void 0;
12
- }
13
- createEntryFromIssuer(issuer, entryName) {
14
- return {
15
- entryName,
16
- entryPath: issuer.resource
17
- };
18
- }
19
- buildModuleToEntriesMapping(compilation) {
20
- this.moduleToEntries.clear();
21
- for (const [entryName, entryDependency] of compilation.entries.entries()){
22
- const entryModule = compilation.moduleGraph.getModule(entryDependency.dependencies[0]);
23
- if (entryModule) this.traverseModulesFromEntry(entryModule, entryName, compilation.moduleGraph, new Set());
24
- }
25
- }
26
- traverseModulesFromEntry(module, entryName, moduleGraph, visited) {
27
- if (!module?.resource || visited.has(module.resource)) return;
28
- visited.add(module.resource);
29
- if (!this.moduleToEntries.has(module.resource)) this.moduleToEntries.set(module.resource, new Set());
30
- this.moduleToEntries.get(module.resource).add(entryName);
31
- for (const connection of moduleGraph.getOutgoingConnections(module))if (connection.module && 'resource' in connection.module) this.traverseModulesFromEntry(connection.module, entryName, moduleGraph, visited);
32
- }
33
- findModuleEntries(module, compilation, resourcePath2Entries, visited = new Set()) {
34
- if (!this.isValidModule(module) || visited.has(module.resource)) return [];
35
- visited.add(module.resource);
36
- const currentEntries = resourcePath2Entries.get(module.resource);
37
- if (this.hasValidEntries(currentEntries)) return currentEntries;
38
- const entryNames = this.moduleToEntries.get(module.resource);
39
- if (entryNames && entryNames.size > 0) {
40
- const entries = [];
41
- for (const entryName of entryNames){
42
- const entryPath = this.getEntryPathByName(entryName, compilation);
43
- if (entryPath) entries.push({
44
- entryName,
45
- entryPath
46
- });
47
- }
48
- return entries;
49
- }
50
- const issuer = findRootIssuer(compilation.moduleGraph, module);
51
- if (!issuer) return [];
52
- const issuerEntries = this.findModuleEntries(issuer, compilation, resourcePath2Entries, visited);
53
- if (issuerEntries.length > 0) return issuerEntries;
54
- const entryName = this.getEntryNameFromIssuer(issuer);
55
- if (entryName) return [
56
- this.createEntryFromIssuer(issuer, entryName)
57
- ];
58
- return [];
59
- }
60
- getEntryPathByName(entryName, compilation) {
61
- const entryDependency = compilation.entries.get(entryName);
62
- if (entryDependency && entryDependency.dependencies.length > 0) {
63
- const firstDep = entryDependency.dependencies[0];
64
- if ('request' in firstDep && 'string' == typeof firstDep.request) return firstDep.request;
65
- }
66
- }
67
- apply(compiler) {
68
- const { EntryPlugin, WebpackError, sources: { RawSource } } = compiler.rspack;
69
- const includeModule = async (compilation, resource, resourceEntryNames, layer)=>{
70
- const entries = Array.from(compilation.entries.entries());
71
- if (0 === entries.length) return void compilation.errors.push(new WebpackError("Could not find an entry in the compilation."));
72
- const includePromises = entries.filter(([entryName])=>resourceEntryNames?.includes(entryName)).map(([entryName])=>{
73
- const dependency = EntryPlugin.createDependency(resource);
74
- return new Promise((resolve, reject)=>{
75
- compilation.addInclude(compiler.context, dependency, {
76
- name: entryName,
77
- layer
78
- }, (error, module)=>{
79
- if (error) {
80
- compilation.errors.push(error);
81
- return reject(error);
82
- }
83
- if (!module) {
84
- const noModuleError = new WebpackError("Module not added");
85
- noModuleError.file = resource;
86
- compilation.errors.push(noModuleError);
87
- return reject(noModuleError);
88
- }
89
- setRscBuildInfo(module, {
90
- __entryName: entryName
91
- });
92
- compilation.moduleGraph.getExportsInfo(module).setUsedInUnknownWay(entryName);
93
- resolve();
94
- });
95
- });
96
- });
97
- await Promise.all(includePromises);
98
- };
99
- let needsAdditionalPass = false;
100
- compiler.hooks.finishMake.tapPromise(RscServerPlugin.name, async (compilation)=>{
101
- this.buildModuleToEntriesMapping(compilation);
102
- const processModules = (modules)=>{
103
- let hasChangeReference = false;
104
- for (const module of modules){
105
- if ('resource' in module && isCssModule(module)) this.styles.add(module.resource);
106
- const buildInfo = getRscBuildInfo(module);
107
- if (!buildInfo || !buildInfo.resourcePath) continue;
108
- if (module.layer && 'server' === buildInfo.type) sharedData.set(buildInfo?.resourcePath, buildInfo);
109
- if (!module.layer && 'client' === buildInfo.type) sharedData.set(buildInfo?.resourcePath, buildInfo);
110
- const currentReference = buildInfo?.type === 'client' ? this.clientReferencesMap.get(buildInfo.resourcePath) : this.serverReferencesMap.get(buildInfo.resourcePath);
111
- if (buildInfo?.type !== 'client' || currentReference) {
112
- if (buildInfo?.type === 'server' && !currentReference) {
113
- hasChangeReference = true;
114
- this.serverReferencesMap.set(buildInfo.resourcePath, buildInfo.exportNames);
115
- }
116
- } else {
117
- hasChangeReference = true;
118
- this.clientReferencesMap.set(buildInfo.resourcePath, buildInfo.clientReferences);
119
- }
120
- const entries = this.findModuleEntries(module, compilation, rspack_rsc_server_plugin_resourcePath2Entries);
121
- if (entries.length > 0) rspack_rsc_server_plugin_resourcePath2Entries.set(module.resource, entries);
122
- }
123
- return hasChangeReference;
124
- };
125
- this.serverManifest = {};
126
- const clientReferences = [
127
- ...this.clientReferencesMap.keys()
128
- ];
129
- const serverReferences = [
130
- ...this.serverReferencesMap.keys()
131
- ];
132
- const referencesBefore = [
133
- ...clientReferences,
134
- ...serverReferences
135
- ];
136
- let hasChangeReference = false;
137
- await Promise.all([
138
- ...clientReferences.map(async (resource)=>{
139
- try {
140
- await includeModule(compilation, resource, rspack_rsc_server_plugin_resourcePath2Entries.get(resource)?.map((entry)=>entry.entryName) || []);
141
- } catch (error) {
142
- console.error(error);
143
- hasChangeReference = true;
144
- this.clientReferencesMap.delete(resource);
145
- }
146
- }),
147
- ...serverReferences.map(async (resource)=>{
148
- try {
149
- await includeModule(compilation, resource, rspack_rsc_server_plugin_resourcePath2Entries.get(resource)?.map((entry)=>entry.entryName) || [], rspackRscLayerName);
150
- } catch (error) {
151
- console.error(error);
152
- hasChangeReference = true;
153
- this.serverReferencesMap.delete(resource);
154
- }
155
- })
156
- ]);
157
- hasChangeReference = processModules(compilation.modules);
158
- const referencesAfter = [
159
- ...this.clientReferencesMap.keys(),
160
- ...this.serverReferencesMap.keys()
161
- ];
162
- if (referencesBefore.length !== referencesAfter.length || !referencesAfter.every((reference)=>referencesBefore.includes(reference)) && hasChangeReference) needsAdditionalPass = true;
163
- });
164
- compiler.hooks.done.tap(RscServerPlugin.name, ()=>{
165
- sharedData.set('serverReferencesMap', this.serverReferencesMap);
166
- sharedData.set('clientReferencesMap', this.clientReferencesMap);
167
- sharedData.set('styles', this.styles);
168
- });
169
- compiler.hooks.afterCompile.tap(RscServerPlugin.name, (compilation)=>{
170
- for (const module of compilation.modules){
171
- const resource = module.nameForCondition();
172
- if (!resource) continue;
173
- const moduleId = compilation.chunkGraph.getModuleId(module);
174
- if (null !== moduleId) {
175
- if (module.layer !== rspackRscLayerName && this.clientReferencesMap.has(resource)) {
176
- const clientReferences = this.clientReferencesMap.get(resource);
177
- if (clientReferences) for (const clientReference of clientReferences)clientReference.ssrId = moduleId;
178
- else compilation.errors.push(new WebpackError(`Could not find client references info in \`clientReferencesMap\` for ${resource}.`));
179
- } else if (module.layer === rspackRscLayerName && getRscBuildInfo(module)?.type === 'server') {
180
- const serverReferencesModuleInfo = getRscBuildInfo(module);
181
- if (serverReferencesModuleInfo) {
182
- serverReferencesModuleInfo.moduleId = moduleId;
183
- for (const exportName of serverReferencesModuleInfo.exportNames)this.serverManifest[`${moduleId}#${exportName}`] = {
184
- id: moduleId,
185
- chunks: [],
186
- name: exportName
187
- };
188
- } else compilation.errors.push(new WebpackError(`Could not find server references module info in \`serverReferencesMap\` for ${resource}.`));
189
- }
190
- }
191
- }
192
- });
193
- compiler.hooks.thisCompilation.tap(RscServerPlugin.name, (compilation)=>{
194
- compilation.hooks.needAdditionalPass.tap(RscServerPlugin.name, ()=>!(needsAdditionalPass = !needsAdditionalPass));
195
- compilation.hooks.processAssets.tap(RscServerPlugin.name, ()=>{
196
- compilation.emitAsset(this.serverManifestFilename, new RawSource(JSON.stringify(this.serverManifest, null, 2), false));
197
- });
198
- });
199
- }
200
- constructor(options){
201
- this.clientReferencesMap = new Map();
202
- this.serverReferencesMap = new Map();
203
- this.serverManifest = {};
204
- this.entryPath2Name = new Map();
205
- this.moduleToEntries = new Map();
206
- this.styles = new Set();
207
- this.serverManifestFilename = options?.serverManifestFilename || "react-server-manifest.json";
208
- this.entryPath2Name = options?.entryPath2Name || new Map();
209
- }
210
- }
211
- export { RscServerPlugin };
@@ -1,37 +0,0 @@
1
- import { isServerModule, parseSource, sharedData } from "./common.mjs";
2
- async function rscClientLoader(source, sourceMap) {
3
- this.cacheable(true);
4
- const callback = this.async();
5
- const ast = await parseSource(source);
6
- const hasUseServerDirective = await isServerModule(ast);
7
- if (!hasUseServerDirective) return void callback(null, source, sourceMap);
8
- const { callServerImport = "@modern-js/runtime/rsc/client", registerImport = "@modern-js/runtime/rsc/client" } = this.getOptions();
9
- const buildInfo = sharedData.get(this.resourcePath);
10
- const moduleInfo = buildInfo ? {
11
- moduleId: buildInfo?.moduleId,
12
- exportNames: buildInfo?.exportNames
13
- } : null;
14
- if (!moduleInfo) {
15
- this.emitError(new Error(`Could not find server module info in \`serverReferencesMap\` for ${this.resourcePath}.`));
16
- callback(null, '');
17
- return;
18
- }
19
- const { moduleId, exportNames } = moduleInfo;
20
- if (!moduleId) {
21
- this.emitError(new Error(`Could not find server module ID in \`serverReferencesMap\` for ${this.resourcePath}.`));
22
- callback(null, '');
23
- return;
24
- }
25
- if (!exportNames) return void callback(null, '');
26
- const importsCode = `
27
- import { createServerReference } from "${registerImport}";
28
- import { callServer } from "${callServerImport}";
29
- `;
30
- const exportsCode = exportNames.map((item)=>{
31
- const name = item;
32
- if ('default' === name) return `export default createServerReference("${moduleId}", callServer);`;
33
- return `export var ${name} = createServerReference("${moduleId}#${name}", callServer);`;
34
- }).join('\n');
35
- callback(null, `${importsCode}\n${exportsCode}`);
36
- }
37
- export { rscClientLoader as default };
@@ -1,8 +0,0 @@
1
- import { setRscBuildInfo } from "./common.mjs";
2
- function rscCssLoader(source) {
3
- this._module && setRscBuildInfo(this._module, {
4
- isCssModule: true
5
- });
6
- return source;
7
- }
8
- export { rscCssLoader as default };
@@ -1,58 +0,0 @@
1
- import path from "path";
2
- import { transform } from "@swc/core";
3
- import { setRscBuildInfo } from "./common.mjs";
4
- function extractMetadata(code) {
5
- const metadataRegex = /\/\* @modern-js-rsc-metadata\n([\s\S]*?)\*\//;
6
- const match = code.match(metadataRegex);
7
- if (!match) return null;
8
- try {
9
- const metadata = JSON.parse(match[1]);
10
- return metadata;
11
- } catch (e) {
12
- console.error('Failed to parse metadata:', e);
13
- return null;
14
- }
15
- }
16
- async function rscServerLoader(source) {
17
- this.cacheable(true);
18
- const callback = this.async();
19
- const { appDir, runtimePath = '@modern-js/runtime/rsc/server' } = this.getOptions();
20
- const result = await transform(source, {
21
- filename: this.resourcePath,
22
- jsc: {
23
- target: 'es2020',
24
- experimental: {
25
- cacheRoot: path.resolve(appDir, 'node_modules/.swc'),
26
- plugins: [
27
- [
28
- require.resolve('@modern-js/flight-server-transform-plugin'),
29
- {
30
- appDir: appDir,
31
- runtimePath: runtimePath
32
- }
33
- ]
34
- ]
35
- }
36
- },
37
- isModule: true
38
- });
39
- const { code, map } = result;
40
- const metadata = extractMetadata(code);
41
- if (metadata?.directive && 'client' === metadata.directive) {
42
- const { exportNames } = metadata;
43
- if (exportNames.length > 0) setRscBuildInfo(this._module, {
44
- type: 'client',
45
- resourcePath: this.resourcePath,
46
- clientReferences: exportNames
47
- });
48
- } else if (metadata) {
49
- const { exportNames } = metadata;
50
- if (exportNames.length > 0) setRscBuildInfo(this._module, {
51
- type: 'server',
52
- resourcePath: this.resourcePath,
53
- exportNames: exportNames.map((item)=>item.exportName)
54
- });
55
- }
56
- return callback(null, code, map);
57
- }
58
- export { rscServerLoader as default };
@@ -1,26 +0,0 @@
1
- import { getExportNames, isServerModule, parseSource, setRscBuildInfo } from "./common.mjs";
2
- async function rscSsrLoader(source, sourceMap) {
3
- this.cacheable(true);
4
- const callback = this.async();
5
- const ast = await parseSource(source);
6
- const hasDeclareServerDirective = await isServerModule(ast);
7
- const resourcePath = this.resourcePath;
8
- if (!hasDeclareServerDirective) return void callback(null, source, sourceMap);
9
- const exportedNames = await getExportNames(ast, true);
10
- const importsCode = `
11
- 'use server';
12
- `;
13
- const exportsCode = exportedNames.map((name)=>{
14
- if ('default' === name) return 'export default () => {throw new Error("Server actions must not be called during server-side rendering.")}';
15
- return `export const ${name} = () => {
16
- throw new Error("Server actions must not be called during server-side rendering.")
17
- }`;
18
- }).join('\n');
19
- if (exportedNames.length > 0) setRscBuildInfo(this._module, {
20
- type: 'server',
21
- resourcePath,
22
- exportNames: exportedNames
23
- });
24
- callback(null, `${importsCode}\n${exportsCode}`, sourceMap);
25
- }
26
- export { rscSsrLoader as default };