@rspress/core 2.0.0-beta.2 → 2.0.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/208.js +39 -0
- package/dist/309.js +27 -0
- package/dist/94.js +1787 -0
- package/dist/index.d.ts +105 -19
- package/dist/index.js +1217 -561
- package/dist/loader.d.ts +38 -34
- package/dist/loader.js +30 -525
- package/dist/processor.d.ts +95 -0
- package/dist/processor.js +740 -0
- package/dist/runtime/App.d.ts +1 -4
- package/dist/runtime/App.js +17 -20
- package/dist/runtime/ClientApp.js +24 -13
- package/dist/runtime/csrClientEntry.js +5 -13
- package/dist/runtime/initPageData.d.ts +0 -1
- package/dist/runtime/initPageData.js +18 -18
- package/dist/runtime/ssrClientEntry.js +14 -14
- package/dist/runtime/ssrServerEntry.d.ts +3 -2
- package/dist/runtime/ssrServerEntry.js +41 -17
- package/dist/runtime.d.ts +8 -0
- package/dist/runtime.js +3 -0
- package/dist/shiki-transformers.d.ts +38 -0
- package/dist/shiki-transformers.js +77 -0
- package/dist/shiki-transformers.js.LICENSE.txt +5 -0
- package/dist/theme.d.ts +4 -0
- package/dist/theme.js +1 -0
- package/package.json +40 -33
- package/static/MediumZoom.css +5 -0
- package/static/MediumZoom.tsx +29 -0
- package/dist/runtime/tsconfig.js +0 -4
- package/runtime.ts +0 -1
- package/theme.ts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,66 +1,184 @@
|
|
|
1
1
|
import __rslib_shim_module__ from 'module';
|
|
2
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";
|
|
4
3
|
import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
|
|
5
|
-
import * as
|
|
4
|
+
import * as __WEBPACK_EXTERNAL_MODULE_child_process__ from "child_process";
|
|
5
|
+
import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
|
|
6
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__ from "node:buffer";
|
|
7
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
|
|
8
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
|
|
9
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
|
|
6
10
|
import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
|
|
7
|
-
import * as
|
|
11
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__ from "node:process";
|
|
12
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__ from "node:timers/promises";
|
|
8
13
|
import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
|
|
9
|
-
import * as
|
|
10
|
-
import * as
|
|
11
|
-
import * as
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import
|
|
15
|
-
import
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
20
|
-
import
|
|
21
|
-
import
|
|
22
|
-
import
|
|
23
|
-
import
|
|
24
|
-
import
|
|
25
|
-
import
|
|
26
|
-
import
|
|
27
|
-
|
|
14
|
+
import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
|
|
15
|
+
import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
|
|
16
|
+
import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
|
|
17
|
+
import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
|
|
18
|
+
import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
|
|
19
|
+
import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
|
|
20
|
+
import { logger } from "@rspress/shared/logger";
|
|
21
|
+
import picocolors from "picocolors";
|
|
22
|
+
import { glob } from "tinyglobby";
|
|
23
|
+
import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
|
|
24
|
+
import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
|
|
25
|
+
import { groupBy } from "lodash-es";
|
|
26
|
+
import { compile } from "@rspress/mdx-rs";
|
|
27
|
+
import { htmlToText } from "html-to-text";
|
|
28
|
+
import { createProcessor } from "@mdx-js/mdx";
|
|
29
|
+
import enhanced_resolve from "enhanced-resolve";
|
|
30
|
+
import { createHash } from "node:crypto";
|
|
31
|
+
import { createHead, transformHtmlTemplate } from "@unhead/react/server";
|
|
32
|
+
import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
|
|
33
|
+
import { visit } from "unist-util-visit";
|
|
34
|
+
import { matchPath } from "@rspress/runtime/server";
|
|
35
|
+
var __webpack_modules__ = {
|
|
36
|
+
"@rspress/shared": function(module) {
|
|
37
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
|
|
38
|
+
},
|
|
39
|
+
child_process: function(module) {
|
|
40
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_child_process__;
|
|
41
|
+
},
|
|
42
|
+
fs: function(module) {
|
|
43
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_fs__;
|
|
44
|
+
},
|
|
45
|
+
"node:buffer": function(module) {
|
|
46
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__;
|
|
47
|
+
},
|
|
48
|
+
"node:child_process": function(module) {
|
|
49
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__;
|
|
50
|
+
},
|
|
51
|
+
"node:fs": function(module) {
|
|
52
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
|
|
53
|
+
},
|
|
54
|
+
"node:os": function(module) {
|
|
55
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__;
|
|
56
|
+
},
|
|
57
|
+
"node:path": function(module) {
|
|
58
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
|
|
59
|
+
},
|
|
60
|
+
"node:process": function(module) {
|
|
61
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__;
|
|
62
|
+
},
|
|
63
|
+
"node:timers/promises": function(module) {
|
|
64
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__;
|
|
65
|
+
},
|
|
66
|
+
"node:url": function(module) {
|
|
67
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
|
|
68
|
+
},
|
|
69
|
+
"node:util": function(module) {
|
|
70
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__;
|
|
71
|
+
},
|
|
72
|
+
path: function(module) {
|
|
73
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_path__;
|
|
74
|
+
},
|
|
75
|
+
stream: function(module) {
|
|
76
|
+
module.exports = __WEBPACK_EXTERNAL_MODULE_stream__;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
var __webpack_module_cache__ = {};
|
|
80
|
+
function __webpack_require__(moduleId) {
|
|
81
|
+
var cachedModule = __webpack_module_cache__[moduleId];
|
|
82
|
+
if (void 0 !== cachedModule) return cachedModule.exports;
|
|
83
|
+
var module = __webpack_module_cache__[moduleId] = {
|
|
84
|
+
exports: {}
|
|
85
|
+
};
|
|
86
|
+
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
87
|
+
return module.exports;
|
|
88
|
+
}
|
|
89
|
+
__webpack_require__.m = __webpack_modules__;
|
|
90
|
+
(()=>{
|
|
91
|
+
__webpack_require__.d = (exports, definition)=>{
|
|
92
|
+
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
|
|
93
|
+
enumerable: true,
|
|
94
|
+
get: definition[key]
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
})();
|
|
98
|
+
(()=>{
|
|
99
|
+
__webpack_require__.f = {};
|
|
100
|
+
__webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
|
|
101
|
+
__webpack_require__.f[key](chunkId, promises);
|
|
102
|
+
return promises;
|
|
103
|
+
}, []));
|
|
104
|
+
})();
|
|
105
|
+
(()=>{
|
|
106
|
+
__webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
|
|
107
|
+
})();
|
|
108
|
+
(()=>{
|
|
109
|
+
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
110
|
+
})();
|
|
111
|
+
(()=>{
|
|
112
|
+
var installedChunks = {
|
|
113
|
+
980: 0
|
|
114
|
+
};
|
|
115
|
+
var installChunk = (data)=>{
|
|
116
|
+
var __webpack_ids__ = data.__webpack_ids__;
|
|
117
|
+
var __webpack_modules__ = data.__webpack_modules__;
|
|
118
|
+
var __webpack_runtime__ = data.__webpack_runtime__;
|
|
119
|
+
var moduleId, chunkId, i = 0;
|
|
120
|
+
for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
|
|
121
|
+
if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
|
|
122
|
+
for(; i < __webpack_ids__.length; i++){
|
|
123
|
+
chunkId = __webpack_ids__[i];
|
|
124
|
+
if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
|
|
125
|
+
installedChunks[__webpack_ids__[i]] = 0;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
__webpack_require__.f.j = function(chunkId, promises) {
|
|
129
|
+
var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
|
|
130
|
+
if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
|
|
131
|
+
else {
|
|
132
|
+
var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
|
|
133
|
+
if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
|
|
134
|
+
throw e;
|
|
135
|
+
});
|
|
136
|
+
var promise = Promise.race([
|
|
137
|
+
promise,
|
|
138
|
+
new Promise((resolve)=>{
|
|
139
|
+
installedChunkData = installedChunks[chunkId] = [
|
|
140
|
+
resolve
|
|
141
|
+
];
|
|
142
|
+
})
|
|
143
|
+
]);
|
|
144
|
+
promises.push(installedChunkData[1] = promise);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
})();
|
|
28
148
|
class PluginDriver {
|
|
29
149
|
#config;
|
|
150
|
+
#configFilePath;
|
|
30
151
|
#plugins;
|
|
31
152
|
#isProd;
|
|
32
|
-
constructor(config, isProd){
|
|
153
|
+
constructor(config, configFilePath, isProd){
|
|
33
154
|
this.#config = config;
|
|
155
|
+
this.#configFilePath = configFilePath;
|
|
34
156
|
this.#isProd = isProd;
|
|
35
157
|
this.#plugins = [];
|
|
36
158
|
}
|
|
159
|
+
getConfigFilePath() {
|
|
160
|
+
return this.#configFilePath;
|
|
161
|
+
}
|
|
37
162
|
async init() {
|
|
38
163
|
this.clearPlugins();
|
|
39
164
|
const config = this.#config;
|
|
40
165
|
const themeConfig = config?.themeConfig || {};
|
|
41
166
|
const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
|
|
42
167
|
const mediumZoomConfig = config?.mediumZoom ?? true;
|
|
43
|
-
const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
|
|
44
168
|
if (enableLastUpdated) {
|
|
45
|
-
const { pluginLastUpdated } = await
|
|
169
|
+
const { pluginLastUpdated } = await Promise.all([
|
|
170
|
+
__webpack_require__.e("94"),
|
|
171
|
+
__webpack_require__.e("208")
|
|
172
|
+
]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
|
|
46
173
|
this.addPlugin(pluginLastUpdated());
|
|
47
174
|
}
|
|
48
175
|
if (mediumZoomConfig) {
|
|
49
|
-
const { pluginMediumZoom } = await
|
|
176
|
+
const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
|
|
50
177
|
this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
|
|
51
178
|
}
|
|
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
179
|
(config.plugins || []).forEach((plugin)=>{
|
|
58
180
|
this.addPlugin(plugin);
|
|
59
181
|
});
|
|
60
|
-
if (!haveNavSidebarConfig) {
|
|
61
|
-
const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
|
|
62
|
-
this.addPlugin(pluginAutoNavSidebar());
|
|
63
|
-
}
|
|
64
182
|
}
|
|
65
183
|
addPlugin(plugin) {
|
|
66
184
|
const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
|
|
@@ -146,25 +264,38 @@ class PluginDriver {
|
|
|
146
264
|
}, Promise.resolve());
|
|
147
265
|
}
|
|
148
266
|
}
|
|
267
|
+
var external_node_path_ = __webpack_require__("node:path");
|
|
268
|
+
var external_node_url_ = __webpack_require__("node:url");
|
|
269
|
+
var shared_ = __webpack_require__("@rspress/shared");
|
|
149
270
|
const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
|
|
150
271
|
const pluginVirtualModule = (pluginOptions = {})=>({
|
|
151
272
|
name: PLUGIN_VIRTUAL_MODULE_NAME,
|
|
152
273
|
async setup (api) {
|
|
153
|
-
const
|
|
154
|
-
const
|
|
274
|
+
const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
|
|
275
|
+
const TEMP_DIR = (0, external_node_path_.join)(api.context.rootPath, 'node_modules', virtualFolderName);
|
|
155
276
|
const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
|
|
156
|
-
let absolutePath = (0,
|
|
157
|
-
if (!(0,
|
|
277
|
+
let absolutePath = (0, external_node_path_.join)(TEMP_DIR, i);
|
|
278
|
+
if (!(0, external_node_path_.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
|
|
158
279
|
return [
|
|
159
280
|
i,
|
|
160
281
|
absolutePath
|
|
161
282
|
];
|
|
162
283
|
});
|
|
284
|
+
api.modifyRsbuildConfig((config)=>{
|
|
285
|
+
if (!config.source) config.source = {};
|
|
286
|
+
config.source.include = [
|
|
287
|
+
...config.source.include || [],
|
|
288
|
+
TEMP_DIR
|
|
289
|
+
];
|
|
290
|
+
});
|
|
163
291
|
api.onBeforeCreateCompiler(async ()=>{
|
|
164
|
-
await (
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
292
|
+
await Promise.all(virtualFileAbsolutePaths.map(async ([_, absolutePath])=>{
|
|
293
|
+
const dir = (0, external_node_path_.dirname)(absolutePath);
|
|
294
|
+
await mkdir(dir, {
|
|
295
|
+
recursive: true
|
|
296
|
+
});
|
|
297
|
+
return writeFile(absolutePath, '', 'utf-8');
|
|
298
|
+
}));
|
|
168
299
|
});
|
|
169
300
|
api.modifyBundlerChain((chain)=>{
|
|
170
301
|
chain.resolve.alias.merge(Object.fromEntries(virtualFileAbsolutePaths));
|
|
@@ -177,43 +308,16 @@ const pluginVirtualModule = (pluginOptions = {})=>({
|
|
|
177
308
|
}
|
|
178
309
|
}
|
|
179
310
|
});
|
|
180
|
-
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.2"}');
|
|
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
311
|
async function pathExists(path) {
|
|
208
312
|
try {
|
|
209
|
-
await
|
|
313
|
+
await node_fs_promises.access(path);
|
|
210
314
|
return true;
|
|
211
315
|
} catch {
|
|
212
316
|
return false;
|
|
213
317
|
}
|
|
214
318
|
}
|
|
215
319
|
async function readJson(path) {
|
|
216
|
-
const raw = await
|
|
320
|
+
const raw = await node_fs_promises.readFile(path, 'utf8');
|
|
217
321
|
return JSON.parse(raw);
|
|
218
322
|
}
|
|
219
323
|
const THEME_DEFAULT_EXPORT_PATTERN = /export\s+default\s+\{/;
|
|
@@ -226,53 +330,115 @@ async function hintThemeBreakingChange(customThemeDir) {
|
|
|
226
330
|
];
|
|
227
331
|
let useDefaultExportFilePath = null;
|
|
228
332
|
for (const file of fileList){
|
|
229
|
-
const filePath = (0,
|
|
333
|
+
const filePath = (0, external_node_path_.join)(customThemeDir, file);
|
|
230
334
|
if (await pathExists(filePath)) {
|
|
231
|
-
const content = await
|
|
335
|
+
const content = await readFile(filePath, {
|
|
232
336
|
encoding: 'utf-8'
|
|
233
337
|
});
|
|
234
338
|
if (THEME_DEFAULT_EXPORT_PATTERN.test(content)) useDefaultExportFilePath = filePath;
|
|
235
339
|
break;
|
|
236
340
|
}
|
|
237
341
|
}
|
|
238
|
-
if (useDefaultExportFilePath)
|
|
342
|
+
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(`
|
|
239
343
|
- import Theme from '@rspress/theme-default';
|
|
240
344
|
- export default {
|
|
241
345
|
- ...Theme,
|
|
242
346
|
- Layout,
|
|
243
347
|
- };
|
|
244
|
-
- export * from 'rspress/theme';`) +
|
|
348
|
+
- export * from 'rspress/theme';`) + picocolors.greenBright(`
|
|
245
349
|
+ import { Layout } from '@rspress/theme-default';
|
|
246
350
|
|
|
247
351
|
+ export { Layout };
|
|
248
352
|
+ export * from 'rspress/theme';
|
|
249
353
|
`));
|
|
250
354
|
}
|
|
355
|
+
function hintBuilderPluginsBreakingChange(config) {
|
|
356
|
+
if ('builderPlugins' in config && Array.isArray(config.builderPlugins) && config.builderPlugins.length > 0) {
|
|
357
|
+
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`, `
|
|
358
|
+
export default defineConfig({
|
|
359
|
+
${picocolors.redBright(` builderPlugins: [
|
|
360
|
+
pluginFoo()
|
|
361
|
+
],`)}
|
|
362
|
+
${picocolors.greenBright(` builderConfig: {
|
|
363
|
+
plugins: [
|
|
364
|
+
pluginFoo()
|
|
365
|
+
],
|
|
366
|
+
},`)}
|
|
367
|
+
});`);
|
|
368
|
+
process.exit(1);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
251
371
|
function hintSSGFailed() {
|
|
252
|
-
|
|
372
|
+
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
373
|
1. Fix code to make it SSR-compatible.
|
|
254
374
|
2. Set \`ssg: false\`, but the SSG feature will be lost.`);
|
|
255
375
|
}
|
|
256
376
|
function hintSSGFalse() {
|
|
257
|
-
|
|
377
|
+
logger.info('`ssg: false` detected, SSG will be disabled.');
|
|
258
378
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
return p.replace(/\\/g, '/');
|
|
379
|
+
function hintReactVersion() {
|
|
380
|
+
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
381
|
}
|
|
263
|
-
function
|
|
264
|
-
|
|
382
|
+
function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
|
|
383
|
+
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))) {
|
|
384
|
+
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.');
|
|
385
|
+
logger.error(error);
|
|
386
|
+
const dir = (0, external_node_path_.relative)(docsDir, metaJsonDir);
|
|
387
|
+
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'))}".`);
|
|
388
|
+
process.exit(1);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
let isLogged = false;
|
|
392
|
+
function hintRelativeMarkdownLink() {
|
|
393
|
+
if (isLogged) return;
|
|
394
|
+
isLogged = true;
|
|
395
|
+
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
396
|
}
|
|
266
397
|
function getPageKey(route) {
|
|
267
|
-
const cleanRoute = (0,
|
|
398
|
+
const cleanRoute = (0, shared_.removeLeadingSlash)(route);
|
|
268
399
|
return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
|
|
269
400
|
}
|
|
270
|
-
|
|
271
|
-
|
|
401
|
+
var external_node_os_ = __webpack_require__("node:os");
|
|
402
|
+
const isWindows = 'win32' === external_node_os_["default"].platform();
|
|
403
|
+
function slash(p) {
|
|
404
|
+
return p.replace(/\\/g, '/');
|
|
405
|
+
}
|
|
406
|
+
function normalizePath(id) {
|
|
407
|
+
return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
|
|
408
|
+
}
|
|
409
|
+
var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.21"}');
|
|
410
|
+
const RSPRESS_VERSION = package_namespaceObject.i8;
|
|
411
|
+
const isProduction = ()=>'production' === process.env.NODE_ENV;
|
|
412
|
+
const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
|
|
413
|
+
const inlineThemeScript = `{
|
|
414
|
+
const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
|
|
415
|
+
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
416
|
+
const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
|
|
417
|
+
document.documentElement.classList.toggle('dark', isDark)
|
|
418
|
+
document.documentElement.classList.toggle('rp-dark', isDark)
|
|
419
|
+
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
|
420
|
+
}`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
|
|
421
|
+
const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
|
|
422
|
+
const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
|
|
423
|
+
const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
|
|
424
|
+
const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
|
|
425
|
+
const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
|
|
426
|
+
const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
|
|
427
|
+
const OUTPUT_DIR = 'doc_build';
|
|
428
|
+
const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
|
|
429
|
+
const HEAD_MARKER = '<!--<?- HEAD ?>-->';
|
|
430
|
+
const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
|
|
431
|
+
const DEFAULT_TITLE = 'Rspress';
|
|
432
|
+
const PUBLIC_DIR = 'public';
|
|
433
|
+
const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
|
|
434
|
+
const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
|
|
435
|
+
const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
|
|
436
|
+
const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
|
|
437
|
+
const hasTrailSlash = relativePath.endsWith('/');
|
|
272
438
|
let versionPart = '';
|
|
273
439
|
let langPart = '';
|
|
274
440
|
let purePathPart = '';
|
|
275
|
-
const parts =
|
|
441
|
+
const parts = relativePath.split('/').filter(Boolean);
|
|
276
442
|
if (version) {
|
|
277
443
|
const versionToMatch = parts[0];
|
|
278
444
|
if (versions.includes(versionToMatch)) {
|
|
@@ -291,19 +457,26 @@ const getRoutePathParts = (routePath, lang, version, langs, versions)=>{
|
|
|
291
457
|
return [
|
|
292
458
|
versionPart,
|
|
293
459
|
langPart,
|
|
294
|
-
hasTrailSlash ? (0,
|
|
460
|
+
hasTrailSlash ? (0, shared_.addTrailingSlash)(purePathPart) : purePathPart
|
|
295
461
|
];
|
|
296
462
|
};
|
|
297
|
-
const normalizeRoutePath = (
|
|
298
|
-
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
463
|
+
const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
|
|
299
464
|
const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
|
|
300
465
|
const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
466
|
+
let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
|
|
467
|
+
const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
|
|
468
|
+
routePath = purePathPart.replace(/\/index$/, '/');
|
|
469
|
+
if ('index' === routePath) routePath = '';
|
|
470
|
+
const normalizedRoutePath = (0, shared_.addLeadingSlash)([
|
|
471
|
+
...[
|
|
472
|
+
versionPart,
|
|
473
|
+
langPart
|
|
474
|
+
].filter(Boolean),
|
|
475
|
+
routePath
|
|
476
|
+
].join('/'));
|
|
305
477
|
return {
|
|
306
|
-
|
|
478
|
+
pureRoutePath: `/${routePath}`,
|
|
479
|
+
routePath: normalizedRoutePath,
|
|
307
480
|
lang: langPart || lang,
|
|
308
481
|
version: versionPart || version
|
|
309
482
|
};
|
|
@@ -318,18 +491,28 @@ class RouteService {
|
|
|
318
491
|
#versions = [];
|
|
319
492
|
#include = [];
|
|
320
493
|
#exclude = [];
|
|
321
|
-
#base = '';
|
|
322
494
|
#tempDir = '';
|
|
323
495
|
#pluginDriver;
|
|
496
|
+
static __instance__ = null;
|
|
497
|
+
static getInstance() {
|
|
498
|
+
return RouteService.__instance__;
|
|
499
|
+
}
|
|
500
|
+
static async create(options) {
|
|
501
|
+
const { scanDir, config, runtimeTempDir, pluginDriver } = options;
|
|
502
|
+
const routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
|
|
503
|
+
RouteService.__instance__ = routeService;
|
|
504
|
+
await routeService.#init();
|
|
505
|
+
await pluginDriver.routeServiceGenerated(routeService);
|
|
506
|
+
return routeService;
|
|
507
|
+
}
|
|
324
508
|
constructor(scanDir, userConfig, tempDir, pluginDriver){
|
|
325
509
|
const routeOptions = userConfig?.route || {};
|
|
326
510
|
this.#scanDir = scanDir;
|
|
327
|
-
this.#extensions = routeOptions.extensions ||
|
|
511
|
+
this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
|
|
328
512
|
this.#include = routeOptions.include || [];
|
|
329
513
|
this.#exclude = routeOptions.exclude || [];
|
|
330
514
|
this.#defaultLang = userConfig?.lang || '';
|
|
331
515
|
this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
|
|
332
|
-
this.#base = userConfig?.base || '';
|
|
333
516
|
this.#tempDir = tempDir;
|
|
334
517
|
this.#pluginDriver = pluginDriver;
|
|
335
518
|
if (userConfig.multiVersion) {
|
|
@@ -340,9 +523,9 @@ class RouteService {
|
|
|
340
523
|
get extensions() {
|
|
341
524
|
return this.#extensions;
|
|
342
525
|
}
|
|
343
|
-
async init() {
|
|
526
|
+
async #init() {
|
|
344
527
|
const extensions = this.#extensions.map((i)=>i.slice(1));
|
|
345
|
-
const files = (await
|
|
528
|
+
const files = (await glob([
|
|
346
529
|
`**/*.{${extensions.join(',')}}`,
|
|
347
530
|
...this.#include
|
|
348
531
|
], {
|
|
@@ -358,140 +541,467 @@ class RouteService {
|
|
|
358
541
|
]
|
|
359
542
|
})).sort();
|
|
360
543
|
files.forEach((filePath)=>{
|
|
361
|
-
const
|
|
362
|
-
|
|
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);
|
|
544
|
+
const routePage = RoutePage.create(filePath, this.#scanDir);
|
|
545
|
+
this.addRoute(routePage);
|
|
373
546
|
});
|
|
374
547
|
const externalPages = await this.#pluginDriver.addPages();
|
|
375
548
|
await Promise.all(externalPages.map(async (route, index)=>{
|
|
376
549
|
const { routePath, content, filepath } = route;
|
|
377
550
|
if (filepath) {
|
|
378
|
-
const
|
|
379
|
-
this.addRoute(
|
|
551
|
+
const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
|
|
552
|
+
this.addRoute(routePage);
|
|
380
553
|
return;
|
|
381
554
|
}
|
|
382
555
|
if (content) {
|
|
383
556
|
const filepath = await this.#writeTempFile(index, content);
|
|
384
|
-
const
|
|
385
|
-
this.addRoute(
|
|
557
|
+
const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
|
|
558
|
+
this.addRoute(routePage);
|
|
386
559
|
}
|
|
387
560
|
}));
|
|
388
561
|
await this.#pluginDriver.routeGenerated(this.getRoutes());
|
|
389
562
|
}
|
|
390
|
-
addRoute(
|
|
391
|
-
const { routePath
|
|
392
|
-
if (this.routeData.has(routePath)) {
|
|
393
|
-
|
|
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);
|
|
563
|
+
async addRoute(routePage) {
|
|
564
|
+
const { routeMeta: { routePath } } = routePage;
|
|
565
|
+
if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
|
|
566
|
+
this.routeData.set(routePath, routePage);
|
|
402
567
|
}
|
|
403
568
|
getRoutes() {
|
|
569
|
+
return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
|
|
570
|
+
}
|
|
571
|
+
getRoutePages() {
|
|
404
572
|
return Array.from(this.routeData.values());
|
|
405
573
|
}
|
|
406
574
|
isExistRoute(routePath) {
|
|
407
|
-
|
|
408
|
-
return Boolean(this.routeData.get(normalizedRoute));
|
|
409
|
-
}
|
|
410
|
-
isEmpty() {
|
|
411
|
-
return 0 === this.routeData.size;
|
|
575
|
+
return this.routeData.has(routePath);
|
|
412
576
|
}
|
|
413
|
-
generateRoutesCode(
|
|
414
|
-
return this.generateRoutesCodeByRouteMeta(this.getRoutes()
|
|
577
|
+
generateRoutesCode() {
|
|
578
|
+
return this.generateRoutesCodeByRouteMeta(this.getRoutes());
|
|
415
579
|
}
|
|
416
|
-
generateRoutesCodeByRouteMeta(routeMeta
|
|
580
|
+
generateRoutesCodeByRouteMeta(routeMeta) {
|
|
417
581
|
return `
|
|
418
582
|
import React from 'react';
|
|
419
583
|
import { lazyWithPreload } from "react-lazy-with-preload";
|
|
420
|
-
${routeMeta.map((route, index)
|
|
584
|
+
${routeMeta.map((route, index)=>`const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`).join('\n')}
|
|
421
585
|
export const routes = [
|
|
422
586
|
${routeMeta.map((route, index)=>{
|
|
423
|
-
const preload =
|
|
587
|
+
const preload = `async () => {
|
|
424
588
|
await Route${index}.preload();
|
|
425
589
|
return import("${route.absolutePath}");
|
|
426
590
|
}`;
|
|
427
|
-
const component =
|
|
591
|
+
const component = `Route${index}`;
|
|
428
592
|
return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
|
|
429
593
|
}).join(',\n')}
|
|
430
594
|
];
|
|
431
595
|
`;
|
|
432
596
|
}
|
|
433
|
-
getRoutePathParts(
|
|
434
|
-
return getRoutePathParts(
|
|
597
|
+
getRoutePathParts(relativePath) {
|
|
598
|
+
return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
|
|
435
599
|
}
|
|
436
|
-
normalizeRoutePath(
|
|
437
|
-
return normalizeRoutePath(
|
|
600
|
+
normalizeRoutePath(relativePath) {
|
|
601
|
+
return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
|
|
602
|
+
}
|
|
603
|
+
absolutePathToRoutePath(absolutePath) {
|
|
604
|
+
return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
|
|
605
|
+
}
|
|
606
|
+
absolutePathToRelativePath(absolutePath) {
|
|
607
|
+
return absolutePathToRelativePath(absolutePath, this.#scanDir);
|
|
438
608
|
}
|
|
439
609
|
async #writeTempFile(index, content) {
|
|
440
|
-
const tempFilePath =
|
|
441
|
-
await
|
|
610
|
+
const tempFilePath = external_node_path_["default"].join(this.#tempDir, `temp-${index}.mdx`);
|
|
611
|
+
await node_fs_promises.writeFile(tempFilePath, content);
|
|
442
612
|
return tempFilePath;
|
|
443
613
|
}
|
|
444
|
-
|
|
445
|
-
|
|
614
|
+
getRoutePageByRoutePath(routePath) {
|
|
615
|
+
return this.routeData.get(routePath);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
class RoutePage {
|
|
619
|
+
routeMeta;
|
|
620
|
+
#docDir;
|
|
621
|
+
static create(absolutePath, docsDir) {
|
|
622
|
+
const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
|
|
623
|
+
return new RoutePage(routeMeta, docsDir);
|
|
624
|
+
}
|
|
625
|
+
static createFromExternal(routePath, filepath, docDir) {
|
|
626
|
+
const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
|
|
627
|
+
return new RoutePage(routeMeta, external_node_path_["default"].dirname(filepath));
|
|
628
|
+
}
|
|
629
|
+
constructor(routeMeta, docDir){
|
|
630
|
+
this.routeMeta = routeMeta;
|
|
631
|
+
this.#docDir = docDir;
|
|
632
|
+
}
|
|
633
|
+
static generateRouteMeta(routePath, filepath, docDir) {
|
|
634
|
+
const routeService = RouteService.getInstance();
|
|
635
|
+
const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
|
|
446
636
|
return {
|
|
447
637
|
routePath: normalizedPath,
|
|
448
638
|
absolutePath: normalizePath(filepath),
|
|
449
|
-
relativePath:
|
|
639
|
+
relativePath: absolutePathToRelativePath(filepath, docDir),
|
|
450
640
|
pageName: getPageKey(routePath),
|
|
451
641
|
lang,
|
|
452
642
|
version
|
|
453
643
|
};
|
|
454
644
|
}
|
|
455
645
|
}
|
|
456
|
-
|
|
457
|
-
|
|
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;
|
|
646
|
+
function absolutePathToRelativePath(absolutePath, docsDir) {
|
|
647
|
+
return slash(external_node_path_["default"].relative(docsDir, absolutePath));
|
|
463
648
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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]: ''
|
|
649
|
+
function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
|
|
650
|
+
const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
|
|
651
|
+
const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
|
|
652
|
+
return {
|
|
653
|
+
pageName: getPageKey(relativePath),
|
|
654
|
+
absolutePath,
|
|
655
|
+
lang,
|
|
656
|
+
version,
|
|
657
|
+
routePath,
|
|
658
|
+
relativePath
|
|
481
659
|
};
|
|
660
|
+
}
|
|
661
|
+
function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
|
|
662
|
+
return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
|
|
663
|
+
}
|
|
664
|
+
function absolutePathToRoutePrefix(absolutePath, docsDir) {
|
|
665
|
+
const relativePath = slash(external_node_path_["default"].relative(docsDir, absolutePath.replace(external_node_path_["default"].extname(absolutePath), '')));
|
|
666
|
+
const routeService = RouteService.getInstance();
|
|
667
|
+
const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
|
|
668
|
+
return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
|
|
669
|
+
}
|
|
670
|
+
function addRoutePrefix(workDir, docsDir, link) {
|
|
671
|
+
const routePrefix = absolutePathToRoutePrefix(workDir, docsDir);
|
|
672
|
+
return `${routePrefix.replace(/\/$/, '')}/${link.replace(/^\//, '')}`;
|
|
673
|
+
}
|
|
674
|
+
async function utils_pathExists(path) {
|
|
675
|
+
try {
|
|
676
|
+
await node_fs_promises.access(path);
|
|
677
|
+
return true;
|
|
678
|
+
} catch {
|
|
679
|
+
return false;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
async function utils_readJson(path) {
|
|
683
|
+
const raw = await node_fs_promises.readFile(path, 'utf8');
|
|
684
|
+
return JSON.parse(raw);
|
|
685
|
+
}
|
|
686
|
+
async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
|
|
687
|
+
const content = await node_fs_promises.readFile(absolutePath, 'utf-8');
|
|
688
|
+
const fileNameWithoutExt = external_node_path_["default"].basename(absolutePath, external_node_path_["default"].extname(absolutePath));
|
|
689
|
+
const h1RegExp = /^#\s+(.*)$/m;
|
|
690
|
+
const match = content.match(h1RegExp);
|
|
691
|
+
const { frontmatter } = loadFrontMatter(content, absolutePath, rootDir);
|
|
482
692
|
return {
|
|
483
|
-
[
|
|
484
|
-
|
|
693
|
+
title: extractTextAndId(frontmatter.title || match?.[1] || fileNameWithoutExt)[0],
|
|
694
|
+
overviewHeaders: frontmatter.overviewHeaders,
|
|
695
|
+
context: frontmatter.context
|
|
485
696
|
};
|
|
486
697
|
}
|
|
487
|
-
function
|
|
488
|
-
return (0,
|
|
698
|
+
function getHmrFileKey(realPath, docsDir) {
|
|
699
|
+
return realPath ? (0, shared_.slash)((0, external_node_path_.relative)(docsDir, realPath).replace((0, external_node_path_.extname)(realPath), '')) : '';
|
|
700
|
+
}
|
|
701
|
+
async function fsDirToMetaItems(workDir, extensions) {
|
|
702
|
+
let subItems;
|
|
703
|
+
try {
|
|
704
|
+
subItems = await readdir(workDir);
|
|
705
|
+
} catch (e) {
|
|
706
|
+
logger.error(`Failed to read directory: ${workDir}, maybe it does not exist. Please check it in "_meta.json".`);
|
|
707
|
+
throw e;
|
|
708
|
+
}
|
|
709
|
+
subItems = subItems.filter((item)=>{
|
|
710
|
+
const hasExtension = extensions.some((ext)=>item.endsWith(ext));
|
|
711
|
+
const hasSameBaseName = subItems.some((elem)=>{
|
|
712
|
+
const baseName = elem.replace(/\.[^/.]+$/, '');
|
|
713
|
+
return baseName === item.replace(/\.[^/.]+$/, '') && elem !== item;
|
|
714
|
+
});
|
|
715
|
+
return !(hasExtension && hasSameBaseName);
|
|
716
|
+
});
|
|
717
|
+
const sideMeta = (await Promise.all(subItems.map(async (item)=>{
|
|
718
|
+
if ('_meta.json' === item) return null;
|
|
719
|
+
const stat = await promises_stat((0, external_node_path_.join)(workDir, item));
|
|
720
|
+
if (stat.isDirectory()) return {
|
|
721
|
+
type: 'dir',
|
|
722
|
+
name: item
|
|
723
|
+
};
|
|
724
|
+
return extensions.some((ext)=>item.endsWith(ext)) ? item : null;
|
|
725
|
+
}))).filter(Boolean);
|
|
726
|
+
return sideMeta;
|
|
489
727
|
}
|
|
728
|
+
async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isFirstDir = false) {
|
|
729
|
+
if ('string' == typeof metaItem) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
|
|
730
|
+
const { type } = metaItem;
|
|
731
|
+
if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
|
|
732
|
+
if ('dir' === type) {
|
|
733
|
+
const { name, label, collapsible, collapsed, tag: metaJsonTag, context: metaJsonContext, overviewHeaders: metaJsonOverviewHeaders } = metaItem;
|
|
734
|
+
const dirAbsolutePath = (0, external_node_path_.join)(workDir, name);
|
|
735
|
+
const dirMetaJsonPath = (0, external_node_path_.join)(dirAbsolutePath, '_meta.json');
|
|
736
|
+
const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
|
|
737
|
+
let dirMetaJson = [];
|
|
738
|
+
dirMetaJson = isMetaJsonExist ? await utils_readJson(dirMetaJsonPath) : await fsDirToMetaItems(dirAbsolutePath, extensions);
|
|
739
|
+
async function getItems(withoutIndex = false) {
|
|
740
|
+
const items = await Promise.all((withoutIndex ? dirMetaJson.filter((i)=>{
|
|
741
|
+
let name;
|
|
742
|
+
if ('object' == typeof i && 'type' in i && 'file' === i.type) name = i.name;
|
|
743
|
+
else {
|
|
744
|
+
if ('string' != typeof i) return true;
|
|
745
|
+
name = i;
|
|
746
|
+
}
|
|
747
|
+
return 'index.md' !== name && 'index.mdx' !== i && 'index' !== i;
|
|
748
|
+
}) : dirMetaJson).map((item)=>metaItemToSidebarItem(item, dirAbsolutePath, docsDir, extensions)));
|
|
749
|
+
return items;
|
|
750
|
+
}
|
|
751
|
+
try {
|
|
752
|
+
const sameNameFile = await metaFileItemToSidebarItem(name, workDir, docsDir, extensions);
|
|
753
|
+
const { link, text, _fileKey, context, overviewHeaders, tag } = sameNameFile;
|
|
754
|
+
return {
|
|
755
|
+
text: label || text || name,
|
|
756
|
+
collapsible,
|
|
757
|
+
collapsed,
|
|
758
|
+
items: await getItems(),
|
|
759
|
+
link,
|
|
760
|
+
tag: metaJsonTag || tag,
|
|
761
|
+
overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
|
|
762
|
+
context: metaJsonContext || context,
|
|
763
|
+
_fileKey
|
|
764
|
+
};
|
|
765
|
+
} catch (e) {
|
|
766
|
+
logger.debug(e);
|
|
767
|
+
const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
|
|
768
|
+
if ('string' == typeof i) return 'index' === i.replace((0, external_node_path_.extname)(i), '');
|
|
769
|
+
return false;
|
|
770
|
+
});
|
|
771
|
+
const isIndexFileExists = await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.mdx')) || await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.md'));
|
|
772
|
+
if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
|
|
773
|
+
text: label || name,
|
|
774
|
+
collapsible,
|
|
775
|
+
collapsed,
|
|
776
|
+
items: await getItems(),
|
|
777
|
+
link: void 0,
|
|
778
|
+
tag: metaJsonTag,
|
|
779
|
+
overviewHeaders: metaJsonOverviewHeaders,
|
|
780
|
+
context: metaJsonContext,
|
|
781
|
+
_fileKey: getHmrFileKey(dirAbsolutePath, docsDir)
|
|
782
|
+
};
|
|
783
|
+
{
|
|
784
|
+
const indexFile = await metaFileItemToSidebarItem('index', dirAbsolutePath, docsDir, extensions);
|
|
785
|
+
const { link, text, _fileKey, context, overviewHeaders, tag } = indexFile;
|
|
786
|
+
return {
|
|
787
|
+
text: label || text || name,
|
|
788
|
+
collapsible,
|
|
789
|
+
collapsed,
|
|
790
|
+
items: await getItems(!isFirstDir),
|
|
791
|
+
link,
|
|
792
|
+
tag: metaJsonTag || tag,
|
|
793
|
+
overviewHeaders: metaJsonOverviewHeaders || overviewHeaders,
|
|
794
|
+
context: metaJsonContext || context,
|
|
795
|
+
_fileKey
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
|
|
801
|
+
if ('divider' === type || 'section-header' === type) return metaDividerToSidebarItem(metaItem);
|
|
802
|
+
throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
803
|
+
}
|
|
804
|
+
async function detectFilePath(absolutePath, extensions) {
|
|
805
|
+
const ext = (0, external_node_path_.extname)(absolutePath);
|
|
806
|
+
if (ext && extensions.includes(ext)) return absolutePath;
|
|
807
|
+
for (const extension of extensions){
|
|
808
|
+
const realPath = absolutePath + extension;
|
|
809
|
+
if (await utils_pathExists(realPath)) return realPath;
|
|
810
|
+
}
|
|
811
|
+
throw new Error(`The file extension "${ext}" is not supported, please use one of the following extensions: ${extensions.join(', ')}`);
|
|
812
|
+
}
|
|
813
|
+
async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensions) {
|
|
814
|
+
let metaItem = null;
|
|
815
|
+
metaItem = 'string' == typeof metaItemRaw ? {
|
|
816
|
+
name: metaItemRaw,
|
|
817
|
+
type: 'file'
|
|
818
|
+
} : metaItemRaw;
|
|
819
|
+
const { name, context, label, overviewHeaders, tag } = metaItem;
|
|
820
|
+
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')}".`);
|
|
821
|
+
const absolutePath = (0, external_node_path_.join)(workDir, name);
|
|
822
|
+
let absolutePathWithExt;
|
|
823
|
+
try {
|
|
824
|
+
absolutePathWithExt = await detectFilePath(absolutePath, extensions);
|
|
825
|
+
} catch {
|
|
826
|
+
throw new Error(`The file "${absolutePath}" does not exist, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
827
|
+
}
|
|
828
|
+
const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
|
|
829
|
+
const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
|
|
830
|
+
const title = label || info.title;
|
|
831
|
+
return {
|
|
832
|
+
text: title,
|
|
833
|
+
link,
|
|
834
|
+
tag,
|
|
835
|
+
overviewHeaders: info.overviewHeaders || overviewHeaders,
|
|
836
|
+
context: info.context || context,
|
|
837
|
+
_fileKey: getHmrFileKey(absolutePathWithExt, docsDir)
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
|
|
841
|
+
if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
|
|
842
|
+
const { label, link, context, items, tag } = metaItem;
|
|
843
|
+
return {
|
|
844
|
+
text: label ?? link,
|
|
845
|
+
context,
|
|
846
|
+
tag,
|
|
847
|
+
link,
|
|
848
|
+
items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(subItem, workDir, docsDir))
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
if ('link' in metaItem && 'string' == typeof metaItem.link) {
|
|
852
|
+
const { label, link, context, tag } = metaItem;
|
|
853
|
+
if ((0, shared_.isExternalUrl)(link)) return {
|
|
854
|
+
text: label ?? link,
|
|
855
|
+
link,
|
|
856
|
+
tag,
|
|
857
|
+
context
|
|
858
|
+
};
|
|
859
|
+
return {
|
|
860
|
+
text: label ?? link,
|
|
861
|
+
link: addRoutePrefix(workDir, docsDir, link),
|
|
862
|
+
tag,
|
|
863
|
+
context
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
const { label } = metaItem;
|
|
867
|
+
throw new Error(`The custom link "${label}" does not have a link, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
|
|
868
|
+
}
|
|
869
|
+
function metaDividerToSidebarItem(metaItem) {
|
|
870
|
+
const { type } = metaItem;
|
|
871
|
+
if ('divider' === type) {
|
|
872
|
+
const { dashed } = metaItem;
|
|
873
|
+
return {
|
|
874
|
+
dividerType: dashed ? 'dashed' : 'solid'
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
const { label, tag } = metaItem;
|
|
878
|
+
return {
|
|
879
|
+
sectionHeaderText: label ?? '',
|
|
880
|
+
tag
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
async function scanSideMeta(workDir, docsDir, extensions) {
|
|
884
|
+
const dir = await metaItemToSidebarItem({
|
|
885
|
+
type: 'dir',
|
|
886
|
+
name: ''
|
|
887
|
+
}, workDir, docsDir, extensions, true);
|
|
888
|
+
return dir.items;
|
|
889
|
+
}
|
|
890
|
+
async function scanNav(workDir, docsDir) {
|
|
891
|
+
let navConfig;
|
|
892
|
+
const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
|
|
893
|
+
try {
|
|
894
|
+
navConfig = await utils_readJson(rootNavJson);
|
|
895
|
+
} catch (e) {
|
|
896
|
+
logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
|
|
897
|
+
navConfig = [];
|
|
898
|
+
}
|
|
899
|
+
navConfig.forEach((navItem)=>{
|
|
900
|
+
if ('items' in navItem) navItem.items.forEach((item)=>{
|
|
901
|
+
if ('link' in item && !(0, shared_.isExternalUrl)(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
|
|
902
|
+
});
|
|
903
|
+
if ('link' in navItem && !(0, shared_.isExternalUrl)(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
|
|
904
|
+
});
|
|
905
|
+
return navConfig;
|
|
906
|
+
}
|
|
907
|
+
async function walk(workDir, docsDir, extensions) {
|
|
908
|
+
const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
|
|
909
|
+
const rootMetaJson = external_node_path_["default"].resolve(workDir, '_meta.json');
|
|
910
|
+
const isRootNavJsonExist = await pathExists(rootNavJson);
|
|
911
|
+
const isRootMetaJsonExist = await pathExists(rootMetaJson);
|
|
912
|
+
if (isRootMetaJsonExist) {
|
|
913
|
+
const metaConfig = await utils_readJson(rootMetaJson);
|
|
914
|
+
hintNavJsonChangeThenPanic(metaConfig, workDir, docsDir);
|
|
915
|
+
}
|
|
916
|
+
if (isRootNavJsonExist) {
|
|
917
|
+
const navConfig = await scanNav(workDir, docsDir);
|
|
918
|
+
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)=>{
|
|
919
|
+
if (s.isDirectory() && 'node_modules' !== v) return v;
|
|
920
|
+
return false;
|
|
921
|
+
})))).filter(Boolean);
|
|
922
|
+
const sidebarConfig = {};
|
|
923
|
+
await Promise.all(subDirs.map(async (subDir)=>{
|
|
924
|
+
const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
|
|
925
|
+
sidebarConfig[sidebarGroupKey] = await scanSideMeta(external_node_path_["default"].join(workDir, subDir), docsDir, extensions);
|
|
926
|
+
}));
|
|
927
|
+
if (isRootMetaJsonExist) {
|
|
928
|
+
const rootMetaConfig = await scanSideMeta(workDir, docsDir, extensions);
|
|
929
|
+
sidebarConfig['/'] = rootMetaConfig;
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
nav: navConfig,
|
|
933
|
+
sidebar: sidebarConfig
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
nav: [],
|
|
938
|
+
sidebar: {
|
|
939
|
+
'/': await scanSideMeta(workDir, docsDir, extensions)
|
|
940
|
+
}
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
function combineWalkResult(walks, versions) {
|
|
944
|
+
return walks.reduce((acc, cur, curIndex)=>({
|
|
945
|
+
nav: {
|
|
946
|
+
...acc.nav,
|
|
947
|
+
[versions[curIndex] || 'default']: cur.nav
|
|
948
|
+
},
|
|
949
|
+
sidebar: {
|
|
950
|
+
...acc.sidebar,
|
|
951
|
+
...cur.sidebar
|
|
952
|
+
}
|
|
953
|
+
}), {
|
|
954
|
+
nav: {},
|
|
955
|
+
sidebar: {}
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
function processLocales(langs, versions, root, extensions) {
|
|
959
|
+
return Promise.all(langs.map(async (lang)=>{
|
|
960
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(root, version, lang), root, extensions))) : [
|
|
961
|
+
await walk(external_node_path_["default"].join(root, lang), root, extensions)
|
|
962
|
+
];
|
|
963
|
+
return combineWalkResult(walks, versions);
|
|
964
|
+
}));
|
|
965
|
+
}
|
|
966
|
+
async function modifyConfigWithAutoNavSide(config) {
|
|
967
|
+
const themeConfig = config.themeConfig || {};
|
|
968
|
+
const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
|
|
969
|
+
if (haveNavSidebarConfig) return config;
|
|
970
|
+
config.themeConfig = config.themeConfig || {};
|
|
971
|
+
config.themeConfig.locales = config.themeConfig.locales || config.locales || [];
|
|
972
|
+
const langs = config.themeConfig.locales.map((locale)=>locale.lang);
|
|
973
|
+
const hasLocales = langs.length > 0;
|
|
974
|
+
const hasLang = Boolean(config.lang);
|
|
975
|
+
const versions = config.multiVersion?.versions || [];
|
|
976
|
+
const { extensions = DEFAULT_PAGE_EXTENSIONS } = config?.route || {};
|
|
977
|
+
if (hasLocales) {
|
|
978
|
+
const metaInfo = await processLocales(langs, versions, config.root, extensions);
|
|
979
|
+
config.themeConfig.locales = config.themeConfig.locales.map((item, index)=>({
|
|
980
|
+
...item,
|
|
981
|
+
...metaInfo[index]
|
|
982
|
+
}));
|
|
983
|
+
} else {
|
|
984
|
+
if (hasLang) {
|
|
985
|
+
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");
|
|
986
|
+
return config;
|
|
987
|
+
}
|
|
988
|
+
const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(config.root, version), config.root, extensions))) : [
|
|
989
|
+
await walk(config.root, config.root, extensions)
|
|
990
|
+
];
|
|
991
|
+
const combined = combineWalkResult(walks, versions);
|
|
992
|
+
config.themeConfig = {
|
|
993
|
+
...config.themeConfig,
|
|
994
|
+
...combined
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
return config;
|
|
998
|
+
}
|
|
999
|
+
var external_node_fs_ = __webpack_require__("node:fs");
|
|
490
1000
|
let flattenMdxContent_resolver;
|
|
491
1001
|
let startFlatten = false;
|
|
492
|
-
const processor =
|
|
493
|
-
const { CachedInputFileSystem, ResolverFactory } =
|
|
494
|
-
const fileSystem =
|
|
1002
|
+
const processor = createProcessor();
|
|
1003
|
+
const { CachedInputFileSystem, ResolverFactory } = enhanced_resolve;
|
|
1004
|
+
const fileSystem = external_node_fs_["default"];
|
|
495
1005
|
async function resolveDepPath(importPath, importer, alias) {
|
|
496
1006
|
if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
|
|
497
1007
|
fileSystem: new CachedInputFileSystem(fileSystem, 0),
|
|
@@ -536,7 +1046,7 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
536
1046
|
try {
|
|
537
1047
|
ast = processor.parse(content);
|
|
538
1048
|
} catch (e) {
|
|
539
|
-
|
|
1049
|
+
logger.debug('flattenMdxContent parse failed: \n', e);
|
|
540
1050
|
return {
|
|
541
1051
|
flattenContent: content,
|
|
542
1052
|
deps
|
|
@@ -548,12 +1058,12 @@ async function flattenMdxContent(content, basePath, alias) {
|
|
|
548
1058
|
const importPath = importNode.source.value;
|
|
549
1059
|
let absoluteImportPath;
|
|
550
1060
|
try {
|
|
551
|
-
absoluteImportPath = await resolveDepPath(importPath,
|
|
1061
|
+
absoluteImportPath = await resolveDepPath(importPath, external_node_path_["default"].dirname(basePath), alias);
|
|
552
1062
|
} catch (_e) {
|
|
553
1063
|
continue;
|
|
554
1064
|
}
|
|
555
|
-
if (
|
|
556
|
-
const importedContent =
|
|
1065
|
+
if (shared_.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
|
|
1066
|
+
const importedContent = external_node_fs_["default"].readFileSync(absoluteImportPath, 'utf-8');
|
|
557
1067
|
const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
|
|
558
1068
|
result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
|
|
559
1069
|
deps.push(...subDeps, absoluteImportPath);
|
|
@@ -574,146 +1084,120 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
|
|
|
574
1084
|
else if ('object' == typeof obj[key] && null !== obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
|
|
575
1085
|
return obj;
|
|
576
1086
|
}
|
|
577
|
-
async function
|
|
578
|
-
const
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
content
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
1087
|
+
async function getPageIndexInfoByRoute(route, options) {
|
|
1088
|
+
const { alias, replaceRules, root, searchCodeBlocks } = options;
|
|
1089
|
+
const defaultIndexInfo = {
|
|
1090
|
+
title: '',
|
|
1091
|
+
content: '',
|
|
1092
|
+
_html: '',
|
|
1093
|
+
_flattenContent: '',
|
|
1094
|
+
routePath: route.routePath,
|
|
1095
|
+
lang: route.lang,
|
|
1096
|
+
toc: [],
|
|
1097
|
+
frontmatter: {},
|
|
1098
|
+
version: route.version,
|
|
1099
|
+
_filepath: route.absolutePath,
|
|
1100
|
+
_relativePath: external_node_path_["default"].relative(root, route.absolutePath).split(external_node_path_["default"].sep).join('/')
|
|
1101
|
+
};
|
|
1102
|
+
if (!shared_.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
|
|
1103
|
+
let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
|
|
1104
|
+
const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
|
|
1105
|
+
applyReplaceRulesToNestedObject(frontmatter, replaceRules);
|
|
1106
|
+
const { flattenContent } = await flattenMdxContent(applyReplaceRules(contentWithoutFrontMatter, replaceRules), route.absolutePath, alias);
|
|
1107
|
+
content = flattenContent.replace(importStatementRegex, '');
|
|
1108
|
+
const { html: rawHtml, title, toc: rawToc } = await compile({
|
|
1109
|
+
value: content,
|
|
1110
|
+
filepath: route.absolutePath,
|
|
1111
|
+
development: 'production' !== process.env.NODE_ENV,
|
|
1112
|
+
root
|
|
1113
|
+
});
|
|
1114
|
+
function encodeHtml(html) {
|
|
1115
|
+
return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
|
|
1116
|
+
return `<code>${innerContent.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')}</code>`;
|
|
605
1117
|
});
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1118
|
+
}
|
|
1119
|
+
const html = encodeHtml(String(rawHtml));
|
|
1120
|
+
content = htmlToText(html, {
|
|
1121
|
+
wordwrap: 80,
|
|
1122
|
+
selectors: [
|
|
1123
|
+
{
|
|
1124
|
+
selector: 'a',
|
|
1125
|
+
options: {
|
|
1126
|
+
ignoreHref: true
|
|
1127
|
+
}
|
|
1128
|
+
},
|
|
1129
|
+
{
|
|
1130
|
+
selector: 'img',
|
|
1131
|
+
format: 'skip'
|
|
1132
|
+
},
|
|
1133
|
+
{
|
|
1134
|
+
selector: 'pre > code',
|
|
1135
|
+
format: searchCodeBlocks ? 'block' : 'skip'
|
|
1136
|
+
},
|
|
1137
|
+
...[
|
|
1138
|
+
'h1',
|
|
1139
|
+
'h2',
|
|
1140
|
+
'h3',
|
|
1141
|
+
'h4',
|
|
1142
|
+
'h5',
|
|
1143
|
+
'h6'
|
|
1144
|
+
].map((tag)=>({
|
|
1145
|
+
selector: tag,
|
|
617
1146
|
options: {
|
|
618
|
-
|
|
1147
|
+
uppercase: false
|
|
619
1148
|
}
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
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
|
-
});
|
|
1149
|
+
}))
|
|
1150
|
+
],
|
|
1151
|
+
tables: true,
|
|
1152
|
+
longWordSplit: {
|
|
1153
|
+
forceWrapOnLimit: true
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
if (content.startsWith(title)) content = content.slice(title.length);
|
|
1157
|
+
const toc = rawToc.map((item)=>{
|
|
1158
|
+
const match = item.id.match(/-(\d+)$/);
|
|
1159
|
+
let position = -1;
|
|
1160
|
+
if (match) for(let i = 0; i < Number(match[1]); i++){
|
|
1161
|
+
position = content.indexOf(`\n${item.text}#\n\n`, position + 1);
|
|
1162
|
+
if (-1 === position) break;
|
|
1163
|
+
}
|
|
662
1164
|
return {
|
|
663
|
-
...
|
|
664
|
-
|
|
665
|
-
toc,
|
|
666
|
-
content,
|
|
667
|
-
_flattenContent: flattenContent,
|
|
668
|
-
_html: html,
|
|
669
|
-
frontmatter: {
|
|
670
|
-
...frontmatter,
|
|
671
|
-
__content: void 0
|
|
672
|
-
}
|
|
1165
|
+
...item,
|
|
1166
|
+
charIndex: content.indexOf(`\n${item.text}#\n\n`, position + 1)
|
|
673
1167
|
};
|
|
674
|
-
})
|
|
675
|
-
return
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
1168
|
+
});
|
|
1169
|
+
return {
|
|
1170
|
+
...defaultIndexInfo,
|
|
1171
|
+
title: frontmatter.title || title,
|
|
1172
|
+
toc,
|
|
1173
|
+
content,
|
|
1174
|
+
_html: html,
|
|
1175
|
+
_flattenContent: flattenContent,
|
|
1176
|
+
frontmatter: {
|
|
1177
|
+
...frontmatter,
|
|
1178
|
+
__content: void 0
|
|
685
1179
|
}
|
|
686
|
-
|
|
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;
|
|
1180
|
+
};
|
|
715
1181
|
}
|
|
716
|
-
|
|
1182
|
+
async function extractPageData(routeService, options) {
|
|
1183
|
+
const pageData = await Promise.all(routeService.getRoutes().map((routeMeta)=>getPageIndexInfoByRoute(routeMeta, options)));
|
|
1184
|
+
return pageData;
|
|
1185
|
+
}
|
|
1186
|
+
function createHash_createHash(str) {
|
|
1187
|
+
return createHash('sha256').update(str).digest('hex').slice(0, 8);
|
|
1188
|
+
}
|
|
1189
|
+
var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
|
|
1190
|
+
RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
|
|
1191
|
+
RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
|
|
1192
|
+
RuntimeModuleID["Routes"] = "virtual-routes";
|
|
1193
|
+
RuntimeModuleID["SiteData"] = "virtual-site-data";
|
|
1194
|
+
RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
|
|
1195
|
+
RuntimeModuleID["I18nText"] = "virtual-i18n-text";
|
|
1196
|
+
RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
|
|
1197
|
+
RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
|
|
1198
|
+
return RuntimeModuleID;
|
|
1199
|
+
}({});
|
|
1200
|
+
const DEFAULT_I18N_SOURCE = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
|
|
717
1201
|
function getI18nData(docConfig) {
|
|
718
1202
|
const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
|
|
719
1203
|
try {
|
|
@@ -721,7 +1205,7 @@ function getI18nData(docConfig) {
|
|
|
721
1205
|
const i18nSource = require(i18nSourcePath);
|
|
722
1206
|
return i18nSource;
|
|
723
1207
|
} catch (e) {
|
|
724
|
-
|
|
1208
|
+
logger.debug('getI18nData Failed: \n', e);
|
|
725
1209
|
return {};
|
|
726
1210
|
}
|
|
727
1211
|
}
|
|
@@ -736,8 +1220,8 @@ const i18nVMPlugin = (context)=>{
|
|
|
736
1220
|
}
|
|
737
1221
|
};
|
|
738
1222
|
};
|
|
739
|
-
function normalizeThemeConfig(docConfig
|
|
740
|
-
const { locales: siteLocales,
|
|
1223
|
+
function normalizeThemeConfig(docConfig) {
|
|
1224
|
+
const { locales: siteLocales, lang, replaceRules = [], multiVersion } = docConfig;
|
|
741
1225
|
const { versions = [] } = multiVersion || {};
|
|
742
1226
|
const hasMultiVersion = versions.length > 0;
|
|
743
1227
|
docConfig.themeConfig = docConfig.themeConfig || {};
|
|
@@ -745,9 +1229,9 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
745
1229
|
const locales = siteLocales ?? (themeConfig?.locales || []);
|
|
746
1230
|
const i18nTextData = getI18nData(docConfig);
|
|
747
1231
|
const normalizeLinkPrefix = (link = '', currentLang = '')=>{
|
|
748
|
-
const normalizedLink = (0,
|
|
749
|
-
if (!currentLang || !link ||
|
|
750
|
-
return lang === currentLang ? normalizedLink : `/${currentLang}${(0,
|
|
1232
|
+
const normalizedLink = (0, shared_.slash)(link);
|
|
1233
|
+
if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || (0, shared_.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
|
|
1234
|
+
return lang === currentLang ? normalizedLink : `/${currentLang}${(0, shared_.addLeadingSlash)(normalizedLink)}`;
|
|
751
1235
|
};
|
|
752
1236
|
const getI18nText = (key = '', currentLang = '')=>{
|
|
753
1237
|
const text = i18nTextData[key]?.[currentLang];
|
|
@@ -771,15 +1255,6 @@ function normalizeThemeConfig(docConfig, pages = []) {
|
|
|
771
1255
|
tag: item.tag,
|
|
772
1256
|
items: item.items.map((subItem)=>normalizeSidebarItem(subItem))
|
|
773
1257
|
};
|
|
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
1258
|
return {
|
|
784
1259
|
...item,
|
|
785
1260
|
text: applyReplaceRules(getI18nText(item.text, currentLang), replaceRules),
|
|
@@ -851,15 +1326,18 @@ async function siteDataVMPlugin(context) {
|
|
|
851
1326
|
const userConfig = config;
|
|
852
1327
|
const tempSearchObj = Object.assign({}, userConfig.search);
|
|
853
1328
|
if (tempSearchObj) tempSearchObj.searchHooks = void 0;
|
|
854
|
-
const highlightLanguages = new Set();
|
|
855
1329
|
const replaceRules = userConfig?.replaceRules || [];
|
|
856
1330
|
const searchConfig = userConfig?.search || {};
|
|
857
|
-
const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
|
|
858
1331
|
const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
|
|
859
|
-
const pages = await extractPageData(
|
|
1332
|
+
const pages = await extractPageData(routeService, {
|
|
1333
|
+
replaceRules,
|
|
1334
|
+
alias,
|
|
1335
|
+
root: userDocRoot,
|
|
1336
|
+
searchCodeBlocks
|
|
1337
|
+
});
|
|
860
1338
|
await pluginDriver.modifySearchIndexData(pages);
|
|
861
|
-
const versioned =
|
|
862
|
-
const groupedPages =
|
|
1339
|
+
const versioned = 'boolean' != typeof userConfig.search && userConfig.search?.versioned;
|
|
1340
|
+
const groupedPages = groupBy(pages, (page)=>{
|
|
863
1341
|
if (page.frontmatter?.pageType === 'home') return 'noindex';
|
|
864
1342
|
const version = versioned ? page.version : '';
|
|
865
1343
|
const lang = page.lang || '';
|
|
@@ -869,24 +1347,23 @@ async function siteDataVMPlugin(context) {
|
|
|
869
1347
|
const indexHashByGroup = {};
|
|
870
1348
|
await Promise.all(Object.keys(groupedPages).map(async (group)=>{
|
|
871
1349
|
const stringifiedIndex = JSON.stringify(groupedPages[group].map(deletePrivateField));
|
|
872
|
-
const indexHash =
|
|
1350
|
+
const indexHash = createHash_createHash(stringifiedIndex);
|
|
873
1351
|
indexHashByGroup[group] = indexHash;
|
|
874
1352
|
const [version, lang] = group.split('###');
|
|
875
1353
|
const indexVersion = version ? `.${version.replace('.', '_')}` : '';
|
|
876
1354
|
const indexLang = lang ? `.${lang}` : '';
|
|
877
|
-
await
|
|
1355
|
+
await node_fs_promises.mkdir(constants_TEMP_DIR, {
|
|
878
1356
|
recursive: true
|
|
879
1357
|
});
|
|
880
|
-
await
|
|
1358
|
+
await node_fs_promises.writeFile(external_node_path_["default"].join(constants_TEMP_DIR, `${shared_.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
|
|
881
1359
|
}));
|
|
882
1360
|
await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
|
|
883
1361
|
const siteData = {
|
|
884
1362
|
title: userConfig?.title || '',
|
|
885
1363
|
description: userConfig?.description || '',
|
|
886
|
-
icon: userConfig?.icon || '',
|
|
1364
|
+
icon: getIconUrlPath(userConfig?.icon) || '',
|
|
887
1365
|
route: userConfig?.route || {},
|
|
888
|
-
themeConfig: normalizeThemeConfig(userConfig
|
|
889
|
-
base: userConfig?.base || '/',
|
|
1366
|
+
themeConfig: normalizeThemeConfig(userConfig),
|
|
890
1367
|
lang: userConfig?.lang || '',
|
|
891
1368
|
locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
|
|
892
1369
|
logo: userConfig?.logo || '',
|
|
@@ -900,7 +1377,7 @@ async function siteDataVMPlugin(context) {
|
|
|
900
1377
|
mode: 'local'
|
|
901
1378
|
},
|
|
902
1379
|
pages: pages.map((page)=>{
|
|
903
|
-
const { content,
|
|
1380
|
+
const { content, _filepath, _html, _flattenContent, ...rest } = page;
|
|
904
1381
|
return isProduction() ? rest : {
|
|
905
1382
|
...rest,
|
|
906
1383
|
_filepath
|
|
@@ -909,56 +1386,45 @@ async function siteDataVMPlugin(context) {
|
|
|
909
1386
|
markdown: {
|
|
910
1387
|
showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
|
|
911
1388
|
defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
|
|
912
|
-
|
|
1389
|
+
shiki: {}
|
|
913
1390
|
}
|
|
914
1391
|
};
|
|
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
1392
|
return {
|
|
921
1393
|
[`${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
|
-
}`
|
|
1394
|
+
[types_RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(indexHashByGroup, null, 2)}`
|
|
929
1395
|
};
|
|
930
1396
|
}
|
|
931
1397
|
const runtimeModuleFactory = [
|
|
932
|
-
routeVMPlugin,
|
|
933
1398
|
siteDataVMPlugin
|
|
934
1399
|
];
|
|
935
1400
|
function rsbuildPluginDocVM(factoryContext) {
|
|
936
|
-
const { pluginDriver } = factoryContext;
|
|
937
1401
|
return {
|
|
938
1402
|
name: 'rsbuild-plugin-doc-vm',
|
|
939
1403
|
setup (api) {
|
|
940
|
-
api.modifyBundlerChain(async (bundlerChain
|
|
941
|
-
const isServer = 'node' === target;
|
|
1404
|
+
api.modifyBundlerChain(async (bundlerChain)=>{
|
|
942
1405
|
const alias = bundlerChain.resolve.alias.entries();
|
|
943
1406
|
const runtimeModule = {};
|
|
944
1407
|
for (const factory of runtimeModuleFactory){
|
|
945
1408
|
const moduleResult = await factory({
|
|
946
1409
|
...factoryContext,
|
|
947
|
-
isSSR: isServer,
|
|
948
1410
|
alias: alias
|
|
949
1411
|
});
|
|
950
1412
|
Object.assign(runtimeModule, moduleResult);
|
|
951
1413
|
}
|
|
952
|
-
|
|
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));
|
|
1414
|
+
bundlerChain.plugin('rspress-runtime-module').use(new RspackVirtualModulePlugin(runtimeModule));
|
|
958
1415
|
});
|
|
959
1416
|
}
|
|
960
1417
|
};
|
|
961
1418
|
}
|
|
1419
|
+
async function getVirtualModulesFromPlugins(pluginDriver) {
|
|
1420
|
+
const runtimeModule = {};
|
|
1421
|
+
const modulesByPlugin = await pluginDriver.addRuntimeModules();
|
|
1422
|
+
Object.keys(modulesByPlugin).forEach((key)=>{
|
|
1423
|
+
if (runtimeModule[key]) throw new Error(`The runtime module ${key} is duplicated, please check your plugin`);
|
|
1424
|
+
runtimeModule[key] = ()=>modulesByPlugin[key];
|
|
1425
|
+
});
|
|
1426
|
+
return runtimeModule;
|
|
1427
|
+
}
|
|
962
1428
|
const globalStylesVMPlugin = (context)=>({
|
|
963
1429
|
[types_RuntimeModuleID.GlobalStyles]: ()=>{
|
|
964
1430
|
const { config, pluginDriver } = context;
|
|
@@ -994,6 +1460,20 @@ const Props_${index++} = ${JSON.stringify(source[1])};\n`;
|
|
|
994
1460
|
return moduleContent;
|
|
995
1461
|
}
|
|
996
1462
|
});
|
|
1463
|
+
const routeListVMPlugin = (context)=>{
|
|
1464
|
+
const { routeService } = context;
|
|
1465
|
+
return {
|
|
1466
|
+
[types_RuntimeModuleID.Routes]: ()=>routeService.generateRoutesCode()
|
|
1467
|
+
};
|
|
1468
|
+
};
|
|
1469
|
+
const runtimeConfigVMPlugin = (context)=>({
|
|
1470
|
+
[types_RuntimeModuleID.RuntimeConfig]: ()=>{
|
|
1471
|
+
const { config } = context;
|
|
1472
|
+
const { base } = config;
|
|
1473
|
+
const normalizedBase = (0, shared_.normalizeSlash)(base ?? '/');
|
|
1474
|
+
return `export const base = ${JSON.stringify(normalizedBase)};`;
|
|
1475
|
+
}
|
|
1476
|
+
});
|
|
997
1477
|
const searchHookVMPlugin = (context)=>({
|
|
998
1478
|
[`${types_RuntimeModuleID.SearchHooks}`]: ()=>{
|
|
999
1479
|
const { config } = context;
|
|
@@ -1005,61 +1485,128 @@ const searchHookVMPlugin = (context)=>({
|
|
|
1005
1485
|
async function writeSearchIndex(config) {
|
|
1006
1486
|
if (config?.search === false) return;
|
|
1007
1487
|
const cwd = process.cwd();
|
|
1008
|
-
const searchIndexFiles = await
|
|
1009
|
-
const outDir = config?.outDir ?? (0,
|
|
1010
|
-
const targetDir = (0,
|
|
1011
|
-
await
|
|
1488
|
+
const searchIndexFiles = await node_fs_promises.readdir(constants_TEMP_DIR);
|
|
1489
|
+
const outDir = config?.outDir ?? (0, external_node_path_.join)(cwd, OUTPUT_DIR);
|
|
1490
|
+
const targetDir = (0, external_node_path_.join)(outDir, 'static');
|
|
1491
|
+
await node_fs_promises.mkdir(targetDir, {
|
|
1012
1492
|
recursive: true
|
|
1013
1493
|
});
|
|
1014
1494
|
let searchIndexData = '[]';
|
|
1015
1495
|
let scanning = false;
|
|
1016
1496
|
for (const searchIndexFile of searchIndexFiles){
|
|
1017
|
-
if (!searchIndexFile.includes(
|
|
1018
|
-
const source = (0,
|
|
1019
|
-
const target = (0,
|
|
1020
|
-
const searchIndex = await
|
|
1497
|
+
if (!searchIndexFile.includes(shared_.SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
|
|
1498
|
+
const source = (0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile);
|
|
1499
|
+
const target = (0, external_node_path_.join)(targetDir, searchIndexFile);
|
|
1500
|
+
const searchIndex = await node_fs_promises.readFile((0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile), 'utf-8');
|
|
1021
1501
|
searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
|
|
1022
|
-
await
|
|
1502
|
+
await node_fs_promises.rename(source, target);
|
|
1023
1503
|
scanning = true;
|
|
1024
1504
|
}
|
|
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
|
-
}
|
|
1039
|
-
}
|
|
1040
1505
|
}
|
|
1041
1506
|
function serveSearchIndexMiddleware(config) {
|
|
1042
1507
|
return (req, res, next)=>{
|
|
1043
|
-
const searchIndexRequestMatch = `/${
|
|
1508
|
+
const searchIndexRequestMatch = `/${shared_.SEARCH_INDEX_NAME}.`;
|
|
1044
1509
|
if (req.url?.includes(searchIndexRequestMatch)) {
|
|
1045
1510
|
res.setHeader('Content-Type', 'application/json');
|
|
1046
|
-
const outDir = config?.outDir ?? (0,
|
|
1511
|
+
const outDir = config?.outDir ?? (0, external_node_path_.join)(process.cwd(), OUTPUT_DIR);
|
|
1047
1512
|
const searchIndexFile = req.url.split('/').pop();
|
|
1048
|
-
(0,
|
|
1513
|
+
(0, external_node_fs_.createReadStream)((0, external_node_path_.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
|
|
1049
1514
|
end: true
|
|
1050
1515
|
});
|
|
1051
1516
|
} else next?.();
|
|
1052
1517
|
};
|
|
1053
1518
|
}
|
|
1054
|
-
async function
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1519
|
+
async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
|
|
1520
|
+
return new Promise((resolve_, reject_)=>{
|
|
1521
|
+
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})`);
|
|
1522
|
+
if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
|
|
1523
|
+
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})`);
|
|
1524
|
+
const result = [];
|
|
1525
|
+
const errors = [];
|
|
1526
|
+
const skippedIndexesMap = new Map();
|
|
1527
|
+
let isRejected = false;
|
|
1528
|
+
let isResolved = false;
|
|
1529
|
+
let isIterableDone = false;
|
|
1530
|
+
let resolvingCount = 0;
|
|
1531
|
+
let currentIndex = 0;
|
|
1532
|
+
const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
1533
|
+
const signalListener = ()=>{
|
|
1534
|
+
reject(signal.reason);
|
|
1535
|
+
};
|
|
1536
|
+
const cleanup = ()=>{
|
|
1537
|
+
signal?.removeEventListener('abort', signalListener);
|
|
1538
|
+
};
|
|
1539
|
+
const resolve = (value)=>{
|
|
1540
|
+
resolve_(value);
|
|
1541
|
+
cleanup();
|
|
1542
|
+
};
|
|
1543
|
+
const reject = (reason)=>{
|
|
1544
|
+
isRejected = true;
|
|
1545
|
+
isResolved = true;
|
|
1546
|
+
reject_(reason);
|
|
1547
|
+
cleanup();
|
|
1548
|
+
};
|
|
1549
|
+
if (signal) {
|
|
1550
|
+
if (signal.aborted) reject(signal.reason);
|
|
1551
|
+
signal.addEventListener('abort', signalListener, {
|
|
1552
|
+
once: true
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
const next = async ()=>{
|
|
1556
|
+
if (isResolved) return;
|
|
1557
|
+
const nextItem = await iterator.next();
|
|
1558
|
+
const index = currentIndex;
|
|
1559
|
+
currentIndex++;
|
|
1560
|
+
if (nextItem.done) {
|
|
1561
|
+
isIterableDone = true;
|
|
1562
|
+
if (0 === resolvingCount && !isResolved) {
|
|
1563
|
+
if (!stopOnError && errors.length > 0) return void reject(new AggregateError(errors));
|
|
1564
|
+
isResolved = true;
|
|
1565
|
+
if (0 === skippedIndexesMap.size) return void resolve(result);
|
|
1566
|
+
const pureResult = [];
|
|
1567
|
+
for (const [index, value] of result.entries())if (skippedIndexesMap.get(index) !== pMapSkip) pureResult.push(value);
|
|
1568
|
+
resolve(pureResult);
|
|
1569
|
+
}
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
resolvingCount++;
|
|
1573
|
+
(async ()=>{
|
|
1574
|
+
try {
|
|
1575
|
+
const element = await nextItem.value;
|
|
1576
|
+
if (isResolved) return;
|
|
1577
|
+
const value = await mapper(element, index);
|
|
1578
|
+
if (value === pMapSkip) skippedIndexesMap.set(index, value);
|
|
1579
|
+
result[index] = value;
|
|
1580
|
+
resolvingCount--;
|
|
1581
|
+
await next();
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
if (stopOnError) reject(error);
|
|
1584
|
+
else {
|
|
1585
|
+
errors.push(error);
|
|
1586
|
+
resolvingCount--;
|
|
1587
|
+
try {
|
|
1588
|
+
await next();
|
|
1589
|
+
} catch (error) {
|
|
1590
|
+
reject(error);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
})();
|
|
1595
|
+
};
|
|
1596
|
+
(async ()=>{
|
|
1597
|
+
for(let index = 0; index < concurrency; index++){
|
|
1598
|
+
try {
|
|
1599
|
+
await next();
|
|
1600
|
+
} catch (error) {
|
|
1601
|
+
reject(error);
|
|
1602
|
+
break;
|
|
1603
|
+
}
|
|
1604
|
+
if (isIterableDone || isRejected) break;
|
|
1605
|
+
}
|
|
1606
|
+
})();
|
|
1058
1607
|
});
|
|
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
1608
|
}
|
|
1609
|
+
const pMapSkip = Symbol('skip');
|
|
1063
1610
|
async function renderConfigHead(config, route) {
|
|
1064
1611
|
if (!isRouteMeta(route)) return '';
|
|
1065
1612
|
if (!config.head || 0 === config.head.length) return '';
|
|
@@ -1085,25 +1632,24 @@ function isRouteMeta(route) {
|
|
|
1085
1632
|
return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
|
|
1086
1633
|
}
|
|
1087
1634
|
async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
|
|
1088
|
-
|
|
1635
|
+
logger.info('Rendering pages...');
|
|
1089
1636
|
const startTime = Date.now();
|
|
1090
1637
|
let render;
|
|
1091
1638
|
try {
|
|
1092
|
-
const { default: ssrExports } = await import((0,
|
|
1093
|
-
|
|
1639
|
+
const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
|
|
1640
|
+
render = await ssrExports.render;
|
|
1094
1641
|
} catch (e) {
|
|
1095
1642
|
if (e instanceof Error) {
|
|
1096
|
-
|
|
1097
|
-
|
|
1643
|
+
logger.error(`Failed to load SSG bundle: ${picocolors.yellow(ssrBundlePath)}: ${e.message}`);
|
|
1644
|
+
logger.debug(e);
|
|
1098
1645
|
hintSSGFailed();
|
|
1099
1646
|
}
|
|
1100
1647
|
throw e;
|
|
1101
1648
|
}
|
|
1102
1649
|
try {
|
|
1103
1650
|
const routes = routeService.getRoutes();
|
|
1104
|
-
const base = config?.base ?? '';
|
|
1105
1651
|
const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
|
|
1106
|
-
routePath:
|
|
1652
|
+
routePath: route.path
|
|
1107
1653
|
}));
|
|
1108
1654
|
const allRoutes = [
|
|
1109
1655
|
...routes,
|
|
@@ -1113,61 +1659,62 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
|
|
|
1113
1659
|
if (!is404RouteInRoutes) allRoutes.push({
|
|
1114
1660
|
routePath: '/404'
|
|
1115
1661
|
});
|
|
1116
|
-
|
|
1117
|
-
|
|
1662
|
+
const filteredRoutes = allRoutes.filter((route)=>!route.routePath.includes(':'));
|
|
1663
|
+
await pMap(filteredRoutes, async (route)=>{
|
|
1664
|
+
const head = createHead();
|
|
1118
1665
|
const { routePath } = route;
|
|
1119
1666
|
let appHtml = '';
|
|
1120
1667
|
if (render) try {
|
|
1121
|
-
({ appHtml } = await render(routePath,
|
|
1668
|
+
({ appHtml } = await render(routePath, head));
|
|
1122
1669
|
} catch (e) {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1670
|
+
if (e instanceof Error) {
|
|
1671
|
+
logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
|
|
1672
|
+
throw e;
|
|
1673
|
+
}
|
|
1126
1674
|
}
|
|
1127
|
-
const
|
|
1128
|
-
|
|
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)
|
|
1675
|
+
const replacedHtmlTemplate = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
|
|
1676
|
+
await renderConfigHead(config, route)
|
|
1136
1677
|
].join(''));
|
|
1137
|
-
|
|
1138
|
-
if (helmet.bodyAttributes) html = html.replace(BODY_START_TAG, `${BODY_START_TAG} ${helmet.bodyAttributes?.toString()}`);
|
|
1678
|
+
const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
|
|
1139
1679
|
const normalizeHtmlFilePath = (path)=>{
|
|
1140
|
-
const normalizedBase = `${(0,
|
|
1680
|
+
const normalizedBase = `${(0, shared_.normalizeSlash)(config?.base || '/')}/`;
|
|
1141
1681
|
if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
|
|
1142
1682
|
return `${path}.html`.replace(normalizedBase, '');
|
|
1143
1683
|
};
|
|
1144
1684
|
const fileName = normalizeHtmlFilePath(routePath);
|
|
1145
1685
|
emitAsset(fileName, html);
|
|
1146
|
-
}
|
|
1686
|
+
}, {
|
|
1687
|
+
concurrency: process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32
|
|
1688
|
+
});
|
|
1147
1689
|
const totalTime = Date.now() - startTime;
|
|
1148
|
-
|
|
1690
|
+
logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
|
|
1149
1691
|
} catch (e) {
|
|
1150
1692
|
if (e instanceof Error) {
|
|
1151
|
-
|
|
1152
|
-
|
|
1693
|
+
logger.error(`Pages render error: ${e.message}`);
|
|
1694
|
+
logger.debug(e);
|
|
1153
1695
|
hintSSGFailed();
|
|
1154
1696
|
}
|
|
1155
1697
|
throw e;
|
|
1156
1698
|
}
|
|
1157
1699
|
}
|
|
1158
|
-
const NODE_SSR_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
|
|
1159
1700
|
const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
1160
1701
|
name: 'rspress-inner-rsbuild-plugin-ssg',
|
|
1161
1702
|
async setup (api) {
|
|
1162
1703
|
api.onBeforeBuild(()=>{
|
|
1163
1704
|
let htmlTemplate = '';
|
|
1705
|
+
let hasError = false;
|
|
1164
1706
|
const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
|
|
1165
1707
|
api.processAssets({
|
|
1166
1708
|
stage: 'report',
|
|
1167
1709
|
targets: [
|
|
1168
1710
|
'web'
|
|
1169
1711
|
]
|
|
1170
|
-
}, ({ assets, compilation })=>{
|
|
1712
|
+
}, ({ assets, compilation, environment })=>{
|
|
1713
|
+
if ('web' !== environment.name) return;
|
|
1714
|
+
if (compilation.errors.length > 0) {
|
|
1715
|
+
hasError = true;
|
|
1716
|
+
return;
|
|
1717
|
+
}
|
|
1171
1718
|
for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
|
|
1172
1719
|
htmlTemplate = assetSource.source().toString();
|
|
1173
1720
|
compilation.deleteAsset(assetName);
|
|
@@ -1178,7 +1725,7 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1178
1725
|
});
|
|
1179
1726
|
}).catch(()=>{
|
|
1180
1727
|
const message = 'SSG requires an `index.html` as entry, but this file is not emitted successfully in the web target.';
|
|
1181
|
-
|
|
1728
|
+
logger.error(message);
|
|
1182
1729
|
const error = new Error(message);
|
|
1183
1730
|
throw error;
|
|
1184
1731
|
});
|
|
@@ -1188,33 +1735,43 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
|
|
|
1188
1735
|
'node'
|
|
1189
1736
|
]
|
|
1190
1737
|
}, async ({ assets, compilation, environment, compiler })=>{
|
|
1738
|
+
if ('node' !== environment.name) return;
|
|
1739
|
+
if (compilation.errors.length > 0) {
|
|
1740
|
+
hasError = true;
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
if (hasError) return;
|
|
1191
1744
|
const distPath = environment.distPath;
|
|
1192
|
-
|
|
1745
|
+
const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
|
|
1746
|
+
const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
|
|
1747
|
+
await mkdir(ssgFolderPath, {
|
|
1193
1748
|
recursive: true
|
|
1194
1749
|
});
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
}
|
|
1750
|
+
await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
|
|
1751
|
+
if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
|
|
1752
|
+
const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
|
|
1753
|
+
await writeFile(fileAbsolutePath, assetSource.source().toString());
|
|
1754
|
+
compilation.deleteAsset(assetName);
|
|
1755
|
+
}
|
|
1756
|
+
}));
|
|
1202
1757
|
const emitAsset = (assetName, content)=>{
|
|
1203
1758
|
compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
|
|
1204
1759
|
};
|
|
1205
1760
|
await indexHtmlEmittedInWeb;
|
|
1206
1761
|
await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
|
|
1207
|
-
if (!(0,
|
|
1762
|
+
if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
|
|
1763
|
+
recursive: true
|
|
1764
|
+
});
|
|
1208
1765
|
});
|
|
1209
1766
|
});
|
|
1210
1767
|
}
|
|
1211
1768
|
});
|
|
1212
|
-
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } =
|
|
1769
|
+
const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = enhanced_resolve;
|
|
1213
1770
|
async function detectPackageMajorVersion(name) {
|
|
1214
1771
|
const cwd = process.cwd();
|
|
1215
|
-
const pkgPath =
|
|
1772
|
+
const pkgPath = external_node_path_["default"].join(cwd, 'node_modules', name);
|
|
1216
1773
|
if (await pathExists(pkgPath)) {
|
|
1217
|
-
const pkgJson = await readJson(
|
|
1774
|
+
const pkgJson = await readJson(external_node_path_["default"].join(pkgPath, 'package.json'));
|
|
1218
1775
|
const version = Number(pkgJson.version?.split('.')[0]);
|
|
1219
1776
|
return version;
|
|
1220
1777
|
}
|
|
@@ -1226,7 +1783,7 @@ async function detectReactVersion() {
|
|
|
1226
1783
|
async function resolveReactRouterDomAlias() {
|
|
1227
1784
|
const alias = {};
|
|
1228
1785
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1229
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1786
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
|
|
1230
1787
|
mainFields: [
|
|
1231
1788
|
'browser',
|
|
1232
1789
|
'module',
|
|
@@ -1250,7 +1807,7 @@ async function resolveReactRouterDomAlias() {
|
|
|
1250
1807
|
'react-router-dom': pkgPath
|
|
1251
1808
|
};
|
|
1252
1809
|
} catch (e) {
|
|
1253
|
-
|
|
1810
|
+
logger.warn('react-router-dom not found: \n', e);
|
|
1254
1811
|
}
|
|
1255
1812
|
return {};
|
|
1256
1813
|
}
|
|
@@ -1261,12 +1818,12 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1261
1818
|
'react/jsx-runtime',
|
|
1262
1819
|
'react/jsx-dev-runtime',
|
|
1263
1820
|
'react-dom',
|
|
1821
|
+
'react-dom/client',
|
|
1264
1822
|
'react-dom/server'
|
|
1265
1823
|
];
|
|
1266
|
-
if (reactVersion >= 18) libPaths.push('react-dom/client');
|
|
1267
1824
|
const alias = {};
|
|
1268
1825
|
const resolver = detectReactVersion_ResolverFactory.createResolver({
|
|
1269
|
-
fileSystem: new detectReactVersion_CachedInputFileSystem(
|
|
1826
|
+
fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
|
|
1270
1827
|
extensions: [
|
|
1271
1828
|
'.js'
|
|
1272
1829
|
],
|
|
@@ -1289,21 +1846,24 @@ async function resolveReactAlias(reactVersion, isSSR) {
|
|
|
1289
1846
|
});
|
|
1290
1847
|
});
|
|
1291
1848
|
} catch (e) {
|
|
1292
|
-
|
|
1849
|
+
if (e instanceof Error) {
|
|
1850
|
+
logger.warn(`${lib} not found: \n ${picocolors.gray(e.toString())}`);
|
|
1851
|
+
hintReactVersion();
|
|
1852
|
+
}
|
|
1293
1853
|
}
|
|
1294
1854
|
}));
|
|
1295
1855
|
return alias;
|
|
1296
1856
|
}
|
|
1297
1857
|
const detectCustomIcon = async (customThemeDir)=>{
|
|
1298
|
-
const assetsDir =
|
|
1858
|
+
const assetsDir = external_node_path_["default"].join(customThemeDir, 'assets');
|
|
1299
1859
|
const alias = {};
|
|
1300
|
-
if (!(0,
|
|
1301
|
-
const files = await
|
|
1860
|
+
if (!(0, external_node_fs_.existsSync)(assetsDir)) return alias;
|
|
1861
|
+
const files = await glob('*.svg', {
|
|
1302
1862
|
cwd: assetsDir
|
|
1303
1863
|
});
|
|
1304
1864
|
files.forEach((file)=>{
|
|
1305
|
-
const name =
|
|
1306
|
-
alias[`@theme-assets/${name}`] =
|
|
1865
|
+
const name = external_node_path_["default"].basename(file, '.svg');
|
|
1866
|
+
alias[`@theme-assets/${name}`] = external_node_path_["default"].join(assetsDir, file);
|
|
1307
1867
|
});
|
|
1308
1868
|
return alias;
|
|
1309
1869
|
};
|
|
@@ -1337,19 +1897,21 @@ function getSocialIcons(socialLinks = []) {
|
|
|
1337
1897
|
return icons;
|
|
1338
1898
|
}
|
|
1339
1899
|
function isPluginIncluded(config, pluginName) {
|
|
1340
|
-
return Boolean(config.
|
|
1900
|
+
return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
|
|
1341
1901
|
}
|
|
1342
|
-
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver
|
|
1902
|
+
async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
|
|
1343
1903
|
const cwd = process.cwd();
|
|
1344
|
-
const CUSTOM_THEME_DIR = config?.themeDir ??
|
|
1904
|
+
const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
|
|
1345
1905
|
const outDir = config?.outDir ?? OUTPUT_DIR;
|
|
1346
1906
|
const DEFAULT_THEME = require.resolve('@rspress/theme-default');
|
|
1347
1907
|
const base = config?.base ?? '';
|
|
1348
|
-
const assetPrefix = isProduction() ? (0,
|
|
1908
|
+
const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
|
|
1349
1909
|
const reactVersion = await detectReactVersion();
|
|
1350
1910
|
const normalizeIcon = (icon)=>{
|
|
1351
1911
|
if (!icon) return;
|
|
1352
|
-
|
|
1912
|
+
icon = icon.toString();
|
|
1913
|
+
if (icon.startsWith('file://')) icon = (0, external_node_url_.fileURLToPath)(icon);
|
|
1914
|
+
else if (external_node_path_["default"].isAbsolute(icon)) return external_node_path_["default"].join(userDocRoot, PUBLIC_DIR, icon);
|
|
1353
1915
|
return icon;
|
|
1354
1916
|
};
|
|
1355
1917
|
await hintThemeBreakingChange(CUSTOM_THEME_DIR);
|
|
@@ -1362,22 +1924,25 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1362
1924
|
const context = {
|
|
1363
1925
|
userDocRoot,
|
|
1364
1926
|
config,
|
|
1365
|
-
runtimeTempDir,
|
|
1366
1927
|
routeService,
|
|
1367
1928
|
pluginDriver
|
|
1368
1929
|
};
|
|
1369
1930
|
return {
|
|
1370
1931
|
plugins: [
|
|
1371
|
-
...isPluginIncluded(config,
|
|
1372
|
-
|
|
1932
|
+
...isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [
|
|
1933
|
+
pluginReact()
|
|
1373
1934
|
],
|
|
1374
1935
|
rsbuildPluginDocVM(context),
|
|
1375
1936
|
pluginVirtualModule({
|
|
1937
|
+
tempDir: '.rspress/runtime',
|
|
1376
1938
|
virtualModules: {
|
|
1377
1939
|
...i18nVMPlugin(context),
|
|
1378
1940
|
...globalUIComponentsVMPlugin(context),
|
|
1379
1941
|
...globalStylesVMPlugin(context),
|
|
1380
|
-
...searchHookVMPlugin(context)
|
|
1942
|
+
...searchHookVMPlugin(context),
|
|
1943
|
+
...routeListVMPlugin(context),
|
|
1944
|
+
...await getVirtualModulesFromPlugins(pluginDriver),
|
|
1945
|
+
...runtimeConfigVMPlugin(context)
|
|
1381
1946
|
}
|
|
1382
1947
|
}),
|
|
1383
1948
|
...enableSSG ? [
|
|
@@ -1390,18 +1955,18 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1390
1955
|
],
|
|
1391
1956
|
server: {
|
|
1392
1957
|
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
1958
|
publicDir: {
|
|
1395
|
-
name:
|
|
1396
|
-
}
|
|
1959
|
+
name: external_node_path_["default"].join(userDocRoot, PUBLIC_DIR)
|
|
1960
|
+
},
|
|
1961
|
+
...base.length > 0 ? {
|
|
1962
|
+
base: (0, shared_.removeTrailingSlash)(base)
|
|
1963
|
+
} : {}
|
|
1397
1964
|
},
|
|
1398
1965
|
dev: {
|
|
1399
|
-
|
|
1400
|
-
setupMiddlewares:
|
|
1401
|
-
(
|
|
1402
|
-
|
|
1403
|
-
}
|
|
1404
|
-
],
|
|
1966
|
+
lazyCompilation: 'false' !== process.env.RSPRESS_LAZY_COMPILATION,
|
|
1967
|
+
setupMiddlewares: (middlewares)=>{
|
|
1968
|
+
middlewares.unshift(serveSearchIndexMiddleware(config));
|
|
1969
|
+
},
|
|
1405
1970
|
cliShortcuts: {
|
|
1406
1971
|
custom: (shortcuts)=>shortcuts.filter(({ key })=>'r' !== key)
|
|
1407
1972
|
}
|
|
@@ -1432,24 +1997,39 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1432
1997
|
CUSTOM_THEME_DIR,
|
|
1433
1998
|
DEFAULT_THEME
|
|
1434
1999
|
],
|
|
1435
|
-
'@theme-assets':
|
|
2000
|
+
'@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
|
|
1436
2001
|
'@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'))
|
|
2002
|
+
'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
|
|
1439
2003
|
}
|
|
1440
2004
|
},
|
|
1441
2005
|
source: {
|
|
1442
2006
|
include: [
|
|
1443
2007
|
PACKAGE_ROOT,
|
|
1444
|
-
|
|
2008
|
+
external_node_path_["default"].join(cwd, 'node_modules', shared_.RSPRESS_TEMP_DIR)
|
|
1445
2009
|
],
|
|
1446
2010
|
define: {
|
|
1447
|
-
'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),
|
|
1448
2011
|
'process.env.TEST': JSON.stringify(process.env.TEST),
|
|
1449
2012
|
'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(config.themeConfig?.socialLinks))
|
|
1450
2013
|
}
|
|
1451
2014
|
},
|
|
1452
2015
|
performance: {
|
|
2016
|
+
...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
|
|
2017
|
+
buildCache: {
|
|
2018
|
+
buildDependencies: [
|
|
2019
|
+
pluginDriver.getConfigFilePath()
|
|
2020
|
+
],
|
|
2021
|
+
cacheDigest: [
|
|
2022
|
+
routeService.generateRoutesCode(),
|
|
2023
|
+
JSON.stringify(config.themeConfig?.locales?.map((i)=>({
|
|
2024
|
+
nav: i.nav,
|
|
2025
|
+
sidebar: i.sidebar
|
|
2026
|
+
})) ?? {
|
|
2027
|
+
nav: config.themeConfig?.nav,
|
|
2028
|
+
sidebar: config.themeConfig?.sidebar
|
|
2029
|
+
})
|
|
2030
|
+
]
|
|
2031
|
+
}
|
|
2032
|
+
} : {},
|
|
1453
2033
|
chunkSplit: {
|
|
1454
2034
|
override: {
|
|
1455
2035
|
cacheGroups: {
|
|
@@ -1470,7 +2050,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1470
2050
|
const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
|
|
1471
2051
|
const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
|
|
1472
2052
|
const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
|
|
1473
|
-
chain.module.rule('MDX').type("javascript/auto").test(
|
|
2053
|
+
chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
|
|
1474
2054
|
conditionNames: jsModuleRule.resolve.conditionNames.values(),
|
|
1475
2055
|
mainFields: jsModuleRule.resolve.mainFields.values()
|
|
1476
2056
|
}).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
|
|
@@ -1484,7 +2064,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1484
2064
|
options[0] ??= {};
|
|
1485
2065
|
options[0].include = [
|
|
1486
2066
|
/\.([cm]js|[jt]sx?|flow)$/i,
|
|
1487
|
-
|
|
2067
|
+
shared_.MDX_OR_MD_REGEXP
|
|
1488
2068
|
];
|
|
1489
2069
|
return options;
|
|
1490
2070
|
});
|
|
@@ -1492,13 +2072,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1492
2072
|
chain.module.rule('css-virtual-module').test(/\.rspress[\\/]runtime[\\/]virtual-global-styles/).merge({
|
|
1493
2073
|
sideEffects: true
|
|
1494
2074
|
});
|
|
1495
|
-
if (isServer)
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
}
|
|
1501
|
-
});
|
|
2075
|
+
if (isServer) {
|
|
2076
|
+
chain.output.filename(`${NODE_SSG_BUNDLE_FOLDER}/${NODE_SSG_BUNDLE_NAME}`);
|
|
2077
|
+
chain.output.chunkFilename(`${NODE_SSG_BUNDLE_FOLDER}/[name].cjs`);
|
|
2078
|
+
chain.target('async-node');
|
|
2079
|
+
}
|
|
1502
2080
|
}
|
|
1503
2081
|
},
|
|
1504
2082
|
environments: {
|
|
@@ -1506,14 +2084,17 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1506
2084
|
resolve: {
|
|
1507
2085
|
alias: {
|
|
1508
2086
|
...reactCSRAlias,
|
|
1509
|
-
...reactRouterDomAlias
|
|
1510
|
-
__VIRTUAL_ROUTES__: 'virtual-routes'
|
|
2087
|
+
...reactRouterDomAlias
|
|
1511
2088
|
}
|
|
1512
2089
|
},
|
|
1513
2090
|
source: {
|
|
1514
2091
|
entry: {
|
|
1515
2092
|
index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
|
|
1516
2093
|
},
|
|
2094
|
+
preEntry: [
|
|
2095
|
+
external_node_path_["default"].join(DEFAULT_THEME, '../styles/index.js'),
|
|
2096
|
+
'virtual-global-styles'
|
|
2097
|
+
],
|
|
1517
2098
|
define: {
|
|
1518
2099
|
'process.env.__SSR__': JSON.stringify(false)
|
|
1519
2100
|
}
|
|
@@ -1530,15 +2111,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1530
2111
|
resolve: {
|
|
1531
2112
|
alias: {
|
|
1532
2113
|
...reactSSRAlias,
|
|
1533
|
-
...reactRouterDomAlias
|
|
1534
|
-
__VIRTUAL_ROUTES__: 'virtual-routes-ssr'
|
|
1535
|
-
}
|
|
1536
|
-
},
|
|
1537
|
-
tools: {
|
|
1538
|
-
rspack: {
|
|
1539
|
-
output: {
|
|
1540
|
-
asyncChunks: false
|
|
1541
|
-
}
|
|
2114
|
+
...reactRouterDomAlias
|
|
1542
2115
|
}
|
|
1543
2116
|
},
|
|
1544
2117
|
source: {
|
|
@@ -1566,56 +2139,57 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
|
|
|
1566
2139
|
}
|
|
1567
2140
|
async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
|
|
1568
2141
|
const cwd = process.cwd();
|
|
1569
|
-
const userDocRoot =
|
|
1570
|
-
const
|
|
1571
|
-
const
|
|
1572
|
-
|
|
1573
|
-
await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(runtimeAbsTempDir, {
|
|
2142
|
+
const userDocRoot = external_node_path_["default"].resolve(rootDir || config?.root || cwd);
|
|
2143
|
+
const runtimeTempDir = external_node_path_["default"].join(shared_.RSPRESS_TEMP_DIR, 'runtime');
|
|
2144
|
+
const runtimeAbsTempDir = external_node_path_["default"].join(cwd, 'node_modules', runtimeTempDir);
|
|
2145
|
+
await node_fs_promises.mkdir(runtimeAbsTempDir, {
|
|
1574
2146
|
recursive: true
|
|
1575
2147
|
});
|
|
1576
|
-
const routeService = await
|
|
1577
|
-
config,
|
|
2148
|
+
const routeService = await RouteService.create({
|
|
2149
|
+
config: config,
|
|
1578
2150
|
runtimeTempDir: runtimeAbsTempDir,
|
|
1579
2151
|
scanDir: userDocRoot,
|
|
1580
2152
|
pluginDriver
|
|
1581
2153
|
});
|
|
2154
|
+
const mergedConfig = await modifyConfigWithAutoNavSide(config);
|
|
2155
|
+
hintBuilderPluginsBreakingChange(mergedConfig);
|
|
1582
2156
|
const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
|
|
1583
|
-
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot,
|
|
2157
|
+
const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, mergedConfig, enableSSG, routeService, pluginDriver);
|
|
1584
2158
|
const rsbuild = await createRsbuild({
|
|
1585
|
-
|
|
2159
|
+
callerName: 'rspress',
|
|
2160
|
+
rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], mergedConfig.builderConfig || {}, extraRsbuildConfig || {})
|
|
1586
2161
|
});
|
|
1587
|
-
rsbuild.addPlugins(builderPlugins);
|
|
1588
2162
|
return rsbuild;
|
|
1589
2163
|
}
|
|
1590
2164
|
function checkLanguageParity_normalizePath(filePath) {
|
|
1591
|
-
return filePath.split(
|
|
2165
|
+
return filePath.split(external_node_path_["default"].sep).join('/');
|
|
1592
2166
|
}
|
|
1593
2167
|
async function getAllMarkdownFilesFrom(dirPath) {
|
|
1594
|
-
const files = await
|
|
2168
|
+
const files = await node_fs_promises.readdir(dirPath, {
|
|
1595
2169
|
withFileTypes: true
|
|
1596
2170
|
});
|
|
1597
2171
|
const allFiles = [];
|
|
1598
2172
|
for (const file of files){
|
|
1599
|
-
const fullPath =
|
|
2173
|
+
const fullPath = external_node_path_["default"].join(dirPath, file.name);
|
|
1600
2174
|
if (file.isDirectory()) {
|
|
1601
2175
|
const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
|
|
1602
2176
|
allFiles.push(...nestedFiles);
|
|
1603
2177
|
} else if ([
|
|
1604
2178
|
'.md',
|
|
1605
2179
|
'.mdx'
|
|
1606
|
-
].includes(
|
|
2180
|
+
].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
|
|
1607
2181
|
}
|
|
1608
2182
|
return allFiles;
|
|
1609
2183
|
}
|
|
1610
2184
|
async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
|
|
1611
|
-
const langDirPath =
|
|
1612
|
-
const langModuleDir =
|
|
2185
|
+
const langDirPath = external_node_path_["default"].join(contentPath, lang);
|
|
2186
|
+
const langModuleDir = external_node_path_["default"].join(langDirPath, includedDir);
|
|
1613
2187
|
try {
|
|
1614
|
-
const moduleDirStats = await
|
|
2188
|
+
const moduleDirStats = await node_fs_promises.stat(langModuleDir);
|
|
1615
2189
|
if (!moduleDirStats.isDirectory()) return fileLangMap;
|
|
1616
2190
|
const files = await getAllMarkdownFilesFrom(langModuleDir);
|
|
1617
2191
|
for (const file of files){
|
|
1618
|
-
const relativePath = checkLanguageParity_normalizePath(
|
|
2192
|
+
const relativePath = checkLanguageParity_normalizePath(external_node_path_["default"].relative(langDirPath, file));
|
|
1619
2193
|
if (excludedDirs.some((excludedDir)=>{
|
|
1620
2194
|
const isFilePath = /\.(md|mdx)$/.test(excludedDir);
|
|
1621
2195
|
return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
|
|
@@ -1625,21 +2199,21 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
|
|
|
1625
2199
|
fileLangMap[baseName].add(lang);
|
|
1626
2200
|
}
|
|
1627
2201
|
} catch (e) {
|
|
1628
|
-
|
|
2202
|
+
logger.error(e);
|
|
1629
2203
|
throw new Error(`Failed to access directory: ${checkLanguageParity_normalizePath(langModuleDir)}`);
|
|
1630
2204
|
}
|
|
1631
2205
|
return fileLangMap;
|
|
1632
2206
|
}
|
|
1633
2207
|
async function checkLanguageParity(config) {
|
|
1634
2208
|
if (!config?.languageParity || false === config.languageParity.enabled) return;
|
|
1635
|
-
|
|
1636
|
-
const contentPath =
|
|
2209
|
+
logger.info('Checking language parity...');
|
|
2210
|
+
const contentPath = external_node_path_["default"].resolve(config.root);
|
|
1637
2211
|
const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
|
|
1638
2212
|
''
|
|
1639
2213
|
];
|
|
1640
2214
|
const excludedDirs = config.languageParity.exclude ?? [];
|
|
1641
2215
|
const supportedLanguages = (config.locales ?? config.themeConfig?.locales)?.map((locale)=>locale.lang) || [];
|
|
1642
|
-
if (!supportedLanguages.length) return void
|
|
2216
|
+
if (!supportedLanguages.length) return void logger.error('No supported languages found in the configuration.');
|
|
1643
2217
|
const missingLanguagesFile = [];
|
|
1644
2218
|
try {
|
|
1645
2219
|
for (const includedDir of includedDirs){
|
|
@@ -1649,27 +2223,27 @@ async function checkLanguageParity(config) {
|
|
|
1649
2223
|
for (const [baseName, langs] of Object.entries(curFileLangMap)){
|
|
1650
2224
|
const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
|
|
1651
2225
|
missingLangs.forEach((lang)=>{
|
|
1652
|
-
const missingPath =
|
|
2226
|
+
const missingPath = external_node_path_["default"].join(lang, baseName);
|
|
1653
2227
|
missingLanguagesFile.push(missingPath);
|
|
1654
2228
|
});
|
|
1655
2229
|
}
|
|
1656
2230
|
}
|
|
1657
2231
|
if (missingLanguagesFile.length > 0) throw new Error(`Check language parity failed! Missing content:\n${missingLanguagesFile.map((file)=>` - ${checkLanguageParity_normalizePath(file)}`).join('\n')}`);
|
|
1658
|
-
|
|
2232
|
+
logger.success('Language parity checked successfully.');
|
|
1659
2233
|
} catch (err) {
|
|
1660
|
-
|
|
2234
|
+
logger.error('Error during language parity check: \n', err);
|
|
1661
2235
|
throw err;
|
|
1662
2236
|
}
|
|
1663
2237
|
}
|
|
1664
2238
|
async function dev(options) {
|
|
1665
|
-
const { docDirectory, config, extraBuilderConfig } = options;
|
|
2239
|
+
const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
|
|
1666
2240
|
const isProd = false;
|
|
1667
|
-
const pluginDriver = new PluginDriver(config, isProd);
|
|
2241
|
+
const pluginDriver = new PluginDriver(config, configFilePath, isProd);
|
|
1668
2242
|
await pluginDriver.init();
|
|
1669
2243
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1670
2244
|
try {
|
|
1671
|
-
await pluginDriver.beforeBuild();
|
|
1672
2245
|
const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
|
|
2246
|
+
await pluginDriver.beforeBuild();
|
|
1673
2247
|
rsbuild.onDevCompileDone(async ()=>{
|
|
1674
2248
|
await pluginDriver.afterBuild();
|
|
1675
2249
|
});
|
|
@@ -1685,44 +2259,44 @@ async function dev(options) {
|
|
|
1685
2259
|
async function bundle(docDirectory, config, pluginDriver, enableSSG) {
|
|
1686
2260
|
try {
|
|
1687
2261
|
const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
|
|
2262
|
+
await pluginDriver.beforeBuild();
|
|
1688
2263
|
await rsbuild.build();
|
|
1689
2264
|
} finally{
|
|
1690
2265
|
await writeSearchIndex(config);
|
|
1691
2266
|
await checkLanguageParity(config);
|
|
1692
2267
|
}
|
|
2268
|
+
await pluginDriver.afterBuild();
|
|
1693
2269
|
}
|
|
1694
2270
|
function emptyDir(path) {
|
|
1695
|
-
return
|
|
2271
|
+
return node_fs_promises.rm(path, {
|
|
1696
2272
|
force: true,
|
|
1697
2273
|
recursive: true
|
|
1698
2274
|
});
|
|
1699
2275
|
}
|
|
1700
2276
|
async function build(options) {
|
|
1701
|
-
const { docDirectory, config } = options;
|
|
1702
|
-
const pluginDriver = new PluginDriver(config, true);
|
|
2277
|
+
const { docDirectory, config, configFilePath } = options;
|
|
2278
|
+
const pluginDriver = new PluginDriver(config, configFilePath, true);
|
|
1703
2279
|
await pluginDriver.init();
|
|
1704
2280
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1705
|
-
await pluginDriver.beforeBuild();
|
|
1706
2281
|
const ssgConfig = modifiedConfig.ssg ?? true;
|
|
1707
2282
|
await emptyDir(constants_TEMP_DIR);
|
|
1708
2283
|
await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
|
|
1709
2284
|
if (!ssgConfig) hintSSGFalse();
|
|
1710
|
-
await pluginDriver.afterBuild();
|
|
1711
2285
|
}
|
|
1712
2286
|
async function serve(options) {
|
|
1713
|
-
const { config, port: userPort, host: userHost } = options;
|
|
2287
|
+
const { config, port: userPort, host: userHost, configFilePath } = options;
|
|
1714
2288
|
const envPort = process.env.PORT;
|
|
1715
2289
|
const envHost = process.env.HOST;
|
|
1716
2290
|
const { builderConfig } = config;
|
|
1717
2291
|
const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
|
|
1718
2292
|
const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
|
|
1719
|
-
config.builderConfig = (
|
|
2293
|
+
config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
|
|
1720
2294
|
server: {
|
|
1721
2295
|
port,
|
|
1722
2296
|
host
|
|
1723
2297
|
}
|
|
1724
2298
|
});
|
|
1725
|
-
const pluginDriver = new PluginDriver(config, true);
|
|
2299
|
+
const pluginDriver = new PluginDriver(config, configFilePath, true);
|
|
1726
2300
|
await pluginDriver.init();
|
|
1727
2301
|
const modifiedConfig = await pluginDriver.modifyConfig();
|
|
1728
2302
|
const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
|
|
@@ -1757,40 +2331,71 @@ const getASTNodeImport = (name, from)=>({
|
|
|
1757
2331
|
}
|
|
1758
2332
|
}
|
|
1759
2333
|
});
|
|
1760
|
-
function
|
|
2334
|
+
function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
|
|
2335
|
+
const errorInfos = [];
|
|
2336
|
+
let possibleBreakingChange = false;
|
|
2337
|
+
[
|
|
2338
|
+
...internalLinks.entries()
|
|
2339
|
+
].forEach(([nodeUrl, link])=>{
|
|
2340
|
+
const cleanLinkPath = linkToRoutePath(link);
|
|
2341
|
+
if (!cleanLinkPath) return;
|
|
2342
|
+
if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
|
|
2343
|
+
if (!routeService.isExistRoute((0, shared_.removeTrailingSlash)(cleanLinkPath)) && !routeService.isExistRoute((0, shared_.addTrailingSlash)(cleanLinkPath))) errorInfos.push([
|
|
2344
|
+
nodeUrl,
|
|
2345
|
+
link
|
|
2346
|
+
]);
|
|
2347
|
+
});
|
|
2348
|
+
if (errorInfos.length > 0) {
|
|
2349
|
+
if (possibleBreakingChange) hintRelativeMarkdownLink();
|
|
2350
|
+
logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
|
|
2351
|
+
${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
|
|
2352
|
+
if ((0, shared_.isProduction)()) throw new Error('Dead link found');
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
|
|
1761
2356
|
if (!nodeUrl) return '';
|
|
1762
|
-
if (nodeUrl.startsWith('#')) return
|
|
1763
|
-
let { url, hash } = (0,
|
|
1764
|
-
if ((0,
|
|
1765
|
-
|
|
1766
|
-
if (
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
const
|
|
1771
|
-
url =
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
}
|
|
1775
|
-
if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
|
|
2357
|
+
if (nodeUrl.startsWith('#')) return nodeUrl;
|
|
2358
|
+
let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
|
|
2359
|
+
if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
|
|
2360
|
+
if (!routeService) return nodeUrl;
|
|
2361
|
+
if (url.startsWith('/')) {
|
|
2362
|
+
const { routePath } = routeService.normalizeRoutePath(url);
|
|
2363
|
+
url = routePath;
|
|
2364
|
+
} else {
|
|
2365
|
+
const anotherFileAbsolutePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filePath), url);
|
|
2366
|
+
url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
|
|
2367
|
+
}
|
|
2368
|
+
if ('boolean' == typeof cleanUrls) url = (0, shared_.normalizeHref)(url, cleanUrls);
|
|
1776
2369
|
else {
|
|
1777
|
-
url = (0,
|
|
2370
|
+
url = (0, shared_.normalizeHref)(url, false);
|
|
1778
2371
|
url = url.replace(/\.html$/, cleanUrls);
|
|
1779
2372
|
}
|
|
2373
|
+
internalLinks.set(nodeUrl, url);
|
|
1780
2374
|
if (hash) url += `#${hash}`;
|
|
2375
|
+
if (__base) url = (0, shared_.withBase)(url, __base);
|
|
1781
2376
|
return url;
|
|
1782
2377
|
}
|
|
2378
|
+
function linkToRoutePath(routePath) {
|
|
2379
|
+
return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
|
|
2380
|
+
}
|
|
1783
2381
|
const normalizeImageUrl = (imageUrl)=>{
|
|
1784
|
-
if ((0,
|
|
2382
|
+
if ((0, shared_.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
1785
2383
|
return imageUrl;
|
|
1786
2384
|
};
|
|
1787
|
-
const remarkPluginNormalizeLink = ({
|
|
1788
|
-
const
|
|
1789
|
-
|
|
2385
|
+
const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
|
|
2386
|
+
const internalLinks = new Map();
|
|
2387
|
+
visit(tree, 'link', (node)=>{
|
|
2388
|
+
const { url: nodeUrl } = node;
|
|
2389
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
2390
|
+
node.url = link;
|
|
2391
|
+
});
|
|
2392
|
+
visit(tree, 'definition', (node)=>{
|
|
1790
2393
|
const { url: nodeUrl } = node;
|
|
1791
|
-
const
|
|
1792
|
-
node.url =
|
|
2394
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
2395
|
+
node.url = link;
|
|
1793
2396
|
});
|
|
2397
|
+
if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
|
|
2398
|
+
const images = [];
|
|
1794
2399
|
const getMdxSrcAttribute = (tempVar)=>({
|
|
1795
2400
|
type: 'mdxJsxAttribute',
|
|
1796
2401
|
name: 'src',
|
|
@@ -1814,7 +2419,7 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1814
2419
|
}
|
|
1815
2420
|
}
|
|
1816
2421
|
});
|
|
1817
|
-
|
|
2422
|
+
visit(tree, 'image', (node)=>{
|
|
1818
2423
|
const { alt, url } = node;
|
|
1819
2424
|
if (!url) return;
|
|
1820
2425
|
const imagePath = normalizeImageUrl(url);
|
|
@@ -1835,9 +2440,9 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1835
2440
|
});
|
|
1836
2441
|
images.push(getASTNodeImport(tempVariableName, imagePath));
|
|
1837
2442
|
});
|
|
1838
|
-
|
|
2443
|
+
visit(tree, (node)=>{
|
|
1839
2444
|
if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
|
|
1840
|
-
const srcAttr =
|
|
2445
|
+
const srcAttr = getNodeAttribute(node, 'src', true);
|
|
1841
2446
|
if ('string' != typeof srcAttr?.value) return;
|
|
1842
2447
|
const imagePath = normalizeImageUrl(srcAttr.value);
|
|
1843
2448
|
if (!imagePath) return;
|
|
@@ -1847,5 +2452,56 @@ const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, fi
|
|
|
1847
2452
|
});
|
|
1848
2453
|
tree.children.unshift(...images);
|
|
1849
2454
|
};
|
|
1850
|
-
|
|
1851
|
-
|
|
2455
|
+
const ERROR_PREFIX = '[remarkFileCodeBlock]';
|
|
2456
|
+
function parseFileFromMeta(meta) {
|
|
2457
|
+
if (!meta) return '';
|
|
2458
|
+
const kvList = meta.split(' ').filter(Boolean);
|
|
2459
|
+
for (const item of kvList){
|
|
2460
|
+
const [k, v] = item.split('=');
|
|
2461
|
+
if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
|
|
2462
|
+
}
|
|
2463
|
+
return '';
|
|
2464
|
+
}
|
|
2465
|
+
const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
|
|
2466
|
+
const promiseList = [];
|
|
2467
|
+
visit(tree, 'code', (node)=>{
|
|
2468
|
+
const { meta, value } = node;
|
|
2469
|
+
const file = parseFileFromMeta(meta ?? '');
|
|
2470
|
+
if (!file) return;
|
|
2471
|
+
if (file.startsWith('./') || file.startsWith('../')) {
|
|
2472
|
+
const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
|
|
2473
|
+
if ('' !== value.trim()) {
|
|
2474
|
+
logger.error(`${ERROR_PREFIX} The content of file code block should be empty.
|
|
2475
|
+
|
|
2476
|
+
\`\`\`tsx file="./filename"
|
|
2477
|
+
content
|
|
2478
|
+
\`\`\`
|
|
2479
|
+
|
|
2480
|
+
this usage is not allowed, please use below:
|
|
2481
|
+
|
|
2482
|
+
\`\`\`tsx file="./filename"
|
|
2483
|
+
\`\`\`
|
|
2484
|
+
`);
|
|
2485
|
+
throw new Error(`${ERROR_PREFIX} The content of file code block should be empty.`);
|
|
2486
|
+
}
|
|
2487
|
+
const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
|
|
2488
|
+
node.value = fileContent;
|
|
2489
|
+
}).catch((e)=>{
|
|
2490
|
+
logger.error(`${ERROR_PREFIX} The file does not exist.
|
|
2491
|
+
\`file="${file}"\` is resolved to ${resolvedFilePath}"`);
|
|
2492
|
+
throw e;
|
|
2493
|
+
});
|
|
2494
|
+
promiseList.push(promise);
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
throw new Error(`${ERROR_PREFIX} The file path should use relative path "./" or "../"`);
|
|
2498
|
+
});
|
|
2499
|
+
await Promise.all(promiseList);
|
|
2500
|
+
};
|
|
2501
|
+
var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
|
|
2502
|
+
var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
|
|
2503
|
+
var __webpack_exports__normalizeHref = shared_.normalizeHref;
|
|
2504
|
+
var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
|
|
2505
|
+
var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
|
|
2506
|
+
var __webpack_exports__withBase = shared_.withBase;
|
|
2507
|
+
export { build, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkPluginNormalizeLink, 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 };
|