@rspress/core 2.0.0-beta.22 → 2.0.0-beta.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- import __rslib_shim_module__ from 'module';
3
- const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
4
2
  import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
5
3
  import * as __WEBPACK_EXTERNAL_MODULE_child_process__ from "child_process";
6
4
  import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
@@ -15,13 +13,15 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
15
13
  import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
16
14
  import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
17
15
  import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
16
+ import { matchPath } from "@rspress/runtime/server";
17
+ import { logger } from "@rspress/shared/logger";
18
+ import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
18
19
  import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
20
+ import { createRequire } from "node:module";
19
21
  import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
20
22
  import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
21
- import { logger } from "@rspress/shared/logger";
22
23
  import picocolors from "picocolors";
23
24
  import { glob } from "tinyglobby";
24
- import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
25
25
  import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
26
26
  import { chunk, groupBy } from "lodash-es";
27
27
  import { compile } from "@rspress/mdx-rs";
@@ -30,9 +30,8 @@ import { createProcessor } from "@mdx-js/mdx";
30
30
  import enhanced_resolve from "enhanced-resolve";
31
31
  import { createHash } from "node:crypto";
32
32
  import { createHead, transformHtmlTemplate } from "@unhead/react/server";
33
- import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
34
33
  import { visit } from "unist-util-visit";
35
- import { matchPath } from "@rspress/runtime/server";
34
+ import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
36
35
  var __webpack_modules__ = {
37
36
  "@rspress/shared": function(module) {
38
37
  module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
@@ -146,124 +145,39 @@ __webpack_require__.m = __webpack_modules__;
146
145
  }
147
146
  };
148
147
  })();
149
- class PluginDriver {
150
- #config;
151
- #configFilePath;
152
- #plugins;
153
- #isProd;
154
- constructor(config, configFilePath, isProd){
155
- this.#config = config;
156
- this.#configFilePath = configFilePath;
157
- this.#isProd = isProd;
158
- this.#plugins = [];
159
- }
160
- getConfigFilePath() {
161
- return this.#configFilePath;
162
- }
163
- async init() {
164
- this.clearPlugins();
165
- const config = this.#config;
166
- const themeConfig = config?.themeConfig || {};
167
- const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
168
- const mediumZoomConfig = config?.mediumZoom ?? true;
169
- if (enableLastUpdated) {
170
- const { pluginLastUpdated } = await Promise.all([
171
- __webpack_require__.e("94"),
172
- __webpack_require__.e("208")
173
- ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
174
- this.addPlugin(pluginLastUpdated());
175
- }
176
- if (mediumZoomConfig) {
177
- const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
178
- this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
179
- }
180
- (config.plugins || []).forEach((plugin)=>{
181
- this.addPlugin(plugin);
182
- });
183
- }
184
- addPlugin(plugin) {
185
- const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
186
- if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
187
- this.#plugins.push(plugin);
188
- }
189
- getPlugins() {
190
- return this.#plugins;
191
- }
192
- clearPlugins() {
193
- this.#plugins = [];
194
- }
195
- removePlugin(pluginName) {
196
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
197
- if (-1 !== index) this.#plugins.splice(index, 1);
198
- }
199
- async modifyConfig() {
200
- let config = this.#config;
201
- for(let i = 0; i < this.#plugins.length; i++){
202
- const plugin = this.#plugins[i];
203
- if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
204
- addPlugin: this.addPlugin.bind(this),
205
- removePlugin: (pluginName)=>{
206
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
207
- this.removePlugin(pluginName);
208
- if (index <= i && index > 0) i--;
209
- }
210
- }, this.#isProd);
211
- }
212
- this.#config = config;
213
- return this.#config;
214
- }
215
- async beforeBuild() {
216
- return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
217
- }
218
- async afterBuild() {
219
- return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
220
- }
221
- async modifySearchIndexData(pages) {
222
- return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
223
- }
224
- async extendPageData(pageData) {
225
- return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
226
- }
227
- async addPages() {
228
- const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
229
- return result.flat();
230
- }
231
- async routeGenerated(routes) {
232
- return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
233
- }
234
- async routeServiceGenerated(routeService) {
235
- return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
236
- }
237
- async addRuntimeModules() {
238
- const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
239
- return result.reduce((prev, current)=>({
240
- ...prev,
241
- ...current
242
- }), {});
243
- }
244
- globalUIComponents() {
245
- const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
246
- return result.flat();
247
- }
248
- globalStyles() {
249
- return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
250
- }
251
- _runParallelAsyncHook(hookName, ...args) {
252
- return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
253
- }
254
- _runSerialAsyncHook(hookName, ...args) {
255
- return this.#plugins.reduce(async (prev, plugin)=>{
256
- if ('function' == typeof plugin[hookName]) {
257
- await prev;
258
- return plugin[hookName](...args);
259
- }
260
- return prev;
261
- }, Promise.resolve());
262
- }
148
+ var shared_ = __webpack_require__("@rspress/shared");
149
+ function defineConfig(config) {
150
+ return config;
263
151
  }
264
152
  var external_node_path_ = __webpack_require__("node:path");
265
153
  var external_node_url_ = __webpack_require__("node:url");
266
- var shared_ = __webpack_require__("@rspress/shared");
154
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.24"}');
155
+ const RSPRESS_VERSION = package_namespaceObject.i8;
156
+ const isProduction = ()=>'production' === process.env.NODE_ENV;
157
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
158
+ const inlineThemeScript = `{
159
+ const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
160
+ const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
161
+ const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
162
+ document.documentElement.classList.toggle('dark', isDark)
163
+ document.documentElement.classList.toggle('rp-dark', isDark)
164
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
165
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
166
+ const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
167
+ const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
168
+ const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
169
+ const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
170
+ const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
171
+ const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
172
+ const OUTPUT_DIR = 'doc_build';
173
+ const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
174
+ const HEAD_MARKER = '<!--<?- HEAD ?>-->';
175
+ const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
176
+ const DEFAULT_TITLE = 'Rspress';
177
+ const PUBLIC_DIR = 'public';
178
+ const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
179
+ const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
180
+ const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
267
181
  const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
268
182
  const pluginVirtualModule = (pluginOptions = {})=>({
269
183
  name: PLUGIN_VIRTUAL_MODULE_NAME,
@@ -403,34 +317,15 @@ function slash(p) {
403
317
  function normalizePath(id) {
404
318
  return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
405
319
  }
406
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.22"}');
407
- const RSPRESS_VERSION = package_namespaceObject.i8;
408
- const isProduction = ()=>'production' === process.env.NODE_ENV;
409
- const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
410
- const inlineThemeScript = `{
411
- const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
412
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
413
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
414
- document.documentElement.classList.toggle('dark', isDark)
415
- document.documentElement.classList.toggle('rp-dark', isDark)
416
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
417
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
418
- const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
419
- const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
420
- const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
421
- const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
422
- const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
423
- const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
424
- const OUTPUT_DIR = 'doc_build';
425
- const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
426
- const HEAD_MARKER = '<!--<?- HEAD ?>-->';
427
- const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
428
- const DEFAULT_TITLE = 'Rspress';
429
- const PUBLIC_DIR = 'public';
430
- const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
431
- const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
432
- const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
433
320
  const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
321
+ const [versionPart, langPart, purePath] = splitRoutePathParts(relativePath, lang, version, langs, versions);
322
+ return [
323
+ versionPart === version ? '' : versionPart,
324
+ langPart === lang ? '' : langPart,
325
+ purePath
326
+ ];
327
+ };
328
+ const splitRoutePathParts = (relativePath, lang, version, langs, versions)=>{
434
329
  const hasTrailSlash = relativePath.endsWith('/');
435
330
  let versionPart = '';
436
331
  let langPart = '';
@@ -438,17 +333,11 @@ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
438
333
  const parts = relativePath.split('/').filter(Boolean);
439
334
  if (version) {
440
335
  const versionToMatch = parts[0];
441
- if (versions.includes(versionToMatch)) {
442
- if (versionToMatch !== version) versionPart = versionToMatch;
443
- parts.shift();
444
- }
336
+ if (versions.includes(versionToMatch)) versionPart = parts.shift() ?? '';
445
337
  }
446
338
  if (lang) {
447
339
  const langToMatch = parts[0];
448
- if (langs.includes(langToMatch)) {
449
- if (langToMatch !== lang) langPart = langToMatch;
450
- parts.shift();
451
- }
340
+ if (langs.includes(langToMatch)) langPart = parts.shift() ?? '';
452
341
  }
453
342
  purePathPart = parts.join('/');
454
343
  return [
@@ -461,6 +350,7 @@ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extens
461
350
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
462
351
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
463
352
  let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
353
+ if (routePath.endsWith('/')) routePath = `${routePath}index`;
464
354
  const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
465
355
  routePath = purePathPart.replace(/\/index$/, '/');
466
356
  if ('index' === routePath) routePath = '';
@@ -482,13 +372,14 @@ class RouteService {
482
372
  routeData = new Map();
483
373
  #scanDir;
484
374
  #defaultLang;
485
- #defaultVersion = '';
486
- #extensions = [];
487
- #langs = [];
488
- #versions = [];
489
- #include = [];
490
- #exclude = [];
491
- #tempDir = '';
375
+ #defaultVersion;
376
+ #extensions;
377
+ #langs;
378
+ #versions;
379
+ #include;
380
+ #exclude;
381
+ #excludeConvention;
382
+ #tempDir;
492
383
  #pluginDriver;
493
384
  static __instance__ = null;
494
385
  static getInstance() {
@@ -508,6 +399,9 @@ class RouteService {
508
399
  this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
509
400
  this.#include = routeOptions.include || [];
510
401
  this.#exclude = routeOptions.exclude || [];
402
+ this.#excludeConvention = routeOptions.excludeConvention || [
403
+ '**/_[^_]*'
404
+ ];
511
405
  this.#defaultLang = userConfig?.lang || '';
512
406
  this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
513
407
  this.#tempDir = tempDir;
@@ -515,6 +409,9 @@ class RouteService {
515
409
  if (userConfig.multiVersion) {
516
410
  this.#defaultVersion = userConfig.multiVersion.default || '';
517
411
  this.#versions = userConfig.multiVersion.versions || [];
412
+ } else {
413
+ this.#defaultVersion = '';
414
+ this.#versions = [];
518
415
  }
519
416
  }
520
417
  get extensions() {
@@ -531,10 +428,12 @@ class RouteService {
531
428
  onlyFiles: true,
532
429
  ignore: [
533
430
  ...this.#exclude,
431
+ ...this.#excludeConvention,
534
432
  '**/node_modules/**',
535
433
  '**/.eslintrc.js',
536
434
  '**/.nx/**',
537
- `./${PUBLIC_DIR}/**`
435
+ `./${PUBLIC_DIR}/**`,
436
+ '**/*.d.ts'
538
437
  ]
539
438
  })).sort();
540
439
  files.forEach((filePath)=>{
@@ -594,12 +493,19 @@ ${routeMeta.map((route, index)=>{
594
493
  getRoutePathParts(relativePath) {
595
494
  return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
596
495
  }
496
+ splitRoutePathParts(relativePath) {
497
+ return splitRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
498
+ }
597
499
  normalizeRoutePath(relativePath) {
598
500
  return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
599
501
  }
600
502
  absolutePathToRoutePath(absolutePath) {
601
503
  return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
602
504
  }
505
+ isInDocsDir(absolutePath) {
506
+ const relativePath = external_node_path_["default"].relative(this.#scanDir, absolutePath);
507
+ return !relativePath.startsWith('..') && !external_node_path_["default"].isAbsolute(relativePath);
508
+ }
603
509
  absolutePathToRelativePath(absolutePath) {
604
510
  return absolutePathToRelativePath(absolutePath, this.#scanDir);
605
511
  }
@@ -894,7 +800,7 @@ async function scanNav(workDir, docsDir) {
894
800
  const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
895
801
  try {
896
802
  navConfig = await utils_readJson(rootNavJson);
897
- } catch (e) {
803
+ } catch (_e) {
898
804
  logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
899
805
  navConfig = [];
900
806
  }
@@ -1199,12 +1105,13 @@ var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
1199
1105
  RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
1200
1106
  return RuntimeModuleID;
1201
1107
  }({});
1108
+ const i18n_require = createRequire(import.meta.url);
1202
1109
  const DEFAULT_I18N_SOURCE = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
1203
1110
  function getI18nData(docConfig) {
1204
1111
  const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
1205
1112
  try {
1206
- delete require.cache[i18nSourcePath];
1207
- const i18nSource = require(i18nSourcePath);
1113
+ delete i18n_require.cache[i18nSourcePath];
1114
+ const i18nSource = i18n_require(i18nSourcePath);
1208
1115
  return i18nSource;
1209
1116
  } catch (e) {
1210
1117
  logger.debug('getI18nData Failed: \n', e);
@@ -1378,7 +1285,7 @@ async function siteDataVMPlugin(context) {
1378
1285
  mode: 'local'
1379
1286
  },
1380
1287
  pages: pages.map((page)=>{
1381
- const { content, _filepath, _html, _flattenContent, ...rest } = page;
1288
+ const { content: _content, _filepath, _html, _flattenContent, ...rest } = page;
1382
1289
  return isProduction() ? rest : {
1383
1290
  ...rest,
1384
1291
  _filepath
@@ -2017,11 +1924,12 @@ function getSocialIcons(socialLinks = []) {
2017
1924
  function isPluginIncluded(config, pluginName) {
2018
1925
  return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
2019
1926
  }
1927
+ const initRsbuild_require = createRequire(import.meta.url);
2020
1928
  async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
2021
1929
  const cwd = process.cwd();
2022
1930
  const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
2023
1931
  const outDir = config?.outDir ?? OUTPUT_DIR;
2024
- const DEFAULT_THEME = require.resolve('@rspress/theme-default');
1932
+ const DEFAULT_THEME = initRsbuild_require.resolve('@rspress/theme-default');
2025
1933
  const base = config?.base ?? '';
2026
1934
  const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
2027
1935
  const reactVersion = await detectReactVersion();
@@ -2110,13 +2018,13 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2110
2018
  resolve: {
2111
2019
  alias: {
2112
2020
  ...detectCustomIconAlias,
2113
- '@mdx-js/react': require.resolve('@mdx-js/react'),
2021
+ '@mdx-js/react': initRsbuild_require.resolve('@mdx-js/react'),
2114
2022
  '@theme': [
2115
2023
  CUSTOM_THEME_DIR,
2116
2024
  DEFAULT_THEME
2117
2025
  ],
2118
2026
  '@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
2119
- 'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
2027
+ 'react-lazy-with-preload': initRsbuild_require.resolve('react-lazy-with-preload')
2120
2028
  }
2121
2029
  },
2122
2030
  source: {
@@ -2133,6 +2041,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2133
2041
  ...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
2134
2042
  buildCache: {
2135
2043
  buildDependencies: [
2044
+ (0, external_node_url_.fileURLToPath)(import.meta.url),
2136
2045
  pluginDriver.getConfigFilePath()
2137
2046
  ],
2138
2047
  cacheDigest: [
@@ -2143,11 +2052,6 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2143
2052
  })) ?? {
2144
2053
  nav: config.themeConfig?.nav,
2145
2054
  sidebar: config.themeConfig?.sidebar
2146
- }),
2147
- JSON.stringify({
2148
- base: config.base,
2149
- ssg: config.ssg,
2150
- pluginLength: config.plugins?.length ?? 0
2151
2055
  })
2152
2056
  ]
2153
2057
  }
@@ -2171,14 +2075,12 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2171
2075
  const isServer = 'node' === target;
2172
2076
  const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
2173
2077
  const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
2174
- const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
2175
2078
  chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
2176
2079
  conditionNames: jsModuleRule.resolve.conditionNames.values(),
2177
2080
  mainFields: jsModuleRule.resolve.mainFields.values()
2178
- }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
2081
+ }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(initRsbuild_require.resolve('./loader.js')).options({
2179
2082
  config,
2180
2083
  docDirectory: userDocRoot,
2181
- checkDeadLinks,
2182
2084
  routeService,
2183
2085
  pluginDriver
2184
2086
  }).end();
@@ -2283,6 +2185,121 @@ async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuil
2283
2185
  });
2284
2186
  return rsbuild;
2285
2187
  }
2188
+ class PluginDriver {
2189
+ #config;
2190
+ #configFilePath;
2191
+ #plugins;
2192
+ #isProd;
2193
+ constructor(config, configFilePath, isProd){
2194
+ this.#config = config;
2195
+ this.#configFilePath = configFilePath;
2196
+ this.#isProd = isProd;
2197
+ this.#plugins = [];
2198
+ }
2199
+ getConfigFilePath() {
2200
+ return this.#configFilePath;
2201
+ }
2202
+ async init() {
2203
+ this.clearPlugins();
2204
+ const config = this.#config;
2205
+ const themeConfig = config?.themeConfig || {};
2206
+ const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
2207
+ const mediumZoomConfig = config?.mediumZoom ?? true;
2208
+ if (enableLastUpdated) {
2209
+ const { pluginLastUpdated } = await Promise.all([
2210
+ __webpack_require__.e("94"),
2211
+ __webpack_require__.e("208")
2212
+ ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
2213
+ this.addPlugin(pluginLastUpdated());
2214
+ }
2215
+ if (mediumZoomConfig) {
2216
+ const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
2217
+ this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
2218
+ }
2219
+ (config.plugins || []).forEach((plugin)=>{
2220
+ this.addPlugin(plugin);
2221
+ });
2222
+ }
2223
+ addPlugin(plugin) {
2224
+ const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
2225
+ if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
2226
+ this.#plugins.push(plugin);
2227
+ }
2228
+ getPlugins() {
2229
+ return this.#plugins;
2230
+ }
2231
+ clearPlugins() {
2232
+ this.#plugins = [];
2233
+ }
2234
+ removePlugin(pluginName) {
2235
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2236
+ if (-1 !== index) this.#plugins.splice(index, 1);
2237
+ }
2238
+ async modifyConfig() {
2239
+ let config = this.#config;
2240
+ for(let i = 0; i < this.#plugins.length; i++){
2241
+ const plugin = this.#plugins[i];
2242
+ if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
2243
+ addPlugin: this.addPlugin.bind(this),
2244
+ removePlugin: (pluginName)=>{
2245
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2246
+ this.removePlugin(pluginName);
2247
+ if (index <= i && index > 0) i--;
2248
+ }
2249
+ }, this.#isProd);
2250
+ }
2251
+ this.#config = config;
2252
+ return this.#config;
2253
+ }
2254
+ async beforeBuild() {
2255
+ return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
2256
+ }
2257
+ async afterBuild() {
2258
+ return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
2259
+ }
2260
+ async modifySearchIndexData(pages) {
2261
+ return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
2262
+ }
2263
+ async extendPageData(pageData) {
2264
+ return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
2265
+ }
2266
+ async addPages() {
2267
+ const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
2268
+ return result.flat();
2269
+ }
2270
+ async routeGenerated(routes) {
2271
+ return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
2272
+ }
2273
+ async routeServiceGenerated(routeService) {
2274
+ return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
2275
+ }
2276
+ async addRuntimeModules() {
2277
+ const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
2278
+ return result.reduce((prev, current)=>({
2279
+ ...prev,
2280
+ ...current
2281
+ }), {});
2282
+ }
2283
+ globalUIComponents() {
2284
+ const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
2285
+ return result.flat();
2286
+ }
2287
+ globalStyles() {
2288
+ return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
2289
+ }
2290
+ _runParallelAsyncHook(hookName, ...args) {
2291
+ return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
2292
+ }
2293
+ _runSerialAsyncHook(hookName, ...args) {
2294
+ return this.#plugins.reduce(async (prev, plugin)=>{
2295
+ if ('function' == typeof plugin[hookName]) {
2296
+ await prev;
2297
+ return plugin[hookName](...args);
2298
+ }
2299
+ return prev;
2300
+ }, Promise.resolve());
2301
+ }
2302
+ }
2286
2303
  function checkLanguageParity_normalizePath(filePath) {
2287
2304
  return filePath.split(external_node_path_["default"].sep).join('/');
2288
2305
  }
@@ -2357,27 +2374,6 @@ async function checkLanguageParity(config) {
2357
2374
  throw err;
2358
2375
  }
2359
2376
  }
2360
- async function dev(options) {
2361
- const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
2362
- const isProd = false;
2363
- const pluginDriver = new PluginDriver(config, configFilePath, isProd);
2364
- await pluginDriver.init();
2365
- const modifiedConfig = await pluginDriver.modifyConfig();
2366
- try {
2367
- const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
2368
- await pluginDriver.beforeBuild();
2369
- rsbuild.onDevCompileDone(async ()=>{
2370
- await pluginDriver.afterBuild();
2371
- });
2372
- const { server } = await rsbuild.startDevServer({
2373
- getPortSilently: true
2374
- });
2375
- return server;
2376
- } finally{
2377
- await writeSearchIndex(modifiedConfig);
2378
- await checkLanguageParity(modifiedConfig);
2379
- }
2380
- }
2381
2377
  async function bundle(docDirectory, config, pluginDriver, enableSSG) {
2382
2378
  try {
2383
2379
  const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
@@ -2405,60 +2401,93 @@ async function build(options) {
2405
2401
  await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
2406
2402
  if (!ssgConfig) hintSSGFalse();
2407
2403
  }
2408
- async function serve(options) {
2409
- const { config, port: userPort, host: userHost, configFilePath } = options;
2410
- const envPort = process.env.PORT;
2411
- const envHost = process.env.HOST;
2412
- const { builderConfig } = config;
2413
- const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
2414
- const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
2415
- config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
2416
- server: {
2417
- port,
2418
- host
2419
- }
2420
- });
2421
- const pluginDriver = new PluginDriver(config, configFilePath, true);
2404
+ async function dev(options) {
2405
+ const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
2406
+ const isProd = false;
2407
+ const pluginDriver = new PluginDriver(config, configFilePath, isProd);
2422
2408
  await pluginDriver.init();
2423
2409
  const modifiedConfig = await pluginDriver.modifyConfig();
2424
- const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
2425
- return rsbuild.preview();
2410
+ try {
2411
+ const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
2412
+ await pluginDriver.beforeBuild();
2413
+ rsbuild.onDevCompileDone(async ()=>{
2414
+ await pluginDriver.afterBuild();
2415
+ });
2416
+ const { server } = await rsbuild.startDevServer({
2417
+ getPortSilently: true
2418
+ });
2419
+ return server;
2420
+ } finally{
2421
+ await writeSearchIndex(modifiedConfig);
2422
+ await checkLanguageParity(modifiedConfig);
2423
+ }
2426
2424
  }
2427
- const getASTNodeImport = (name, from)=>({
2428
- type: 'mdxjsEsm',
2429
- value: `import ${name} from ${JSON.stringify(from)}`,
2430
- data: {
2431
- estree: {
2432
- type: 'Program',
2433
- sourceType: 'module',
2434
- body: [
2435
- {
2436
- type: 'ImportDeclaration',
2437
- specifiers: [
2438
- {
2439
- type: 'ImportDefaultSpecifier',
2440
- local: {
2441
- type: 'Identifier',
2442
- name
2443
- }
2444
- }
2445
- ],
2446
- source: {
2447
- type: 'Literal',
2448
- value: from,
2449
- raw: `${JSON.stringify(from)}`
2450
- }
2451
- }
2452
- ]
2425
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
2426
+ function parseFileFromMeta(meta) {
2427
+ if (!meta) return '';
2428
+ const kvList = meta.split(' ').filter(Boolean);
2429
+ for (const item of kvList){
2430
+ const [k, v = ''] = item.split('=');
2431
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
2432
+ }
2433
+ return '';
2434
+ }
2435
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
2436
+ const promiseList = [];
2437
+ visit(tree, 'code', (node)=>{
2438
+ const { meta, value, lang } = node;
2439
+ const file = parseFileFromMeta(meta ?? '');
2440
+ if (!file) return;
2441
+ const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
2442
+ if (file.startsWith('./') || file.startsWith('../')) {
2443
+ const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2444
+ if ('' !== value.trim()) {
2445
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
2446
+
2447
+ \`\`\`tsx file="./filename"
2448
+ content
2449
+ \`\`\`
2450
+
2451
+ this usage is not allowed, please use below:
2452
+
2453
+ \`\`\`tsx file="./filename"
2454
+ \`\`\`
2455
+ `);
2456
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
2457
+ }
2458
+ const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2459
+ addDependency?.(resolvedFilePath);
2460
+ node.value = fileContent;
2461
+ }).catch((e)=>{
2462
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
2463
+ logger.error(message);
2464
+ e.message = `${message}\n${e.message}`;
2465
+ throw e;
2466
+ });
2467
+ promiseList.push(promise);
2468
+ return;
2453
2469
  }
2454
- }
2455
- });
2456
- function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2470
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
2471
+ Please use below:
2472
+
2473
+ \`\`\`tsx file="./filename"
2474
+ \`\`\`
2475
+ `);
2476
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
2477
+ });
2478
+ await Promise.all(promiseList);
2479
+ };
2480
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, filePath, routeService) {
2457
2481
  const errorInfos = [];
2482
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
2483
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
2484
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
2458
2485
  let possibleBreakingChange = false;
2459
2486
  [
2460
2487
  ...internalLinks.entries()
2461
2488
  ].forEach(([nodeUrl, link])=>{
2489
+ if (excludesUrl?.has(nodeUrl)) return;
2490
+ if (excludesFn?.(nodeUrl)) return;
2462
2491
  const cleanLinkPath = linkToRoutePath(link);
2463
2492
  if (!cleanLinkPath) return;
2464
2493
  if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
@@ -2474,13 +2503,31 @@ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)}
2474
2503
  if ((0, shared_.isProduction)()) throw new Error('Dead link found');
2475
2504
  }
2476
2505
  }
2477
- function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
2506
+ function looseMarkdownLink(url, routeService, filePath) {
2507
+ if (!routeService.isInDocsDir(filePath)) return url;
2508
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
2509
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
2510
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
2511
+ if ('' === versionPart) {
2512
+ if ('' === langPart) return (0, shared_.addLeadingSlash)(`${[
2513
+ versionPartCurrFile,
2514
+ langPartCurrFile
2515
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2516
+ return (0, shared_.addLeadingSlash)(`${[
2517
+ versionPartCurrFile,
2518
+ langPart
2519
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2520
+ }
2521
+ return url;
2522
+ }
2523
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, internalLinks, __base) {
2478
2524
  if (!nodeUrl) return '';
2479
2525
  if (nodeUrl.startsWith('#')) return nodeUrl;
2480
2526
  let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
2481
2527
  if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
2482
2528
  if (!routeService) return nodeUrl;
2483
2529
  if (url.startsWith('/')) {
2530
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
2484
2531
  const { routePath } = routeService.normalizeRoutePath(url);
2485
2532
  url = routePath;
2486
2533
  } else {
@@ -2500,136 +2547,39 @@ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks
2500
2547
  function linkToRoutePath(routePath) {
2501
2548
  return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
2502
2549
  }
2503
- const normalizeImageUrl = (imageUrl)=>{
2504
- if ((0, shared_.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
2505
- return imageUrl;
2506
- };
2507
- const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
2550
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, __base })=>(tree, file)=>{
2551
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
2508
2552
  const internalLinks = new Map();
2509
2553
  visit(tree, 'link', (node)=>{
2510
2554
  const { url: nodeUrl } = node;
2511
- const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2555
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
2512
2556
  node.url = link;
2513
2557
  });
2514
2558
  visit(tree, 'definition', (node)=>{
2515
2559
  const { url: nodeUrl } = node;
2516
- const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2560
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
2517
2561
  node.url = link;
2518
2562
  });
2519
- if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
2520
- const images = [];
2521
- const getMdxSrcAttribute = (tempVar)=>({
2522
- type: 'mdxJsxAttribute',
2523
- name: 'src',
2524
- value: {
2525
- type: 'mdxJsxAttributeValueExpression',
2526
- value: tempVar,
2527
- data: {
2528
- estree: {
2529
- type: 'Program',
2530
- sourceType: 'module',
2531
- body: [
2532
- {
2533
- type: 'ExpressionStatement',
2534
- expression: {
2535
- type: 'Identifier',
2536
- name: tempVar
2537
- }
2538
- }
2539
- ]
2540
- }
2541
- }
2542
- }
2543
- });
2544
- visit(tree, 'image', (node)=>{
2545
- const { alt, url } = node;
2546
- if (!url) return;
2547
- const imagePath = normalizeImageUrl(url);
2548
- if (!imagePath) return;
2549
- const tempVariableName = `image${images.length}`;
2550
- Object.assign(node, {
2551
- type: 'mdxJsxFlowElement',
2552
- name: 'img',
2553
- children: [],
2554
- attributes: [
2555
- alt && {
2556
- type: 'mdxJsxAttribute',
2557
- name: 'alt',
2558
- value: alt
2559
- },
2560
- getMdxSrcAttribute(tempVariableName)
2561
- ].filter(Boolean)
2562
- });
2563
- images.push(getASTNodeImport(tempVariableName, imagePath));
2564
- });
2565
- visit(tree, (node)=>{
2566
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
2567
- const srcAttr = getNodeAttribute(node, 'src', true);
2568
- if ('string' != typeof srcAttr?.value) return;
2569
- const imagePath = normalizeImageUrl(srcAttr.value);
2570
- if (!imagePath) return;
2571
- const tempVariableName = `image${images.length}`;
2572
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
2573
- images.push(getASTNodeImport(tempVariableName, imagePath));
2574
- });
2575
- tree.children.unshift(...images);
2576
- };
2577
- const ERROR_PREFIX = '[remarkFileCodeBlock]';
2578
- function parseFileFromMeta(meta) {
2579
- if (!meta) return '';
2580
- const kvList = meta.split(' ').filter(Boolean);
2581
- for (const item of kvList){
2582
- const [k, v = ''] = item.split('=');
2583
- if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
2584
- }
2585
- return '';
2586
- }
2587
- const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
2588
- const promiseList = [];
2589
- visit(tree, 'code', (node)=>{
2590
- const { meta, value, lang } = node;
2591
- const file = parseFileFromMeta(meta ?? '');
2592
- if (!file) return;
2593
- const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
2594
- if (file.startsWith('./') || file.startsWith('../')) {
2595
- const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2596
- if ('' !== value.trim()) {
2597
- logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
2598
-
2599
- \`\`\`tsx file="./filename"
2600
- content
2601
- \`\`\`
2602
-
2603
- this usage is not allowed, please use below:
2604
-
2605
- \`\`\`tsx file="./filename"
2606
- \`\`\`
2607
- `);
2608
- throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
2609
- }
2610
- const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2611
- node.value = fileContent;
2612
- }).catch((e)=>{
2613
- const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
2614
- logger.error(message);
2615
- e.message = `${message}\n${e.message}`;
2616
- throw e;
2617
- });
2618
- promiseList.push(promise);
2619
- return;
2620
- }
2621
- logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
2622
- Please use below:
2623
-
2624
- \`\`\`tsx file="./filename"
2625
- \`\`\`
2626
- `);
2627
- throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
2628
- });
2629
- await Promise.all(promiseList);
2563
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, internalLinks, file.path, routeService);
2630
2564
  };
2631
- function defineConfig(config) {
2632
- return config;
2565
+ async function serve(options) {
2566
+ const { config, port: userPort, host: userHost, configFilePath } = options;
2567
+ const envPort = process.env.PORT;
2568
+ const envHost = process.env.HOST;
2569
+ const { builderConfig } = config;
2570
+ const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
2571
+ const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
2572
+ config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
2573
+ server: {
2574
+ port,
2575
+ host
2576
+ }
2577
+ });
2578
+ const pluginDriver = new PluginDriver(config, configFilePath, true);
2579
+ await pluginDriver.init();
2580
+ const modifiedConfig = await pluginDriver.modifyConfig();
2581
+ const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
2582
+ return rsbuild.preview();
2633
2583
  }
2634
2584
  var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
2635
2585
  var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
@@ -2637,4 +2587,4 @@ var __webpack_exports__normalizeHref = shared_.normalizeHref;
2637
2587
  var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
2638
2588
  var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
2639
2589
  var __webpack_exports__withBase = shared_.withBase;
2640
- export { build, defineConfig, 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 };
2590
+ export { build, defineConfig, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };