@rspress/core 2.0.0-beta.3 → 2.0.0-beta.31

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/dist/index.js CHANGED
@@ -1,170 +1,175 @@
1
- import __rslib_shim_module__ from 'module';
2
- const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_plugin_container_syntax_12d3c700__ from "@rspress/plugin-container-syntax";
1
+ /*! For license information please see index.js.LICENSE.txt */
4
2
  import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
5
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
6
5
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
7
- import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__ from "@rsbuild/plugin-react";
8
6
  import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
9
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__ from "@rspress/shared/logger";
10
- import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
11
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__ from "@rspress/shared/constants";
12
- import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
13
- import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
14
- import * as __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__ from "rspack-plugin-virtual-module";
15
- import * as __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__ from "lodash-es";
16
- import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
17
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__ from "@rspress/mdx-rs";
18
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
19
- import * as __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__ from "html-to-text";
20
- import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
21
- import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
22
- import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
23
- import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module";
24
- import * as __WEBPACK_EXTERNAL_MODULE__dr_pogodin_react_helmet_ecf718aa__ from "@dr.pogodin/react-helmet";
25
- import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
26
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
27
- export * from "@rspress/shared";
28
- class PluginDriver {
29
- #config;
30
- #plugins;
31
- #isProd;
32
- constructor(config, isProd){
33
- this.#config = config;
34
- this.#isProd = isProd;
35
- this.#plugins = [];
7
+ import { matchPath } from "@rspress/runtime/server";
8
+ import { logger } from "@rspress/shared/logger";
9
+ import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
10
+ import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
11
+ import { createRequire } from "node:module";
12
+ import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
13
+ import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
14
+ import picocolors from "picocolors";
15
+ import { glob } from "tinyglobby";
16
+ import { chunk, groupBy } from "lodash-es";
17
+ import { compile } from "@rspress/mdx-rs";
18
+ import { htmlToText } from "html-to-text";
19
+ import { createProcessor } from "@mdx-js/mdx";
20
+ import enhanced_resolve from "enhanced-resolve";
21
+ import { createHash } from "node:crypto";
22
+ import { createHead, transformHtmlTemplate } from "@unhead/react/server";
23
+ import { visit } from "unist-util-visit";
24
+ import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
25
+ var __webpack_modules__ = {
26
+ "@rspress/shared": function(module) {
27
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
28
+ },
29
+ "node:fs": function(module) {
30
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
31
+ },
32
+ "node:os": function(module) {
33
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__;
34
+ },
35
+ "node:path": function(module) {
36
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
37
+ },
38
+ "node:url": function(module) {
39
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
36
40
  }
37
- async init() {
38
- this.clearPlugins();
39
- const config = this.#config;
40
- const themeConfig = config?.themeConfig || {};
41
- const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
42
- const mediumZoomConfig = config?.mediumZoom ?? true;
43
- const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
44
- if (enableLastUpdated) {
45
- const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
46
- this.addPlugin(pluginLastUpdated());
47
- }
48
- if (mediumZoomConfig) {
49
- const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
50
- this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
51
- }
52
- this.addPlugin((0, __WEBPACK_EXTERNAL_MODULE__rspress_plugin_container_syntax_12d3c700__.pluginContainerSyntax)());
53
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isDevDebugMode)()) {
54
- const SourceBuildPlugin = await import("@rspress/theme-default/node/source-build-plugin.js").then((r)=>r.SourceBuildPlugin, ()=>null);
55
- if (SourceBuildPlugin) this.addPlugin(SourceBuildPlugin());
56
- }
57
- (config.plugins || []).forEach((plugin)=>{
58
- this.addPlugin(plugin);
41
+ };
42
+ var __webpack_module_cache__ = {};
43
+ function __webpack_require__(moduleId) {
44
+ var cachedModule = __webpack_module_cache__[moduleId];
45
+ if (void 0 !== cachedModule) return cachedModule.exports;
46
+ var module = __webpack_module_cache__[moduleId] = {
47
+ exports: {}
48
+ };
49
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
50
+ return module.exports;
51
+ }
52
+ __webpack_require__.m = __webpack_modules__;
53
+ (()=>{
54
+ __webpack_require__.d = (exports, definition)=>{
55
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
56
+ enumerable: true,
57
+ get: definition[key]
59
58
  });
60
- if (!haveNavSidebarConfig) {
61
- const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
62
- this.addPlugin(pluginAutoNavSidebar());
59
+ };
60
+ })();
61
+ (()=>{
62
+ __webpack_require__.f = {};
63
+ __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
64
+ __webpack_require__.f[key](chunkId, promises);
65
+ return promises;
66
+ }, []));
67
+ })();
68
+ (()=>{
69
+ __webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
70
+ })();
71
+ (()=>{
72
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
73
+ })();
74
+ (()=>{
75
+ var installedChunks = {
76
+ 410: 0
77
+ };
78
+ var installChunk = (data)=>{
79
+ var __webpack_ids__ = data.__webpack_ids__;
80
+ var __webpack_modules__ = data.__webpack_modules__;
81
+ var __webpack_runtime__ = data.__webpack_runtime__;
82
+ var moduleId, chunkId, i = 0;
83
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
84
+ if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
85
+ for(; i < __webpack_ids__.length; i++){
86
+ chunkId = __webpack_ids__[i];
87
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
88
+ installedChunks[__webpack_ids__[i]] = 0;
63
89
  }
64
- }
65
- addPlugin(plugin) {
66
- const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
67
- if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
68
- this.#plugins.push(plugin);
69
- }
70
- getPlugins() {
71
- return this.#plugins;
72
- }
73
- clearPlugins() {
74
- this.#plugins = [];
75
- }
76
- removePlugin(pluginName) {
77
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
78
- if (-1 !== index) this.#plugins.splice(index, 1);
79
- }
80
- async modifyConfig() {
81
- let config = this.#config;
82
- for(let i = 0; i < this.#plugins.length; i++){
83
- const plugin = this.#plugins[i];
84
- if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
85
- addPlugin: this.addPlugin.bind(this),
86
- removePlugin: (pluginName)=>{
87
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
88
- this.removePlugin(pluginName);
89
- if (index <= i && index > 0) i--;
90
- }
91
- }, this.#isProd);
90
+ };
91
+ __webpack_require__.f.j = function(chunkId, promises) {
92
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
93
+ if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
94
+ else {
95
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
96
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
97
+ throw e;
98
+ });
99
+ var promise = Promise.race([
100
+ promise,
101
+ new Promise((resolve)=>{
102
+ installedChunkData = installedChunks[chunkId] = [
103
+ resolve
104
+ ];
105
+ })
106
+ ]);
107
+ promises.push(installedChunkData[1] = promise);
92
108
  }
93
- this.#config = config;
94
- return this.#config;
95
- }
96
- async beforeBuild() {
97
- return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
98
- }
99
- async afterBuild() {
100
- return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
101
- }
102
- async modifySearchIndexData(pages) {
103
- return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
104
- }
105
- async extendPageData(pageData) {
106
- return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
107
- }
108
- async addPages() {
109
- const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
110
- return result.flat();
111
- }
112
- async routeGenerated(routes) {
113
- return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
114
- }
115
- async routeServiceGenerated(routeService) {
116
- return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
117
- }
118
- async addRuntimeModules() {
119
- const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
120
- return result.reduce((prev, current)=>({
121
- ...prev,
122
- ...current
123
- }), {});
124
- }
125
- async addSSGRoutes() {
126
- const result = await this._runParallelAsyncHook('addSSGRoutes', this.#config || {}, this.#isProd);
127
- return result.flat();
128
- }
129
- globalUIComponents() {
130
- const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
131
- return result.flat();
132
- }
133
- globalStyles() {
134
- return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
135
- }
136
- _runParallelAsyncHook(hookName, ...args) {
137
- return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
138
- }
139
- _runSerialAsyncHook(hookName, ...args) {
140
- return this.#plugins.reduce(async (prev, plugin)=>{
141
- if ('function' == typeof plugin[hookName]) {
142
- await prev;
143
- return plugin[hookName](...args);
144
- }
145
- return prev;
146
- }, Promise.resolve());
147
- }
109
+ };
110
+ })();
111
+ var shared_ = __webpack_require__("@rspress/shared");
112
+ function defineConfig(config) {
113
+ return config;
148
114
  }
115
+ var external_node_path_ = __webpack_require__("node:path");
116
+ var external_node_url_ = __webpack_require__("node:url");
117
+ var package_namespaceObject = JSON.parse('{"rE":"2.0.0-beta.31"}');
118
+ const RSPRESS_VERSION = package_namespaceObject.rE;
119
+ const isProduction = ()=>'production' === process.env.NODE_ENV;
120
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
121
+ const inlineThemeScript = `{
122
+ const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
123
+ const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
124
+ const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
125
+ document.documentElement.classList.toggle('dark', isDark)
126
+ document.documentElement.classList.toggle('rp-dark', isDark)
127
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
128
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
129
+ const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
130
+ const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
131
+ const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
132
+ const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
133
+ const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
134
+ const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
135
+ const OUTPUT_DIR = 'doc_build';
136
+ const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
137
+ const HEAD_MARKER = '<!--<?- HEAD ?>-->';
138
+ const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
139
+ const DEFAULT_TITLE = 'Rspress';
140
+ const PUBLIC_DIR = 'public';
141
+ const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
142
+ const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
143
+ const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
149
144
  const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
150
145
  const pluginVirtualModule = (pluginOptions = {})=>({
151
146
  name: PLUGIN_VIRTUAL_MODULE_NAME,
152
147
  async setup (api) {
153
- const TEMP_DIR = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), 'node_modules/.rsbuild-virtual-module');
154
- const { virtualModules = {} } = pluginOptions;
148
+ const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
149
+ const TEMP_DIR = (0, external_node_path_.join)(api.context.rootPath, 'node_modules', virtualFolderName);
155
150
  const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
156
- let absolutePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(TEMP_DIR, i);
157
- if (!(0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
151
+ let absolutePath = (0, external_node_path_.join)(TEMP_DIR, i);
152
+ if (!(0, external_node_path_.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
158
153
  return [
159
154
  i,
160
155
  absolutePath
161
156
  ];
162
157
  });
158
+ api.modifyRsbuildConfig((config)=>{
159
+ if (!config.source) config.source = {};
160
+ config.source.include = [
161
+ ...config.source.include || [],
162
+ TEMP_DIR
163
+ ];
164
+ });
163
165
  api.onBeforeCreateCompiler(async ()=>{
164
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.mkdir)(TEMP_DIR, {
165
- recursive: true
166
- });
167
- await Promise.all(virtualFileAbsolutePaths.map(([_, absolutePath])=>(0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.writeFile)(absolutePath, '', 'utf-8')));
166
+ await Promise.all(virtualFileAbsolutePaths.map(async ([_, absolutePath])=>{
167
+ const dir = (0, external_node_path_.dirname)(absolutePath);
168
+ await mkdir(dir, {
169
+ recursive: true
170
+ });
171
+ return writeFile(absolutePath, '', 'utf-8');
172
+ }));
168
173
  });
169
174
  api.modifyBundlerChain((chain)=>{
170
175
  chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
@@ -177,43 +182,16 @@ const pluginVirtualModule = (pluginOptions = {})=>({
177
182
  }
178
183
  }
179
184
  });
180
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.3"}');
181
- const RSPRESS_VERSION = package_namespaceObject.i8;
182
- const isProduction = ()=>'production' === process.env.NODE_ENV;
183
- const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
184
- const inlineThemeScript = `{
185
- const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
186
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
187
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
188
- document.documentElement.classList.toggle('dark', isDark)
189
- document.documentElement.classList.toggle('rp-dark', isDark)
190
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
191
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
192
- const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
193
- const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
194
- const TEMPLATE_PATH = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html');
195
- const CSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
196
- const SSR_CLIENT_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
197
- const SSR_SERVER_ENTRY = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
198
- const OUTPUT_DIR = 'doc_build';
199
- const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
200
- const HEAD_MARKER = '<!--<?- HEAD ?>-->';
201
- const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
202
- const HTML_START_TAG = '<html';
203
- const BODY_START_TAG = '<body';
204
- const DEFAULT_TITLE = 'Rspress';
205
- const PUBLIC_DIR = 'public';
206
- const constants_TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
207
185
  async function pathExists(path) {
208
186
  try {
209
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].access(path);
187
+ await node_fs_promises.access(path);
210
188
  return true;
211
189
  } catch {
212
190
  return false;
213
191
  }
214
192
  }
215
193
  async function readJson(path) {
216
- const raw = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(path, 'utf8');
194
+ const raw = await node_fs_promises.readFile(path, 'utf8');
217
195
  return JSON.parse(raw);
218
196
  }
219
197
  const THEME_DEFAULT_EXPORT_PATTERN = /export\s+default\s+\{/;
@@ -226,84 +204,129 @@ async function hintThemeBreakingChange(customThemeDir) {
226
204
  ];
227
205
  let useDefaultExportFilePath = null;
228
206
  for (const file of fileList){
229
- const filePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(customThemeDir, file);
207
+ const filePath = (0, external_node_path_.join)(customThemeDir, file);
230
208
  if (await pathExists(filePath)) {
231
- const content = await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.readFile)(filePath, {
209
+ const content = await readFile(filePath, {
232
210
  encoding: 'utf-8'
233
211
  });
234
212
  if (THEME_DEFAULT_EXPORT_PATTERN.test(content)) useDefaultExportFilePath = filePath;
235
213
  break;
236
214
  }
237
215
  }
238
- if (useDefaultExportFilePath) __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, __WEBPACK_EXTERNAL_MODULE_picocolors__["default"].redBright(`
239
- - import Theme from '@rspress/theme-default';
216
+ if (useDefaultExportFilePath) logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${picocolors.greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, picocolors.redBright(`
217
+ - import Theme from '@rspress/core/theme';
240
218
  - export default {
241
219
  - ...Theme,
242
220
  - Layout,
243
221
  - };
244
- - export * from 'rspress/theme';`) + __WEBPACK_EXTERNAL_MODULE_picocolors__["default"].greenBright(`
245
- + import { Layout } from '@rspress/theme-default';
222
+ - export * from '@rspress/core/theme';`) + picocolors.greenBright(`
223
+ + import { Layout } from '@rspress/core/theme';
246
224
 
247
225
  + export { Layout };
248
- + export * from 'rspress/theme';
226
+ + export * from '@rspress/core/theme';
249
227
  `));
250
228
  }
229
+ function hintBuilderPluginsBreakingChange(config) {
230
+ if ('builderPlugins' in config && Array.isArray(config.builderPlugins) && config.builderPlugins.length > 0) {
231
+ logger.error(`[Rspress v2] The "builderPlugins" option has been renamed to "builderConfig.plugins", please update your config accordingly (https://rspress.rs/api/config/config-build#builderconfigplugins).\n`, `
232
+ export default defineConfig({
233
+ ${picocolors.redBright(` builderPlugins: [
234
+ pluginFoo()
235
+ ],`)}
236
+ ${picocolors.greenBright(` builderConfig: {
237
+ plugins: [
238
+ pluginFoo()
239
+ ],
240
+ },`)}
241
+ });`);
242
+ process.exit(1);
243
+ }
244
+ }
251
245
  function hintSSGFailed() {
252
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
246
+ logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
253
247
  1. Fix code to make it SSR-compatible.
254
- 2. Set \`ssg: false\`, but the SSG feature will be lost.`);
248
+ 2. Set \`ssg: false\` if the code in node_modules may be difficult to fix, but the SSG feature will be lost.`);
255
249
  }
256
250
  function hintSSGFalse() {
257
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('`ssg: false` detected, SSG will be disabled.');
251
+ logger.info('`ssg: false` detected, SSG will be disabled.');
258
252
  }
259
- const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
260
- function slash(p) {
261
- return p.replace(/\\/g, '/');
253
+ function hintReactVersion() {
254
+ logger.info('[Rspress v2] Rspress support React 18 and 19, please confirm that both react and react-dom are installed in package.json with the same version. ');
262
255
  }
263
- function normalizePath(id) {
264
- return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
256
+ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
257
+ if (metaJson.some((i)=>'object' == typeof i && ('activeMatch' in i || 'text' in i || 'link' in i || 'items' in i || 'icon' in i || 'ariaLabel' in i || 'target' in i))) {
258
+ const error = new Error('[Rspress v2] Detected that you are still using top level `_meta.json` to configure the nav, but it has been changed to `_nav.json` in Rspress v2. Please rename the top level `_meta.json` to `_nav.json` accordingly.');
259
+ logger.error(error);
260
+ const dir = (0, external_node_path_.relative)(docsDir, metaJsonDir);
261
+ logger.info(`Please rename "${picocolors.greenBright((0, external_node_path_.join)(dir, '_meta.json'))}" to "${picocolors.greenBright((0, external_node_path_.join)(dir, '_nav.json'))}".`);
262
+ process.exit(1);
263
+ }
264
+ }
265
+ let isLogged = false;
266
+ function hintRelativeMarkdownLink() {
267
+ if (isLogged) return;
268
+ isLogged = true;
269
+ logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
265
270
  }
266
271
  function getPageKey(route) {
267
- const cleanRoute = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeLeadingSlash)(route);
272
+ const cleanRoute = (0, shared_.removeLeadingSlash)(route);
268
273
  return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
269
274
  }
270
- const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
271
- const hasTrailSlash = routePath.endsWith('/');
275
+ var external_node_os_ = __webpack_require__("node:os");
276
+ const isWindows = 'win32' === external_node_os_["default"].platform();
277
+ function slash(p) {
278
+ return p.replace(/\\/g, '/');
279
+ }
280
+ function normalizePath(id) {
281
+ return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
282
+ }
283
+ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
284
+ const [versionPart, langPart, purePath] = splitRoutePathParts(relativePath, lang, version, langs, versions);
285
+ return [
286
+ versionPart === version ? '' : versionPart,
287
+ langPart === lang ? '' : langPart,
288
+ purePath
289
+ ];
290
+ };
291
+ const splitRoutePathParts = (relativePath, lang, version, langs, versions)=>{
292
+ const hasTrailSlash = relativePath.endsWith('/');
272
293
  let versionPart = '';
273
294
  let langPart = '';
274
295
  let purePathPart = '';
275
- const parts = routePath.split('/').filter(Boolean);
296
+ const parts = relativePath.split('/').filter(Boolean);
276
297
  if (version) {
277
298
  const versionToMatch = parts[0];
278
- if (versions.includes(versionToMatch)) {
279
- if (versionToMatch !== version) versionPart = versionToMatch;
280
- parts.shift();
281
- }
299
+ if (versions.includes(versionToMatch)) versionPart = parts.shift() ?? '';
282
300
  }
283
301
  if (lang) {
284
302
  const langToMatch = parts[0];
285
- if (langs.includes(langToMatch)) {
286
- if (langToMatch !== lang) langPart = langToMatch;
287
- parts.shift();
288
- }
303
+ if (langs.includes(langToMatch)) langPart = parts.shift() ?? '';
289
304
  }
290
305
  purePathPart = parts.join('/');
291
306
  return [
292
307
  versionPart,
293
308
  langPart,
294
- hasTrailSlash ? (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addTrailingSlash)(purePathPart) : purePathPart
309
+ hasTrailSlash ? (0, shared_.addTrailingSlash)(purePathPart) : purePathPart
295
310
  ];
296
311
  };
297
- const normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS)=>{
298
- const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
312
+ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
299
313
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
300
314
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
301
- const normalizedRoutePath = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)([
302
- versionPart,
303
- langPart
304
- ].filter(Boolean).join('/') + (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(purePathPart)).replace(cleanExtensionPattern, '').replace(/\.html$/, '').replace(/\/index$/, '/');
315
+ let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
316
+ if (routePath.endsWith('/')) routePath = `${routePath}index`;
317
+ const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
318
+ routePath = purePathPart.replace(/\/index$/, '/');
319
+ if ('index' === routePath) routePath = '';
320
+ const normalizedRoutePath = (0, shared_.addLeadingSlash)([
321
+ ...[
322
+ versionPart,
323
+ langPart
324
+ ].filter(Boolean),
325
+ routePath
326
+ ].join('/'));
305
327
  return {
306
- routePath: (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(normalizedRoutePath, base),
328
+ pureRoutePath: `/${routePath}`,
329
+ routePath: normalizedRoutePath,
307
330
  lang: langPart || lang,
308
331
  version: versionPart || version
309
332
  };
@@ -312,37 +335,54 @@ class RouteService {
312
335
  routeData = new Map();
313
336
  #scanDir;
314
337
  #defaultLang;
315
- #defaultVersion = '';
316
- #extensions = [];
317
- #langs = [];
318
- #versions = [];
319
- #include = [];
320
- #exclude = [];
321
- #base = '';
322
- #tempDir = '';
338
+ #defaultVersion;
339
+ #extensions;
340
+ #langs;
341
+ #versions;
342
+ #include;
343
+ #exclude;
344
+ #excludeConvention;
345
+ #tempDir;
323
346
  #pluginDriver;
347
+ static __instance__ = null;
348
+ static getInstance() {
349
+ return RouteService.__instance__;
350
+ }
351
+ static async create(options) {
352
+ const { scanDir, config, runtimeTempDir, pluginDriver } = options;
353
+ const routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
354
+ RouteService.__instance__ = routeService;
355
+ await routeService.#init();
356
+ await pluginDriver.routeServiceGenerated(routeService);
357
+ return routeService;
358
+ }
324
359
  constructor(scanDir, userConfig, tempDir, pluginDriver){
325
360
  const routeOptions = userConfig?.route || {};
326
361
  this.#scanDir = scanDir;
327
- this.#extensions = routeOptions.extensions || __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS;
362
+ this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
328
363
  this.#include = routeOptions.include || [];
329
364
  this.#exclude = routeOptions.exclude || [];
365
+ this.#excludeConvention = routeOptions.excludeConvention || [
366
+ '**/_[^_]*'
367
+ ];
330
368
  this.#defaultLang = userConfig?.lang || '';
331
369
  this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
332
- this.#base = userConfig?.base || '';
333
370
  this.#tempDir = tempDir;
334
371
  this.#pluginDriver = pluginDriver;
335
372
  if (userConfig.multiVersion) {
336
373
  this.#defaultVersion = userConfig.multiVersion.default || '';
337
374
  this.#versions = userConfig.multiVersion.versions || [];
375
+ } else {
376
+ this.#defaultVersion = '';
377
+ this.#versions = [];
338
378
  }
339
379
  }
340
380
  get extensions() {
341
381
  return this.#extensions;
342
382
  }
343
- async init() {
383
+ async #init() {
344
384
  const extensions = this.#extensions.map((i)=>i.slice(1));
345
- const files = (await (0, __WEBPACK_EXTERNAL_MODULE_tinyglobby__.glob)([
385
+ const files = (await glob([
346
386
  `**/*.{${extensions.join(',')}}`,
347
387
  ...this.#include
348
388
  ], {
@@ -351,209 +391,621 @@ class RouteService {
351
391
  onlyFiles: true,
352
392
  ignore: [
353
393
  ...this.#exclude,
394
+ ...this.#excludeConvention,
354
395
  '**/node_modules/**',
355
396
  '**/.eslintrc.js',
356
397
  '**/.nx/**',
357
- `./${PUBLIC_DIR}/**`
398
+ `./${PUBLIC_DIR}/**`,
399
+ '**/*.d.ts'
358
400
  ]
359
401
  })).sort();
360
402
  files.forEach((filePath)=>{
361
- const fileRelativePath = normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filePath));
362
- const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
363
- const absolutePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(this.#scanDir, fileRelativePath);
364
- const routeInfo = {
365
- routePath,
366
- absolutePath: normalizePath(absolutePath),
367
- relativePath: fileRelativePath,
368
- pageName: getPageKey(fileRelativePath),
369
- lang,
370
- version
371
- };
372
- this.addRoute(routeInfo);
403
+ const routePage = RoutePage.create(filePath, this.#scanDir);
404
+ this.addRoute(routePage);
373
405
  });
374
406
  const externalPages = await this.#pluginDriver.addPages();
375
407
  await Promise.all(externalPages.map(async (route, index)=>{
376
408
  const { routePath, content, filepath } = route;
377
409
  if (filepath) {
378
- const routeInfo = this.#generateRouteInfo(routePath, filepath);
379
- this.addRoute(routeInfo);
410
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
411
+ this.addRoute(routePage);
380
412
  return;
381
413
  }
382
414
  if (content) {
383
415
  const filepath = await this.#writeTempFile(index, content);
384
- const routeInfo = this.#generateRouteInfo(routePath, filepath);
385
- this.addRoute(routeInfo);
416
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
417
+ this.addRoute(routePage);
386
418
  }
387
419
  }));
388
420
  await this.#pluginDriver.routeGenerated(this.getRoutes());
389
421
  }
390
- addRoute(routeInfo) {
391
- const { routePath, absolutePath } = routeInfo;
392
- if (this.routeData.has(routePath)) {
393
- const preRouteExtIndex = this.#extensions.indexOf(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(this.routeData.get(routePath).absolutePath));
394
- const currRouteExtIndex = this.#extensions.indexOf(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(absolutePath));
395
- if (-1 !== currRouteExtIndex && (currRouteExtIndex < preRouteExtIndex || -1 === preRouteExtIndex)) this.routeData.set(routePath, routeInfo);
396
- } else this.routeData.set(routePath, routeInfo);
397
- }
398
- removeRoute(filePath) {
399
- const fileRelativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filePath);
400
- const { routePath } = this.normalizeRoutePath(fileRelativePath);
401
- this.routeData.delete(routePath);
422
+ async addRoute(routePage) {
423
+ const { routeMeta: { routePath } } = routePage;
424
+ if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
425
+ this.routeData.set(routePath, routePage);
402
426
  }
403
427
  getRoutes() {
404
- return Array.from(this.routeData.values());
428
+ return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
405
429
  }
406
- isExistRoute(routePath) {
407
- const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
408
- return Boolean(this.routeData.get(normalizedRoute));
430
+ getRoutePages() {
431
+ return Array.from(this.routeData.values());
409
432
  }
410
- isEmpty() {
411
- return 0 === this.routeData.size;
433
+ isExistRoute(link) {
434
+ function linkToRoutePath(routePath) {
435
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
436
+ }
437
+ const cleanLinkPath = linkToRoutePath(link);
438
+ if (!this.routeData.has((0, shared_.removeTrailingSlash)(cleanLinkPath)) && !this.routeData.has((0, shared_.addTrailingSlash)(cleanLinkPath))) return false;
439
+ return true;
412
440
  }
413
- generateRoutesCode(isStaticImport = false) {
414
- return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);
441
+ generateRoutesCode() {
442
+ return this.generateRoutesCodeByRouteMeta(this.getRoutes());
415
443
  }
416
- generateRoutesCodeByRouteMeta(routeMeta, isStaticImport) {
444
+ generateRoutesCodeByRouteMeta(routeMeta) {
417
445
  return `
418
446
  import React from 'react';
419
447
  import { lazyWithPreload } from "react-lazy-with-preload";
420
- ${routeMeta.map((route, index)=>isStaticImport ? `import * as Route${index} from '${route.absolutePath}';` : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
448
+ ${routeMeta.map((route, index)=>`const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
421
449
  export const routes = [
422
450
  ${routeMeta.map((route, index)=>{
423
- const preload = isStaticImport ? `() => Route${index}` : `async () => {
451
+ const preload = `async () => {
424
452
  await Route${index}.preload();
425
453
  return import("${route.absolutePath}");
426
454
  }`;
427
- const component = isStaticImport ? `Route${index}.default` : `Route${index}`;
455
+ const component = `Route${index}`;
428
456
  return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
429
457
  }).join(',\n')}
430
458
  ];
431
459
  `;
432
460
  }
433
- getRoutePathParts(routePath) {
434
- return getRoutePathParts(routePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
461
+ getRoutePathParts(relativePath) {
462
+ return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
463
+ }
464
+ splitRoutePathParts(relativePath) {
465
+ return splitRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
435
466
  }
436
- normalizeRoutePath(routePath) {
437
- return normalizeRoutePath(routePath, this.#base, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
467
+ normalizeRoutePath(relativePath) {
468
+ return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
469
+ }
470
+ absolutePathToRoutePath(absolutePath) {
471
+ return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
472
+ }
473
+ isInDocsDir(absolutePath) {
474
+ const relativePath = external_node_path_["default"].relative(this.#scanDir, absolutePath);
475
+ return !relativePath.startsWith('..') && !external_node_path_["default"].isAbsolute(relativePath);
476
+ }
477
+ absolutePathToRelativePath(absolutePath) {
478
+ return absolutePathToRelativePath(absolutePath, this.#scanDir);
438
479
  }
439
480
  async #writeTempFile(index, content) {
440
- const tempFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(this.#tempDir, `temp-${index}.mdx`);
441
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(tempFilePath, content);
481
+ const tempFilePath = external_node_path_["default"].join(this.#tempDir, `temp-${index}.mdx`);
482
+ await node_fs_promises.writeFile(tempFilePath, content);
442
483
  return tempFilePath;
443
484
  }
444
- #generateRouteInfo(routePath, filepath) {
445
- const { routePath: normalizedPath, lang, version } = this.normalizeRoutePath(routePath);
485
+ getRoutePageByRoutePath(routePath) {
486
+ return this.routeData.get(routePath);
487
+ }
488
+ }
489
+ class RoutePage {
490
+ routeMeta;
491
+ #docDir;
492
+ static create(absolutePath, docsDir) {
493
+ const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
494
+ return new RoutePage(routeMeta, docsDir);
495
+ }
496
+ static createFromExternal(routePath, filepath, docDir) {
497
+ const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
498
+ return new RoutePage(routeMeta, external_node_path_["default"].dirname(filepath));
499
+ }
500
+ constructor(routeMeta, docDir){
501
+ this.routeMeta = routeMeta;
502
+ this.#docDir = docDir;
503
+ }
504
+ static generateRouteMeta(routePath, filepath, docDir) {
505
+ const routeService = RouteService.getInstance();
506
+ const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
446
507
  return {
447
508
  routePath: normalizedPath,
448
509
  absolutePath: normalizePath(filepath),
449
- relativePath: normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(this.#scanDir, filepath)),
510
+ relativePath: absolutePathToRelativePath(filepath, docDir),
450
511
  pageName: getPageKey(routePath),
451
512
  lang,
452
513
  version
453
514
  };
454
515
  }
455
516
  }
456
- let init_routeService = null;
457
- async function initRouteService(options) {
458
- const { scanDir, config, runtimeTempDir, pluginDriver } = options;
459
- init_routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
460
- await init_routeService.init();
461
- await pluginDriver.routeServiceGenerated(init_routeService);
462
- return init_routeService;
463
- }
464
- var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
465
- RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
466
- RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
467
- RuntimeModuleID["RouteForClient"] = "virtual-routes";
468
- RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
469
- RuntimeModuleID["SiteData"] = "virtual-site-data";
470
- RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
471
- RuntimeModuleID["I18nText"] = "virtual-i18n-text";
472
- RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
473
- RuntimeModuleID["PrismLanguages"] = "virtual-prism-languages";
474
- return RuntimeModuleID;
475
- }({});
476
- async function routeVMPlugin(context) {
477
- const { routeService, isSSR } = context;
478
- if (!isSSR) return {
479
- [types_RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),
480
- [types_RuntimeModuleID.RouteForSSR]: ''
481
- };
517
+ function absolutePathToRelativePath(absolutePath, docsDir) {
518
+ return slash(external_node_path_["default"].relative(docsDir, absolutePath));
519
+ }
520
+ function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
521
+ const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
522
+ const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
482
523
  return {
483
- [types_RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),
484
- [types_RuntimeModuleID.RouteForSSR]: routeService.generateRoutesCode(true)
524
+ pageName: getPageKey(relativePath),
525
+ absolutePath,
526
+ lang,
527
+ version,
528
+ routePath,
529
+ relativePath
485
530
  };
486
531
  }
487
- function createHash(str) {
488
- return (0, __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__.createHash)('sha256').update(str).digest('hex').slice(0, 8);
532
+ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
533
+ return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
489
534
  }
490
- let flattenMdxContent_resolver;
491
- let startFlatten = false;
492
- const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
493
- const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
494
- const fileSystem = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"];
495
- async function resolveDepPath(importPath, importer, alias) {
496
- if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
497
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
498
- extensions: [
499
- '.mdx',
500
- '.md'
501
- ],
502
- alias
503
- });
504
- const resolveResult = await new Promise((resolve, reject)=>{
505
- flattenMdxContent_resolver.resolve({
506
- importer
507
- }, importer, importPath, {}, (err, filePath)=>{
508
- if (err) return reject(err);
509
- if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
510
- return resolve(filePath);
511
- });
512
- });
513
- return resolveResult;
535
+ function absolutePathToRoutePrefix(absolutePath, docsDir) {
536
+ const relativePath = slash(external_node_path_["default"].relative(docsDir, absolutePath.replace(external_node_path_["default"].extname(absolutePath), '')));
537
+ const routeService = RouteService.getInstance();
538
+ const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
539
+ return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
514
540
  }
515
- async function flattenMdxContent(content, basePath, alias) {
516
- const deps = [];
517
- const regex = new RegExp(importStatementRegex);
518
- if (!regex.test(content)) return {
519
- flattenContent: content,
520
- deps
521
- };
522
- if (!startFlatten) {
523
- flattenMdxContent_resolver = ResolverFactory.createResolver({
524
- fileSystem: new CachedInputFileSystem(fileSystem, 0),
525
- extensions: [
526
- '.mdx',
527
- '.md',
528
- '.js'
529
- ],
530
- alias
531
- });
532
- startFlatten = true;
541
+ function addRoutePrefix(workDir, docsDir, link) {
542
+ const routePrefix = absolutePathToRoutePrefix(workDir, docsDir);
543
+ return `${routePrefix.replace(/\/$/, '')}/${link.replace(/^\//, '')}`;
544
+ }
545
+ async function utils_pathExists(path) {
546
+ try {
547
+ await node_fs_promises.access(path);
548
+ return true;
549
+ } catch {
550
+ return false;
533
551
  }
534
- let ast;
535
- let result = content;
552
+ }
553
+ async function utils_readJson(path) {
554
+ const raw = await node_fs_promises.readFile(path, 'utf8');
555
+ return JSON.parse(raw);
556
+ }
557
+ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
558
+ const content = await node_fs_promises.readFile(absolutePath, 'utf-8');
559
+ const fileNameWithoutExt = external_node_path_["default"].basename(absolutePath, external_node_path_["default"].extname(absolutePath));
560
+ const h1RegExp = /^#\s+(.*)$/m;
561
+ const match = content.match(h1RegExp);
562
+ const { frontmatter } = loadFrontMatter(content, absolutePath, rootDir);
563
+ return {
564
+ title: extractTextAndId(frontmatter.title || match?.[1] || fileNameWithoutExt)[0],
565
+ overviewHeaders: frontmatter.overviewHeaders,
566
+ context: frontmatter.context
567
+ };
568
+ }
569
+ function getHmrFileKey(realPath, docsDir) {
570
+ return realPath ? (0, shared_.slash)((0, external_node_path_.relative)(docsDir, realPath).replace((0, external_node_path_.extname)(realPath), '')) : '';
571
+ }
572
+ async function fsDirToMetaItems(workDir, extensions) {
573
+ let subItems;
536
574
  try {
537
- ast = processor.parse(content);
575
+ subItems = await readdir(workDir);
538
576
  } catch (e) {
539
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('flattenMdxContent parse failed: \n', e);
540
- return {
541
- flattenContent: content,
542
- deps
543
- };
577
+ logger.error(`Failed to read directory: ${workDir}, maybe it does not exist. Please check it in "_meta.json".`);
578
+ throw e;
544
579
  }
545
- const importNodes = ast.children.filter((node)=>'mdxjsEsm' === node.type).flatMap((node)=>node.data?.estree?.body || []).filter((node)=>'ImportDeclaration' === node.type);
546
- for (const importNode of importNodes){
547
- const id = importNode.specifiers[0].local.name;
580
+ subItems = subItems.filter((item)=>{
581
+ const hasExtension = extensions.some((ext)=>item.endsWith(ext));
582
+ const hasSameBaseName = subItems.some((elem)=>{
583
+ const baseName = elem.replace(/\.[^/.]+$/, '');
584
+ return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
585
+ });
586
+ return !(hasExtension && hasSameBaseName);
587
+ });
588
+ const sideMeta = (await Promise.all(subItems.map(async (item)=>{
589
+ if ('_meta.json' === item) return null;
590
+ const stat = await promises_stat((0, external_node_path_.join)(workDir, item));
591
+ if (stat.isDirectory()) return {
592
+ type: 'dir',
593
+ name: item
594
+ };
595
+ return extensions.some((ext)=>item.endsWith(ext)) ? item : null;
596
+ }))).filter(Boolean);
597
+ return sideMeta;
598
+ }
599
+ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isFirstDir = false) {
600
+ if ('string' == typeof metaItem) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
601
+ const { type } = metaItem;
602
+ if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
603
+ if ('dir' === type) {
604
+ const { name, label, collapsible, collapsed, tag: metaJsonTag, context: metaJsonContext, overviewHeaders: metaJsonOverviewHeaders } = metaItem;
605
+ const dirAbsolutePath = (0, external_node_path_.join)(workDir, name);
606
+ const dirMetaJsonPath = (0, external_node_path_.join)(dirAbsolutePath, '_meta.json');
607
+ const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
608
+ let dirMetaJson = [];
609
+ dirMetaJson = isMetaJsonExist ? await utils_readJson(dirMetaJsonPath) : await fsDirToMetaItems(dirAbsolutePath, extensions);
610
+ async function getItems(withoutIndex = false) {
611
+ const items = await Promise.all((withoutIndex ? dirMetaJson.filter((i)=>{
612
+ let name;
613
+ if ('object' == typeof i && 'type' in i && 'file' === i.type) name = i.name;
614
+ else {
615
+ if ('string' != typeof i) return true;
616
+ name = i;
617
+ }
618
+ return 'index.md' !== name && 'index.mdx' !== i && 'index' !== i;
619
+ }) : dirMetaJson).map((item)=>metaItemToSidebarItem(item, dirAbsolutePath, docsDir, extensions)));
620
+ return items;
621
+ }
622
+ try {
623
+ const sameNameFile = await metaFileItemToSidebarItem(name, workDir, docsDir, extensions);
624
+ const { link, text, _fileKey, context, overviewHeaders, tag } = sameNameFile;
625
+ return {
626
+ text: label || text || name,
627
+ collapsible,
628
+ collapsed,
629
+ items: await getItems(),
630
+ link,
631
+ tag: metaJsonTag || tag,
632
+ overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
633
+ context: metaJsonContext || context,
634
+ _fileKey
635
+ };
636
+ } catch (e) {
637
+ logger.debug(e);
638
+ const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
639
+ if ('string' == typeof i) return 'index' === i.replace((0, external_node_path_.extname)(i), '');
640
+ return false;
641
+ });
642
+ const isIndexFileExists = await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.mdx')) || await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.md'));
643
+ if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
644
+ text: label || name,
645
+ collapsible,
646
+ collapsed,
647
+ items: await getItems(),
648
+ link: void 0,
649
+ tag: metaJsonTag,
650
+ overviewHeaders: metaJsonOverviewHeaders,
651
+ context: metaJsonContext,
652
+ _fileKey: getHmrFileKey(dirAbsolutePath, docsDir)
653
+ };
654
+ {
655
+ const indexFile = await metaFileItemToSidebarItem('index', dirAbsolutePath, docsDir, extensions);
656
+ const { link, text, _fileKey, context, overviewHeaders, tag } = indexFile;
657
+ return {
658
+ text: label || text || name,
659
+ collapsible,
660
+ collapsed,
661
+ items: await getItems(!isFirstDir),
662
+ link,
663
+ tag: metaJsonTag || tag,
664
+ overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
665
+ context: metaJsonContext || context,
666
+ _fileKey
667
+ };
668
+ }
669
+ }
670
+ }
671
+ if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
672
+ if ('divider' === type || 'section-header' === type) return metaDividerToSidebarItem(metaItem);
673
+ throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
674
+ }
675
+ async function detectFilePath(absolutePath, extensions) {
676
+ const ext = (0, external_node_path_.extname)(absolutePath);
677
+ if (ext && extensions.includes(ext)) return absolutePath;
678
+ for (const extension of extensions){
679
+ const realPath = absolutePath + extension;
680
+ if (await utils_pathExists(realPath)) return realPath;
681
+ }
682
+ throw new Error(`The file extension "${ext}" is not supported, please use one of the following extensions: ${extensions.join(', ')}`);
683
+ }
684
+ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensions) {
685
+ let metaItem = null;
686
+ metaItem = 'string' == typeof metaItemRaw ? {
687
+ name: metaItemRaw,
688
+ type: 'file'
689
+ } : metaItemRaw;
690
+ const { name, context, label, overviewHeaders, tag } = metaItem;
691
+ if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
692
+ const absolutePath = (0, external_node_path_.join)(workDir, name);
693
+ let absolutePathWithExt;
694
+ try {
695
+ absolutePathWithExt = await detectFilePath(absolutePath, extensions);
696
+ } catch {
697
+ throw new Error(`The file "${absolutePath}" does not exist, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
698
+ }
699
+ const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
700
+ const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
701
+ const title = label || info.title;
702
+ return {
703
+ text: title,
704
+ link,
705
+ tag,
706
+ overviewHeaders: info.overviewHeaders || overviewHeaders,
707
+ context: info.context || context,
708
+ _fileKey: getHmrFileKey(absolutePathWithExt, docsDir)
709
+ };
710
+ }
711
+ function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
712
+ if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
713
+ const { label, link, context, items, tag, collapsed, collapsible, overviewHeaders } = metaItem;
714
+ return {
715
+ text: label ?? link,
716
+ context,
717
+ tag,
718
+ link,
719
+ items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(Object.assign(subItem, {
720
+ type: 'custom-link'
721
+ }), workDir, docsDir)),
722
+ collapsed,
723
+ collapsible,
724
+ overviewHeaders
725
+ };
726
+ }
727
+ if ('link' in metaItem && 'string' == typeof metaItem.link) {
728
+ const { label, link, context, tag } = metaItem;
729
+ if ((0, shared_.isExternalUrl)(link)) return {
730
+ text: label ?? link,
731
+ link,
732
+ tag,
733
+ context
734
+ };
735
+ return {
736
+ text: label ?? link,
737
+ link: addRoutePrefix(workDir, docsDir, link),
738
+ tag,
739
+ context
740
+ };
741
+ }
742
+ const { label } = metaItem;
743
+ throw new Error(`The custom link "${label}" does not have a link, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
744
+ }
745
+ function metaDividerToSidebarItem(metaItem) {
746
+ const { type } = metaItem;
747
+ if ('divider' === type) {
748
+ const { dashed } = metaItem;
749
+ return {
750
+ dividerType: dashed ? 'dashed' : 'solid'
751
+ };
752
+ }
753
+ const { label, tag } = metaItem;
754
+ return {
755
+ sectionHeaderText: label ?? '',
756
+ tag
757
+ };
758
+ }
759
+ async function scanSideMeta(workDir, docsDir, extensions) {
760
+ const dir = await metaItemToSidebarItem({
761
+ type: 'dir',
762
+ name: ''
763
+ }, workDir, docsDir, extensions, true);
764
+ return dir.items;
765
+ }
766
+ async function scanNav(workDir, docsDir) {
767
+ let navConfig;
768
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
769
+ try {
770
+ navConfig = await utils_readJson(rootNavJson);
771
+ } catch (_e) {
772
+ logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
773
+ navConfig = [];
774
+ }
775
+ navConfig.forEach((navItem)=>{
776
+ if ('items' in navItem) navItem.items.forEach((item)=>{
777
+ if ('link' in item && !(0, shared_.isExternalUrl)(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
778
+ });
779
+ if ('link' in navItem && !(0, shared_.isExternalUrl)(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
780
+ });
781
+ return navConfig;
782
+ }
783
+ async function walk(workDir, docsDir, extensions) {
784
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
785
+ const rootMetaJson = external_node_path_["default"].resolve(workDir, '_meta.json');
786
+ const isRootNavJsonExist = await pathExists(rootNavJson);
787
+ const isRootMetaJsonExist = await pathExists(rootMetaJson);
788
+ if (isRootMetaJsonExist) {
789
+ const metaConfig = await utils_readJson(rootMetaJson);
790
+ hintNavJsonChangeThenPanic(metaConfig, workDir, docsDir);
791
+ }
792
+ if (isRootMetaJsonExist && isRootNavJsonExist) {
793
+ const navConfig = await scanNav(workDir, docsDir);
794
+ return {
795
+ nav: navConfig,
796
+ sidebar: {
797
+ '/': await scanSideMeta(workDir, docsDir, extensions)
798
+ }
799
+ };
800
+ }
801
+ if (isRootNavJsonExist) {
802
+ const navConfig = await scanNav(workDir, docsDir);
803
+ const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(external_node_path_["default"].join(workDir, v)).then((s)=>{
804
+ if (s.isDirectory() && 'node_modules' !== v) return v;
805
+ return false;
806
+ })))).filter(Boolean);
807
+ const sidebarConfig = {};
808
+ await Promise.all(subDirs.map(async (subDir)=>{
809
+ const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
810
+ sidebarConfig[sidebarGroupKey] = await scanSideMeta(external_node_path_["default"].join(workDir, subDir), docsDir, extensions);
811
+ }));
812
+ return {
813
+ nav: navConfig,
814
+ sidebar: sidebarConfig
815
+ };
816
+ }
817
+ return {
818
+ nav: [],
819
+ sidebar: {
820
+ '/': await scanSideMeta(workDir, docsDir, extensions)
821
+ }
822
+ };
823
+ }
824
+ function combineWalkResult(walks, versions) {
825
+ return walks.reduce((acc, cur, curIndex)=>({
826
+ nav: {
827
+ ...acc.nav,
828
+ [versions[curIndex] || 'default']: cur.nav
829
+ },
830
+ sidebar: {
831
+ ...acc.sidebar,
832
+ ...cur.sidebar
833
+ }
834
+ }), {
835
+ nav: {},
836
+ sidebar: {}
837
+ });
838
+ }
839
+ function processLocales(langs, versions, root, extensions) {
840
+ return Promise.all(langs.map(async (lang)=>{
841
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(root, version, lang), root, extensions))) : [
842
+ await walk(external_node_path_["default"].join(root, lang), root, extensions)
843
+ ];
844
+ return combineWalkResult(walks, versions);
845
+ }));
846
+ }
847
+ async function modifyConfigWithAutoNavSide(config) {
848
+ const themeConfig = config.themeConfig || {};
849
+ const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
850
+ if (haveNavSidebarConfig) return config;
851
+ config.themeConfig = config.themeConfig || {};
852
+ config.themeConfig.locales = config.themeConfig.locales || config.locales || [];
853
+ const langs = config.themeConfig.locales.map((locale)=>locale.lang);
854
+ const hasLocales = langs.length > 0;
855
+ const hasLang = Boolean(config.lang);
856
+ const versions = config.multiVersion?.versions || [];
857
+ const { extensions = DEFAULT_PAGE_EXTENSIONS } = config?.route || {};
858
+ if (hasLocales) {
859
+ const metaInfo = await processLocales(langs, versions, config.root, extensions);
860
+ config.themeConfig.locales = config.themeConfig.locales.map((item, index)=>({
861
+ ...item,
862
+ ...metaInfo[index]
863
+ }));
864
+ } else {
865
+ if (hasLang) {
866
+ logger.error("`lang` is configured but `locales` not, thus `auto-nav-sidebar` can not auto generate navbar level config correctly!\nplease check your config file");
867
+ return config;
868
+ }
869
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(config.root, version), config.root, extensions))) : [
870
+ await walk(config.root, config.root, extensions)
871
+ ];
872
+ const combined = combineWalkResult(walks, versions);
873
+ config.themeConfig = {
874
+ ...config.themeConfig,
875
+ ...combined
876
+ };
877
+ }
878
+ return config;
879
+ }
880
+ const globalStylesVMPlugin = (context)=>({
881
+ ["virtual-global-styles"]: ()=>{
882
+ const { config, pluginDriver } = context;
883
+ const globalStylesByPlugins = pluginDriver.globalStyles();
884
+ const moduleContent = [
885
+ config?.globalStyles,
886
+ ...globalStylesByPlugins
887
+ ].filter(Boolean).map((source)=>`import ${JSON.stringify(source)};`).join('');
888
+ return moduleContent;
889
+ }
890
+ });
891
+ const globalUIComponentsVMPlugin = (context)=>({
892
+ ["virtual-global-components"]: ()=>{
893
+ const { config, pluginDriver } = context;
894
+ let index = 0;
895
+ const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
896
+ const globalComponents = [
897
+ ...config?.globalUIComponents || [],
898
+ ...globalUIComponentsByPlugins
899
+ ];
900
+ const moduleContent = globalComponents.map((source)=>{
901
+ const name = `Comp_${index}`;
902
+ if (Array.isArray(source)) return `import ${name} from ${JSON.stringify(source[0])};
903
+ const Props_${index++} = ${JSON.stringify(source[1])};\n`;
904
+ index++;
905
+ return `import ${name} from ${JSON.stringify(source)};\n`;
906
+ }).concat(`export default [${Array.from({
907
+ length: index
908
+ }, (_, i)=>{
909
+ if (Array.isArray(globalComponents[i])) return `[Comp_${i}, Props_${i}]`;
910
+ return `Comp_${i}`;
911
+ }).join(', ')}];`).join('');
912
+ return moduleContent;
913
+ }
914
+ });
915
+ const i18n_require = createRequire(import.meta.url);
916
+ const DEFAULT_I18N_SOURCE = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
917
+ function getI18nData(docConfig) {
918
+ const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
919
+ try {
920
+ delete i18n_require.cache[i18nSourcePath];
921
+ const i18nSource = i18n_require(i18nSourcePath);
922
+ return i18nSource;
923
+ } catch (e) {
924
+ logger.debug('getI18nData Failed: \n', e);
925
+ return {};
926
+ }
927
+ }
928
+ const i18nVMPlugin = (context)=>{
929
+ const { config } = context;
930
+ return {
931
+ ["virtual-i18n-text"]: async ({ addDependency, addMissingDependency })=>{
932
+ const configPath = config.i18nSourcePath || DEFAULT_I18N_SOURCE;
933
+ const isExist = await pathExists(configPath);
934
+ if (isExist) addDependency(configPath);
935
+ else addMissingDependency(configPath);
936
+ const i18nData = getI18nData(config);
937
+ return `export default ${JSON.stringify(i18nData, null, 2)}`;
938
+ }
939
+ };
940
+ };
941
+ var external_node_fs_ = __webpack_require__("node:fs");
942
+ let flattenMdxContent_resolver;
943
+ let startFlatten = false;
944
+ const processor = createProcessor();
945
+ const { CachedInputFileSystem, ResolverFactory } = enhanced_resolve;
946
+ const fileSystem = external_node_fs_["default"];
947
+ async function resolveDepPath(importPath, importer, alias) {
948
+ if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
949
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
950
+ extensions: [
951
+ '.mdx',
952
+ '.md'
953
+ ],
954
+ alias
955
+ });
956
+ const resolveResult = await new Promise((resolve, reject)=>{
957
+ flattenMdxContent_resolver.resolve({
958
+ importer
959
+ }, importer, importPath, {}, (err, filePath)=>{
960
+ if (err) return reject(err);
961
+ if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
962
+ return resolve(filePath);
963
+ });
964
+ });
965
+ return resolveResult;
966
+ }
967
+ async function flattenMdxContent(content, basePath, alias) {
968
+ const deps = [];
969
+ const regex = new RegExp(importStatementRegex);
970
+ if (!regex.test(content)) return {
971
+ flattenContent: content,
972
+ deps
973
+ };
974
+ if (!startFlatten) {
975
+ flattenMdxContent_resolver = ResolverFactory.createResolver({
976
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
977
+ extensions: [
978
+ '.mdx',
979
+ '.md',
980
+ '.js'
981
+ ],
982
+ alias
983
+ });
984
+ startFlatten = true;
985
+ }
986
+ let ast;
987
+ let result = content;
988
+ try {
989
+ ast = processor.parse(content);
990
+ } catch (e) {
991
+ logger.debug('flattenMdxContent parse failed: \n', e);
992
+ return {
993
+ flattenContent: content,
994
+ deps
995
+ };
996
+ }
997
+ const importNodes = ast.children.filter((node)=>'mdxjsEsm' === node.type).flatMap((node)=>node.data?.estree?.body || []).filter((node)=>'ImportDeclaration' === node.type);
998
+ for (const importNode of importNodes){
999
+ const id = importNode.specifiers[0].local.name;
548
1000
  const importPath = importNode.source.value;
549
1001
  let absoluteImportPath;
550
1002
  try {
551
- absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
1003
+ absoluteImportPath = await resolveDepPath(importPath, external_node_path_["default"].dirname(basePath), alias);
552
1004
  } catch (_e) {
553
1005
  continue;
554
1006
  }
555
- if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
556
- const importedContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(absoluteImportPath, 'utf-8');
1007
+ if (shared_.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
1008
+ const importedContent = external_node_fs_["default"].readFileSync(absoluteImportPath, 'utf-8');
557
1009
  const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
558
1010
  result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
559
1011
  deps.push(...subDeps, absoluteImportPath);
@@ -574,217 +1026,273 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
574
1026
  else if ('object' == typeof obj[key] && null !== obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
575
1027
  return obj;
576
1028
  }
577
- async function extractPageData(replaceRules, alias, domain, root, routeService, highlighterLangs, searchCodeBlocks) {
578
- const pageData = await Promise.all(routeService.getRoutes().map(async (route, index)=>{
579
- const defaultIndexInfo = {
580
- id: index,
581
- title: '',
582
- content: '',
583
- _flattenContent: '',
584
- _html: '',
585
- routePath: route.routePath,
586
- lang: route.lang,
587
- toc: [],
588
- domain,
589
- frontmatter: {},
590
- version: route.version,
591
- _filepath: route.absolutePath,
592
- _relativePath: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, route.absolutePath).split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')
593
- };
594
- if (!__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
595
- let content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(route.absolutePath, 'utf8');
596
- const { frontmatter, content: contentWithoutFrontMatter } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(content, route.absolutePath, root);
597
- applyReplaceRulesToNestedObject(frontmatter, replaceRules);
598
- const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
599
- content = flattenContent.replace(importStatementRegex, '');
600
- const { html: rawHtml, title, toc: rawToc, languages } = await (0, __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__.compile)({
601
- value: content,
602
- filepath: route.absolutePath,
603
- development: 'production' !== process.env.NODE_ENV,
604
- root
1029
+ async function getPageIndexInfoByRoute(route, options) {
1030
+ const { alias, replaceRules, root, searchCodeBlocks } = options;
1031
+ const defaultIndexInfo = {
1032
+ title: '',
1033
+ content: '',
1034
+ _html: '',
1035
+ _flattenContent: '',
1036
+ routePath: route.routePath,
1037
+ lang: route.lang,
1038
+ toc: [],
1039
+ frontmatter: {},
1040
+ version: route.version,
1041
+ _filepath: route.absolutePath,
1042
+ _relativePath: external_node_path_["default"].relative(root, route.absolutePath).split(external_node_path_["default"].sep).join('/')
1043
+ };
1044
+ if (!shared_.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
1045
+ let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
1046
+ const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
1047
+ applyReplaceRulesToNestedObject(frontmatter, replaceRules);
1048
+ const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
1049
+ content = flattenContent.replace(importStatementRegex, '');
1050
+ const { html: rawHtml, title, toc: rawToc } = await compile({
1051
+ value: content,
1052
+ filepath: route.absolutePath,
1053
+ development: 'production' !== process.env.NODE_ENV,
1054
+ root
1055
+ });
1056
+ function encodeHtml(html) {
1057
+ return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
1058
+ return `<code>${innerContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`;
605
1059
  });
606
- function encodeHtml(html) {
607
- return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
608
- return `<code>${innerContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`;
609
- });
610
- }
611
- const html = encodeHtml(String(rawHtml));
612
- content = (0, __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__.htmlToText)(html, {
613
- wordwrap: 80,
614
- selectors: [
615
- {
616
- selector: 'a',
1060
+ }
1061
+ const html = encodeHtml(String(rawHtml));
1062
+ content = htmlToText(html, {
1063
+ wordwrap: 80,
1064
+ selectors: [
1065
+ {
1066
+ selector: 'a',
1067
+ options: {
1068
+ ignoreHref: true
1069
+ }
1070
+ },
1071
+ {
1072
+ selector: 'img',
1073
+ format: 'skip'
1074
+ },
1075
+ {
1076
+ selector: 'pre > code',
1077
+ format: searchCodeBlocks ? 'block' : 'skip'
1078
+ },
1079
+ ...[
1080
+ 'h1',
1081
+ 'h2',
1082
+ 'h3',
1083
+ 'h4',
1084
+ 'h5',
1085
+ 'h6'
1086
+ ].map((tag)=>({
1087
+ selector: tag,
617
1088
  options: {
618
- ignoreHref: true
1089
+ uppercase: false
619
1090
  }
620
- },
621
- {
622
- selector: 'img',
623
- format: 'skip'
624
- },
625
- {
626
- selector: 'pre > code',
627
- format: searchCodeBlocks ? 'block' : 'skip'
628
- },
629
- ...[
630
- 'h1',
631
- 'h2',
632
- 'h3',
633
- 'h4',
634
- 'h5',
635
- 'h6'
636
- ].map((tag)=>({
637
- selector: tag,
638
- options: {
639
- uppercase: false
640
- }
641
- }))
642
- ],
643
- tables: true,
644
- longWordSplit: {
645
- forceWrapOnLimit: true
646
- }
647
- });
648
- if (content.startsWith(title)) content = content.slice(title.length);
649
- languages.forEach((lang)=>highlighterLangs.add(lang));
650
- const toc = rawToc.map((item)=>{
651
- const match = item.id.match(/-(\d+)$/);
652
- let position = -1;
653
- if (match) for(let i = 0; i < Number(match[1]); i++){
654
- position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
655
- if (-1 === position) break;
656
- }
657
- return {
658
- ...item,
659
- charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
660
- };
661
- });
1091
+ }))
1092
+ ],
1093
+ tables: true,
1094
+ longWordSplit: {
1095
+ forceWrapOnLimit: true
1096
+ }
1097
+ });
1098
+ if (content.startsWith(title)) content = content.slice(title.length);
1099
+ const toc = rawToc.map((item)=>{
1100
+ const match = item.id.match(/-(\d+)$/);
1101
+ let position = -1;
1102
+ if (match) for(let i = 0; i < Number(match[1]); i++){
1103
+ position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
1104
+ if (-1 === position) break;
1105
+ }
662
1106
  return {
663
- ...defaultIndexInfo,
664
- title: frontmatter.title || title,
665
- toc,
666
- content,
667
- _flattenContent: flattenContent,
668
- _html: html,
669
- frontmatter: {
670
- ...frontmatter,
671
- __content: void 0
672
- }
1107
+ ...item,
1108
+ charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
673
1109
  };
674
- }));
675
- return pageData.filter(Boolean);
676
- }
677
- const highlightLanguages_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__.createRequire)(import.meta.url);
678
- let highlightLanguages_supportedLanguages;
679
- function handleHighlightLanguages(highlightLanguages, defaultLanguages) {
680
- const aliases = {};
681
- if (highlightLanguages.size) {
682
- if (!highlightLanguages_supportedLanguages) {
683
- const langs = highlightLanguages_require('react-syntax-highlighter/dist/cjs/languages/prism/supported-languages').default;
684
- highlightLanguages_supportedLanguages = new Set(langs);
1110
+ });
1111
+ return {
1112
+ ...defaultIndexInfo,
1113
+ title: frontmatter.title || title,
1114
+ toc,
1115
+ content,
1116
+ _html: html,
1117
+ _flattenContent: flattenContent,
1118
+ frontmatter: {
1119
+ ...frontmatter,
1120
+ __content: void 0
685
1121
  }
686
- let useDeprecatedTypeWarning = true;
687
- const names = {};
688
- [
689
- ...__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.DEFAULT_HIGHLIGHT_LANGUAGES,
690
- ...defaultLanguages
691
- ].forEach((lang)=>{
692
- if (Array.isArray(lang)) {
693
- const [alias, name] = lang;
694
- names[alias] = name;
695
- } else if (useDeprecatedTypeWarning) {
696
- console.log(`${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellowBright('warning')} Automatic import is supported. \`highlightLanguages\` is now used only as alias, and string types will be ignored. \n`);
697
- useDeprecatedTypeWarning = false;
698
- }
699
- });
700
- [
701
- ...highlightLanguages.values()
702
- ].forEach((lang)=>{
703
- const name = names[lang];
704
- if (name && highlightLanguages_supportedLanguages.has(name)) {
705
- const temp = aliases[name] || (aliases[name] = []);
706
- if (!temp.includes(lang)) temp.push(lang);
707
- highlightLanguages.delete(lang);
708
- highlightLanguages.add(name);
709
- return;
710
- }
711
- if (!highlightLanguages_supportedLanguages.has(lang)) highlightLanguages.delete(lang);
712
- });
713
- }
714
- return aliases;
1122
+ };
715
1123
  }
716
- const DEFAULT_I18N_SOURCE = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), 'i18n.json');
717
- function getI18nData(docConfig) {
718
- const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
719
- try {
720
- delete require.cache[i18nSourcePath];
721
- const i18nSource = require(i18nSourcePath);
722
- return i18nSource;
723
- } catch (e) {
724
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('getI18nData Failed: \n', e);
725
- return {};
726
- }
1124
+ async function extractPageData(routeService, options) {
1125
+ const pageData = await Promise.all(routeService.getRoutes().map((routeMeta)=>getPageIndexInfoByRoute(routeMeta, options)));
1126
+ return pageData;
727
1127
  }
728
- const i18nVMPlugin = (context)=>{
729
- const { config } = context;
1128
+ function createHash_createHash(str) {
1129
+ return createHash('sha256').update(str).digest('hex').slice(0, 8);
1130
+ }
1131
+ function deletePrivateField(obj) {
1132
+ if ('object' != typeof obj || null === obj) return obj;
1133
+ const newObj = {
1134
+ ...obj
1135
+ };
1136
+ for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
1137
+ return newObj;
1138
+ }
1139
+ async function createPageData(context) {
1140
+ const { config, alias, userDocRoot, routeService, pluginDriver } = context;
1141
+ const userConfig = config;
1142
+ const tempSearchObj = Object.assign({}, userConfig.search);
1143
+ if (tempSearchObj) tempSearchObj.searchHooks = void 0;
1144
+ const replaceRules = userConfig?.replaceRules || [];
1145
+ const searchConfig = userConfig?.search || {};
1146
+ const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
1147
+ const pages = await extractPageData(routeService, {
1148
+ replaceRules,
1149
+ alias,
1150
+ root: userDocRoot,
1151
+ searchCodeBlocks
1152
+ });
1153
+ await pluginDriver.modifySearchIndexData(pages);
1154
+ const versioned = 'boolean' != typeof userConfig.search && userConfig.search?.versioned;
1155
+ const groupedPages = groupBy(pages, (page)=>{
1156
+ if (page.frontmatter?.pageType === 'home') return 'noindex';
1157
+ const version = versioned ? page.version : '';
1158
+ const lang = page.lang || '';
1159
+ return `${version}###${lang}`;
1160
+ });
1161
+ delete groupedPages.noindex;
1162
+ const indexHashByGroup = {};
1163
+ const searchIndex = {};
1164
+ await Promise.all(Object.keys(groupedPages).map(async (group)=>{
1165
+ const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
1166
+ const indexHash = createHash_createHash(stringifiedIndex);
1167
+ indexHashByGroup[group] = indexHash;
1168
+ const [version, lang] = group.split('###');
1169
+ const indexVersion = version ? `.${version.replace('.', '_')}` : '';
1170
+ const indexLang = lang ? `.${lang}` : '';
1171
+ const filename = `${shared_.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`;
1172
+ searchIndex[filename] = stringifiedIndex;
1173
+ }));
1174
+ await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
1175
+ const filepaths = [];
1176
+ const pageData = {
1177
+ pages: pages.map((page)=>{
1178
+ const { content: _content, _filepath, _html, _flattenContent, ...rest } = page;
1179
+ filepaths.push(_filepath);
1180
+ return rest;
1181
+ })
1182
+ };
730
1183
  return {
731
- [types_RuntimeModuleID.I18nText]: ({ addDependency, addMissingDependency })=>{
732
- addDependency(config.i18nSourcePath || DEFAULT_I18N_SOURCE);
733
- addMissingDependency(config.i18nSourcePath || DEFAULT_I18N_SOURCE);
734
- const i18nData = getI18nData(config);
735
- return `export default ${JSON.stringify(i18nData, null, 2)}`;
1184
+ filepaths,
1185
+ pageData,
1186
+ searchIndex,
1187
+ indexHashByGroup
1188
+ };
1189
+ }
1190
+ const rsbuildPluginDocVM = async ({ config, userDocRoot, routeService, pluginDriver })=>{
1191
+ const ref = {
1192
+ pageData: null,
1193
+ searchIndex: null,
1194
+ indexHashByGroup: null,
1195
+ filepaths: []
1196
+ };
1197
+ const searchIndexRsbuildPlugin = {
1198
+ name: 'rsbuild-plugin-searchIndex',
1199
+ async setup (api) {
1200
+ api.modifyBundlerChain(async (bundlerChain)=>{
1201
+ const alias = bundlerChain.resolve.alias.entries();
1202
+ const { pageData, indexHashByGroup, searchIndex, filepaths } = await createPageData({
1203
+ config,
1204
+ alias: alias,
1205
+ userDocRoot,
1206
+ routeService,
1207
+ pluginDriver
1208
+ });
1209
+ ref.pageData = pageData;
1210
+ ref.searchIndex = searchIndex;
1211
+ ref.indexHashByGroup = indexHashByGroup;
1212
+ ref.filepaths = filepaths;
1213
+ api.processAssets({
1214
+ stage: 'report',
1215
+ environments: [
1216
+ 'web'
1217
+ ]
1218
+ }, ({ compilation, compiler })=>{
1219
+ for (const [filename, stringifiedIndex] of Object.entries(searchIndex))compilation.emitAsset(`static/${filename}`, new compiler.webpack.sources.RawSource(stringifiedIndex));
1220
+ });
1221
+ });
736
1222
  }
737
1223
  };
1224
+ return [
1225
+ searchIndexRsbuildPlugin,
1226
+ pluginVirtualModule({
1227
+ tempDir: '.rspress',
1228
+ virtualModules: {
1229
+ ["virtual-page-data"]: async ({ addDependency })=>{
1230
+ for (const file of ref.filepaths)addDependency(file);
1231
+ return `export const pageData = ${JSON.stringify(ref.pageData, null, 2)};
1232
+ export const searchIndexHash = ${JSON.stringify(ref.indexHashByGroup, null, 2)};`;
1233
+ }
1234
+ }
1235
+ })
1236
+ ];
1237
+ };
1238
+ const routeListVMPlugin = (context)=>{
1239
+ const { routeService } = context;
1240
+ return {
1241
+ ["virtual-routes"]: ()=>routeService.generateRoutesCode()
1242
+ };
738
1243
  };
739
- function normalizeThemeConfig(docConfig, pages = []) {
740
- const { locales: siteLocales, base = '', lang, replaceRules = [], multiVersion } = docConfig;
1244
+ const searchHookVMPlugin = (context)=>({
1245
+ ["virtual-search-hooks"]: ()=>{
1246
+ const { config } = context;
1247
+ let content = 'export const onSearch = () => {};';
1248
+ const searchHooks = 'object' == typeof config.search && config.search?.searchHooks;
1249
+ if (searchHooks) content = `export * from ${JSON.stringify(external_node_path_["default"].posix.normalize(searchHooks))}`;
1250
+ return content;
1251
+ }
1252
+ });
1253
+ function normalizeThemeConfig(docConfig) {
1254
+ const { locales: siteLocales, lang, replaceRules = [], multiVersion } = docConfig;
741
1255
  const { versions = [] } = multiVersion || {};
742
1256
  const hasMultiVersion = versions.length > 0;
743
1257
  docConfig.themeConfig = docConfig.themeConfig || {};
744
1258
  const { themeConfig } = docConfig;
745
1259
  const locales = siteLocales ?? (themeConfig?.locales || []);
746
1260
  const i18nTextData = getI18nData(docConfig);
747
- const normalizeLinkPrefix = (link = '', currentLang = '')=>{
748
- const normalizedLink = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(link);
749
- if (!currentLang || !link || (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withoutBase)(normalizedLink, base).startsWith(`/${currentLang}`) || (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
750
- return lang === currentLang ? normalizedLink : `/${currentLang}${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(normalizedLink)}`;
1261
+ const normalizeLinkPrefix = (link, currentLang)=>{
1262
+ const normalizedLink = (0, shared_.slash)(link);
1263
+ if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || (0, shared_.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
1264
+ return lang === currentLang ? normalizedLink : `/${currentLang}${(0, shared_.addLeadingSlash)(normalizedLink)}`;
751
1265
  };
752
- const getI18nText = (key = '', currentLang = '')=>{
1266
+ const getI18nText = (key, currentLang)=>{
753
1267
  const text = i18nTextData[key]?.[currentLang];
754
1268
  return text || key;
755
1269
  };
756
- const normalizeSidebar = (sidebar, currentLang = '')=>{
1270
+ const cleanUrls = false;
1271
+ const transformLink = (link, currentLang)=>(0, shared_.normalizeHref)(normalizeLinkPrefix(link, currentLang), cleanUrls);
1272
+ const textReplace = (text, currentLang)=>applyReplaceRules(getI18nText(text, currentLang), replaceRules);
1273
+ const normalizeSidebar = (sidebar, currentLang)=>{
757
1274
  const normalizedSidebar = {};
758
1275
  if (!sidebar) return {};
759
1276
  const normalizeSidebarItem = (item)=>{
760
1277
  if ('object' == typeof item && 'dividerType' in item) return item;
761
1278
  if ('object' == typeof item && 'sectionHeaderText' in item) {
762
- item.sectionHeaderText = applyReplaceRules(getI18nText(item.sectionHeaderText, currentLang), replaceRules);
1279
+ item.sectionHeaderText = textReplace(item.sectionHeaderText, currentLang);
763
1280
  return item;
764
1281
  }
765
1282
  if ('object' == typeof item && 'items' in item) return {
766
1283
  ...item,
767
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
768
- link: normalizeLinkPrefix(item.link),
1284
+ text: textReplace(item.text, currentLang),
1285
+ ...'link' in item && item.link ? {
1286
+ link: transformLink(item.link, currentLang)
1287
+ } : {},
769
1288
  collapsed: item.collapsed ?? false,
770
1289
  collapsible: item.collapsible ?? true,
771
- tag: item.tag,
772
1290
  items: item.items.map((subItem)=>normalizeSidebarItem(subItem))
773
1291
  };
774
- if ('string' == typeof item) {
775
- const normalizedItem = normalizeLinkPrefix(item, currentLang);
776
- const page = pages.find((page)=>page.routePath === (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(normalizedItem, base));
777
- return {
778
- text: applyReplaceRules(page?.title || '', replaceRules),
779
- link: normalizedItem,
780
- _fileKey: page?._relativePath.replace(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(page._relativePath), '')
781
- };
782
- }
783
1292
  return {
784
1293
  ...item,
785
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
786
- link: normalizeLinkPrefix(item.link),
787
- tag: item.tag
1294
+ text: textReplace(item.text, currentLang),
1295
+ link: transformLink(item.link, currentLang)
788
1296
  };
789
1297
  };
790
1298
  const normalizeSidebar = (sidebar)=>{
@@ -798,24 +1306,18 @@ function normalizeThemeConfig(docConfig, pages = []) {
798
1306
  };
799
1307
  const normalizeNav = (nav, currentLang)=>{
800
1308
  if (!nav) return [];
801
- const transformNavItem = (navItem)=>{
802
- const text = applyReplaceRules(getI18nText(navItem.text, currentLang), replaceRules);
803
- if ('link' in navItem) return {
1309
+ const transformNavItem = (navItem)=>({
804
1310
  ...navItem,
805
- text,
806
- link: normalizeLinkPrefix(navItem.link, currentLang)
807
- };
808
- if ('items' in navItem) return {
809
- ...navItem,
810
- text,
811
- items: navItem.items.map((item)=>({
812
- ...item,
813
- text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
814
- link: normalizeLinkPrefix(item.link, currentLang)
815
- }))
816
- };
817
- return navItem;
818
- };
1311
+ ...navItem.text ? {
1312
+ text: textReplace(navItem.text, currentLang)
1313
+ } : {},
1314
+ ...'link' in navItem ? {
1315
+ link: transformLink(navItem.link, currentLang)
1316
+ } : {},
1317
+ ...'items' in navItem ? {
1318
+ items: navItem.items.map((item)=>transformNavItem(item))
1319
+ } : {}
1320
+ });
819
1321
  if (Array.isArray(nav)) return nav.map(transformNavItem);
820
1322
  return Object.entries(nav).reduce((acc, [key, value])=>{
821
1323
  acc[key] = value.map(transformNavItem);
@@ -827,71 +1329,33 @@ function normalizeThemeConfig(docConfig, pages = []) {
827
1329
  return {
828
1330
  lang: currentLang,
829
1331
  label,
830
- ...localeInThemeConfig || {},
1332
+ ...localeInThemeConfig,
831
1333
  sidebar: normalizeSidebar(localeInThemeConfig?.sidebar ?? themeConfig.sidebar, currentLang),
832
1334
  nav: normalizeNav(localeInThemeConfig?.nav ?? themeConfig.nav, currentLang)
833
1335
  };
834
1336
  });
835
1337
  else {
836
- themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar);
837
- themeConfig.nav = normalizeNav(themeConfig?.nav);
1338
+ themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar, '');
1339
+ themeConfig.nav = normalizeNav(themeConfig?.nav, '');
838
1340
  }
839
1341
  return themeConfig;
840
1342
  }
841
- function deletePrivateField(obj) {
842
- if ('object' != typeof obj || null === obj) return obj;
843
- const newObj = {
844
- ...obj
845
- };
846
- for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
847
- return newObj;
848
- }
849
- async function siteDataVMPlugin(context) {
850
- const { config, alias, userDocRoot, routeService, pluginDriver } = context;
851
- const userConfig = config;
1343
+ async function createSiteData(userConfig) {
852
1344
  const tempSearchObj = Object.assign({}, userConfig.search);
853
1345
  if (tempSearchObj) tempSearchObj.searchHooks = void 0;
854
- const highlightLanguages = new Set();
855
- const replaceRules = userConfig?.replaceRules || [];
856
- const searchConfig = userConfig?.search || {};
857
- const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
858
- const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
859
- const pages = await extractPageData(replaceRules, alias, domain, userDocRoot, routeService, highlightLanguages, searchCodeBlocks);
860
- await pluginDriver.modifySearchIndexData(pages);
861
- const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
862
- const groupedPages = (0, __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__.groupBy)(pages, (page)=>{
863
- if (page.frontmatter?.pageType === 'home') return 'noindex';
864
- const version = versioned ? page.version : '';
865
- const lang = page.lang || '';
866
- return `${version}###${lang}`;
867
- });
868
- delete groupedPages.noindex;
869
- const indexHashByGroup = {};
870
- await Promise.all(Object.keys(groupedPages).map(async (group)=>{
871
- const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
872
- const indexHash = createHash(stringifiedIndex);
873
- indexHashByGroup[group] = indexHash;
874
- const [version, lang] = group.split('###');
875
- const indexVersion = version ? `.${version.replace('.', '_')}` : '';
876
- const indexLang = lang ? `.${lang}` : '';
877
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(constants_TEMP_DIR, {
878
- recursive: true
879
- });
880
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(constants_TEMP_DIR, `${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
881
- }));
882
- await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
1346
+ const { base } = userConfig;
1347
+ const normalizedBase = (0, shared_.addTrailingSlash)((0, shared_.addLeadingSlash)(base ?? '/'));
883
1348
  const siteData = {
1349
+ base: normalizedBase,
884
1350
  title: userConfig?.title || '',
885
1351
  description: userConfig?.description || '',
886
- icon: userConfig?.icon || '',
1352
+ icon: getIconUrlPath(userConfig?.icon) || '',
887
1353
  route: userConfig?.route || {},
888
- themeConfig: normalizeThemeConfig(userConfig, pages),
889
- base: userConfig?.base || '/',
1354
+ themeConfig: normalizeThemeConfig(userConfig),
890
1355
  lang: userConfig?.lang || '',
891
1356
  locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
892
1357
  logo: userConfig?.logo || '',
893
1358
  logoText: userConfig?.logoText || '',
894
- ssg: Boolean(userConfig?.ssg ?? true),
895
1359
  multiVersion: {
896
1360
  default: userConfig?.multiVersion?.default || '',
897
1361
  versions: userConfig?.multiVersion?.versions || []
@@ -899,171 +1363,156 @@ async function siteDataVMPlugin(context) {
899
1363
  search: tempSearchObj ?? {
900
1364
  mode: 'local'
901
1365
  },
902
- pages: pages.map((page)=>{
903
- const { content, id, domain, _filepath, _html, _flattenContent, ...rest } = page;
904
- return isProduction() ? rest : {
905
- ...rest,
906
- _filepath
907
- };
908
- }),
909
1366
  markdown: {
910
1367
  showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
911
1368
  defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
912
- codeHighlighter: userConfig?.markdown?.codeHighlighter || 'prism'
1369
+ shiki: {}
913
1370
  }
914
1371
  };
915
- const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};
916
- if (Array.isArray(siteData.pages[0]?.extraHighlightLanguages)) siteData.pages[0].extraHighlightLanguages.forEach((lang)=>highlightLanguages.add(lang));
917
- const aliases = handleHighlightLanguages(highlightLanguages, defaultLanguages);
918
- const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());
919
- const sortedHighlightLanguages = Array.from(highlightLanguages).sort();
920
1372
  return {
921
- [`${types_RuntimeModuleID.SiteData}.mjs`]: `export default ${JSON.stringify(siteData, null, 2)}`,
922
- [types_RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(indexHashByGroup, null, 2)}`,
923
- [types_RuntimeModuleID.PrismLanguages]: `export const aliases = ${JSON.stringify(sortedAliases, null, 2)};
924
- export const languages = {
925
- ${sortedHighlightLanguages.map((lang)=>`"${lang}": require(
926
- "react-syntax-highlighter/dist/cjs/languages/prism/${lang}"
927
- ).default`)}
928
- }`
1373
+ siteData
929
1374
  };
930
1375
  }
931
- const runtimeModuleFactory = [
932
- routeVMPlugin,
933
- siteDataVMPlugin
934
- ];
935
- function rsbuildPluginDocVM(factoryContext) {
936
- const { pluginDriver } = factoryContext;
1376
+ const siteDataVMPlugin = (context)=>{
1377
+ const { config } = context;
937
1378
  return {
938
- name: 'rsbuild-plugin-doc-vm',
939
- setup (api) {
940
- api.modifyBundlerChain(async (bundlerChain, { target })=>{
941
- const isServer = 'node' === target;
942
- const alias = bundlerChain.resolve.alias.entries();
943
- const runtimeModule = {};
944
- for (const factory of runtimeModuleFactory){
945
- const moduleResult = await factory({
946
- ...factoryContext,
947
- isSSR: isServer,
948
- alias: alias
949
- });
950
- Object.assign(runtimeModule, moduleResult);
951
- }
952
- const modulesByPlugin = await pluginDriver.addRuntimeModules();
953
- Object.keys(modulesByPlugin).forEach((key)=>{
954
- if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
955
- runtimeModule[key] = modulesByPlugin[key];
956
- });
957
- bundlerChain.plugin('rspress-runtime-module').use(new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin(runtimeModule, factoryContext.runtimeTempDir));
958
- });
1379
+ ["virtual-site-data"]: async ()=>{
1380
+ const { siteData } = await createSiteData(config);
1381
+ return `export default ${JSON.stringify(siteData, null, 2)}`;
959
1382
  }
960
1383
  };
961
- }
962
- const globalStylesVMPlugin = (context)=>({
963
- [types_RuntimeModuleID.GlobalStyles]: ()=>{
964
- const { config, pluginDriver } = context;
965
- const globalStylesByPlugins = pluginDriver.globalStyles();
966
- const moduleContent = [
967
- config?.globalStyles,
968
- ...globalStylesByPlugins
969
- ].filter(Boolean).map((source)=>`import ${JSON.stringify(source)};`).join('');
970
- return moduleContent;
971
- }
972
- });
973
- const globalUIComponentsVMPlugin = (context)=>({
974
- [types_RuntimeModuleID.GlobalComponents]: ()=>{
975
- const { config, pluginDriver } = context;
976
- let index = 0;
977
- const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
978
- const globalComponents = [
979
- ...config?.globalUIComponents || [],
980
- ...globalUIComponentsByPlugins
981
- ];
982
- const moduleContent = globalComponents.map((source)=>{
983
- const name = `Comp_${index}`;
984
- if (Array.isArray(source)) return `import ${name} from ${JSON.stringify(source[0])};
985
- const Props_${index++} = ${JSON.stringify(source[1])};\n`;
986
- index++;
987
- return `import ${name} from ${JSON.stringify(source)};\n`;
988
- }).concat(`export default [${Array.from({
989
- length: index
990
- }, (_, i)=>{
991
- if (Array.isArray(globalComponents[i])) return `[Comp_${i}, Props_${i}]`;
992
- return `Comp_${i}`;
993
- }).join(', ')}];`).join('');
994
- return moduleContent;
995
- }
996
- });
997
- const searchHookVMPlugin = (context)=>({
998
- [`${types_RuntimeModuleID.SearchHooks}`]: ()=>{
999
- const { config } = context;
1000
- let content = 'export const onSearch = () => {};';
1001
- if ('object' == typeof config.search && 'string' == typeof config.search.searchHooks) content = `export * from '${config.search.searchHooks}'`;
1002
- return content;
1003
- }
1004
- });
1005
- async function writeSearchIndex(config) {
1006
- if (config?.search === false) return;
1007
- const cwd = process.cwd();
1008
- const searchIndexFiles = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readdir(constants_TEMP_DIR);
1009
- const outDir = config?.outDir ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cwd, OUTPUT_DIR);
1010
- const targetDir = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outDir, 'static');
1011
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(targetDir, {
1012
- recursive: true
1013
- });
1014
- let searchIndexData = '[]';
1015
- let scanning = false;
1016
- for (const searchIndexFile of searchIndexFiles){
1017
- if (!searchIndexFile.includes(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
1018
- const source = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(constants_TEMP_DIR, searchIndexFile);
1019
- const target = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(targetDir, searchIndexFile);
1020
- const searchIndex = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(constants_TEMP_DIR, searchIndexFile), 'utf-8');
1021
- searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
1022
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].rename(source, target);
1023
- scanning = true;
1024
- }
1025
- if (isProduction() && (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isSCM)() && config?.search?.mode === 'remote') {
1026
- const { apiUrl, indexName } = config.search;
1027
- try {
1028
- await fetch(`${apiUrl}?index=${indexName}`, {
1029
- method: 'PUT',
1030
- body: searchIndexData,
1031
- headers: {
1032
- 'Content-Type': 'application/json'
1033
- }
1034
- });
1035
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
1036
- } catch (e) {
1037
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info(__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
1038
- }
1384
+ };
1385
+ const presetIcons = {
1386
+ discord: '<path fill="currentColor" d="M20.317 4.37a19.8 19.8 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.3 18.3 0 0 0-5.487 0a13 13 0 0 0-.617-1.25a.08.08 0 0 0-.079-.037A19.7 19.7 0 0 0 3.677 4.37a.1.1 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.08.08 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.08.08 0 0 0 .084-.028a14 14 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13 13 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10 10 0 0 0 .372-.292a.07.07 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.07.07 0 0 1 .078.01q.181.149.373.292a.077.077 0 0 1-.006.127a12.3 12.3 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.08.08 0 0 0 .084.028a19.8 19.8 0 0 0 6.002-3.03a.08.08 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.06.06 0 0 0-.031-.03M8.02 15.33c-1.182 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418m7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418"/>',
1387
+ facebook: '<path fill="currentColor" d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978c.401 0 .955.042 1.468.103a9 9 0 0 1 1.141.195v3.325a9 9 0 0 0-.653-.036a27 27 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.7 1.7 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103l-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647"/>',
1388
+ github: '<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12c0 5.303 3.438 9.8 8.205 11.385c.6.113.82-.258.82-.577c0-.285-.01-1.04-.015-2.04c-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729c1.205.084 1.838 1.236 1.838 1.236c1.07 1.835 2.809 1.305 3.495.998c.108-.776.417-1.305.76-1.605c-2.665-.3-5.466-1.332-5.466-5.93c0-1.31.465-2.38 1.235-3.22c-.135-.303-.54-1.523.105-3.176c0 0 1.005-.322 3.3 1.23c.96-.267 1.98-.399 3-.405c1.02.006 2.04.138 3 .405c2.28-1.552 3.285-1.23 3.285-1.23c.645 1.653.24 2.873.12 3.176c.765.84 1.23 1.91 1.23 3.22c0 4.61-2.805 5.625-5.475 5.92c.42.36.81 1.096.81 2.22c0 1.606-.015 2.896-.015 3.286c0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>',
1389
+ gitlab: '<path fill="currentColor" d="m23.6 9.593l-.033-.086L20.3.98a.85.85 0 0 0-.336-.405a.875.875 0 0 0-1 .054a.9.9 0 0 0-.29.44L16.47 7.818H7.537L5.333 1.07a.86.86 0 0 0-.29-.441a.875.875 0 0 0-1-.054a.86.86 0 0 0-.336.405L.433 9.502l-.032.086a6.066 6.066 0 0 0 2.012 7.01l.01.009l.03.021l4.977 3.727l2.462 1.863l1.5 1.132a1.01 1.01 0 0 0 1.22 0l1.499-1.132l2.461-1.863l5.006-3.75l.013-.01a6.07 6.07 0 0 0 2.01-7.002"/>',
1390
+ instagram: '<path fill="currentColor" d="M7.03.084c-1.277.06-2.149.264-2.91.563a5.9 5.9 0 0 0-2.124 1.388a5.9 5.9 0 0 0-1.38 2.127C.321 4.926.12 5.8.064 7.076s-.069 1.688-.063 4.947s.021 3.667.083 4.947c.061 1.277.264 2.149.563 2.911c.308.789.72 1.457 1.388 2.123a5.9 5.9 0 0 0 2.129 1.38c.763.295 1.636.496 2.913.552c1.278.056 1.689.069 4.947.063s3.668-.021 4.947-.082c1.28-.06 2.147-.265 2.91-.563a5.9 5.9 0 0 0 2.123-1.388a5.9 5.9 0 0 0 1.38-2.129c.295-.763.496-1.636.551-2.912c.056-1.28.07-1.69.063-4.948c-.006-3.258-.02-3.667-.081-4.947c-.06-1.28-.264-2.148-.564-2.911a5.9 5.9 0 0 0-1.387-2.123a5.9 5.9 0 0 0-2.128-1.38c-.764-.294-1.636-.496-2.914-.55C15.647.009 15.236-.006 11.977 0S8.31.021 7.03.084m.14 21.693c-1.17-.05-1.805-.245-2.228-.408a3.7 3.7 0 0 1-1.382-.895a3.7 3.7 0 0 1-.9-1.378c-.165-.423-.363-1.058-.417-2.228c-.06-1.264-.072-1.644-.08-4.848c-.006-3.204.006-3.583.061-4.848c.05-1.169.246-1.805.408-2.228c.216-.561.477-.96.895-1.382a3.7 3.7 0 0 1 1.379-.9c.423-.165 1.057-.361 2.227-.417c1.265-.06 1.644-.072 4.848-.08c3.203-.006 3.583.006 4.85.062c1.168.05 1.804.244 2.227.408c.56.216.96.475 1.382.895s.681.817.9 1.378c.165.422.362 1.056.417 2.227c.06 1.265.074 1.645.08 4.848c.005 3.203-.006 3.583-.061 4.848c-.051 1.17-.245 1.805-.408 2.23c-.216.56-.477.96-.896 1.38a3.7 3.7 0 0 1-1.378.9c-.422.165-1.058.362-2.226.418c-1.266.06-1.645.072-4.85.079s-3.582-.006-4.848-.06m9.783-16.192a1.44 1.44 0 1 0 1.437-1.442a1.44 1.44 0 0 0-1.437 1.442M5.839 12.012a6.161 6.161 0 1 0 12.323-.024a6.162 6.162 0 0 0-12.323.024M8 12.008A4 4 0 1 1 12.008 16A4 4 0 0 1 8 12.008"/>',
1391
+ linkedin: '<path fill="currentColor" d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037c-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85c3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.06 2.06 0 0 1-2.063-2.065a2.064 2.064 0 1 1 2.063 2.065m1.782 13.019H3.555V9h3.564zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0z"/>',
1392
+ slack: '<path fill="currentColor" d="M5.042 15.165a2.53 2.53 0 0 1-2.52 2.523A2.53 2.53 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52a2.527 2.527 0 0 1 2.521 2.52v6.313A2.53 2.53 0 0 1 8.834 24a2.53 2.53 0 0 1-2.521-2.522zM8.834 5.042a2.53 2.53 0 0 1-2.521-2.52A2.53 2.53 0 0 1 8.834 0a2.53 2.53 0 0 1 2.521 2.522v2.52zm0 1.271a2.53 2.53 0 0 1 2.521 2.521a2.53 2.53 0 0 1-2.521 2.521H2.522A2.53 2.53 0 0 1 0 8.834a2.53 2.53 0 0 1 2.522-2.521zm10.122 2.521a2.53 2.53 0 0 1 2.522-2.521A2.53 2.53 0 0 1 24 8.834a2.53 2.53 0 0 1-2.522 2.521h-2.522zm-1.268 0a2.53 2.53 0 0 1-2.523 2.521a2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.53 2.53 0 0 1 2.523 2.522zm-2.523 10.122a2.53 2.53 0 0 1 2.523 2.522A2.53 2.53 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522zm0-1.268a2.527 2.527 0 0 1-2.52-2.523a2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.53 2.53 0 0 1-2.522 2.523z"/>',
1393
+ youtube: '<path fill="currentColor" d="M23.498 6.186a3.02 3.02 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.02 3.02 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.02 3.02 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.02 3.02 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814M9.545 15.568V8.432L15.818 12z"/>',
1394
+ juejin: '<path fill="currentColor" d="m12 14.316l7.454-5.88l-2.022-1.625L12 11.1l-.004.003l-5.432-4.288l-2.02 1.624l7.452 5.88Zm0-7.247l2.89-2.298L12 2.453l-.004-.005l-2.884 2.318l2.884 2.3Zm0 11.266l-.005.002l-9.975-7.87L0 12.088l.194.156l11.803 9.308l7.463-5.885L24 12.085l-2.023-1.624Z"/>',
1395
+ qq: '<path fill="currentColor" d="M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673c.54.065 2.103-2.472 2.103-2.472c0 1.469.756 3.387 2.394 4.771c-.612.188-1.363.479-1.845.835c-.434.32-.379.646-.301.778c.343.578 5.883.369 7.482.189c1.6.18 7.14.389 7.483-.189c.078-.132.132-.458-.301-.778c-.483-.356-1.233-.646-1.846-.836c1.637-1.384 2.393-3.302 2.393-4.771c0 0 1.563 2.537 2.103 2.472c.251-.03.581-1.39-.438-4.673"/>',
1396
+ wechat: '<path fill="currentColor" d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213c0 .163.13.295.29.295a.33.33 0 0 0 .167-.054l1.903-1.114a.86.86 0 0 1 .717-.098a10.2 10.2 0 0 0 2.837.403c.276 0 .543-.027.811-.05c-.857-2.578.157-4.972 1.932-6.446c1.703-1.415 3.882-1.98 5.853-1.838c-.576-3.583-4.196-6.348-8.596-6.348M5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178a1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18m5.34 2.867c-1.797-.052-3.746.512-5.28 1.786c-1.72 1.428-2.687 3.72-1.78 6.22c.942 2.453 3.666 4.229 6.884 4.229c.826 0 1.622-.12 2.361-.336a.72.72 0 0 1 .598.082l1.584.926a.3.3 0 0 0 .14.047c.134 0 .24-.111.24-.247c0-.06-.023-.12-.038-.177l-.327-1.233a.6.6 0 0 1-.023-.156a.49.49 0 0 1 .201-.398C23.024 18.48 24 16.82 24 14.98c0-3.21-2.931-5.837-6.656-6.088V8.89c-.135-.01-.27-.027-.407-.03zm-2.53 3.274c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.97-.982zm4.844 0c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982"/>',
1397
+ weibo: '<path fill="currentColor" d="M17.525 11.378c1.263.392 2.669 1.336 2.669 3.004c0 2.763-3.98 6.239-9.964 6.239c-4.565 0-9.23-2.213-9.23-5.852c0-1.902 1.204-4.102 3.277-6.177c2.773-2.77 6.004-4.033 7.219-2.816c.537.537.588 1.464.244 2.572c-.178.557.525.25.525.25c2.24-.938 4.196-.994 4.909.027c.38.543.343 1.306-.008 2.19c-.163.407.048.471.36.563zm-7.282 7.939c3.641-.362 6.401-2.592 6.167-4.983c-.237-2.391-3.382-4.038-7.023-3.677c-3.64.36-6.403 2.59-6.167 4.98c.237 2.394 3.382 4.039 7.023 3.68zM6.16 14.438c.754-1.527 2.712-2.39 4.446-1.94c1.793.463 2.707 2.154 1.976 3.8c-.744 1.682-2.882 2.578-4.695 1.993c-1.752-.566-2.493-2.294-1.727-3.853zm1.446 2.587c.568.257 1.325.013 1.676-.55c.346-.568.163-1.217-.407-1.459c-.563-.237-1.291.008-1.64.553c-.354.547-.189 1.202.371 1.456zm2.206-1.808c.219.092.501-.012.628-.231c.123-.22.044-.466-.178-.548c-.216-.084-.486.018-.613.232c-.123.214-.054.458.163.547zM19.873 9.5a.725.725 0 1 1-1.378-.451a1.38 1.38 0 0 0-.288-1.357a1.395 1.395 0 0 0-1.321-.425a.723.723 0 1 1-.303-1.416a2.836 2.836 0 0 1 3.29 3.649zm-3.916-6.575A5.831 5.831 0 0 1 21.5 4.72a5.836 5.836 0 0 1 1.22 5.704a.838.838 0 0 1-1.06.54a.844.844 0 0 1-.542-1.062a4.143 4.143 0 0 0-4.807-5.327a.845.845 0 0 1-.354-1.65z"/>',
1398
+ zhihu: '<path fill="currentColor" d="M5.721 0C2.251 0 0 2.25 0 5.719V18.28C0 21.751 2.252 24 5.721 24h12.56C21.751 24 24 21.75 24 18.281V5.72C24 2.249 21.75 0 18.281 0zm1.964 4.078q-.408 1.096-.68 2.11h4.587c.545-.006.445 1.168.445 1.171H9.384a58 58 0 0 1-.112 3.797h2.712c.388.023.393 1.251.393 1.266H9.183a9.2 9.2 0 0 1-.408 2.102l.757-.604c.452.456 1.512 1.712 1.906 2.177c.473.681.063 2.081.063 2.081l-2.794-3.382c-.653 2.518-1.845 3.607-1.845 3.607c-.523.468-1.58.82-2.64.516c2.218-1.73 3.44-3.917 3.667-6.497H4.491c0-.015.197-1.243.806-1.266h2.71c.024-.32.086-3.254.086-3.797H6.598c-.136.406-.158.447-.268.753c-.594 1.095-1.603 1.122-1.907 1.155c.906-1.821 1.416-3.6 1.591-4.064c.425-1.124 1.671-1.125 1.671-1.125M13.078 6h6.377v11.33h-2.573l-2.184 1.373l-.401-1.373h-1.219zm1.313 1.219v8.86h.623l.263.937l1.455-.938h1.456v-8.86z"/>',
1399
+ bilibili: '<path fill="currentColor" d="M17.813 4.653h.854q2.266.08 3.773 1.574Q23.946 7.72 24 9.987v7.36q-.054 2.266-1.56 3.773c-1.506 1.507-2.262 1.524-3.773 1.56H5.333q-2.266-.054-3.773-1.56C.053 19.614.036 18.858 0 17.347v-7.36q.054-2.267 1.56-3.76t3.773-1.574h.774l-1.174-1.12a1.23 1.23 0 0 1-.373-.906q0-.534.373-.907l.027-.027q.4-.373.92-.373t.92.373L9.653 4.44q.107.106.187.213h4.267a.8.8 0 0 1 .16-.213l2.853-2.747q.4-.373.92-.373c.347 0 .662.151.929.4s.391.551.391.907q0 .532-.373.906zM5.333 7.24q-1.12.027-1.88.773q-.76.748-.786 1.894v7.52q.026 1.146.786 1.893t1.88.773h13.334q1.12-.026 1.88-.773t.786-1.893v-7.52q-.026-1.147-.786-1.894t-1.88-.773zM8 11.107q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q0-.56.386-.947q.387-.386.947-.386m8 0q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q.025-.586.4-.96q.373-.373.933-.373"/>',
1400
+ lark: '<path d="M6.14 3.8a28.88 28.88 0 0 1 6.6 7.63l1.7-1.67a8.37 8.37 0 0 1 2.82-1.83 12.23 12.23 0 0 0-2.32-4.28.67.67 0 0 0-.53-.25H6.28c-.21 0-.3.27-.14.4Z" fill="currentColor"></path><path d="m20.57 14.2.01-.02.04-.07-.05.08Z" fill="currentColor"></path><path d="M11.04 14.56c1.23.52 2.34.97 3.65 1.32a4.75 4.75 0 0 0 5.63-2.4l1.32-2.63c.3-.64.67-1.23 1.12-1.78a6.2 6.2 0 0 0-2.3-.44c-1.9 0-3.7.73-5.06 2.06l-2.02 2c-.72.7-1.5 1.33-2.34 1.87Z" fill="currentColor"></path><path d="M20.8 13.78v-.02l.01-.01s0 .02-.02.03Z" fill="currentColor"></path><path d="M1.63 9.75a.23.23 0 0 0-.4.16v7.96c0 .23.12.44.3.56a12.95 12.95 0 0 0 14.08.2c.78-.5 1.39-.92 2.04-1.55-1.05.3-2.2.33-3.37.01A28.99 28.99 0 0 1 1.63 9.75Z" fill="currentColor"></path>',
1401
+ x: '<path fill="currentColor" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584l-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/>',
1402
+ bluesky: '<path fill="currentColor" d="M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565C.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479c.815 2.736 3.713 3.66 6.383 3.364q.204-.03.415-.056q-.207.033-.415.056c-3.912.58-7.387 2.005-2.83 7.078c5.013 5.19 6.87-1.113 7.823-4.308c.953 3.195 2.05 9.271 7.733 4.308c4.267-4.308 1.172-6.498-2.74-7.078a9 9 0 0 1-.415-.056q.21.026.415.056c2.67.297 5.568-.628 6.383-3.364c.246-.828.624-5.79.624-6.478c0-.69-.139-1.861-.902-2.206c-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8"/>',
1403
+ npm: '<path fill="currentColor" d="M1.763 0C.786 0 0 .786 0 1.763v20.474C0 23.214.786 24 1.763 24h20.474c.977 0 1.763-.786 1.763-1.763V1.763C24 .786 23.214 0 22.237 0zM5.13 5.323l13.837.019l-.009 13.836h-3.464l.01-10.382h-3.456L12.04 19.17H5.113z"/>'
1404
+ };
1405
+ const formatIconName = (icon)=>icon.toLowerCase();
1406
+ function getSocialIcons(socialLinks = []) {
1407
+ const icons = {};
1408
+ for (const link of socialLinks)if ('string' == typeof link.icon) {
1409
+ const pathContent = presetIcons[formatIconName(link.icon)];
1410
+ if (!pathContent) throw new Error(`Icon "${link.icon}" not found in preset icons.`);
1411
+ icons[link.icon] = `<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 24 24">${pathContent}</svg>`;
1039
1412
  }
1413
+ return icons;
1040
1414
  }
1041
- function serveSearchIndexMiddleware(config) {
1042
- return (req, res, next)=>{
1043
- const searchIndexRequestMatch = `/${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME}.`;
1044
- if (req.url?.includes(searchIndexRequestMatch)) {
1045
- res.setHeader('Content-Type', 'application/json');
1046
- const outDir = config?.outDir ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), OUTPUT_DIR);
1047
- const searchIndexFile = req.url.split('/').pop();
1048
- (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.createReadStream)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
1049
- end: true
1050
- });
1051
- } else next?.();
1415
+ const socialLinksVMPlugin = (context)=>{
1416
+ const { config } = context;
1417
+ return {
1418
+ ["virtual-social-links"]: ()=>`export default ${JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks), null, 2)}`
1052
1419
  };
1053
- }
1054
- async function renderFrontmatterHead(route) {
1055
- if (!isRouteMeta(route)) return '';
1056
- const content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(route.absolutePath, {
1057
- encoding: 'utf-8'
1420
+ };
1421
+ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
1422
+ return new Promise((resolve_, reject_)=>{
1423
+ if (void 0 === iterable[Symbol.iterator] && void 0 === iterable[Symbol.asyncIterator]) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
1424
+ if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
1425
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === 1 / 0)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
1426
+ const result = [];
1427
+ const errors = [];
1428
+ const skippedIndexesMap = new Map();
1429
+ let isRejected = false;
1430
+ let isResolved = false;
1431
+ let isIterableDone = false;
1432
+ let resolvingCount = 0;
1433
+ let currentIndex = 0;
1434
+ const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
1435
+ const signalListener = ()=>{
1436
+ reject(signal.reason);
1437
+ };
1438
+ const cleanup = ()=>{
1439
+ signal?.removeEventListener('abort', signalListener);
1440
+ };
1441
+ const resolve = (value)=>{
1442
+ resolve_(value);
1443
+ cleanup();
1444
+ };
1445
+ const reject = (reason)=>{
1446
+ isRejected = true;
1447
+ isResolved = true;
1448
+ reject_(reason);
1449
+ cleanup();
1450
+ };
1451
+ if (signal) {
1452
+ if (signal.aborted) reject(signal.reason);
1453
+ signal.addEventListener('abort', signalListener, {
1454
+ once: true
1455
+ });
1456
+ }
1457
+ const next = async ()=>{
1458
+ if (isResolved) return;
1459
+ const nextItem = await iterator.next();
1460
+ const index = currentIndex;
1461
+ currentIndex++;
1462
+ if (nextItem.done) {
1463
+ isIterableDone = true;
1464
+ if (0 === resolvingCount && !isResolved) {
1465
+ if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
1466
+ isResolved = true;
1467
+ if (0 === skippedIndexesMap.size) return void resolve(result);
1468
+ const pureResult = [];
1469
+ for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
1470
+ resolve(pureResult);
1471
+ }
1472
+ return;
1473
+ }
1474
+ resolvingCount++;
1475
+ (async ()=>{
1476
+ try {
1477
+ const element = await nextItem.value;
1478
+ if (isResolved) return;
1479
+ const value = await mapper(element, index);
1480
+ if (value === pMapSkip) skippedIndexesMap.set(index, value);
1481
+ result[index] = value;
1482
+ resolvingCount--;
1483
+ await next();
1484
+ } catch (error) {
1485
+ if (stopOnError) reject(error);
1486
+ else {
1487
+ errors.push(error);
1488
+ resolvingCount--;
1489
+ try {
1490
+ await next();
1491
+ } catch (error) {
1492
+ reject(error);
1493
+ }
1494
+ }
1495
+ }
1496
+ })();
1497
+ };
1498
+ (async ()=>{
1499
+ for(let index = 0; index < concurrency; index++){
1500
+ try {
1501
+ await next();
1502
+ } catch (error) {
1503
+ reject(error);
1504
+ break;
1505
+ }
1506
+ if (isIterableDone || isRejected) break;
1507
+ }
1508
+ })();
1058
1509
  });
1059
- const { frontmatter: { head } } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(content, route.absolutePath, '', true);
1060
- if (!head || 0 === head.length) return '';
1061
- return head.map(([tag, attrs])=>`<${tag} ${renderAttrs(attrs)}>`).join('');
1062
1510
  }
1063
- async function renderConfigHead(config, route) {
1511
+ const pMapSkip = Symbol('skip');
1512
+ async function renderConfigHead(head, route) {
1064
1513
  if (!isRouteMeta(route)) return '';
1065
- if (!config.head || 0 === config.head.length) return '';
1066
- return config.head.map((head)=>{
1514
+ if (!head || 0 === head.length) return '';
1515
+ return head.map((head)=>{
1067
1516
  if ('string' == typeof head) return head;
1068
1517
  if ('function' == typeof head) {
1069
1518
  const resultHead = head(route);
@@ -1074,6 +1523,12 @@ async function renderConfigHead(config, route) {
1074
1523
  return `<${head[0]} ${renderAttrs(head[1])}>`;
1075
1524
  }).join('');
1076
1525
  }
1526
+ async function renderHtmlTemplate(htmlTemplate, head, route, appHtml = '') {
1527
+ const replacedHtmlTemplate = htmlTemplate.replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1528
+ await renderConfigHead(head, route)
1529
+ ].join(''));
1530
+ return replacedHtmlTemplate;
1531
+ }
1077
1532
  function renderAttrs(attrs) {
1078
1533
  return Object.entries(attrs).map(([key, value])=>{
1079
1534
  if ('boolean' == typeof value) return key;
@@ -1084,90 +1539,202 @@ function renderAttrs(attrs) {
1084
1539
  function isRouteMeta(route) {
1085
1540
  return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
1086
1541
  }
1087
- async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
1088
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Rendering pages...');
1089
- const startTime = Date.now();
1542
+ async function renderPage(route, htmlTemplate, configHead, ssrBundlePath) {
1090
1543
  let render;
1091
1544
  try {
1092
- const { default: ssrExports } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(ssrBundlePath).toString());
1093
- ({ render } = ssrExports);
1545
+ const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
1546
+ render = await ssrExports.render;
1094
1547
  } catch (e) {
1095
1548
  if (e instanceof Error) {
1096
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Failed to load SSG bundle: ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(ssrBundlePath)}: ${e.message}`);
1097
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1549
+ logger.error(`Failed to load SSG bundle: ${picocolors.yellow(ssrBundlePath)}: ${e.message}`);
1550
+ logger.debug(e);
1098
1551
  hintSSGFailed();
1099
1552
  }
1100
1553
  throw e;
1101
1554
  }
1555
+ const head = createHead();
1556
+ const { routePath } = route;
1557
+ let appHtml = '';
1558
+ if (render) try {
1559
+ ({ appHtml } = await render(routePath, head));
1560
+ } catch (e) {
1561
+ if (e instanceof Error) {
1562
+ logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
1563
+ throw e;
1564
+ }
1565
+ }
1566
+ const replacedHtmlTemplate = await renderHtmlTemplate(htmlTemplate, configHead, route, appHtml);
1567
+ const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
1568
+ return html;
1569
+ }
1570
+ /**
1571
+ * these codes are copied from
1572
+ * @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
1573
+ * @license MIT
1574
+ */ function SSGWorkerThreadTaskSize() {
1575
+ return process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE, 10) : 10;
1576
+ }
1577
+ function SSGWorkerThreadRecyclerMaxMemory() {
1578
+ return process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY, 10) : 1000000000;
1579
+ }
1580
+ function inferNumberOfThreads({ pageCount, cpuCount, minPagesPerCpu }) {
1581
+ const threadsByWorkload = Math.ceil(pageCount / minPagesPerCpu);
1582
+ return Math.max(1, Math.min(threadsByWorkload, cpuCount));
1583
+ }
1584
+ function SSGWorkerThreadCount() {
1585
+ return process.env.RSPRESS_SSG_WORKER_THREAD_COUNT ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_COUNT, 10) : void 0;
1586
+ }
1587
+ function getNumberOfThreads(pathnamesLength) {
1588
+ const workerCount = SSGWorkerThreadCount();
1589
+ if (void 0 !== workerCount) return workerCount;
1590
+ const cpuCount = 'function' == typeof external_node_os_["default"].availableParallelism ? external_node_os_["default"].availableParallelism() : external_node_os_["default"].cpus().length;
1591
+ return inferNumberOfThreads({
1592
+ pageCount: pathnamesLength,
1593
+ cpuCount,
1594
+ minPagesPerCpu: 100
1595
+ });
1596
+ }
1597
+ function SSGConcurrency() {
1598
+ return process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32;
1599
+ }
1600
+ const routePath2HtmlFileName = (routePath)=>{
1601
+ let fileName = routePath;
1602
+ fileName = fileName.endsWith('/') ? `${routePath}index.html` : `${routePath}.html`;
1603
+ return fileName.replace(/^\/+/, '');
1604
+ };
1605
+ async function renderPages(routeService, config, ssrBundlePath, htmlTemplate, emitAsset) {
1606
+ logger.info('Rendering pages...');
1607
+ const startTime = Date.now();
1608
+ const ssg = config.ssg || true;
1102
1609
  try {
1103
1610
  const routes = routeService.getRoutes();
1104
- const base = config?.base ?? '';
1105
- const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
1106
- routePath: (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.withBase)(route.path, base)
1107
- }));
1108
- const allRoutes = [
1109
- ...routes,
1110
- ...additionalRoutes
1111
- ];
1112
- const is404RouteInRoutes = allRoutes.some((route)=>'/404' === route.routePath);
1113
- if (!is404RouteInRoutes) allRoutes.push({
1611
+ if (!routeService.isExistRoute('/404')) routes.push({
1114
1612
  routePath: '/404'
1115
1613
  });
1116
- await Promise.all(allRoutes.filter((route)=>!route.routePath.includes(':')).map(async (route)=>{
1117
- const helmetContext = new __WEBPACK_EXTERNAL_MODULE__dr_pogodin_react_helmet_ecf718aa__.HelmetData({});
1118
- const { routePath } = route;
1119
- let appHtml = '';
1120
- if (render) try {
1121
- ({ appHtml } = await render(routePath, helmetContext.context));
1122
- } catch (e) {
1123
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Page "${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(routePath)}" SSG rendering failed.`);
1124
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1125
- throw e;
1614
+ if ('object' == typeof ssg && Array.isArray(ssg?.experimentalExcludeRoutePaths) && ssg.experimentalExcludeRoutePaths.length > 0) {
1615
+ const shouldIgnoreRoutePaths = new Set();
1616
+ const shouldIgnoreRoutePathsRegExp = [];
1617
+ for (const routePath of ssg.experimentalExcludeRoutePaths)if ('string' == typeof routePath) shouldIgnoreRoutePaths.add(routePath);
1618
+ else if (routePath instanceof RegExp) shouldIgnoreRoutePathsRegExp.push(routePath);
1619
+ const promiseList = [];
1620
+ const csrRoutes = [];
1621
+ const ssgRoutes = [];
1622
+ for (const route of routes)if (shouldIgnoreRoutePaths.has(route.routePath) || shouldIgnoreRoutePathsRegExp.some((reg)=>reg.test(route.routePath))) {
1623
+ csrRoutes.push(route);
1624
+ promiseList.push(renderCSRPage(config.head, route, htmlTemplate, emitAsset));
1625
+ } else ssgRoutes.push(route);
1626
+ if (csrRoutes.length > 0) {
1627
+ logger.warn(`Some routes are ignored in SSG and fallback to CSR via \`ssg.experimentalExcludeRoutePaths\`: ${picocolors.yellow(csrRoutes.map((r)=>r.routePath).join(', '))}`);
1628
+ await Promise.all(promiseList);
1629
+ routes.length = 0;
1630
+ routes.push(...ssgRoutes);
1126
1631
  }
1127
- const { helmet } = helmetContext.context;
1128
- let html = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1129
- await renderConfigHead(config, route),
1130
- helmet.title.toString(),
1131
- helmet.meta.toString(),
1132
- helmet.link.toString(),
1133
- helmet.style.toString(),
1134
- helmet.script.toString(),
1135
- await renderFrontmatterHead(route)
1136
- ].join(''));
1137
- if (helmet.htmlAttributes) html = html.replace(HTML_START_TAG, `${HTML_START_TAG} ${helmet.htmlAttributes?.toString()}`);
1138
- if (helmet.bodyAttributes) html = html.replace(BODY_START_TAG, `${BODY_START_TAG} ${helmet.bodyAttributes?.toString()}`);
1139
- const normalizeHtmlFilePath = (path)=>{
1140
- const normalizedBase = `${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeSlash)(config?.base || '/')}/`;
1141
- if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
1142
- return `${path}.html`.replace(normalizedBase, '');
1143
- };
1144
- const fileName = normalizeHtmlFilePath(routePath);
1632
+ }
1633
+ if ('object' == typeof ssg && ssg?.experimentalWorker) {
1634
+ const numberOfThreads = getNumberOfThreads(routes.length);
1635
+ const Tinypool = await import("tinypool").then((m)=>m.default);
1636
+ const pool = new Tinypool({
1637
+ filename: new URL('./renderPageWorker.js', import.meta.url).href,
1638
+ concurrentTasksPerWorker: 1,
1639
+ minThreads: numberOfThreads,
1640
+ maxThreads: numberOfThreads,
1641
+ /**
1642
+ * https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
1643
+ * @license MIT
1644
+ */ maxMemoryLimitBeforeRecycle: SSGWorkerThreadRecyclerMaxMemory(),
1645
+ isolateWorkers: false,
1646
+ workerData: {
1647
+ params: {
1648
+ htmlTemplate,
1649
+ head: config.head,
1650
+ ssrBundlePath
1651
+ }
1652
+ }
1653
+ });
1654
+ await Promise.all(chunk(routes, SSGWorkerThreadTaskSize()).map(async (routes)=>{
1655
+ const htmlList = await pool.run({
1656
+ routes
1657
+ });
1658
+ for(let i = 0; i < routes.length; i++){
1659
+ const route = routes[i];
1660
+ const html = htmlList[i];
1661
+ const fileName = routePath2HtmlFileName(route.routePath);
1662
+ emitAsset(fileName, html);
1663
+ }
1664
+ }));
1665
+ await pool.destroy();
1666
+ } else await pMap(routes, async (route)=>{
1667
+ const html = await renderPage(route, htmlTemplate, config.head, ssrBundlePath);
1668
+ const fileName = routePath2HtmlFileName(route.routePath);
1145
1669
  emitAsset(fileName, html);
1146
- }));
1670
+ }, {
1671
+ concurrency: SSGConcurrency()
1672
+ });
1147
1673
  const totalTime = Date.now() - startTime;
1148
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.success(`Pages rendered in ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(totalTime)} ms.`);
1674
+ logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
1149
1675
  } catch (e) {
1150
1676
  if (e instanceof Error) {
1151
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Pages render error: ${e.message}`);
1152
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
1677
+ logger.error(`Pages render error: ${e.message}`);
1678
+ logger.debug(e);
1153
1679
  hintSSGFailed();
1154
1680
  }
1155
1681
  throw e;
1156
1682
  }
1157
1683
  }
1158
- const NODE_SSR_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
1159
- const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1684
+ async function renderCSRPage(head, route, htmlTemplate, emitAsset) {
1685
+ const html = await renderHtmlTemplate(htmlTemplate, head, route, '');
1686
+ const fileName = routePath2HtmlFileName(route.routePath);
1687
+ emitAsset(fileName, html);
1688
+ }
1689
+ async function renderCSRPages(routeService, config, htmlTemplate, emitAsset) {
1690
+ const routes = routeService.getRoutes();
1691
+ if (!routeService.isExistRoute('/404')) routes.push({
1692
+ routePath: '/404'
1693
+ });
1694
+ await Promise.all(routes.map((route)=>renderCSRPage(config.head, route, htmlTemplate, emitAsset)));
1695
+ }
1696
+ const rsbuildPluginCSR = ({ routeService, config })=>({
1697
+ name: 'rspress-inner-rsbuild-plugin-csr',
1698
+ async setup (api) {
1699
+ api.onBeforeBuild(()=>{
1700
+ api.processAssets({
1701
+ stage: 'report',
1702
+ environments: [
1703
+ 'web'
1704
+ ]
1705
+ }, async ({ assets, compilation, compiler })=>{
1706
+ if (compilation.errors.length > 0) return;
1707
+ const emitAsset = (assetName, content)=>{
1708
+ compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1709
+ };
1710
+ let htmlTemplate = '';
1711
+ for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1712
+ htmlTemplate = assetSource.source().toString();
1713
+ compilation.deleteAsset(assetName);
1714
+ break;
1715
+ }
1716
+ await renderCSRPages(routeService, config, htmlTemplate, emitAsset);
1717
+ });
1718
+ });
1719
+ }
1720
+ });
1721
+ const rsbuildPluginSSG = ({ routeService, config })=>({
1160
1722
  name: 'rspress-inner-rsbuild-plugin-ssg',
1161
1723
  async setup (api) {
1162
1724
  api.onBeforeBuild(()=>{
1163
1725
  let htmlTemplate = '';
1726
+ let hasError = false;
1164
1727
  const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
1165
1728
  api.processAssets({
1166
1729
  stage: 'report',
1167
- targets: [
1730
+ environments: [
1168
1731
  'web'
1169
1732
  ]
1170
1733
  }, ({ assets, compilation })=>{
1734
+ if (compilation.errors.length > 0) {
1735
+ hasError = true;
1736
+ return;
1737
+ }
1171
1738
  for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1172
1739
  htmlTemplate = assetSource.source().toString();
1173
1740
  compilation.deleteAsset(assetName);
@@ -1178,43 +1745,52 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1178
1745
  });
1179
1746
  }).catch(()=>{
1180
1747
  const message = 'SSG requires an `index.html` as entry, but this file is not emitted successfully in the web target.';
1181
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(message);
1748
+ logger.error(message);
1182
1749
  const error = new Error(message);
1183
1750
  throw error;
1184
1751
  });
1185
1752
  api.processAssets({
1186
1753
  stage: 'optimize-transfer',
1187
- targets: [
1188
- 'node'
1189
- ]
1190
- }, async ({ assets, compilation, environment, compiler })=>{
1191
- const distPath = environment.distPath;
1192
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.mkdir)(distPath, {
1193
- recursive: true
1194
- });
1195
- let mainCjsAbsolutePath = '';
1196
- for (const [assetName, assetSource] of Object.entries(assets))if (assetName.includes(NODE_SSR_BUNDLE_NAME)) {
1197
- mainCjsAbsolutePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(distPath, assetName);
1198
- await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.writeFile)(mainCjsAbsolutePath, assetSource.source().toString());
1199
- compilation.deleteAsset(assetName);
1200
- break;
1754
+ environments: [
1755
+ 'node'
1756
+ ]
1757
+ }, async ({ assets, compilation, environment, compiler })=>{
1758
+ if (compilation.errors.length > 0) {
1759
+ hasError = true;
1760
+ return;
1201
1761
  }
1762
+ if (hasError) return;
1202
1763
  const emitAsset = (assetName, content)=>{
1203
1764
  compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1204
1765
  };
1766
+ const distPath = environment.distPath;
1767
+ const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
1768
+ const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
1769
+ await mkdir(ssgFolderPath, {
1770
+ recursive: true
1771
+ });
1772
+ await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
1773
+ if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
1774
+ const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
1775
+ await writeFile(fileAbsolutePath, assetSource.source().toString());
1776
+ compilation.deleteAsset(assetName);
1777
+ }
1778
+ }));
1205
1779
  await indexHtmlEmittedInWeb;
1206
- await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1207
- if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isDebugMode)()) await (0, __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__.rm)(mainCjsAbsolutePath);
1780
+ await renderPages(routeService, config, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1781
+ if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
1782
+ recursive: true
1783
+ });
1208
1784
  });
1209
1785
  });
1210
1786
  }
1211
1787
  });
1212
- const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
1788
+ const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = enhanced_resolve;
1213
1789
  async function detectPackageMajorVersion(name) {
1214
1790
  const cwd = process.cwd();
1215
- const pkgPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', name);
1791
+ const pkgPath = external_node_path_["default"].join(cwd, 'node_modules', name);
1216
1792
  if (await pathExists(pkgPath)) {
1217
- const pkgJson = await readJson(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(pkgPath, 'package.json'));
1793
+ const pkgJson = await readJson(external_node_path_["default"].join(pkgPath, 'package.json'));
1218
1794
  const version = Number(pkgJson.version?.split('.')[0]);
1219
1795
  return version;
1220
1796
  }
@@ -1226,7 +1802,7 @@ async function detectReactVersion() {
1226
1802
  async function resolveReactRouterDomAlias() {
1227
1803
  const alias = {};
1228
1804
  const resolver = detectReactVersion_ResolverFactory.createResolver({
1229
- fileSystem: new detectReactVersion_CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
1805
+ fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
1230
1806
  mainFields: [
1231
1807
  'browser',
1232
1808
  'module',
@@ -1250,7 +1826,7 @@ async function resolveReactRouterDomAlias() {
1250
1826
  'react-router-dom': pkgPath
1251
1827
  };
1252
1828
  } catch (e) {
1253
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn('react-router-dom not found: \n', e);
1829
+ logger.warn('react-router-dom not found: \n', e);
1254
1830
  }
1255
1831
  return {};
1256
1832
  }
@@ -1261,12 +1837,12 @@ async function resolveReactAlias(reactVersion, isSSR) {
1261
1837
  'react/jsx-runtime',
1262
1838
  'react/jsx-dev-runtime',
1263
1839
  'react-dom',
1840
+ 'react-dom/client',
1264
1841
  'react-dom/server'
1265
1842
  ];
1266
- if (reactVersion >= 18) libPaths.push('react-dom/client');
1267
1843
  const alias = {};
1268
1844
  const resolver = detectReactVersion_ResolverFactory.createResolver({
1269
- fileSystem: new detectReactVersion_CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
1845
+ fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
1270
1846
  extensions: [
1271
1847
  '.js'
1272
1848
  ],
@@ -1289,67 +1865,55 @@ async function resolveReactAlias(reactVersion, isSSR) {
1289
1865
  });
1290
1866
  });
1291
1867
  } catch (e) {
1292
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn(`${lib} not found: \n`, e);
1868
+ if (e instanceof Error) {
1869
+ logger.warn(`${lib} not found: \n ${picocolors.gray(e.toString())}`);
1870
+ hintReactVersion();
1871
+ }
1293
1872
  }
1294
1873
  }));
1295
1874
  return alias;
1296
1875
  }
1297
1876
  const detectCustomIcon = async (customThemeDir)=>{
1298
- const assetsDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(customThemeDir, 'assets');
1877
+ const assetsDir = external_node_path_["default"].join(customThemeDir, 'assets');
1299
1878
  const alias = {};
1300
- if (!(0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(assetsDir)) return alias;
1301
- const files = await (0, __WEBPACK_EXTERNAL_MODULE_tinyglobby__.glob)('*.svg', {
1879
+ if (!(0, external_node_fs_.existsSync)(assetsDir)) return alias;
1880
+ const files = await glob('*.svg', {
1302
1881
  cwd: assetsDir
1303
1882
  });
1304
1883
  files.forEach((file)=>{
1305
- const name = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].basename(file, '.svg');
1306
- alias[`@theme-assets/${name}`] = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(assetsDir, file);
1884
+ const name = external_node_path_["default"].basename(file, '.svg');
1885
+ alias[`@theme-assets/${name}`] = external_node_path_["default"].join(assetsDir, file);
1307
1886
  });
1308
1887
  return alias;
1309
1888
  };
1310
- const presetIcons = {
1311
- discord: '<path fill="currentColor" d="M20.317 4.37a19.8 19.8 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.3 18.3 0 0 0-5.487 0a13 13 0 0 0-.617-1.25a.08.08 0 0 0-.079-.037A19.7 19.7 0 0 0 3.677 4.37a.1.1 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.08.08 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.08.08 0 0 0 .084-.028a14 14 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13 13 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10 10 0 0 0 .372-.292a.07.07 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.07.07 0 0 1 .078.01q.181.149.373.292a.077.077 0 0 1-.006.127a12.3 12.3 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.08.08 0 0 0 .084.028a19.8 19.8 0 0 0 6.002-3.03a.08.08 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.06.06 0 0 0-.031-.03M8.02 15.33c-1.182 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418m7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418"/>',
1312
- facebook: '<path fill="currentColor" d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978c.401 0 .955.042 1.468.103a9 9 0 0 1 1.141.195v3.325a9 9 0 0 0-.653-.036a27 27 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.7 1.7 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103l-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647"/>',
1313
- github: '<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12c0 5.303 3.438 9.8 8.205 11.385c.6.113.82-.258.82-.577c0-.285-.01-1.04-.015-2.04c-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729c1.205.084 1.838 1.236 1.838 1.236c1.07 1.835 2.809 1.305 3.495.998c.108-.776.417-1.305.76-1.605c-2.665-.3-5.466-1.332-5.466-5.93c0-1.31.465-2.38 1.235-3.22c-.135-.303-.54-1.523.105-3.176c0 0 1.005-.322 3.3 1.23c.96-.267 1.98-.399 3-.405c1.02.006 2.04.138 3 .405c2.28-1.552 3.285-1.23 3.285-1.23c.645 1.653.24 2.873.12 3.176c.765.84 1.23 1.91 1.23 3.22c0 4.61-2.805 5.625-5.475 5.92c.42.36.81 1.096.81 2.22c0 1.606-.015 2.896-.015 3.286c0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>',
1314
- gitlab: '<path fill="currentColor" d="m23.6 9.593l-.033-.086L20.3.98a.85.85 0 0 0-.336-.405a.875.875 0 0 0-1 .054a.9.9 0 0 0-.29.44L16.47 7.818H7.537L5.333 1.07a.86.86 0 0 0-.29-.441a.875.875 0 0 0-1-.054a.86.86 0 0 0-.336.405L.433 9.502l-.032.086a6.066 6.066 0 0 0 2.012 7.01l.01.009l.03.021l4.977 3.727l2.462 1.863l1.5 1.132a1.01 1.01 0 0 0 1.22 0l1.499-1.132l2.461-1.863l5.006-3.75l.013-.01a6.07 6.07 0 0 0 2.01-7.002"/>',
1315
- instagram: '<path fill="currentColor" d="M7.03.084c-1.277.06-2.149.264-2.91.563a5.9 5.9 0 0 0-2.124 1.388a5.9 5.9 0 0 0-1.38 2.127C.321 4.926.12 5.8.064 7.076s-.069 1.688-.063 4.947s.021 3.667.083 4.947c.061 1.277.264 2.149.563 2.911c.308.789.72 1.457 1.388 2.123a5.9 5.9 0 0 0 2.129 1.38c.763.295 1.636.496 2.913.552c1.278.056 1.689.069 4.947.063s3.668-.021 4.947-.082c1.28-.06 2.147-.265 2.91-.563a5.9 5.9 0 0 0 2.123-1.388a5.9 5.9 0 0 0 1.38-2.129c.295-.763.496-1.636.551-2.912c.056-1.28.07-1.69.063-4.948c-.006-3.258-.02-3.667-.081-4.947c-.06-1.28-.264-2.148-.564-2.911a5.9 5.9 0 0 0-1.387-2.123a5.9 5.9 0 0 0-2.128-1.38c-.764-.294-1.636-.496-2.914-.55C15.647.009 15.236-.006 11.977 0S8.31.021 7.03.084m.14 21.693c-1.17-.05-1.805-.245-2.228-.408a3.7 3.7 0 0 1-1.382-.895a3.7 3.7 0 0 1-.9-1.378c-.165-.423-.363-1.058-.417-2.228c-.06-1.264-.072-1.644-.08-4.848c-.006-3.204.006-3.583.061-4.848c.05-1.169.246-1.805.408-2.228c.216-.561.477-.96.895-1.382a3.7 3.7 0 0 1 1.379-.9c.423-.165 1.057-.361 2.227-.417c1.265-.06 1.644-.072 4.848-.08c3.203-.006 3.583.006 4.85.062c1.168.05 1.804.244 2.227.408c.56.216.96.475 1.382.895s.681.817.9 1.378c.165.422.362 1.056.417 2.227c.06 1.265.074 1.645.08 4.848c.005 3.203-.006 3.583-.061 4.848c-.051 1.17-.245 1.805-.408 2.23c-.216.56-.477.96-.896 1.38a3.7 3.7 0 0 1-1.378.9c-.422.165-1.058.362-2.226.418c-1.266.06-1.645.072-4.85.079s-3.582-.006-4.848-.06m9.783-16.192a1.44 1.44 0 1 0 1.437-1.442a1.44 1.44 0 0 0-1.437 1.442M5.839 12.012a6.161 6.161 0 1 0 12.323-.024a6.162 6.162 0 0 0-12.323.024M8 12.008A4 4 0 1 1 12.008 16A4 4 0 0 1 8 12.008"/>',
1316
- linkedin: '<path fill="currentColor" d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037c-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85c3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.06 2.06 0 0 1-2.063-2.065a2.064 2.064 0 1 1 2.063 2.065m1.782 13.019H3.555V9h3.564zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0z"/>',
1317
- slack: '<path fill="currentColor" d="M5.042 15.165a2.53 2.53 0 0 1-2.52 2.523A2.53 2.53 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52a2.527 2.527 0 0 1 2.521 2.52v6.313A2.53 2.53 0 0 1 8.834 24a2.53 2.53 0 0 1-2.521-2.522zM8.834 5.042a2.53 2.53 0 0 1-2.521-2.52A2.53 2.53 0 0 1 8.834 0a2.53 2.53 0 0 1 2.521 2.522v2.52zm0 1.271a2.53 2.53 0 0 1 2.521 2.521a2.53 2.53 0 0 1-2.521 2.521H2.522A2.53 2.53 0 0 1 0 8.834a2.53 2.53 0 0 1 2.522-2.521zm10.122 2.521a2.53 2.53 0 0 1 2.522-2.521A2.53 2.53 0 0 1 24 8.834a2.53 2.53 0 0 1-2.522 2.521h-2.522zm-1.268 0a2.53 2.53 0 0 1-2.523 2.521a2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.53 2.53 0 0 1 2.523 2.522zm-2.523 10.122a2.53 2.53 0 0 1 2.523 2.522A2.53 2.53 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522zm0-1.268a2.527 2.527 0 0 1-2.52-2.523a2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.53 2.53 0 0 1-2.522 2.523z"/>',
1318
- youtube: '<path fill="currentColor" d="M23.498 6.186a3.02 3.02 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.02 3.02 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.02 3.02 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.02 3.02 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814M9.545 15.568V8.432L15.818 12z"/>',
1319
- juejin: '<path fill="currentColor" d="m12 14.316l7.454-5.88l-2.022-1.625L12 11.1l-.004.003l-5.432-4.288l-2.02 1.624l7.452 5.88Zm0-7.247l2.89-2.298L12 2.453l-.004-.005l-2.884 2.318l2.884 2.3Zm0 11.266l-.005.002l-9.975-7.87L0 12.088l.194.156l11.803 9.308l7.463-5.885L24 12.085l-2.023-1.624Z"/>',
1320
- qq: '<path fill="currentColor" d="M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673c.54.065 2.103-2.472 2.103-2.472c0 1.469.756 3.387 2.394 4.771c-.612.188-1.363.479-1.845.835c-.434.32-.379.646-.301.778c.343.578 5.883.369 7.482.189c1.6.18 7.14.389 7.483-.189c.078-.132.132-.458-.301-.778c-.483-.356-1.233-.646-1.846-.836c1.637-1.384 2.393-3.302 2.393-4.771c0 0 1.563 2.537 2.103 2.472c.251-.03.581-1.39-.438-4.673"/>',
1321
- wechat: '<path fill="currentColor" d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213c0 .163.13.295.29.295a.33.33 0 0 0 .167-.054l1.903-1.114a.86.86 0 0 1 .717-.098a10.2 10.2 0 0 0 2.837.403c.276 0 .543-.027.811-.05c-.857-2.578.157-4.972 1.932-6.446c1.703-1.415 3.882-1.98 5.853-1.838c-.576-3.583-4.196-6.348-8.596-6.348M5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178a1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18m5.34 2.867c-1.797-.052-3.746.512-5.28 1.786c-1.72 1.428-2.687 3.72-1.78 6.22c.942 2.453 3.666 4.229 6.884 4.229c.826 0 1.622-.12 2.361-.336a.72.72 0 0 1 .598.082l1.584.926a.3.3 0 0 0 .14.047c.134 0 .24-.111.24-.247c0-.06-.023-.12-.038-.177l-.327-1.233a.6.6 0 0 1-.023-.156a.49.49 0 0 1 .201-.398C23.024 18.48 24 16.82 24 14.98c0-3.21-2.931-5.837-6.656-6.088V8.89c-.135-.01-.27-.027-.407-.03zm-2.53 3.274c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.97-.982zm4.844 0c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983a.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982"/>',
1322
- weibo: '<path fill="currentColor" d="M17.525 11.378c1.263.392 2.669 1.336 2.669 3.004c0 2.763-3.98 6.239-9.964 6.239c-4.565 0-9.23-2.213-9.23-5.852c0-1.902 1.204-4.102 3.277-6.177c2.773-2.77 6.004-4.033 7.219-2.816c.537.537.588 1.464.244 2.572c-.178.557.525.25.525.25c2.24-.938 4.196-.994 4.909.027c.38.543.343 1.306-.008 2.19c-.163.407.048.471.36.563zm-7.282 7.939c3.641-.362 6.401-2.592 6.167-4.983c-.237-2.391-3.382-4.038-7.023-3.677c-3.64.36-6.403 2.59-6.167 4.98c.237 2.394 3.382 4.039 7.023 3.68zM6.16 14.438c.754-1.527 2.712-2.39 4.446-1.94c1.793.463 2.707 2.154 1.976 3.8c-.744 1.682-2.882 2.578-4.695 1.993c-1.752-.566-2.493-2.294-1.727-3.853zm1.446 2.587c.568.257 1.325.013 1.676-.55c.346-.568.163-1.217-.407-1.459c-.563-.237-1.291.008-1.64.553c-.354.547-.189 1.202.371 1.456zm2.206-1.808c.219.092.501-.012.628-.231c.123-.22.044-.466-.178-.548c-.216-.084-.486.018-.613.232c-.123.214-.054.458.163.547zM19.873 9.5a.725.725 0 1 1-1.378-.451a1.38 1.38 0 0 0-.288-1.357a1.395 1.395 0 0 0-1.321-.425a.723.723 0 1 1-.303-1.416a2.836 2.836 0 0 1 3.29 3.649zm-3.916-6.575A5.831 5.831 0 0 1 21.5 4.72a5.836 5.836 0 0 1 1.22 5.704a.838.838 0 0 1-1.06.54a.844.844 0 0 1-.542-1.062a4.143 4.143 0 0 0-4.807-5.327a.845.845 0 0 1-.354-1.65z"/>',
1323
- zhihu: '<path fill="currentColor" d="M5.721 0C2.251 0 0 2.25 0 5.719V18.28C0 21.751 2.252 24 5.721 24h12.56C21.751 24 24 21.75 24 18.281V5.72C24 2.249 21.75 0 18.281 0zm1.964 4.078q-.408 1.096-.68 2.11h4.587c.545-.006.445 1.168.445 1.171H9.384a58 58 0 0 1-.112 3.797h2.712c.388.023.393 1.251.393 1.266H9.183a9.2 9.2 0 0 1-.408 2.102l.757-.604c.452.456 1.512 1.712 1.906 2.177c.473.681.063 2.081.063 2.081l-2.794-3.382c-.653 2.518-1.845 3.607-1.845 3.607c-.523.468-1.58.82-2.64.516c2.218-1.73 3.44-3.917 3.667-6.497H4.491c0-.015.197-1.243.806-1.266h2.71c.024-.32.086-3.254.086-3.797H6.598c-.136.406-.158.447-.268.753c-.594 1.095-1.603 1.122-1.907 1.155c.906-1.821 1.416-3.6 1.591-4.064c.425-1.124 1.671-1.125 1.671-1.125M13.078 6h6.377v11.33h-2.573l-2.184 1.373l-.401-1.373h-1.219zm1.313 1.219v8.86h.623l.263.937l1.455-.938h1.456v-8.86z"/>',
1324
- bilibili: '<path fill="currentColor" d="M17.813 4.653h.854q2.266.08 3.773 1.574Q23.946 7.72 24 9.987v7.36q-.054 2.266-1.56 3.773c-1.506 1.507-2.262 1.524-3.773 1.56H5.333q-2.266-.054-3.773-1.56C.053 19.614.036 18.858 0 17.347v-7.36q.054-2.267 1.56-3.76t3.773-1.574h.774l-1.174-1.12a1.23 1.23 0 0 1-.373-.906q0-.534.373-.907l.027-.027q.4-.373.92-.373t.92.373L9.653 4.44q.107.106.187.213h4.267a.8.8 0 0 1 .16-.213l2.853-2.747q.4-.373.92-.373c.347 0 .662.151.929.4s.391.551.391.907q0 .532-.373.906zM5.333 7.24q-1.12.027-1.88.773q-.76.748-.786 1.894v7.52q.026 1.146.786 1.893t1.88.773h13.334q1.12-.026 1.88-.773t.786-1.893v-7.52q-.026-1.147-.786-1.894t-1.88-.773zM8 11.107q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q0-.56.386-.947q.387-.386.947-.386m8 0q.56 0 .933.373q.375.374.4.96v1.173q-.025.586-.4.96q-.373.375-.933.374c-.56-.001-.684-.125-.933-.374q-.375-.373-.4-.96V12.44q.025-.586.4-.96q.373-.373.933-.373"/>',
1325
- lark: `<path d="M8.813 5.477c1.038.836 2.286 2.045 3.3 3.495.171.23.377.576.457.71l.034.056a8.803 8.803 0 0 0-.922 1.3l-.271-.494C9.655 7.53 6.3 5.477 6.137 5.377a.447.447 0 0 1-.006-.004l-.666-.393-.107-.086a.499.499 0 0 1 .306-.885L6.084 4h7.997c.159.006.318.037.47.092.174.064.317.174.458.308.134.143.272.296.403.448.622.675 1.324 1.688 1.324 1.688-.573.193-1.349.736-1.349.736a5.095 5.095 0 0 0-.348-.54 20.665 20.665 0 0 0-1.037-1.255H8.813Z" fill="currentColor"/>
1326
- <path d="M18.482 7.507a5.42 5.42 0 0 1 4.04.717c.248.168.788.635.242 1.233-1.7 1.67-2.194 3.225-2.63 4.599-.278.873-.541 1.697-1.066 2.424-1.813 2.508-4.114 4-6.837 4.434-.561.089-1.132.131-1.7.131-3.958 0-7.498-2.035-8.75-2.844h.003l-.161-.107c-.534-.378-.61-.723-.623-.989V7.055a.486.486 0 0 1 .827-.317l.482.589c5.082 6.201 9.126 8.063 11.626 8.53 2.246.424 3.631-.165 4.022-.37.333-.51.534-1.143.764-1.865l.006-.021c.406-1.276.898-2.821 2.322-4.477a3.93 3.93 0 0 0-2.28-.168c-1.761.394-3.403 1.96-4.89 4.643a8.27 8.27 0 0 0-.341.671c-.724-.107-1.334-.65-1.334-.65.128-.269.22-.455.345-.672 1.718-3.125 3.714-4.962 5.933-5.441ZM2.477 16.889c1.145.744 5.341 3.232 9.532 2.563 1.56-.247 2.963-.915 4.196-1.99-2.771.254-7.557-.753-13.728-7.666v7.093Z" fill="currentColor"/>`,
1327
- x: '<path fill="currentColor" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584l-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/>',
1328
- bluesky: '<path fill="currentColor" d="M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565C.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479c.815 2.736 3.713 3.66 6.383 3.364q.204-.03.415-.056q-.207.033-.415.056c-3.912.58-7.387 2.005-2.83 7.078c5.013 5.19 6.87-1.113 7.823-4.308c.953 3.195 2.05 9.271 7.733 4.308c4.267-4.308 1.172-6.498-2.74-7.078a9 9 0 0 1-.415-.056q.21.026.415.056c2.67.297 5.568-.628 6.383-3.364c.246-.828.624-5.79.624-6.478c0-.69-.139-1.861-.902-2.206c-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8"/>'
1329
- };
1330
- const formatIconName = (icon)=>icon.toLowerCase();
1331
- function getSocialIcons(socialLinks = []) {
1332
- const icons = {};
1333
- for (const link of socialLinks)if ('string' == typeof link.icon) {
1334
- const pathContent = presetIcons[formatIconName(link.icon)];
1335
- icons[link.icon] = `<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 24 24">${pathContent}</svg>`;
1336
- }
1337
- return icons;
1338
- }
1339
1889
  function isPluginIncluded(config, pluginName) {
1340
- return Boolean(config.builderPlugins?.some((plugin)=>plugin.name === pluginName) || config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
1890
+ return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
1891
+ }
1892
+ const initRsbuild_require = createRequire(import.meta.url);
1893
+ const initRsbuild_filename = (0, external_node_url_.fileURLToPath)(import.meta.url);
1894
+ const initRsbuild_dirname = external_node_path_["default"].dirname(initRsbuild_filename);
1895
+ async function getVirtualModulesFromPlugins(pluginDriver) {
1896
+ const runtimeModule = {};
1897
+ const modulesByPlugin = await pluginDriver.addRuntimeModules();
1898
+ Object.keys(modulesByPlugin).forEach((key)=>{
1899
+ if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
1900
+ runtimeModule[key] = ()=>modulesByPlugin[key];
1901
+ });
1902
+ return runtimeModule;
1341
1903
  }
1342
- async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver, runtimeTempDir) {
1904
+ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
1343
1905
  const cwd = process.cwd();
1344
- const CUSTOM_THEME_DIR = config?.themeDir ?? __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'theme');
1906
+ const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
1345
1907
  const outDir = config?.outDir ?? OUTPUT_DIR;
1346
- const DEFAULT_THEME = require.resolve('@rspress/theme-default');
1908
+ const DEFAULT_THEME = initRsbuild_require.resolve('@rspress/theme-default');
1347
1909
  const base = config?.base ?? '';
1348
- const assetPrefix = isProduction() ? (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1910
+ const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1349
1911
  const reactVersion = await detectReactVersion();
1350
1912
  const normalizeIcon = (icon)=>{
1351
1913
  if (!icon) return;
1352
- if (__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].isAbsolute(icon)) return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(userDocRoot, PUBLIC_DIR, icon);
1914
+ icon = icon.toString();
1915
+ if (icon.startsWith('file://')) icon = (0, external_node_url_.fileURLToPath)(icon);
1916
+ else if (external_node_path_["default"].isAbsolute(icon)) return external_node_path_["default"].join(userDocRoot, PUBLIC_DIR, icon);
1353
1917
  return icon;
1354
1918
  };
1355
1919
  await hintThemeBreakingChange(CUSTOM_THEME_DIR);
@@ -1362,46 +1926,52 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1362
1926
  const context = {
1363
1927
  userDocRoot,
1364
1928
  config,
1365
- runtimeTempDir,
1366
1929
  routeService,
1367
1930
  pluginDriver
1368
1931
  };
1369
1932
  return {
1370
1933
  plugins: [
1371
- ...isPluginIncluded(config, __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__.PLUGIN_REACT_NAME) ? [] : [
1372
- (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_plugin_react_7b149ee4__.pluginReact)()
1934
+ ...isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [
1935
+ pluginReact()
1373
1936
  ],
1374
- rsbuildPluginDocVM(context),
1937
+ rsbuildPluginDocVM({
1938
+ config,
1939
+ pluginDriver,
1940
+ routeService,
1941
+ userDocRoot
1942
+ }),
1375
1943
  pluginVirtualModule({
1944
+ tempDir: '.rspress/runtime',
1376
1945
  virtualModules: {
1946
+ ...socialLinksVMPlugin(context),
1377
1947
  ...i18nVMPlugin(context),
1378
1948
  ...globalUIComponentsVMPlugin(context),
1379
1949
  ...globalStylesVMPlugin(context),
1380
- ...searchHookVMPlugin(context)
1950
+ ...searchHookVMPlugin(context),
1951
+ ...routeListVMPlugin(context),
1952
+ ...await getVirtualModulesFromPlugins(pluginDriver),
1953
+ ...siteDataVMPlugin(context)
1381
1954
  }
1382
1955
  }),
1383
- ...enableSSG ? [
1384
- rsbuildPluginSSG({
1385
- routeService,
1386
- config,
1387
- pluginDriver
1388
- })
1389
- ] : []
1956
+ enableSSG ? rsbuildPluginSSG({
1957
+ routeService,
1958
+ config
1959
+ }) : rsbuildPluginCSR({
1960
+ routeService,
1961
+ config
1962
+ })
1390
1963
  ],
1391
1964
  server: {
1392
1965
  port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1393
- printUrls: ({ urls })=>urls.map((url)=>`${url}/${(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.removeLeadingSlash)(base)}`),
1394
1966
  publicDir: {
1395
- name: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(userDocRoot, PUBLIC_DIR)
1396
- }
1967
+ name: external_node_path_["default"].join(userDocRoot, PUBLIC_DIR)
1968
+ },
1969
+ ...base.length > 0 ? {
1970
+ base: (0, shared_.removeTrailingSlash)(base)
1971
+ } : {}
1397
1972
  },
1398
1973
  dev: {
1399
- progressBar: false,
1400
- setupMiddlewares: [
1401
- (middlewares)=>{
1402
- middlewares.unshift(serveSearchIndexMiddleware(config));
1403
- }
1404
- ],
1974
+ lazyCompilation: 'false' !== process.env.RSPRESS_LAZY_COMPILATION,
1405
1975
  cliShortcuts: {
1406
1976
  custom: (shortcuts)=>shortcuts.filter(({ key })=>'r' !== key)
1407
1977
  }
@@ -1427,29 +1997,46 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1427
1997
  resolve: {
1428
1998
  alias: {
1429
1999
  ...detectCustomIconAlias,
1430
- '@mdx-js/react': require.resolve('@mdx-js/react'),
2000
+ '@mdx-js/react': initRsbuild_require.resolve('@mdx-js/react'),
1431
2001
  '@theme': [
1432
2002
  CUSTOM_THEME_DIR,
1433
2003
  DEFAULT_THEME
1434
2004
  ],
1435
- '@theme-assets': __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(DEFAULT_THEME, '../assets'),
1436
- '@rspress/core': PACKAGE_ROOT,
1437
- 'react-lazy-with-preload': require.resolve('react-lazy-with-preload'),
1438
- 'react-syntax-highlighter': __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(require.resolve('react-syntax-highlighter/package.json'))
2005
+ '@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
2006
+ 'react-lazy-with-preload': initRsbuild_require.resolve('react-lazy-with-preload'),
2007
+ '@rspress/core/theme': external_node_path_["default"].join(initRsbuild_dirname, 'theme.js'),
2008
+ '@rspress/core/runtime': external_node_path_["default"].join(initRsbuild_dirname, 'runtime.js'),
2009
+ '@rspress/core/shiki-transformers': external_node_path_["default"].join(initRsbuild_dirname, 'shiki-transformers.js')
1439
2010
  }
1440
2011
  },
1441
2012
  source: {
1442
2013
  include: [
1443
2014
  PACKAGE_ROOT,
1444
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR)
2015
+ external_node_path_["default"].join(cwd, 'node_modules', shared_.RSPRESS_TEMP_DIR)
1445
2016
  ],
1446
2017
  define: {
1447
- 'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),
1448
- 'process.env.TEST': JSON.stringify(process.env.TEST),
1449
- 'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks))
2018
+ 'process.env.TEST': JSON.stringify(process.env.TEST)
1450
2019
  }
1451
2020
  },
1452
2021
  performance: {
2022
+ ...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
2023
+ buildCache: {
2024
+ buildDependencies: [
2025
+ initRsbuild_filename,
2026
+ pluginDriver.getConfigFilePath()
2027
+ ],
2028
+ cacheDigest: [
2029
+ routeService.generateRoutesCode(),
2030
+ JSON.stringify(config.themeConfig?.locales?.map((i)=>({
2031
+ nav: i.nav,
2032
+ sidebar: i.sidebar
2033
+ })) ?? {
2034
+ nav: config.themeConfig?.nav,
2035
+ sidebar: config.themeConfig?.sidebar
2036
+ })
2037
+ ]
2038
+ }
2039
+ } : {},
1453
2040
  chunkSplit: {
1454
2041
  override: {
1455
2042
  cacheGroups: {
@@ -1469,22 +2056,28 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1469
2056
  const isServer = 'node' === target;
1470
2057
  const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
1471
2058
  const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
1472
- const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
1473
- chain.module.rule('MDX').type("javascript/auto").test(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP).resolve.merge({
2059
+ chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
1474
2060
  conditionNames: jsModuleRule.resolve.conditionNames.values(),
1475
2061
  mainFields: jsModuleRule.resolve.mainFields.values()
1476
- }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
2062
+ }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(initRsbuild_require.resolve('./loader.js')).options({
1477
2063
  config,
1478
2064
  docDirectory: userDocRoot,
1479
- checkDeadLinks,
1480
2065
  routeService,
1481
2066
  pluginDriver
1482
2067
  }).end();
2068
+ chain.experiments({
2069
+ ...chain.get('experiments'),
2070
+ nativeWatcher: 'false' !== process.env.RSPRESS_NATIVE_WATCHER
2071
+ });
1483
2072
  if (chain.plugins.has(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH)) chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).tap((options)=>{
1484
2073
  options[0] ??= {};
2074
+ options[0].test = [
2075
+ /\.([cm]js|[jt]sx?|flow)$/i,
2076
+ shared_.MDX_OR_MD_REGEXP
2077
+ ];
1485
2078
  options[0].include = [
1486
2079
  /\.([cm]js|[jt]sx?|flow)$/i,
1487
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_OR_MD_REGEXP
2080
+ shared_.MDX_OR_MD_REGEXP
1488
2081
  ];
1489
2082
  return options;
1490
2083
  });
@@ -1492,13 +2085,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1492
2085
  chain.module.rule('css-virtual-module').test(/\.rspress[\\/]runtime[\\/]virtual-global-styles/).merge({
1493
2086
  sideEffects: true
1494
2087
  });
1495
- if (isServer) chain.output.filename(NODE_SSR_BUNDLE_NAME);
1496
- const enableIncremental = !isProduction() && !process.env.DISABLE_RSPACK_INCREMENTAL;
1497
- if (enableIncremental) chain.merge({
1498
- experiments: {
1499
- incremental: true
1500
- }
1501
- });
2088
+ if (isServer) {
2089
+ chain.output.filename(`${NODE_SSG_BUNDLE_FOLDER}/${NODE_SSG_BUNDLE_NAME}`);
2090
+ chain.output.chunkFilename(`${NODE_SSG_BUNDLE_FOLDER}/[name].cjs`);
2091
+ chain.target('async-node');
2092
+ }
1502
2093
  }
1503
2094
  },
1504
2095
  environments: {
@@ -1506,14 +2097,17 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1506
2097
  resolve: {
1507
2098
  alias: {
1508
2099
  ...reactCSRAlias,
1509
- ...reactRouterDomAlias,
1510
- __VIRTUAL_ROUTES__: 'virtual-routes'
2100
+ ...reactRouterDomAlias
1511
2101
  }
1512
2102
  },
1513
2103
  source: {
1514
2104
  entry: {
1515
2105
  index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1516
2106
  },
2107
+ preEntry: [
2108
+ external_node_path_["default"].join(DEFAULT_THEME, '../styles/index.js'),
2109
+ 'virtual-global-styles'
2110
+ ],
1517
2111
  define: {
1518
2112
  'process.env.__SSR__': JSON.stringify(false)
1519
2113
  }
@@ -1530,15 +2124,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1530
2124
  resolve: {
1531
2125
  alias: {
1532
2126
  ...reactSSRAlias,
1533
- ...reactRouterDomAlias,
1534
- __VIRTUAL_ROUTES__: 'virtual-routes-ssr'
1535
- }
1536
- },
1537
- tools: {
1538
- rspack: {
1539
- output: {
1540
- asyncChunks: false
1541
- }
2127
+ ...reactRouterDomAlias
1542
2128
  }
1543
2129
  },
1544
2130
  source: {
@@ -1566,56 +2152,172 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1566
2152
  }
1567
2153
  async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
1568
2154
  const cwd = process.cwd();
1569
- const userDocRoot = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(rootDir || config?.root || cwd);
1570
- const builderPlugins = config?.builderPlugins ?? [];
1571
- const runtimeTempDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR, 'runtime');
1572
- const runtimeAbsTempDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'node_modules', runtimeTempDir);
1573
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(runtimeAbsTempDir, {
2155
+ const userDocRoot = external_node_path_["default"].resolve(rootDir || config?.root || cwd);
2156
+ const runtimeTempDir = external_node_path_["default"].join(shared_.RSPRESS_TEMP_DIR, 'runtime');
2157
+ const runtimeAbsTempDir = external_node_path_["default"].join(cwd, 'node_modules', runtimeTempDir);
2158
+ await node_fs_promises.mkdir(runtimeAbsTempDir, {
1574
2159
  recursive: true
1575
2160
  });
1576
- const routeService = await initRouteService({
1577
- config,
2161
+ const routeService = await RouteService.create({
2162
+ config: config,
1578
2163
  runtimeTempDir: runtimeAbsTempDir,
1579
2164
  scanDir: userDocRoot,
1580
2165
  pluginDriver
1581
2166
  });
2167
+ const mergedConfig = await modifyConfigWithAutoNavSide(config);
2168
+ hintBuilderPluginsBreakingChange(mergedConfig);
1582
2169
  const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
1583
- const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver, runtimeTempDir);
2170
+ const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, mergedConfig, enableSSG, routeService, pluginDriver);
1584
2171
  const rsbuild = await createRsbuild({
1585
- rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], config?.builderConfig || {}, extraRsbuildConfig || {})
2172
+ callerName: 'rspress',
2173
+ rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], mergedConfig.builderConfig || {}, extraRsbuildConfig || {})
1586
2174
  });
1587
- rsbuild.addPlugins(builderPlugins);
1588
2175
  return rsbuild;
1589
2176
  }
2177
+ class PluginDriver {
2178
+ #config;
2179
+ #configFilePath;
2180
+ #plugins;
2181
+ #isProd;
2182
+ constructor(config, configFilePath, isProd){
2183
+ this.#config = config;
2184
+ this.#configFilePath = configFilePath;
2185
+ this.#isProd = isProd;
2186
+ this.#plugins = [];
2187
+ }
2188
+ getConfigFilePath() {
2189
+ return this.#configFilePath;
2190
+ }
2191
+ async init() {
2192
+ this.clearPlugins();
2193
+ const config = this.#config;
2194
+ const themeConfig = config?.themeConfig || {};
2195
+ const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
2196
+ const mediumZoomConfig = config?.mediumZoom ?? true;
2197
+ if (enableLastUpdated) {
2198
+ const { pluginLastUpdated } = await Promise.all([
2199
+ __webpack_require__.e("101"),
2200
+ __webpack_require__.e("395")
2201
+ ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
2202
+ this.addPlugin(pluginLastUpdated());
2203
+ }
2204
+ if (mediumZoomConfig) {
2205
+ const { pluginMediumZoom } = await __webpack_require__.e("335").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
2206
+ this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
2207
+ }
2208
+ (config.plugins || []).forEach((plugin)=>{
2209
+ this.addPlugin(plugin);
2210
+ });
2211
+ }
2212
+ addPlugin(plugin) {
2213
+ const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
2214
+ if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
2215
+ this.#plugins.push(plugin);
2216
+ }
2217
+ getPlugins() {
2218
+ return this.#plugins;
2219
+ }
2220
+ clearPlugins() {
2221
+ this.#plugins = [];
2222
+ }
2223
+ removePlugin(pluginName) {
2224
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2225
+ if (-1 !== index) this.#plugins.splice(index, 1);
2226
+ }
2227
+ async modifyConfig() {
2228
+ let config = this.#config;
2229
+ for(let i = 0; i < this.#plugins.length; i++){
2230
+ const plugin = this.#plugins[i];
2231
+ if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
2232
+ addPlugin: this.addPlugin.bind(this),
2233
+ removePlugin: (pluginName)=>{
2234
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2235
+ this.removePlugin(pluginName);
2236
+ if (index <= i && index > 0) i--;
2237
+ }
2238
+ }, this.#isProd);
2239
+ }
2240
+ this.#config = config;
2241
+ return this.#config;
2242
+ }
2243
+ async beforeBuild() {
2244
+ return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
2245
+ }
2246
+ async afterBuild() {
2247
+ return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
2248
+ }
2249
+ async modifySearchIndexData(pages) {
2250
+ return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
2251
+ }
2252
+ async extendPageData(pageData) {
2253
+ return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
2254
+ }
2255
+ async addPages() {
2256
+ const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
2257
+ return result.flat();
2258
+ }
2259
+ async routeGenerated(routes) {
2260
+ return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
2261
+ }
2262
+ async routeServiceGenerated(routeService) {
2263
+ return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
2264
+ }
2265
+ async addRuntimeModules() {
2266
+ const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
2267
+ return result.reduce((prev, current)=>({
2268
+ ...prev,
2269
+ ...current
2270
+ }), {});
2271
+ }
2272
+ globalUIComponents() {
2273
+ const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
2274
+ return result.flat();
2275
+ }
2276
+ globalStyles() {
2277
+ return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
2278
+ }
2279
+ _runParallelAsyncHook(hookName, ...args) {
2280
+ return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
2281
+ }
2282
+ _runSerialAsyncHook(hookName, ...args) {
2283
+ return this.#plugins.reduce(async (prev, plugin)=>{
2284
+ if ('function' == typeof plugin[hookName]) {
2285
+ await prev;
2286
+ return plugin[hookName](...args);
2287
+ }
2288
+ return prev;
2289
+ }, Promise.resolve());
2290
+ }
2291
+ }
1590
2292
  function checkLanguageParity_normalizePath(filePath) {
1591
- return filePath.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/');
2293
+ return filePath.split(external_node_path_["default"].sep).join('/');
1592
2294
  }
1593
2295
  async function getAllMarkdownFilesFrom(dirPath) {
1594
- const files = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readdir(dirPath, {
2296
+ const files = await node_fs_promises.readdir(dirPath, {
1595
2297
  withFileTypes: true
1596
2298
  });
1597
2299
  const allFiles = [];
1598
2300
  for (const file of files){
1599
- const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirPath, file.name);
2301
+ const fullPath = external_node_path_["default"].join(dirPath, file.name);
1600
2302
  if (file.isDirectory()) {
1601
2303
  const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
1602
2304
  allFiles.push(...nestedFiles);
1603
2305
  } else if ([
1604
2306
  '.md',
1605
2307
  '.mdx'
1606
- ].includes(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(file.name))) allFiles.push(fullPath);
2308
+ ].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
1607
2309
  }
1608
2310
  return allFiles;
1609
2311
  }
1610
2312
  async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
1611
- const langDirPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(contentPath, lang);
1612
- const langModuleDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(langDirPath, includedDir);
2313
+ const langDirPath = external_node_path_["default"].join(contentPath, lang);
2314
+ const langModuleDir = external_node_path_["default"].join(langDirPath, includedDir);
1613
2315
  try {
1614
- const moduleDirStats = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].stat(langModuleDir);
2316
+ const moduleDirStats = await node_fs_promises.stat(langModuleDir);
1615
2317
  if (!moduleDirStats.isDirectory()) return fileLangMap;
1616
2318
  const files = await getAllMarkdownFilesFrom(langModuleDir);
1617
2319
  for (const file of files){
1618
- const relativePath = checkLanguageParity_normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(langDirPath, file));
2320
+ const relativePath = checkLanguageParity_normalizePath(external_node_path_["default"].relative(langDirPath, file));
1619
2321
  if (excludedDirs.some((excludedDir)=>{
1620
2322
  const isFilePath = /\.(md|mdx)$/.test(excludedDir);
1621
2323
  return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
@@ -1625,21 +2327,21 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
1625
2327
  fileLangMap[baseName].add(lang);
1626
2328
  }
1627
2329
  } catch (e) {
1628
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(e);
2330
+ logger.error(e);
1629
2331
  throw new Error(`Failed to access directory: ${checkLanguageParity_normalizePath(langModuleDir)}`);
1630
2332
  }
1631
2333
  return fileLangMap;
1632
2334
  }
1633
2335
  async function checkLanguageParity(config) {
1634
2336
  if (!config?.languageParity || false === config.languageParity.enabled) return;
1635
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Checking language parity...');
1636
- const contentPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(config.root);
2337
+ logger.info('Checking language parity...');
2338
+ const contentPath = external_node_path_["default"].resolve(config.root);
1637
2339
  const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
1638
2340
  ''
1639
2341
  ];
1640
2342
  const excludedDirs = config.languageParity.exclude ?? [];
1641
2343
  const supportedLanguages = (config.locales ?? config.themeConfig?.locales)?.map((locale)=>locale.lang) || [];
1642
- if (!supportedLanguages.length) return void __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error('No supported languages found in the configuration.');
2344
+ if (!supportedLanguages.length) return void logger.error('No supported languages found in the configuration.');
1643
2345
  const missingLanguagesFile = [];
1644
2346
  try {
1645
2347
  for (const includedDir of includedDirs){
@@ -1649,27 +2351,53 @@ async function checkLanguageParity(config) {
1649
2351
  for (const [baseName, langs] of Object.entries(curFileLangMap)){
1650
2352
  const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
1651
2353
  missingLangs.forEach((lang)=>{
1652
- const missingPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(lang, baseName);
2354
+ const missingPath = external_node_path_["default"].join(lang, baseName);
1653
2355
  missingLanguagesFile.push(missingPath);
1654
2356
  });
1655
2357
  }
1656
2358
  }
1657
2359
  if (missingLanguagesFile.length > 0) throw new Error(`Check language parity failed! Missing content:\n${missingLanguagesFile.map((file)=>` - ${checkLanguageParity_normalizePath(file)}`).join('\n')}`);
1658
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.success('Language parity checked successfully.');
2360
+ logger.success('Language parity checked successfully.');
1659
2361
  } catch (err) {
1660
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error('Error during language parity check: \n', err);
2362
+ logger.error('Error during language parity check: \n', err);
1661
2363
  throw err;
1662
2364
  }
1663
2365
  }
2366
+ async function bundle(docDirectory, config, pluginDriver, enableSSG) {
2367
+ try {
2368
+ const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
2369
+ await pluginDriver.beforeBuild();
2370
+ await rsbuild.build();
2371
+ } finally{
2372
+ await checkLanguageParity(config);
2373
+ }
2374
+ await pluginDriver.afterBuild();
2375
+ }
2376
+ function emptyDir(path) {
2377
+ return node_fs_promises.rm(path, {
2378
+ force: true,
2379
+ recursive: true
2380
+ });
2381
+ }
2382
+ async function build(options) {
2383
+ const { docDirectory, config, configFilePath } = options;
2384
+ const pluginDriver = new PluginDriver(config, configFilePath, true);
2385
+ await pluginDriver.init();
2386
+ const modifiedConfig = await pluginDriver.modifyConfig();
2387
+ const ssgConfig = Boolean(modifiedConfig.ssg ?? true);
2388
+ await emptyDir(constants_TEMP_DIR);
2389
+ await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
2390
+ if (!ssgConfig) hintSSGFalse();
2391
+ }
1664
2392
  async function dev(options) {
1665
- const { docDirectory, config, extraBuilderConfig } = options;
2393
+ const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
1666
2394
  const isProd = false;
1667
- const pluginDriver = new PluginDriver(config, isProd);
2395
+ const pluginDriver = new PluginDriver(config, configFilePath, isProd);
1668
2396
  await pluginDriver.init();
1669
2397
  const modifiedConfig = await pluginDriver.modifyConfig();
1670
2398
  try {
1671
- await pluginDriver.beforeBuild();
1672
2399
  const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
2400
+ await pluginDriver.beforeBuild();
1673
2401
  rsbuild.onDevCompileDone(async ()=>{
1674
2402
  await pluginDriver.afterBuild();
1675
2403
  });
@@ -1678,174 +2406,170 @@ async function dev(options) {
1678
2406
  });
1679
2407
  return server;
1680
2408
  } finally{
1681
- await writeSearchIndex(modifiedConfig);
1682
2409
  await checkLanguageParity(modifiedConfig);
1683
2410
  }
1684
2411
  }
1685
- async function bundle(docDirectory, config, pluginDriver, enableSSG) {
1686
- try {
1687
- const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
1688
- await rsbuild.build();
1689
- } finally{
1690
- await writeSearchIndex(config);
1691
- await checkLanguageParity(config);
2412
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
2413
+ function parseFileFromMeta(meta) {
2414
+ if (!meta) return '';
2415
+ const kvList = meta.split(' ').filter(Boolean);
2416
+ for (const item of kvList){
2417
+ const [k, v = ''] = item.split('=');
2418
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
1692
2419
  }
2420
+ return '';
1693
2421
  }
1694
- function emptyDir(path) {
1695
- return __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].rm(path, {
1696
- force: true,
1697
- recursive: true
2422
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
2423
+ const promiseList = [];
2424
+ visit(tree, 'code', (node)=>{
2425
+ const { meta, value, lang } = node;
2426
+ const file = parseFileFromMeta(meta ?? '');
2427
+ if (!file) return;
2428
+ const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
2429
+ if (file.startsWith('./') || file.startsWith('../')) {
2430
+ const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2431
+ if ('' !== value.trim()) {
2432
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
2433
+
2434
+ \`\`\`tsx file="./filename"
2435
+ content
2436
+ \`\`\`
2437
+
2438
+ this usage is not allowed, please use below:
2439
+
2440
+ \`\`\`tsx file="./filename"
2441
+ \`\`\`
2442
+ `);
2443
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
2444
+ }
2445
+ const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2446
+ addDependency?.(resolvedFilePath);
2447
+ node.value = fileContent;
2448
+ }).catch((e)=>{
2449
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
2450
+ logger.error(message);
2451
+ e.message = `${message}\n${e.message}`;
2452
+ throw e;
2453
+ });
2454
+ promiseList.push(promise);
2455
+ return;
2456
+ }
2457
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
2458
+ Please use below:
2459
+
2460
+ \`\`\`tsx file="./filename"
2461
+ \`\`\`
2462
+ `);
2463
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
2464
+ });
2465
+ await Promise.all(promiseList);
2466
+ };
2467
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, filePath) {
2468
+ const errorInfos = [];
2469
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
2470
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
2471
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
2472
+ let possibleBreakingChange = false;
2473
+ [
2474
+ ...internalLinks.entries()
2475
+ ].forEach(([nodeUrl, link])=>{
2476
+ if (excludesUrl?.has(nodeUrl)) return;
2477
+ if (excludesFn?.(nodeUrl)) return;
2478
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
2479
+ errorInfos.push([
2480
+ nodeUrl,
2481
+ link
2482
+ ]);
1698
2483
  });
2484
+ if (errorInfos.length > 0) {
2485
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
2486
+ logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
2487
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
2488
+ if ((0, shared_.isProduction)()) throw new Error('Dead link found');
2489
+ }
1699
2490
  }
1700
- async function build(options) {
1701
- const { docDirectory, config } = options;
1702
- const pluginDriver = new PluginDriver(config, true);
1703
- await pluginDriver.init();
1704
- const modifiedConfig = await pluginDriver.modifyConfig();
1705
- await pluginDriver.beforeBuild();
1706
- const ssgConfig = modifiedConfig.ssg ?? true;
1707
- await emptyDir(constants_TEMP_DIR);
1708
- await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
1709
- if (!ssgConfig) hintSSGFalse();
1710
- await pluginDriver.afterBuild();
2491
+ function looseMarkdownLink(url, routeService, filePath) {
2492
+ if (!routeService.isInDocsDir(filePath)) return url;
2493
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
2494
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
2495
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
2496
+ if ('' === versionPart) {
2497
+ if ('' === langPart) return (0, shared_.addLeadingSlash)(`${[
2498
+ versionPartCurrFile,
2499
+ langPartCurrFile
2500
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2501
+ return (0, shared_.addLeadingSlash)(`${[
2502
+ versionPartCurrFile,
2503
+ langPart
2504
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2505
+ }
2506
+ return url;
2507
+ }
2508
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, deadLinks, __base) {
2509
+ if (!nodeUrl) return '';
2510
+ if (nodeUrl.startsWith('#')) return nodeUrl;
2511
+ let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
2512
+ if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
2513
+ if (!routeService) return nodeUrl;
2514
+ if (url.startsWith('/')) {
2515
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
2516
+ const { routePath } = routeService.normalizeRoutePath(url);
2517
+ url = routePath;
2518
+ } else {
2519
+ const anotherFileAbsolutePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filePath), url);
2520
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
2521
+ }
2522
+ if ('boolean' == typeof cleanUrls) url = (0, shared_.normalizeHref)(url, cleanUrls);
2523
+ else {
2524
+ url = (0, shared_.normalizeHref)(url, false);
2525
+ url = url.replace(/\.html$/, cleanUrls);
2526
+ }
2527
+ if (!routeService.isExistRoute(url)) {
2528
+ deadLinks.set(nodeUrl, url);
2529
+ return nodeUrl;
2530
+ }
2531
+ if (hash) url += `#${hash}`;
2532
+ if (__base) url = (0, shared_.withBase)(url, __base);
2533
+ return url;
1711
2534
  }
2535
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, __base })=>(tree, file)=>{
2536
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
2537
+ const deadLinks = new Map();
2538
+ visit(tree, 'link', (node)=>{
2539
+ const { url: nodeUrl } = node;
2540
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
2541
+ node.url = link;
2542
+ });
2543
+ visit(tree, 'definition', (node)=>{
2544
+ const { url: nodeUrl } = node;
2545
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
2546
+ node.url = link;
2547
+ });
2548
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, deadLinks, file.path);
2549
+ };
1712
2550
  async function serve(options) {
1713
- const { config, port: userPort, host: userHost } = options;
2551
+ const { config, port: userPort, host: userHost, configFilePath } = options;
1714
2552
  const envPort = process.env.PORT;
1715
2553
  const envHost = process.env.HOST;
1716
2554
  const { builderConfig } = config;
1717
2555
  const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
1718
2556
  const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
1719
- config.builderConfig = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.mergeRsbuildConfig)(builderConfig, {
2557
+ config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
1720
2558
  server: {
1721
2559
  port,
1722
2560
  host
1723
2561
  }
1724
2562
  });
1725
- const pluginDriver = new PluginDriver(config, true);
2563
+ const pluginDriver = new PluginDriver(config, configFilePath, true);
1726
2564
  await pluginDriver.init();
1727
2565
  const modifiedConfig = await pluginDriver.modifyConfig();
1728
2566
  const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
1729
2567
  return rsbuild.preview();
1730
2568
  }
1731
- const getASTNodeImport = (name, from)=>({
1732
- type: 'mdxjsEsm',
1733
- value: `import ${name} from ${JSON.stringify(from)}`,
1734
- data: {
1735
- estree: {
1736
- type: 'Program',
1737
- sourceType: 'module',
1738
- body: [
1739
- {
1740
- type: 'ImportDeclaration',
1741
- specifiers: [
1742
- {
1743
- type: 'ImportDefaultSpecifier',
1744
- local: {
1745
- type: 'Identifier',
1746
- name
1747
- }
1748
- }
1749
- ],
1750
- source: {
1751
- type: 'Literal',
1752
- value: from,
1753
- raw: `${JSON.stringify(from)}`
1754
- }
1755
- }
1756
- ]
1757
- }
1758
- }
1759
- });
1760
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
1761
- if (!nodeUrl) return '';
1762
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
1763
- let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(nodeUrl);
1764
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
1765
- const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
1766
- if ((routeService?.extensions ?? __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
1767
- if (url.startsWith('.')) url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(relativePath)), url);
1768
- else if (routeService) {
1769
- const [pathVersion, pathLang] = routeService.getRoutePathParts((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(relativePath));
1770
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
1771
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(urlPath);
1772
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
1773
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
1774
- }
1775
- if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
1776
- else {
1777
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, false);
1778
- url = url.replace(/\.html$/, cleanUrls);
1779
- }
1780
- if (hash) url += `#${hash}`;
1781
- return url;
1782
- }
1783
- const normalizeImageUrl = (imageUrl)=>{
1784
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
1785
- return imageUrl;
1786
- };
1787
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
1788
- const images = [];
1789
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
1790
- const { url: nodeUrl } = node;
1791
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
1792
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
1793
- });
1794
- const getMdxSrcAttribute = (tempVar)=>({
1795
- type: 'mdxJsxAttribute',
1796
- name: 'src',
1797
- value: {
1798
- type: 'mdxJsxAttributeValueExpression',
1799
- value: tempVar,
1800
- data: {
1801
- estree: {
1802
- type: 'Program',
1803
- sourceType: 'module',
1804
- body: [
1805
- {
1806
- type: 'ExpressionStatement',
1807
- expression: {
1808
- type: 'Identifier',
1809
- name: tempVar
1810
- }
1811
- }
1812
- ]
1813
- }
1814
- }
1815
- }
1816
- });
1817
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
1818
- const { alt, url } = node;
1819
- if (!url) return;
1820
- const imagePath = normalizeImageUrl(url);
1821
- if (!imagePath) return;
1822
- const tempVariableName = `image${images.length}`;
1823
- Object.assign(node, {
1824
- type: 'mdxJsxFlowElement',
1825
- name: 'img',
1826
- children: [],
1827
- attributes: [
1828
- alt && {
1829
- type: 'mdxJsxAttribute',
1830
- name: 'alt',
1831
- value: alt
1832
- },
1833
- getMdxSrcAttribute(tempVariableName)
1834
- ].filter(Boolean)
1835
- });
1836
- images.push(getASTNodeImport(tempVariableName, imagePath));
1837
- });
1838
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>{
1839
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
1840
- const srcAttr = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src', true);
1841
- if ('string' != typeof srcAttr?.value) return;
1842
- const imagePath = normalizeImageUrl(srcAttr.value);
1843
- if (!imagePath) return;
1844
- const tempVariableName = `image${images.length}`;
1845
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
1846
- images.push(getASTNodeImport(tempVariableName, imagePath));
1847
- });
1848
- tree.children.unshift(...images);
1849
- };
1850
- var __webpack_exports__mergeDocConfig = __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.mergeDocConfig;
1851
- export { build, dev, remarkPluginNormalizeLink, serve, __webpack_exports__mergeDocConfig as mergeDocConfig };
2569
+ var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
2570
+ var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
2571
+ var __webpack_exports__normalizeHref = shared_.normalizeHref;
2572
+ var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
2573
+ var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
2574
+ var __webpack_exports__withBase = shared_.withBase;
2575
+ export { build, defineConfig, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };