@module-federation/rspress-plugin 0.0.0-perf-devtools-20260108034446 → 0.0.0-perf-website-code-usage-20260914033703

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.
package/README.md CHANGED
@@ -1,33 +1,32 @@
1
- # @examples/mf-react-component
1
+ # @module-federation/rspress-plugin
2
2
 
3
- This example demonstrates how to use Rslib to build a simple Module Federation React component.
3
+ Module Federation plugin for [Rspress](https://rspress.dev/). Wraps the Rsbuild Module Federation plugin and can rebuild search / LLM indexes from HTML after the build.
4
4
 
5
- ### Command
5
+ ## Install
6
6
 
7
- Build package
8
-
9
- ```
10
- nx build rslib-module
7
+ ```bash
8
+ pnpm add @module-federation/rspress-plugin
11
9
  ```
12
10
 
13
- Serve package
11
+ ## Build
14
12
 
13
+ ```bash
14
+ pnpm --filter @module-federation/rspress-plugin run build
15
15
  ```
16
- nx serve rslib-module
17
- ```
18
-
19
- Dev package
20
16
 
21
- 1.
17
+ ## Usage
22
18
 
23
- ```
24
- nx dev rslib-module
25
- ```
19
+ ```ts
20
+ import { pluginModuleFederation } from '@module-federation/rspress-plugin';
26
21
 
27
- 2.
28
-
29
- ```
30
- nx storybook rslib-module
22
+ export default {
23
+ plugins: [
24
+ pluginModuleFederation({
25
+ name: 'doc-app',
26
+ // ...Module Federation options
27
+ }),
28
+ ],
29
+ };
31
30
  ```
32
31
 
33
- visit http://localhost:6006
32
+ Optional second argument controls Rspress-specific behavior (`autoShared`, `rebuildSearchIndex`, `rebuildLlms`).
package/dist/index.js ADDED
@@ -0,0 +1,461 @@
1
+ import { pluginModuleFederation } from "@module-federation/rsbuild-plugin";
2
+ import { BUILD_002, buildDescMap } from "@module-federation/error-codes";
3
+ import { logAndReport } from "@module-federation/error-codes/node";
4
+ import { createLogger, createModuleFederationConfig } from "@module-federation/sdk";
5
+ import promises from "node:fs/promises";
6
+ import node_path from "node:path";
7
+ import { htmlToText } from "html-to-text";
8
+ import "node:crypto";
9
+ import { groupBy } from "lodash-es";
10
+ import { SEARCH_INDEX_NAME } from "@rspress/shared";
11
+ import path from "path";
12
+ import fs from "fs";
13
+ import * as __rspack_external_cheerio from "cheerio";
14
+ const logger = createLogger('[ Module Federation Rspress Plugin ]');
15
+ const src_logger = logger;
16
+ const replaceHtmlExt = (filepath)=>filepath.replace(node_path.extname(filepath), '.html');
17
+ const routePageToMdFilename = (routePath)=>{
18
+ const fileName = routePath.endsWith('/') ? `${routePath}index.md` : `${routePath}.md`;
19
+ return fileName.replace(/^\/+/, '');
20
+ };
21
+ const addBase = (url, base)=>{
22
+ if (!base || '/' === base) return url;
23
+ return `${base.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
24
+ };
25
+ const routePathToMdPath = (routePath, base)=>{
26
+ const normalizedRoutePath = routePath.replace(/\.html$/, '');
27
+ const mdPath = normalizedRoutePath.endsWith('/') ? `${normalizedRoutePath}index.md` : `${normalizedRoutePath}.md`;
28
+ return addBase(mdPath, base);
29
+ };
30
+ const getRouteHtmlPath = (route, { outputDir, defaultLang })=>replaceHtmlExt(node_path.join(outputDir, route.lang === defaultLang ? route.relativePath.replace(route.lang, '') : route.relativePath));
31
+ function normalizeText(text) {
32
+ return text.replace(/\s+/g, ' ').replace(/^#+\s*/, '').trim();
33
+ }
34
+ function htmlToMarkdown(html) {
35
+ const $ = __rspack_external_cheerio.load(html);
36
+ $("script, style, noscript, template").remove();
37
+ $('header, nav, aside, footer').remove();
38
+ $(".rp-nav,.rp-sidebar,.rp-aside,.rp-footer,.rp-doc-footer,.rp-not-doc").remove();
39
+ const docHtml = $('main').first().html() || $('article').first().html() || $('.rp-doc').first().html() || $('body').html() || html;
40
+ return htmlToText(docHtml, {
41
+ wordwrap: 80,
42
+ selectors: [
43
+ {
44
+ selector: 'a',
45
+ options: {
46
+ ignoreHref: false
47
+ }
48
+ },
49
+ {
50
+ selector: 'img',
51
+ format: 'skip'
52
+ },
53
+ ...[
54
+ 'h1',
55
+ 'h2',
56
+ 'h3',
57
+ 'h4',
58
+ 'h5',
59
+ 'h6'
60
+ ].map((tag)=>({
61
+ selector: tag,
62
+ options: {
63
+ uppercase: false
64
+ }
65
+ }))
66
+ ],
67
+ tables: true,
68
+ longWordSplit: {
69
+ forceWrapOnLimit: true
70
+ }
71
+ }).trim();
72
+ }
73
+ function extractPageInfoFromHtml(html) {
74
+ const $ = __rspack_external_cheerio.load(html);
75
+ const $doc = $('main').first().length ? $('main').first() : $('article').first().length ? $('article').first() : $('.rp-doc').first().length ? $('.rp-doc').first() : $('body');
76
+ $doc.find('a.header-anchor, .header-anchor, .rp-copy, .rp-llms-button').remove();
77
+ const title = normalizeText($doc.find('h1').first().text()) || normalizeText($('h1').first().text()) || normalizeText($('title').first().text());
78
+ const description = $doc.find('p').toArray().map((paragraph)=>normalizeText($(paragraph).text())).find(Boolean);
79
+ return {
80
+ title,
81
+ description
82
+ };
83
+ }
84
+ async function extractRouteMarkdown(routes, options) {
85
+ return Promise.all(routes.map(async (route)=>{
86
+ const htmlPath = getRouteHtmlPath(route, options);
87
+ const html = await promises.readFile(htmlPath, 'utf-8');
88
+ const { title, description } = extractPageInfoFromHtml(html);
89
+ return {
90
+ route,
91
+ markdown: htmlToMarkdown(html),
92
+ title,
93
+ description
94
+ };
95
+ }));
96
+ }
97
+ function getDefaultVersion(routeMarkdownList) {
98
+ return routeMarkdownList.find(({ route })=>route.version)?.route.version;
99
+ }
100
+ function getLlmsOutputPrefix(route, defaultLang, defaultVersion) {
101
+ const langPrefix = route.lang === defaultLang ? '' : `${route.lang}/`;
102
+ const versionPrefix = defaultVersion && route.version && route.version !== defaultVersion ? `${route.version}/` : '';
103
+ return `${versionPrefix}${langPrefix}`;
104
+ }
105
+ function generateLlmsFullTxt(routeMarkdownList, options) {
106
+ return routeMarkdownList.map(({ route, markdown })=>[
107
+ '---',
108
+ `url: ${routePathToMdPath(route.routePath, options.base)}`,
109
+ '---',
110
+ '',
111
+ markdown,
112
+ ''
113
+ ].join('\n')).join('\n');
114
+ }
115
+ async function writeRouteMarkdownIfEmpty(routeMarkdownList, options) {
116
+ await Promise.all(routeMarkdownList.map(async ({ route, markdown })=>{
117
+ const mdFilename = routePageToMdFilename(route.routePath);
118
+ const mdPath = node_path.join(options.outputDir, mdFilename);
119
+ await promises.mkdir(node_path.dirname(mdPath), {
120
+ recursive: true
121
+ });
122
+ let existingContent = '';
123
+ try {
124
+ existingContent = await promises.readFile(mdPath, 'utf-8');
125
+ } catch (error) {
126
+ if ('ENOENT' !== error.code) throw error;
127
+ }
128
+ if (!existingContent.trim()) await promises.writeFile(mdPath, markdown);
129
+ }));
130
+ }
131
+ async function patchLlmsFullTxtIfEmpty(routeMarkdownList, options, outputPrefix) {
132
+ const llmsFullPath = node_path.join(options.outputDir, outputPrefix, 'llms-full.txt');
133
+ await promises.mkdir(node_path.dirname(llmsFullPath), {
134
+ recursive: true
135
+ });
136
+ const markdownMap = new Map(routeMarkdownList.map(({ route, markdown })=>[
137
+ routePathToMdPath(route.routePath, options.base),
138
+ markdown
139
+ ]));
140
+ let original = '';
141
+ try {
142
+ original = await promises.readFile(llmsFullPath, 'utf-8');
143
+ } catch (error) {
144
+ if ('ENOENT' !== error.code) throw error;
145
+ }
146
+ if (!original) return void await promises.writeFile(llmsFullPath, generateLlmsFullTxt(routeMarkdownList, options));
147
+ const patched = original.replace(/(---\nurl:\s*([^\n]+)\n---\n)([\s\S]*?)(?=\n---\nurl:|$)/g, (section, header, url, body)=>{
148
+ if (body.trim()) return section;
149
+ const markdown = markdownMap.get(url.trim());
150
+ if (!markdown) return section;
151
+ return `${header}${markdown}\n`;
152
+ });
153
+ await promises.writeFile(llmsFullPath, patched);
154
+ }
155
+ async function patchLlmsTxtIfEmpty(routeMarkdownList, options, outputPrefix) {
156
+ const llmsPath = node_path.join(options.outputDir, outputPrefix, 'llms.txt');
157
+ let original = '';
158
+ try {
159
+ original = await promises.readFile(llmsPath, 'utf-8');
160
+ } catch (error) {
161
+ if ('ENOENT' !== error.code) throw error;
162
+ return;
163
+ }
164
+ const pageInfoMap = new Map(routeMarkdownList.map(({ route, title, description })=>[
165
+ routePathToMdPath(route.routePath, options.base),
166
+ {
167
+ title,
168
+ description
169
+ }
170
+ ]));
171
+ const patched = original.replace(/^- \[\]\(([^)]+)\)(?::\s*)?$/gm, (line, url)=>{
172
+ const pageInfo = pageInfoMap.get(url.trim());
173
+ if (!pageInfo?.title) return line;
174
+ const suffix = pageInfo.description ? `: ${pageInfo.description}` : '';
175
+ return `- [${pageInfo.title}](${url})${suffix}`;
176
+ });
177
+ if (patched !== original) await promises.writeFile(llmsPath, patched);
178
+ }
179
+ async function rebuildLlmsByHtml(routes, options) {
180
+ const routeMarkdownList = await extractRouteMarkdown(routes, options);
181
+ const defaultVersion = options.defaultVersion || getDefaultVersion(routeMarkdownList);
182
+ const groupedRouteMarkdown = new Map();
183
+ await writeRouteMarkdownIfEmpty(routeMarkdownList, options);
184
+ for (const routeMarkdown of routeMarkdownList){
185
+ const outputPrefix = getLlmsOutputPrefix(routeMarkdown.route, options.defaultLang, defaultVersion);
186
+ const group = groupedRouteMarkdown.get(outputPrefix) || [];
187
+ group.push(routeMarkdown);
188
+ groupedRouteMarkdown.set(outputPrefix, group);
189
+ }
190
+ await Promise.all(Array.from(groupedRouteMarkdown.entries()).map(async ([outputPrefix, group])=>{
191
+ await patchLlmsTxtIfEmpty(group, options, outputPrefix);
192
+ await patchLlmsFullTxtIfEmpty(group, options, outputPrefix);
193
+ }));
194
+ }
195
+ function findSearchIndexPaths(outputDir) {
196
+ const staticDir = path.join(outputDir, 'static');
197
+ if (!fs.existsSync(staticDir)) return;
198
+ const files = fs.readdirSync(staticDir);
199
+ const searchIndexFiles = files.filter((file)=>file.startsWith(SEARCH_INDEX_NAME) && file.endsWith('.json') && fs.statSync(path.join(staticDir, file)).isFile());
200
+ if (searchIndexFiles) return searchIndexFiles.map((searchIndexFile)=>path.join(staticDir, searchIndexFile));
201
+ }
202
+ function generateTocFromHtml(html) {
203
+ const $ = __rspack_external_cheerio.load(html);
204
+ const headings = $('h1, h2, h3, h4, h5, h6');
205
+ const toc = [];
206
+ let title = '';
207
+ headings.each((index, heading)=>{
208
+ const $heading = $(heading);
209
+ const text = $heading.text();
210
+ const id = $heading.attr('id');
211
+ const depth = parseInt(heading.tagName.replace('h', ''), 10);
212
+ if (id) toc.push({
213
+ text,
214
+ id,
215
+ depth
216
+ });
217
+ if (1 === depth) title = text;
218
+ });
219
+ return {
220
+ toc,
221
+ title
222
+ };
223
+ }
224
+ const rebuildSearchIndexByHtml_replaceHtmlExt = (filepath)=>filepath.replace(node_path.extname(filepath), '.html');
225
+ async function extractPageDataFromHtml(routes, options) {
226
+ return Promise.all(routes.map(async (route)=>{
227
+ const { searchCodeBlocks, outputDir, defaultLang } = options;
228
+ const defaultIndexInfo = {
229
+ title: '',
230
+ content: '',
231
+ _flattenContent: '',
232
+ routePath: route.routePath,
233
+ lang: route.lang,
234
+ toc: [],
235
+ frontmatter: {},
236
+ version: route.version,
237
+ _filepath: route.absolutePath,
238
+ _relativePath: ''
239
+ };
240
+ const htmlPath = rebuildSearchIndexByHtml_replaceHtmlExt(node_path.join(outputDir, route.lang === defaultLang ? route.relativePath.replace(route.lang, '') : route.relativePath));
241
+ const html = await promises.readFile(htmlPath, 'utf-8');
242
+ let { toc: rawToc, title } = generateTocFromHtml(html);
243
+ let content = html;
244
+ content = htmlToText(html, {
245
+ wordwrap: 80,
246
+ selectors: [
247
+ {
248
+ selector: 'a',
249
+ options: {
250
+ ignoreHref: true
251
+ }
252
+ },
253
+ {
254
+ selector: 'img',
255
+ format: 'skip'
256
+ },
257
+ {
258
+ selector: 'pre > code',
259
+ format: searchCodeBlocks ? 'block' : 'skip'
260
+ },
261
+ ...[
262
+ 'h1',
263
+ 'h2',
264
+ 'h3',
265
+ 'h4',
266
+ 'h5',
267
+ 'h6'
268
+ ].map((tag)=>({
269
+ selector: tag,
270
+ options: {
271
+ uppercase: false
272
+ }
273
+ }))
274
+ ],
275
+ tables: true,
276
+ longWordSplit: {
277
+ forceWrapOnLimit: true
278
+ }
279
+ });
280
+ if (content.startsWith(title)) content = content.slice(title.length);
281
+ const toc = rawToc.map((item)=>{
282
+ const match = item.id.match(/-(\d+)$/);
283
+ let position = -1;
284
+ if (match) for(let i = 0; i < Number(match[1]); i++){
285
+ position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
286
+ if (-1 === position) break;
287
+ }
288
+ return {
289
+ ...item,
290
+ charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
291
+ };
292
+ });
293
+ return {
294
+ ...defaultIndexInfo,
295
+ title,
296
+ toc,
297
+ content
298
+ };
299
+ }));
300
+ }
301
+ function deletePrivateField(obj) {
302
+ if ('object' != typeof obj || null === obj) return obj;
303
+ const newObj = {
304
+ ...obj
305
+ };
306
+ for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
307
+ return newObj;
308
+ }
309
+ async function rebuildSearchIndexByHtml(routes, options) {
310
+ const { versioned, outputDir } = options;
311
+ const searchFilePaths = findSearchIndexPaths(outputDir);
312
+ if (!searchFilePaths) {
313
+ src_logger.error('Cannot find search index files!');
314
+ process.exit(1);
315
+ }
316
+ const pages = await extractPageDataFromHtml(routes, options);
317
+ const groupedPages = groupBy(pages, (page)=>{
318
+ if (page.frontmatter?.pageType === 'home') return 'noindex';
319
+ const version = versioned ? page.version : '';
320
+ const lang = page.lang || '';
321
+ return `${version}###${lang}`;
322
+ });
323
+ delete groupedPages.noindex;
324
+ await Promise.all(Object.keys(groupedPages).map(async (group)=>{
325
+ const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
326
+ const [version, lang] = group.split('###');
327
+ const indexVersion = version ? `.${version.replace('.', '_')}` : '';
328
+ const indexLang = lang ? `.${lang}` : '';
329
+ const searchFilePath = searchFilePaths.find((filePath)=>filePath.replace(`${node_path.dirname(filePath)}/`, '').startsWith(`${SEARCH_INDEX_NAME}${indexVersion}${indexLang}`));
330
+ if (!searchFilePath) {
331
+ src_logger.error(`Cannot find search index file for version ${version} and lang ${lang}!`);
332
+ process.exit(1);
333
+ }
334
+ await promises.writeFile(searchFilePath, stringifiedIndex);
335
+ }));
336
+ }
337
+ const isDev = ()=>'development' === process.env.NODE_ENV;
338
+ function plugin_pluginModuleFederation(mfConfig, rspressOptions) {
339
+ const { autoShared = true, rebuildSearchIndex = true, rebuildLlms = true } = rspressOptions || {};
340
+ if (autoShared) mfConfig.shared = {
341
+ react: {
342
+ singleton: true,
343
+ requiredVersion: false
344
+ },
345
+ 'react-dom': {
346
+ singleton: true,
347
+ requiredVersion: false
348
+ },
349
+ 'react/': {
350
+ singleton: true,
351
+ requiredVersion: false
352
+ },
353
+ 'react-dom/': {
354
+ singleton: true,
355
+ requiredVersion: false
356
+ },
357
+ '@mdx-js/react': {
358
+ singleton: true,
359
+ requiredVersion: false
360
+ },
361
+ '@rspress/core/runtime': {
362
+ singleton: true,
363
+ requiredVersion: false
364
+ },
365
+ 'react-router-dom': {
366
+ singleton: true,
367
+ requiredVersion: false
368
+ },
369
+ ...mfConfig.shared
370
+ };
371
+ mfConfig.experiments ||= {};
372
+ mfConfig.experiments.asyncStartup = true;
373
+ let enableSSG = false;
374
+ let outputDir = '';
375
+ let routes = [];
376
+ return {
377
+ name: 'plugin-module-federation',
378
+ async config (config) {
379
+ if (!isDev() && false !== config.ssg) {
380
+ enableSSG = true;
381
+ if (config.llms) {
382
+ src_logger.info('Detect you set "llms: true", enable experimentalWorker for ssg to enable parallel build');
383
+ config.ssg = {
384
+ ...'object' == typeof config.ssg ? config.ssg : {},
385
+ experimentalWorker: true
386
+ };
387
+ }
388
+ }
389
+ config.builderConfig ||= {};
390
+ config.builderConfig.plugins ||= [];
391
+ config.builderConfig.plugins.push(pluginModuleFederation(mfConfig, {
392
+ target: enableSSG ? 'dual' : 'web',
393
+ ssrDir: 'mf-ssg'
394
+ }));
395
+ return config;
396
+ },
397
+ builderConfig: {
398
+ plugins: [],
399
+ tools: {
400
+ rspack (config) {
401
+ if ('node' === config.name) {
402
+ if (('/' === config.output.publicPath || 'auto' === config.output.publicPath) && mfConfig.exposes) {
403
+ logAndReport(BUILD_002, buildDescMap, {
404
+ publicPath: config.output.publicPath
405
+ }, src_logger.error.bind(src_logger), void 0, {
406
+ bundler: {
407
+ name: 'rsbuild'
408
+ },
409
+ mfConfig: {
410
+ name: mfConfig.name,
411
+ filename: mfConfig.filename,
412
+ exposes: mfConfig.exposes
413
+ }
414
+ });
415
+ process.exit(1);
416
+ }
417
+ outputDir = config.output.path;
418
+ }
419
+ }
420
+ }
421
+ },
422
+ routeGenerated (routeMetaArr) {
423
+ routes = routeMetaArr;
424
+ },
425
+ async afterBuild (config) {
426
+ const shouldRebuildLlms = Boolean(config.llms && rebuildLlms);
427
+ if (!mfConfig.remotes || isDev() || !rebuildSearchIndex && !shouldRebuildLlms) return;
428
+ if (!enableSSG) {
429
+ src_logger.error('rebuildSearchIndex and rebuildLlms are only supported for ssg');
430
+ process.exit(1);
431
+ }
432
+ const defaultLang = config.lang || 'en';
433
+ if (rebuildSearchIndex) {
434
+ const searchConfig = config?.search || {};
435
+ const replaceRules = config?.replaceRules || [];
436
+ const domain = '';
437
+ const versioned = searchConfig && searchConfig.versioned;
438
+ const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
439
+ await rebuildSearchIndexByHtml(routes, {
440
+ outputDir,
441
+ versioned,
442
+ replaceRules,
443
+ domain,
444
+ searchCodeBlocks,
445
+ defaultLang
446
+ });
447
+ src_logger.info('rebuildSearchIndex success!');
448
+ }
449
+ if (shouldRebuildLlms) {
450
+ await rebuildLlmsByHtml(routes, {
451
+ outputDir,
452
+ defaultLang,
453
+ base: config.base,
454
+ defaultVersion: config.multiVersion?.default
455
+ });
456
+ src_logger.info('rebuildLlms success!');
457
+ }
458
+ }
459
+ };
460
+ }
461
+ export { createModuleFederationConfig, plugin_pluginModuleFederation as pluginModuleFederation };
@@ -1,8 +1,9 @@
1
1
  import type { moduleFederationPlugin } from '@module-federation/sdk';
2
- import type { RspressPlugin } from '@rspress/shared';
2
+ import type { RspressPlugin } from '@rspress/core';
3
3
  type RspressPluginOptions = {
4
4
  autoShared?: boolean;
5
5
  rebuildSearchIndex?: boolean;
6
+ rebuildLlms?: boolean;
6
7
  };
7
8
  export declare function pluginModuleFederation(mfConfig: moduleFederationPlugin.ModuleFederationPluginOptions, rspressOptions?: RspressPluginOptions): RspressPlugin;
8
9
  export { createModuleFederationConfig } from '@module-federation/sdk';
@@ -0,0 +1,8 @@
1
+ import type { RouteMeta } from '@rspress/shared';
2
+ export type RebuildLlmsByHtmlOptions = {
3
+ outputDir: string;
4
+ defaultLang: string;
5
+ base?: string;
6
+ defaultVersion?: string;
7
+ };
8
+ export declare function rebuildLlmsByHtml(routes: RouteMeta[], options: RebuildLlmsByHtmlOptions): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/rspress-plugin",
3
- "version": "0.0.0-perf-devtools-20260108034446",
3
+ "version": "0.0.0-perf-website-code-usage-20260914033703",
4
4
  "type": "module",
5
5
  "description": "Module Federation plugin for Rspress",
6
6
  "keywords": [
@@ -23,32 +23,37 @@
23
23
  "author": "hanric <hanric.zhang@gmail.com>",
24
24
  "exports": {
25
25
  ".": {
26
- "types": "./dist/esm/packages/rspress-plugin/src/plugin.d.ts",
27
- "import": "./dist/esm/index.js"
26
+ "types": "./dist/plugin.d.ts",
27
+ "import": "./dist/index.js"
28
28
  }
29
29
  },
30
- "module": "./dist/esm/index.js",
31
- "types": "./dist/esm/packages/rspress-plugin/src/plugin.d.ts",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/plugin.d.ts",
32
32
  "devDependencies": {
33
- "@rslib/core": "^0.9.2",
34
- "@rspress/shared": "2.0.0-beta.16",
33
+ "@rslib/core": "^0.23.2",
34
+ "@rspress/core": "2.0.14",
35
35
  "@types/html-to-text": "^9.0.4",
36
36
  "@types/lodash-es": "^4.17.12",
37
- "@types/react": "^18.3.11"
37
+ "@types/react": "^18.3.11",
38
+ "typescript": "7.0.2"
38
39
  },
39
40
  "dependencies": {
40
41
  "cheerio": "1.0.0-rc.12",
41
- "fs-extra": "11.3.0",
42
- "html-to-text": "^9.0.5",
43
- "lodash-es": "^4.17.21",
44
- "@module-federation/sdk": "0.0.0-perf-devtools-20260108034446",
45
- "@module-federation/enhanced": "0.0.0-perf-devtools-20260108034446",
46
- "@module-federation/rsbuild-plugin": "0.0.0-perf-devtools-20260108034446",
47
- "@module-federation/error-codes": "0.0.0-perf-devtools-20260108034446"
42
+ "html-to-text": "9.0.5",
43
+ "lodash-es": "4.18.1",
44
+ "@rspress/shared": "2.0.14",
45
+ "@module-federation/sdk": "0.0.0-perf-website-code-usage-20260914033703",
46
+ "@module-federation/enhanced": "0.0.0-perf-website-code-usage-20260914033703",
47
+ "@module-federation/rsbuild-plugin": "0.0.0-perf-website-code-usage-20260914033703",
48
+ "@module-federation/error-codes": "0.0.0-perf-website-code-usage-20260914033703"
49
+ },
50
+ "peerDependencies": {
51
+ "@rspress/core": "2.0.14"
48
52
  },
49
53
  "scripts": {
50
54
  "build": "rslib build",
51
- "dev": "rslib mf-dev",
52
- "build:watch": "rslib build --watch"
55
+ "build:watch": "rslib build --watch",
56
+ "dev": "pnpm run build:watch",
57
+ "pre-release": "pnpm exec turbo run build --filter=@module-federation/webpack-bundler-runtime"
53
58
  }
54
59
  }
package/dist/esm/index.js DELETED
@@ -1,296 +0,0 @@
1
- import external_path_default from "path";
2
- import external_fs_extra_default from "fs-extra";
3
- import { pluginModuleFederation } from "@module-federation/rsbuild-plugin";
4
- import { BUILD_002, buildDescMap, getShortErrorMsg } from "@module-federation/error-codes";
5
- import { createLogger, createModuleFederationConfig } from "@module-federation/sdk";
6
- import promises_default from "node:fs/promises";
7
- import external_node_path_default from "node:path";
8
- import { load } from "cheerio";
9
- import { htmlToText } from "html-to-text";
10
- import { groupBy } from "lodash-es";
11
- import external_fs_default from "fs";
12
- const logger = createLogger('[ Module Federation Rspress Plugin ]');
13
- const src_logger = logger;
14
- const SEARCH_INDEX_NAME = 'search_index';
15
- function findSearchIndexPaths(outputDir) {
16
- const staticDir = external_path_default.join(outputDir, 'static');
17
- if (!external_fs_default.existsSync(staticDir)) return;
18
- const files = external_fs_default.readdirSync(staticDir);
19
- const searchIndexFiles = files.filter((file)=>file.startsWith(SEARCH_INDEX_NAME) && file.endsWith('.json') && external_fs_default.statSync(external_path_default.join(staticDir, file)).isFile());
20
- if (searchIndexFiles) return searchIndexFiles.map((searchIndexFile)=>external_path_default.join(staticDir, searchIndexFile));
21
- }
22
- function generateTocFromHtml(html) {
23
- const $ = load(html);
24
- const headings = $('h1, h2, h3, h4, h5, h6');
25
- const toc = [];
26
- let title = '';
27
- headings.each((index, heading)=>{
28
- const $heading = $(heading);
29
- const text = $heading.text();
30
- const id = $heading.attr('id');
31
- const depth = parseInt(heading.tagName.replace('h', ''), 10);
32
- if (id) toc.push({
33
- text,
34
- id,
35
- depth
36
- });
37
- if (1 === depth) title = text;
38
- });
39
- return {
40
- toc,
41
- title
42
- };
43
- }
44
- const replaceHtmlExt = (filepath)=>filepath.replace(external_node_path_default.extname(filepath), '.html');
45
- async function extractPageDataFromHtml(routes, options) {
46
- return Promise.all(routes.map(async (route)=>{
47
- const { domain, searchCodeBlocks, outputDir, defaultLang } = options;
48
- const defaultIndexInfo = {
49
- title: '',
50
- content: '',
51
- _html: '',
52
- _flattenContent: '',
53
- routePath: route.routePath,
54
- lang: route.lang,
55
- toc: [],
56
- domain,
57
- frontmatter: {},
58
- version: route.version,
59
- _filepath: route.absolutePath,
60
- _relativePath: ''
61
- };
62
- const htmlPath = replaceHtmlExt(external_node_path_default.join(outputDir, route.lang === defaultLang ? route.relativePath.replace(route.lang, '') : route.relativePath));
63
- const html = await promises_default.readFile(htmlPath, 'utf-8');
64
- let { toc: rawToc, title } = generateTocFromHtml(html);
65
- let content = html;
66
- content = htmlToText(html, {
67
- wordwrap: 80,
68
- selectors: [
69
- {
70
- selector: 'a',
71
- options: {
72
- ignoreHref: true
73
- }
74
- },
75
- {
76
- selector: 'img',
77
- format: 'skip'
78
- },
79
- {
80
- selector: 'pre > code',
81
- format: searchCodeBlocks ? 'block' : 'skip'
82
- },
83
- ...[
84
- 'h1',
85
- 'h2',
86
- 'h3',
87
- 'h4',
88
- 'h5',
89
- 'h6'
90
- ].map((tag)=>({
91
- selector: tag,
92
- options: {
93
- uppercase: false
94
- }
95
- }))
96
- ],
97
- tables: true,
98
- longWordSplit: {
99
- forceWrapOnLimit: true
100
- }
101
- });
102
- if (content.startsWith(title)) content = content.slice(title.length);
103
- const toc = rawToc.map((item)=>{
104
- const match = item.id.match(/-(\d+)$/);
105
- let position = -1;
106
- if (match) for(let i = 0; i < Number(match[1]); i++){
107
- position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
108
- if (-1 === position) break;
109
- }
110
- return {
111
- ...item,
112
- charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
113
- };
114
- });
115
- return {
116
- ...defaultIndexInfo,
117
- title,
118
- toc,
119
- content,
120
- _html: html
121
- };
122
- }));
123
- }
124
- function deletePrivateField(obj) {
125
- if ('object' != typeof obj || null === obj) return obj;
126
- const newObj = {
127
- ...obj
128
- };
129
- for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
130
- return newObj;
131
- }
132
- async function rebuildSearchIndexByHtml(routes, options) {
133
- const { versioned, outputDir } = options;
134
- const searchFilePaths = findSearchIndexPaths(outputDir);
135
- if (!searchFilePaths) {
136
- src_logger.error('Cannot find search index files!');
137
- process.exit(1);
138
- }
139
- const pages = await extractPageDataFromHtml(routes, options);
140
- const groupedPages = groupBy(pages, (page)=>{
141
- if (page.frontmatter?.pageType === 'home') return 'noindex';
142
- const version = versioned ? page.version : '';
143
- const lang = page.lang || '';
144
- return `${version}###${lang}`;
145
- });
146
- delete groupedPages.noindex;
147
- await Promise.all(Object.keys(groupedPages).map(async (group)=>{
148
- const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
149
- const [version, lang] = group.split('###');
150
- const indexVersion = version ? `.${version.replace('.', '_')}` : '';
151
- const indexLang = lang ? `.${lang}` : '';
152
- const searchFilePath = searchFilePaths.find((filePath)=>filePath.replace(`${external_node_path_default.dirname(filePath)}/`, '').startsWith(`${SEARCH_INDEX_NAME}${indexVersion}${indexLang}`));
153
- if (!searchFilePath) {
154
- src_logger.error(`Cannot find search index file for version ${version} and lang ${lang}!`);
155
- process.exit(1);
156
- }
157
- await promises_default.writeFile(searchFilePath, stringifiedIndex);
158
- }));
159
- }
160
- const isDev = ()=>'development' === process.env.NODE_ENV;
161
- function replaceEntryWithBootstrapEntry(bundlerConfig) {
162
- const { entry } = bundlerConfig;
163
- if (!entry) {
164
- src_logger.error('No entry found!');
165
- process.exit(1);
166
- }
167
- if ('function' == typeof entry) {
168
- src_logger.error('Not support entry function!');
169
- process.exit(1);
170
- }
171
- const replaceWithAsyncEntry = (entries, entryName)=>{
172
- const entryPath = external_path_default.resolve(process.cwd(), `node_modules/.federation/${entryName}-bootstrap.js`);
173
- external_fs_extra_default.ensureDirSync(external_path_default.dirname(entryPath));
174
- if ('string' == typeof entries) {
175
- external_fs_extra_default.writeFileSync(entryPath, `const entry = import ('${entries}');
176
- const render = entry.then(({render})=>(render));
177
- const routes = entry.then(({routes})=>(routes));
178
- export {
179
- render,
180
- routes
181
- };`);
182
- return entryPath;
183
- }
184
- external_fs_extra_default.writeFileSync(entryPath, `const entry = import ('${entries.slice(-1)[0]}');
185
- const render = entry.then(({render})=>(render));
186
- const routes = entry.then(({routes})=>(routes));
187
- export {
188
- render,
189
- routes
190
- };`);
191
- return entries.slice(0, -1).concat(entryPath);
192
- };
193
- if ('object' == typeof entry && !Array.isArray(entry)) return void Object.keys(entry).forEach((entryName)=>{
194
- const entryValue = entry[entryName];
195
- if (!Array.isArray(entryValue)) {
196
- src_logger.error(`Not support entry ${typeof entryValue}!`);
197
- process.exit(1);
198
- }
199
- entry[entryName] = replaceWithAsyncEntry(entryValue, `${entryName}${bundlerConfig.name ? `-${bundlerConfig.name}` : ''}`);
200
- });
201
- bundlerConfig.entry = replaceWithAsyncEntry(entry, bundlerConfig.name || 'index');
202
- }
203
- function plugin_pluginModuleFederation(mfConfig, rspressOptions) {
204
- const { autoShared = true, rebuildSearchIndex = true } = rspressOptions || {};
205
- if (autoShared) mfConfig.shared = {
206
- react: {
207
- singleton: true,
208
- requiredVersion: false
209
- },
210
- 'react-dom': {
211
- singleton: true,
212
- requiredVersion: false
213
- },
214
- 'react/': {
215
- singleton: true,
216
- requiredVersion: false
217
- },
218
- 'react-dom/': {
219
- singleton: true,
220
- requiredVersion: false
221
- },
222
- '@mdx-js/react': {
223
- singleton: true,
224
- requiredVersion: false
225
- },
226
- '@rspress/runtime': {
227
- singleton: true,
228
- requiredVersion: false
229
- },
230
- ...mfConfig.shared
231
- };
232
- let enableSSG = false;
233
- let outputDir = '';
234
- let routes = [];
235
- return {
236
- name: 'plugin-module-federation',
237
- async config (config) {
238
- if (!isDev() && false !== config.ssg) enableSSG = true;
239
- config.builderConfig ||= {};
240
- config.builderConfig.dev ||= {};
241
- if (isDev() && void 0 === config.builderConfig.dev.lazyCompilation) {
242
- src_logger.warn('lazyCompilation is not fully supported for module federation, set lazyCompilation to false');
243
- config.builderConfig.dev.lazyCompilation = false;
244
- }
245
- config.builderConfig.plugins ||= [];
246
- config.builderConfig.plugins.push(pluginModuleFederation(mfConfig, {
247
- ssr: enableSSG,
248
- environment: 'node',
249
- ssrDir: 'mf-ssg'
250
- }));
251
- return config;
252
- },
253
- builderConfig: {
254
- plugins: [],
255
- tools: {
256
- rspack (config) {
257
- replaceEntryWithBootstrapEntry(config);
258
- if ('node' === config.name) {
259
- if (('/' === config.output.publicPath || 'auto' === config.output.publicPath) && mfConfig.exposes) {
260
- src_logger.error(getShortErrorMsg(BUILD_002, buildDescMap, {
261
- publicPath: config.output.publicPath
262
- }));
263
- process.exit(1);
264
- }
265
- outputDir = config.output.path;
266
- }
267
- }
268
- }
269
- },
270
- routeGenerated (routeMetaArr) {
271
- routes = routeMetaArr;
272
- },
273
- async afterBuild (config) {
274
- if (!mfConfig.remotes || isDev() || !rebuildSearchIndex) return;
275
- if (!enableSSG) {
276
- src_logger.error('rebuildSearchIndex is only supported for ssg');
277
- process.exit(1);
278
- }
279
- const searchConfig = config?.search || {};
280
- const replaceRules = config?.replaceRules || [];
281
- const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
282
- const versioned = searchConfig && 'remote' !== searchConfig.mode && searchConfig.versioned;
283
- const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
284
- await rebuildSearchIndexByHtml(routes, {
285
- outputDir,
286
- versioned,
287
- replaceRules,
288
- domain,
289
- searchCodeBlocks,
290
- defaultLang: config.lang || 'en'
291
- });
292
- src_logger.info('rebuildSearchIndex success!');
293
- }
294
- };
295
- }
296
- export { createModuleFederationConfig, plugin_pluginModuleFederation as pluginModuleFederation };