@rspress/core 1.38.0 → 1.39.0

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
@@ -66,7 +66,7 @@ var require_package = __commonJS({
66
66
  "package.json"(exports, module) {
67
67
  module.exports = {
68
68
  name: "@rspress/core",
69
- version: "1.38.0",
69
+ version: "1.39.0",
70
70
  description: "The Rspress Documentation Framework",
71
71
  bugs: "https://github.com/web-infra-dev/rspress/issues",
72
72
  repository: {
@@ -108,7 +108,7 @@ var require_package = __commonJS({
108
108
  "@mdx-js/loader": "2.3.0",
109
109
  "@mdx-js/mdx": "2.3.0",
110
110
  "@mdx-js/react": "2.3.0",
111
- "@rsbuild/core": "~1.1.9",
111
+ "@rsbuild/core": "~1.1.12",
112
112
  "@rsbuild/plugin-less": "~1.1.0",
113
113
  "@rsbuild/plugin-react": "~1.1.0",
114
114
  "@rsbuild/plugin-sass": "~1.1.2",
@@ -120,7 +120,7 @@ var require_package = __commonJS({
120
120
  "@rspress/runtime": "workspace:*",
121
121
  "@rspress/shared": "workspace:*",
122
122
  "@rspress/theme-default": "workspace:*",
123
- "enhanced-resolve": "5.17.1",
123
+ "enhanced-resolve": "5.18.0",
124
124
  "github-slugger": "^2.0.0",
125
125
  "hast-util-from-html": "^2.0.3",
126
126
  "hast-util-heading-rank": "^3.0.0",
@@ -128,7 +128,6 @@ var require_package = __commonJS({
128
128
  htmr: "^1.0.2",
129
129
  "lodash-es": "^4.17.21",
130
130
  "mdast-util-mdxjs-esm": "^1.3.1",
131
- "node-fetch": "3.3.2",
132
131
  react: "^18.3.1",
133
132
  "react-dom": "^18.3.1",
134
133
  "react-helmet-async": "^1.3.0",
@@ -143,22 +142,22 @@ var require_package = __commonJS({
143
142
  "unist-util-visit-children": "^3.0.0"
144
143
  },
145
144
  devDependencies: {
146
- "@modern-js/plugin-tailwindcss": "2.63.1",
147
- "@modern-js/tsconfig": "2.63.1",
145
+ "@modern-js/plugin-tailwindcss": "2.63.3",
146
+ "@modern-js/tsconfig": "2.63.3",
148
147
  "@types/hast": "3.0.4",
149
148
  "@types/html-to-text": "^9.0.4",
150
149
  "@types/jest": "~29.5.14",
151
150
  "@types/lodash-es": "^4.17.12",
152
151
  "@types/mdast": "^4.0.4",
153
152
  "@types/node": "^18.11.17",
154
- "@types/react": "^18.3.14",
155
- "@types/react-dom": "^18.3.2",
153
+ "@types/react": "^18.3.18",
154
+ "@types/react-dom": "^18.3.5",
156
155
  postcss: "8.4.49",
157
156
  "rehype-stringify": "^9.0.4",
158
157
  "remark-parse": "^10.0.2",
159
158
  "remark-rehype": "^10.1.0",
160
159
  rimraf: "^3.0.2",
161
- tailwindcss: "^3.4.16",
160
+ tailwindcss: "^3.4.17",
162
161
  typescript: "^5.5.3",
163
162
  vitest: "2.1.8"
164
163
  },
@@ -1092,7 +1091,6 @@ function rsbuildPluginDocVM(factoryContext) {
1092
1091
  import path8, { join as join2 } from "path";
1093
1092
  import fs6 from "@rspress/shared/fs-extra";
1094
1093
  import chalk2 from "@rspress/shared/chalk";
1095
- import fetch from "node-fetch";
1096
1094
  import { isSCM, SEARCH_INDEX_NAME as SEARCH_INDEX_NAME2 } from "@rspress/shared";
1097
1095
  import { logger as logger2 } from "@rspress/shared/logger";
1098
1096
  async function writeSearchIndex(config) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,QACP,WAAa;AAAA,MACf;AAAA,MACA,SAAW;AAAA,MACX,MAAQ;AAAA,MACR,iBAAiB;AAAA,MACjB,OAAS;AAAA,MACT,MAAQ;AAAA,MACR,QAAU;AAAA,MAC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,IACpB,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,QAAQ,QAAQ;AACxB;;;AC1CA,cAAc;AACd,SAAS,sBAAsB","names":["path","removeLeadingSlash","MDX_REGEXP","RSPRESS_TEMP_DIR","fs","routeService","resolver","enhancedResolve","CachedInputFileSystem","ResolverFactory","slash","page","normalizeSidebar","sidebar","domain","join","chalk","SEARCH_INDEX_NAME","logger","addLeadingSlash","withBase","filepath","mergeRsbuildConfig","dirname","isDebugMode","loadFrontMatter"],"ignoreList":[],"sources":["../package.json","../src/node/initRsbuild.ts","../src/node/constants.ts","../src/node/runtimeModule/index.ts","../src/node/runtimeModule/routeData.ts","../src/node/runtimeModule/siteData/index.ts","../src/node/utils/normalizePath.ts","../src/node/utils/getPageKey.ts","../src/node/utils/createHash.ts","../src/node/utils/detectReactVersion.ts","../src/node/utils/flattenMdxContent.ts","../src/node/utils/applyReplaceRules.ts","../src/node/runtimeModule/siteData/extractPageData.ts","../src/node/runtimeModule/siteData/normalizeThemeConfig.ts","../src/node/runtimeModule/i18n.ts","../src/node/runtimeModule/siteData/highlightLanguages.ts","../src/node/runtimeModule/globalUIComponents.ts","../src/node/runtimeModule/globalStyles.ts","../src/node/runtimeModule/searchHooks.ts","../src/node/searchIndex.ts","../src/node/route/RouteService.ts","../src/node/route/init.ts","../src/node/utils/detectCustomIcon.ts","../src/node/PluginDriver.ts","../src/node/dev.ts","../src/node/build.ts","../src/node/utils/renderHead.ts","../src/node/serve.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"@rspress/core\",\n \"version\": \"1.38.0\",\n \"description\": \"The Rspress Documentation Framework\",\n \"bugs\": \"https://github.com/web-infra-dev/rspress/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/web-infra-dev/rspress\",\n \"directory\": \"packages/cli/core\"\n },\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"jsnext:source\": \"./src/index.ts\",\n \"types\": \"./dist/index.d.ts\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/node/index.js\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./dist/*\": \"./dist/*\",\n \"./package.json\": \"./package.json\",\n \"./theme\": {\n \"default\": \"./theme.ts\"\n },\n \"./theme.css\": \"./theme.css\",\n \"./runtime\": {\n \"default\": \"./runtime.ts\"\n }\n },\n \"scripts\": {\n \"dev\": \"modern build -w\",\n \"build\": \"modern build\",\n \"reset\": \"rimraf ./**/node_modules\",\n \"test\": \"vitest run --passWithNoTests\"\n },\n \"engines\": {\n \"node\": \">=14.17.6\"\n },\n \"dependencies\": {\n \"@mdx-js/loader\": \"2.3.0\",\n \"@mdx-js/mdx\": \"2.3.0\",\n \"@mdx-js/react\": \"2.3.0\",\n \"@rsbuild/core\": \"~1.1.9\",\n \"@rsbuild/plugin-less\": \"~1.1.0\",\n \"@rsbuild/plugin-react\": \"~1.1.0\",\n \"@rsbuild/plugin-sass\": \"~1.1.2\",\n \"@rspress/mdx-rs\": \"0.6.4\",\n \"@rspress/plugin-auto-nav-sidebar\": \"workspace:*\",\n \"@rspress/plugin-container-syntax\": \"workspace:*\",\n \"@rspress/plugin-last-updated\": \"workspace:*\",\n \"@rspress/plugin-medium-zoom\": \"workspace:*\",\n \"@rspress/runtime\": \"workspace:*\",\n \"@rspress/shared\": \"workspace:*\",\n \"@rspress/theme-default\": \"workspace:*\",\n \"enhanced-resolve\": \"5.17.1\",\n \"github-slugger\": \"^2.0.0\",\n \"hast-util-from-html\": \"^2.0.3\",\n \"hast-util-heading-rank\": \"^3.0.0\",\n \"html-to-text\": \"^9.0.5\",\n \"htmr\": \"^1.0.2\",\n \"lodash-es\": \"^4.17.21\",\n \"mdast-util-mdxjs-esm\": \"^1.3.1\",\n \"node-fetch\": \"3.3.2\",\n \"react\": \"^18.3.1\",\n \"react-dom\": \"^18.3.1\",\n \"react-helmet-async\": \"^1.3.0\",\n \"react-lazy-with-preload\": \"^2.2.1\",\n \"react-syntax-highlighter\": \"^15.6.1\",\n \"rehype-external-links\": \"^3.0.0\",\n \"remark\": \"^14.0.3\",\n \"remark-gfm\": \"3.0.1\",\n \"rspack-plugin-virtual-module\": \"0.1.13\",\n \"unified\": \"^10.1.2\",\n \"unist-util-visit\": \"^4.1.2\",\n \"unist-util-visit-children\": \"^3.0.0\"\n },\n \"devDependencies\": {\n \"@modern-js/plugin-tailwindcss\": \"2.63.1\",\n \"@modern-js/tsconfig\": \"2.63.1\",\n \"@types/hast\": \"3.0.4\",\n \"@types/html-to-text\": \"^9.0.4\",\n \"@types/jest\": \"~29.5.14\",\n \"@types/lodash-es\": \"^4.17.12\",\n \"@types/mdast\": \"^4.0.4\",\n \"@types/node\": \"^18.11.17\",\n \"@types/react\": \"^18.3.14\",\n \"@types/react-dom\": \"^18.3.2\",\n \"postcss\": \"8.4.49\",\n \"rehype-stringify\": \"^9.0.4\",\n \"remark-parse\": \"^10.0.2\",\n \"remark-rehype\": \"^10.1.0\",\n \"rimraf\": \"^3.0.2\",\n \"tailwindcss\": \"^3.4.16\",\n \"typescript\": \"^5.5.3\",\n \"vitest\": \"2.1.8\"\n },\n \"sideEffects\": [\n \"*.css\",\n \"*.less\",\n \"*.sass\",\n \"*.scss\",\n \"**/virtual-global-styles.js\",\n \"virtual-global-styles\",\n \"./src/theme-default/styles/index.ts\"\n ],\n \"files\": [\n \"dist\",\n \"src/runtime\",\n \"src/theme-default\",\n \"src/shared\",\n \"index.html\",\n \"runtime.ts\",\n \"theme.ts\",\n \"loader.cjs\",\n \"compiled\"\n ],\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true,\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","import path from 'node:path';\nimport {\n type UserConfig,\n removeLeadingSlash,\n MDX_REGEXP,\n RSPRESS_TEMP_DIR,\n removeTrailingSlash,\n isDebugMode,\n} from '@rspress/shared';\nimport fs from '@rspress/shared/fs-extra';\nimport type {\n RsbuildInstance,\n RsbuildConfig,\n RsbuildPlugin,\n} from '@rsbuild/core';\nimport {\n CLIENT_ENTRY,\n SSR_ENTRY,\n PACKAGE_ROOT,\n OUTPUT_DIR,\n isProduction,\n inlineThemeScript,\n PUBLIC_DIR,\n DEFAULT_TITLE,\n} from './constants';\nimport { rsbuildPluginDocVM } from './runtimeModule';\nimport { serveSearchIndexMiddleware } from './searchIndex';\nimport { detectReactVersion, resolveReactAlias } from './utils';\nimport { initRouteService } from './route/init';\nimport type { PluginDriver } from './PluginDriver';\nimport type { RouteService } from './route/RouteService';\nimport { detectCustomIcon } from './utils/detectCustomIcon';\nimport { PLUGIN_REACT_NAME, pluginReact } from '@rsbuild/plugin-react';\nimport { PLUGIN_SASS_NAME, pluginSass } from '@rsbuild/plugin-sass';\nimport { PLUGIN_LESS_NAME, pluginLess } from '@rsbuild/plugin-less';\n\nexport interface MdxRsLoaderCallbackContext {\n resourcePath: string;\n links: string[];\n root: string;\n base: string;\n}\n\nfunction isPluginIncluded(config: UserConfig, pluginName: string): boolean {\n return (\n config.builderPlugins?.some(plugin => plugin.name === pluginName) ||\n config.builderConfig?.plugins?.some(\n plugin => plugin && (plugin as RsbuildPlugin).name === pluginName,\n )\n );\n}\n\nasync function createInternalBuildConfig(\n userDocRoot: string,\n config: UserConfig,\n enableSSG: boolean,\n routeService: RouteService,\n pluginDriver: PluginDriver,\n runtimeTempDir: string,\n): Promise<RsbuildConfig> {\n const cwd = process.cwd();\n const CUSTOM_THEME_DIR =\n config?.themeDir ?? path.join(process.cwd(), 'theme');\n const baseOutDir = config?.outDir ?? OUTPUT_DIR;\n const csrOutDir = baseOutDir;\n const ssrOutDir = path.join(baseOutDir, 'ssr');\n\n const DEFAULT_THEME = require.resolve('@rspress/theme-default');\n const base = config?.base ?? '';\n\n // In production, we need to add assetPrefix in asset path\n const assetPrefix = isProduction()\n ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base)\n : '';\n const reactVersion = await detectReactVersion();\n\n const normalizeIcon = (icon: string | undefined) => {\n if (!icon) {\n return undefined;\n }\n\n if (path.isAbsolute(icon)) {\n return path.join(userDocRoot, PUBLIC_DIR, icon);\n }\n\n return icon;\n };\n\n const [detectCustomIconAlias, reactCSRAlias, reactSSRAlias] =\n await Promise.all([\n detectCustomIcon(CUSTOM_THEME_DIR),\n resolveReactAlias(reactVersion, false),\n enableSSG ? resolveReactAlias(reactVersion, true) : Promise.resolve({}),\n ]);\n\n return {\n plugins: [\n ...(isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [pluginReact()]),\n ...(isPluginIncluded(config, PLUGIN_SASS_NAME) ? [] : [pluginSass()]),\n ...(isPluginIncluded(config, PLUGIN_LESS_NAME) ? [] : [pluginLess()]),\n rsbuildPluginDocVM({\n userDocRoot,\n config,\n runtimeTempDir,\n routeService,\n pluginDriver,\n }),\n ],\n server: {\n port:\n !isProduction() && process.env.PORT\n ? Number(process.env.PORT)\n : undefined,\n printUrls: ({ urls }) => {\n return urls.map(url => `${url}/${removeLeadingSlash(base)}`);\n },\n publicDir: {\n name: path.join(userDocRoot, PUBLIC_DIR),\n },\n },\n dev: {\n progressBar: false,\n // Serve static files\n setupMiddlewares: [\n middlewares => {\n middlewares.unshift(serveSearchIndexMiddleware(config));\n },\n ],\n cliShortcuts: {\n // does not support restart server yet\n custom: shortcuts => shortcuts.filter(({ key }) => key !== 'r'),\n },\n },\n html: {\n title: config?.title ?? DEFAULT_TITLE,\n favicon: normalizeIcon(config?.icon),\n template: path.join(PACKAGE_ROOT, 'index.html'),\n tags: [\n config.themeConfig?.darkMode !== false && {\n tag: 'script',\n children: inlineThemeScript,\n append: false,\n },\n ].filter(Boolean),\n },\n output: {\n assetPrefix,\n distPath: {\n // just for rsbuild preview\n root: csrOutDir,\n },\n },\n resolve: {\n alias: {\n ...detectCustomIconAlias,\n '@mdx-js/react': require.resolve('@mdx-js/react'),\n '@theme': [CUSTOM_THEME_DIR, DEFAULT_THEME],\n '@/theme-default': DEFAULT_THEME,\n '@rspress/core': PACKAGE_ROOT,\n 'react-lazy-with-preload': require.resolve('react-lazy-with-preload'),\n 'react-syntax-highlighter': path.dirname(\n require.resolve('react-syntax-highlighter/package.json'),\n ),\n '@theme-assets': path.join(DEFAULT_THEME, '../assets'),\n },\n },\n source: {\n include: [PACKAGE_ROOT, path.join(cwd, 'node_modules', RSPRESS_TEMP_DIR)],\n define: {\n 'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),\n 'process.env.TEST': JSON.stringify(process.env.TEST),\n },\n },\n performance: {\n chunkSplit: {\n override: {\n cacheGroups: {\n // extract all CSS into a single file\n // ensure CSS in async chunks can be loaded for SSG\n styles: {\n name: 'styles',\n minSize: 0,\n chunks: 'all',\n test: /\\.(?:css|less|sass|scss)$/,\n priority: 99,\n },\n },\n },\n },\n },\n tools: {\n bundlerChain(chain, { CHAIN_ID, target }) {\n const isServer = target === 'node';\n const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);\n\n const swcLoaderOptions = jsModuleRule\n .use(CHAIN_ID.USE.SWC)\n .get('options');\n\n const checkDeadLinks =\n (config?.markdown?.checkDeadLinks && !isServer) ?? false;\n\n chain.module\n .rule('MDX')\n .type('javascript/auto')\n .test(MDX_REGEXP)\n .resolve.merge({\n conditionNames: jsModuleRule.resolve.conditionNames.values(),\n mainFields: jsModuleRule.resolve.mainFields.values(),\n })\n .end()\n .oneOf('MDXCompile')\n .use('builtin:swc-loader')\n .loader('builtin:swc-loader')\n .options(swcLoaderOptions)\n .end()\n .use('mdx-loader')\n .loader(require.resolve('../loader.cjs'))\n .options({\n config,\n docDirectory: userDocRoot,\n checkDeadLinks,\n routeService,\n pluginDriver,\n })\n .end();\n\n if (chain.plugins.has(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH)) {\n chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).tap(options => {\n options[0] ??= {};\n options[0].include = [/\\.([cm]js|[jt]sx?|flow)$/i, MDX_REGEXP];\n return options;\n });\n }\n\n chain.resolve.extensions.prepend('.md').prepend('.mdx').prepend('.mjs');\n\n chain.module\n .rule('css-virtual-module')\n .test(/\\.rspress[\\\\/]runtime[\\\\/]virtual-global-styles/)\n .merge({ sideEffects: true });\n\n if (isServer) {\n chain.output.filename('main.cjs');\n }\n\n const enableIncremental =\n !isProduction() && !process.env.DISABLE_RSPACK_INCREMENTAL;\n if (enableIncremental) {\n chain.merge({ experiments: { incremental: true } });\n }\n },\n },\n environments: {\n web: {\n resolve: {\n alias: reactCSRAlias,\n },\n source: {\n entry: {\n index: CLIENT_ENTRY,\n },\n define: {\n 'process.env.__SSR__': JSON.stringify(false),\n },\n },\n output: {\n target: 'web',\n distPath: {\n root: csrOutDir,\n },\n },\n },\n ...(enableSSG\n ? {\n node: {\n resolve: {\n alias: reactSSRAlias,\n },\n source: {\n entry: {\n index: SSR_ENTRY,\n },\n define: {\n 'process.env.__SSR__': JSON.stringify(true),\n },\n },\n performance: {\n printFileSize: isDebugMode(),\n },\n output: {\n emitAssets: false,\n target: 'node',\n distPath: {\n root: ssrOutDir,\n },\n minify: false,\n },\n },\n }\n : {}),\n },\n };\n}\n\nexport async function initRsbuild(\n rootDir: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n enableSSG: boolean,\n extraRsbuildConfig?: RsbuildConfig,\n): Promise<RsbuildInstance> {\n const cwd = process.cwd();\n const userDocRoot = path.resolve(rootDir || config?.root || cwd);\n const builderPlugins = config?.builderPlugins ?? [];\n // We use a temp dir to store runtime files, so we can separate client and server build\n // and we should empty temp dir before build\n const runtimeTempDir = path.join(RSPRESS_TEMP_DIR, 'runtime');\n const runtimeAbsTempDir = path.join(cwd, 'node_modules', runtimeTempDir);\n await fs.ensureDir(runtimeAbsTempDir);\n\n const routeService = await initRouteService({\n config,\n runtimeTempDir: runtimeAbsTempDir,\n scanDir: userDocRoot,\n pluginDriver,\n });\n const { createRsbuild, mergeRsbuildConfig } = await import('@rsbuild/core');\n\n const internalRsbuildConfig = await createInternalBuildConfig(\n userDocRoot,\n config,\n enableSSG,\n routeService,\n pluginDriver,\n runtimeTempDir,\n );\n\n const rsbuild = await createRsbuild({\n rsbuildConfig: mergeRsbuildConfig(\n internalRsbuildConfig,\n ...(pluginDriver\n .getPlugins()\n ?.map(plugin => plugin.builderConfig ?? {}) || []),\n config?.builderConfig || {},\n extraRsbuildConfig || {},\n ),\n });\n\n rsbuild.addPlugins(builderPlugins);\n\n return rsbuild;\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from '@rspress/shared';\n\nexport const isProduction = () => process.env.NODE_ENV === 'production';\n\n// Keep the quotation marks consistent before and after.\nexport const importStatementRegex =\n /import\\s+(.*?)\\s+from\\s+(['\"])(.*?)(?:\"|');?/gm;\n\n// In the first render, the theme will be set according to the user's system theme\n// - Should be injected into both development and production modes\n// - Class hook (.dark) is set for internal use (Tailwind)\n// - Style hook (colorScheme) is set for external use (CSS media queries or `light-dark()` function)\nexport const inlineThemeScript = `{\n const saved = localStorage.getItem('${APPEARANCE_KEY}')\n const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches\n const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'\n document.documentElement.classList.toggle('dark', isDark)\n document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'\n}`\n .replace(/\\n/g, ';')\n .replace(/\\s{2,}/g, '');\n\nconst dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));\n\nexport const PACKAGE_ROOT = path.join(dirname, '..');\n\nexport const CLIENT_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'clientEntry.js',\n);\n\nexport const SSR_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'ssrEntry.js',\n);\n\nexport const OUTPUT_DIR = 'doc_build';\n\nexport const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';\nexport const HEAD_MARKER = '<!--<?- HEAD ?>-->';\nexport const META_GENERATOR = '<!--<?- GENERATOR ?>-->';\nexport const HTML_START_TAG = '<html';\nexport const BODY_START_TAG = '<body';\n\nexport const DEFAULT_TITLE = 'Rspress';\n\nexport const PUBLIC_DIR = 'public';\nexport const TEMP_DIR = path.join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n);\n","import type { UserConfig } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type { RsbuildPlugin } from '@rsbuild/core';\nimport type { RouteService } from '../route/RouteService';\nimport type { PluginDriver } from '../PluginDriver';\nimport { routeVMPlugin } from './routeData';\nimport { siteDataVMPlugin } from './siteData/index';\nimport { i18nVMPlugin } from './i18n';\nimport { globalUIComponentsVMPlugin } from './globalUIComponents';\nimport { globalStylesVMPlugin } from './globalStyles';\nimport { searchHookVMPlugin } from './searchHooks';\n\nexport interface FactoryContext {\n userDocRoot: string;\n config: UserConfig;\n isSSR: boolean;\n runtimeTempDir: string;\n alias: Record<string, string | string[]>;\n routeService: RouteService;\n pluginDriver: PluginDriver;\n}\n\ntype RuntimeModuleFactory = (\n context: FactoryContext,\n) => Record<string, string> | Promise<Record<string, string>>;\n\nexport const runtimeModuleFactory: RuntimeModuleFactory[] = [\n /**\n * Generate route data for client and server runtime\n */\n routeVMPlugin,\n /**\n * Generate search index and site data for client runtime\n * Also responsible for automatically importing prism languages\n */\n siteDataVMPlugin,\n /**\n * Generate global components from config and plugins\n */\n globalUIComponentsVMPlugin,\n /**\n * Generate global styles from config and plugins\n */\n globalStylesVMPlugin,\n /**\n * Generate i18n text for client runtime\n */\n i18nVMPlugin,\n /**\n * Generate search hook module\n */\n searchHookVMPlugin,\n];\n\n// We will use this plugin to generate runtime module in browser, which is important to ensure the client have access to some compile-time data\nexport function rsbuildPluginDocVM(\n factoryContext: Omit<FactoryContext, 'alias' | 'isSSR'>,\n): RsbuildPlugin {\n const { pluginDriver } = factoryContext;\n return {\n name: 'rsbuild-plugin-doc-vm',\n setup(api) {\n api.modifyBundlerChain(async (bundlerChain, { target }) => {\n const isServer = target === 'node';\n // The order should be sync\n const alias = bundlerChain.resolve.alias.entries();\n const runtimeModule: Record<string, string> = {};\n // Add internal runtime module\n for (const factory of runtimeModuleFactory) {\n const moduleResult = await factory({\n ...factoryContext,\n isSSR: isServer,\n alias: alias as Record<string, string>,\n });\n Object.assign(runtimeModule, moduleResult);\n }\n // Add runtime module from outer plugins\n const modulesByPlugin = await pluginDriver.addRuntimeModules();\n Object.keys(modulesByPlugin).forEach(key => {\n if (runtimeModule[key]) {\n throw new Error(\n `The runtime module ${key} is duplicated, please check your plugin`,\n );\n }\n runtimeModule[key] = modulesByPlugin[key];\n });\n bundlerChain\n .plugin('rspress-runtime-module')\n .use(\n new RspackVirtualModulePlugin(\n runtimeModule,\n factoryContext.runtimeTempDir,\n ),\n );\n });\n },\n };\n}\n\nexport enum RuntimeModuleID {\n GlobalStyles = 'virtual-global-styles',\n GlobalComponents = 'virtual-global-components',\n RouteForClient = 'virtual-routes',\n RouteForSSR = 'virtual-routes-ssr',\n SiteData = 'virtual-site-data',\n SearchIndexHash = 'virtual-search-index-hash',\n I18nText = 'virtual-i18n-text',\n SearchHooks = 'virtual-search-hooks',\n PrismLanguages = 'virtual-prism-languages',\n}\n\nexport const runtimeModuleIDs = [\n RuntimeModuleID.GlobalStyles,\n RuntimeModuleID.GlobalComponents,\n RuntimeModuleID.RouteForClient,\n RuntimeModuleID.RouteForSSR,\n RuntimeModuleID.SiteData,\n RuntimeModuleID.SearchIndexHash,\n RuntimeModuleID.I18nText,\n RuntimeModuleID.SearchHooks,\n];\n","import { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function routeVMPlugin(context: FactoryContext) {\n const { routeService, isSSR } = context;\n\n // client: The components of route is lazy loaded\n if (!isSSR) {\n return {\n [RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),\n };\n }\n\n return {\n [RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),\n [RuntimeModuleID.RouteForSSR]: routeService.generateRoutesCode(true),\n };\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { groupBy } from 'lodash-es';\nimport { SEARCH_INDEX_NAME, type SiteData } from '@rspress/shared';\nimport { createHash } from '@/node/utils';\nimport { TEMP_DIR, isProduction } from '@/node/constants';\nimport { extractPageData } from './extractPageData';\nimport { normalizeThemeConfig } from './normalizeThemeConfig';\nimport { handleHighlightLanguages } from './highlightLanguages';\nimport { type FactoryContext, RuntimeModuleID } from '..';\n\n// How can we let the client runtime access the `indexHash`?\n// We can only do something after the Rspack build process becuase the index hash is generated within Rspack build process.There are two ways to do this:\n// 1. insert window.__INDEX_HASH__ = 'foo' into the html template manually\n// 2. replace the `__INDEX_HASH__` placeholder in the html template with the real index hash after Rspack build\nexport const indexHash = '';\n\nfunction deletePrivateField<T>(obj: T): T {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n const newObj = { ...obj };\n Object.keys(newObj).forEach(key => {\n if (key.startsWith('_')) {\n delete newObj[key];\n }\n });\n return newObj;\n}\n\nexport async function siteDataVMPlugin(context: FactoryContext) {\n const { config, alias, userDocRoot, routeService, pluginDriver } = context;\n const userConfig = config;\n // prevent modify the origin config object\n const tempSearchObj = Object.assign({}, userConfig.search);\n\n // searchHooks is a absolute path which may leak information\n if (tempSearchObj) {\n tempSearchObj.searchHooks = undefined;\n }\n\n const highlightLanguages: Set<string> = new Set();\n const replaceRules = userConfig?.replaceRules || [];\n // If the dev server restart when config file, we will reuse the siteData instead of extracting the siteData from source files again.\n const domain =\n userConfig?.search && userConfig?.search?.mode === 'remote'\n ? (userConfig?.search.domain ?? '')\n : '';\n const pages = await extractPageData(\n replaceRules,\n alias,\n domain,\n userDocRoot,\n routeService,\n highlightLanguages,\n );\n // modify page index by plugins\n await pluginDriver.modifySearchIndexData(pages);\n\n const versioned =\n userConfig.search &&\n userConfig.search.mode !== 'remote' &&\n userConfig.search.versioned;\n\n const groupedPages = groupBy(pages, page => {\n if (page.frontmatter?.pageType === 'home') {\n return 'noindex';\n }\n\n const version = versioned ? page.version : '';\n const lang = page.lang || '';\n\n return `${version}###${lang}`;\n });\n // remove the pages marked as noindex\n delete groupedPages.noindex;\n\n const indexHashByGroup = {} as Record<string, string>;\n\n // Generate search index by different versions & languages, file name is {SEARCH_INDEX_NAME}.{version}.{lang}.{hash}.json\n await Promise.all(\n Object.keys(groupedPages).map(async group => {\n // Avoid writing filepath in compile-time\n const stringifiedIndex = JSON.stringify(\n groupedPages[group].map(deletePrivateField),\n );\n const indexHash = createHash(stringifiedIndex);\n indexHashByGroup[group] = indexHash;\n\n const [version, lang] = group.split('###');\n const indexVersion = version ? `.${version.replace('.', '_')}` : '';\n const indexLang = lang ? `.${lang}` : '';\n\n await fs.ensureDir(TEMP_DIR);\n await fs.writeFile(\n path.join(\n TEMP_DIR,\n `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`,\n ),\n stringifiedIndex,\n );\n }),\n );\n\n // Run extendPageData hook in plugins\n await Promise.all(\n pages.map(async pageData => pluginDriver.extendPageData(pageData)),\n );\n\n const siteData: SiteData = {\n title: userConfig?.title || '',\n description: userConfig?.description || '',\n icon: userConfig?.icon || '',\n route: userConfig?.route,\n themeConfig: normalizeThemeConfig(userConfig, pages),\n base: userConfig?.base || '/',\n lang: userConfig?.lang || '',\n locales: userConfig?.locales || userConfig.themeConfig?.locales || [],\n logo: userConfig?.logo || '',\n logoText: userConfig?.logoText || '',\n ssg: Boolean(userConfig?.ssg) ?? true,\n multiVersion: {\n default: userConfig?.multiVersion?.default || '',\n versions: userConfig?.multiVersion?.versions || [],\n },\n search: tempSearchObj ?? { mode: 'local' },\n pages: pages.map(page => {\n // omit some fields for runtime size\n const { content, id, domain, _filepath, _html, ...rest } = page;\n // In production, we cannot expose the complete filepath for security reasons\n return isProduction() ? rest : { ...rest, _filepath };\n }),\n markdown: {\n showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,\n defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,\n codeHighlighter: userConfig?.markdown?.codeHighlighter || 'prism',\n },\n };\n\n const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};\n\n // @ts-ignore this field is extended in \"plugin-preview\"\n if (siteData.pages[0]?.extraHighlightLanguages?.length) {\n (siteData.pages[0] as any).extraHighlightLanguages.forEach((lang: string) =>\n highlightLanguages.add(lang),\n );\n }\n\n const aliases = handleHighlightLanguages(\n highlightLanguages,\n defaultLanguages,\n );\n const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());\n const sortedHighlightLanguages = Array.from(highlightLanguages).sort();\n\n return {\n [`${RuntimeModuleID.SiteData}.mjs`]: `export default ${JSON.stringify(\n siteData,\n null,\n 2,\n )}`,\n [RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(\n indexHashByGroup,\n null,\n 2,\n )}`,\n [RuntimeModuleID.PrismLanguages]: `export const aliases = ${JSON.stringify(\n sortedAliases,\n null,\n 2,\n )};\n export const languages = {\n ${sortedHighlightLanguages.map(lang => {\n return `\"${lang}\": require(\n \"react-syntax-highlighter/dist/cjs/languages/prism/${lang}\"\n ).default`;\n })}\n }`,\n };\n}\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const isWindows = os.platform() === 'win32';\n\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function normalizePath(id: string): string {\n return path.posix.normalize(isWindows ? slash(id) : id);\n}\n","import { removeLeadingSlash } from '@rspress/shared';\n\nexport function getPageKey(route: string) {\n const cleanRoute = removeLeadingSlash(route);\n return cleanRoute.replace(/\\//g, '_').replace(/\\.[^.]+$/, '') || 'index';\n}\n","import { createHash as createHashFunc } from 'node:crypto';\n\nexport function createHash(str: string) {\n return createHashFunc('sha256').update(str).digest('hex').slice(0, 8);\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { logger } from '@rspress/shared/logger';\nimport { PACKAGE_ROOT } from '../constants';\n\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nconst DEFAULT_REACT_VERSION = 18;\n\nexport async function detectReactVersion(): Promise<number> {\n // Detect react version from current cwd\n // return the major version of react\n // if not found, return 18\n const cwd = process.cwd();\n const reactPath = path.join(cwd, 'node_modules', 'react');\n if (await fs.pathExists(reactPath)) {\n const reactPkg = await fs.readJson(path.join(reactPath, 'package.json'));\n const version = Number(reactPkg.version.split('.')[0]);\n return version;\n }\n\n return DEFAULT_REACT_VERSION;\n}\n\nexport async function resolveReactAlias(reactVersion: number, isSSR: boolean) {\n const basedir =\n reactVersion === DEFAULT_REACT_VERSION ? PACKAGE_ROOT : process.cwd();\n const libPaths = [\n 'react',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n 'react-dom',\n 'react-dom/server',\n ];\n if (reactVersion >= DEFAULT_REACT_VERSION) {\n libPaths.push('react-dom/client');\n }\n const alias: Record<string, string> = {};\n const resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.js'],\n alias,\n conditionNames: isSSR ? ['...'] : ['browser', '...'],\n });\n await Promise.all(\n libPaths.map(async lib => {\n try {\n alias[lib] = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n { importer: basedir },\n basedir,\n lib,\n {},\n (err, filePath) => {\n if (err || filePath === false) {\n return reject(err);\n }\n return resolve(filePath);\n },\n );\n });\n } catch (e) {\n console.log(e);\n logger.warn(`${lib} not found`);\n }\n }),\n );\n return alias;\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { MDX_REGEXP } from '@rspress/shared';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { importStatementRegex } from '../constants';\n\nimport type { Root } from 'hast';\nimport type { Resolver } from 'enhanced-resolve';\n\nlet resolver: Resolver;\nlet startFlatten = false;\n\nconst processor = createProcessor();\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nexport async function resolveDepPath(\n importPath: string,\n importer: string,\n alias: Record<string, string | string[]>,\n) {\n if (!resolver) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md'],\n alias,\n });\n }\n const resolveResult = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n {\n importer,\n },\n importer,\n importPath,\n {},\n (err, filePath) => {\n if (err) {\n return reject(err);\n }\n if (!filePath) {\n return reject(\n new Error(\n `Empty result when resolving ${importPath} from ${importer}`,\n ),\n );\n }\n return resolve(filePath);\n },\n );\n });\n return resolveResult;\n}\n\ninterface ESTree {\n body: {\n type: 'ImportDeclaration';\n specifiers: { local: { name: string } }[];\n source: { value: string };\n }[];\n}\n\nexport async function flattenMdxContent(\n content: string,\n basePath: string,\n alias: Record<string, string | string[]>,\n): Promise<{ flattenContent: string; deps: string[] }> {\n const deps = [];\n // Performance optimization: if the content does not contain any import statement, we can skip the parsing process\n // So we need to check this match\n\n // Create new regExp to avoid the regex cache the last match index\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag\n const regex = new RegExp(importStatementRegex);\n if (!regex.test(content)) {\n return { flattenContent: content, deps };\n }\n\n // We should update the resolver instanceof because the alias should be passed to it\n // If we reuse the resolver instance in `detectReactVersion` method, the resolver will lose the alias info and cannot resolve path correctly in mdx files.\n if (!startFlatten) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md', '.js'],\n alias,\n });\n startFlatten = true;\n }\n\n let ast: Root;\n let result = content;\n\n try {\n ast = processor.parse(content) as Root;\n } catch (e) {\n // Fallback: if mdx parse failed, just return the content\n return { flattenContent: content, deps };\n }\n\n const importNodes = ast.children\n .filter(node => node.type === ('mdxjsEsm' as any))\n .flatMap(node => (node.data?.estree as ESTree)?.body || [])\n .filter(node => node.type === 'ImportDeclaration');\n for (const importNode of importNodes) {\n // import Comp from './a';\n // {id: Comp, importPath: './a'}\n const id = importNode.specifiers[0].local.name;\n const importPath = importNode.source.value;\n\n let absoluteImportPath: string;\n try {\n absoluteImportPath = await resolveDepPath(\n importPath,\n path.dirname(basePath),\n alias,\n );\n } catch (e) {\n continue;\n }\n\n if (MDX_REGEXP.test(absoluteImportPath)) {\n // replace import statement with the content of the imported file\n const importedContent = fs.readFileSync(absoluteImportPath, 'utf-8');\n const { flattenContent: replacedValue, deps: subDeps } =\n await flattenMdxContent(importedContent, absoluteImportPath, alias);\n\n result = result\n .replace(\n new RegExp(`import\\\\s+${id}\\\\s+from\\\\s+['\"](${importPath})['\"];?`),\n '',\n )\n .replace(new RegExp(`<${id}\\\\s*/>`, 'g'), () => replacedValue);\n\n deps.push(...subDeps, absoluteImportPath);\n }\n }\n\n return { flattenContent: result, deps };\n}\n","import type { ReplaceRule } from '@rspress/shared';\n\nexport function applyReplaceRules(\n code = '',\n replaceRules: ReplaceRule[] = [],\n): string {\n let result = code;\n for (const rule of replaceRules) {\n result = result.replace(rule.search, rule.replace);\n }\n return result;\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { htmlToText } from 'html-to-text';\nimport { compile } from '@rspress/mdx-rs';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\nimport {\n type Header,\n MDX_REGEXP,\n type ReplaceRule,\n type PageIndexInfo,\n} from '@rspress/shared';\nimport { flattenMdxContent } from '@/node/utils';\nimport { importStatementRegex } from '@/node/constants';\nimport type { RouteService } from '@/node/route/RouteService';\nimport { applyReplaceRules } from '@/node/utils/applyReplaceRules';\n\nexport function applyReplaceRulesToNestedObject(\n obj: Record<string, any>,\n replaceRules: ReplaceRule[],\n) {\n for (const key in obj) {\n if (typeof obj[key] === 'string') {\n obj[key] = applyReplaceRules(obj[key], replaceRules);\n } else if (typeof obj[key] === 'object') {\n obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);\n }\n }\n\n return obj;\n}\n\nexport async function extractPageData(\n replaceRules: ReplaceRule[],\n alias: Record<string, string | string[]>,\n domain: string,\n root: string,\n routeService: RouteService,\n highlighterLangs: Set<string>,\n): Promise<PageIndexInfo[]> {\n const pageData = await Promise.all(\n routeService\n .getRoutes()\n .map(async (route, index): Promise<PageIndexInfo> => {\n const defaultIndexInfo: PageIndexInfo = {\n id: index,\n title: '',\n content: '',\n _html: '',\n routePath: route.routePath,\n lang: route.lang,\n toc: [],\n domain,\n frontmatter: {},\n version: route.version,\n _filepath: route.absolutePath,\n _relativePath: path.relative(root, route.absolutePath),\n };\n if (!MDX_REGEXP.test(route.absolutePath)) {\n return defaultIndexInfo;\n }\n let content: string = await fs.readFile(route.absolutePath, 'utf8');\n const { frontmatter, content: strippedFrontMatter } = loadFrontMatter(\n content,\n route.absolutePath,\n root,\n );\n\n // 1. Replace rules for frontmatter & content\n applyReplaceRulesToNestedObject(frontmatter, replaceRules);\n\n const { flattenContent } = await flattenMdxContent(\n applyReplaceRules(strippedFrontMatter, replaceRules),\n route.absolutePath,\n alias,\n );\n\n content = flattenContent.replace(importStatementRegex, '');\n\n const {\n html,\n title,\n toc: rawToc,\n languages,\n } = await compile({\n value: content,\n filepath: route.absolutePath,\n development: process.env.NODE_ENV !== 'production',\n root,\n });\n\n if (!title?.length && !frontmatter && !frontmatter.title?.length) {\n return null;\n }\n\n content = htmlToText(String(html), {\n wordwrap: 80,\n selectors: [\n {\n selector: 'a',\n options: {\n ignoreHref: true,\n },\n },\n {\n selector: 'img',\n format: 'skip',\n },\n {\n // Skip code blocks\n selector: 'pre > code',\n format: 'skip',\n },\n ...['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(tag => ({\n selector: tag,\n options: {\n uppercase: false,\n },\n })),\n ],\n tables: true,\n longWordSplit: {\n forceWrapOnLimit: true,\n },\n });\n if (content.startsWith(title)) {\n // Remove the title from the content\n content = content.slice(title.length);\n }\n\n languages.forEach(lang => highlighterLangs.add(lang));\n\n // rawToc comes from mdx compile and it uses `-number` to unique toc of same id\n // We need to find the character index position of each toc in the content thus benefiting for search engines\n const toc: Header[] = rawToc.map(item => {\n const match = item.id.match(/-(\\d+)$/);\n let position = -1;\n if (match) {\n for (let i = 0; i < Number(match[1]); i++) {\n // When text is repeated, the position needs to be determined based on -number\n position = content.indexOf(`\\n${item.text}#\\n\\n`, position + 1);\n\n // If the positions don't match, it means the text itself may exist -number\n if (position === -1) {\n break;\n }\n }\n }\n return {\n ...item,\n charIndex: content.indexOf(`\\n${item.text}#\\n\\n`, position + 1),\n };\n });\n\n return {\n ...defaultIndexInfo,\n title: frontmatter.title || title,\n toc,\n // Stripped frontmatter content\n content,\n _html: html,\n frontmatter: {\n ...frontmatter,\n __content: undefined,\n },\n };\n }),\n );\n return pageData.filter(Boolean);\n}\n","import {\n type UserConfig,\n type DefaultThemeConfig,\n type NormalizedDefaultThemeConfig,\n type SidebarItem,\n type SidebarGroup,\n type NormalizedSidebarGroup,\n type PageIndexInfo,\n type NavItemWithLink,\n withBase,\n addLeadingSlash,\n isExternalUrl,\n withoutBase,\n type NavItem,\n type Sidebar,\n type SidebarDivider,\n slash,\n type SidebarSectionHeader,\n} from '@rspress/shared';\nimport { applyReplaceRules } from '../../utils/applyReplaceRules';\nimport { getI18nData } from '../i18n';\n\nexport function normalizeThemeConfig(\n docConfig: UserConfig,\n pages: PageIndexInfo[] = [],\n): NormalizedDefaultThemeConfig {\n const {\n locales: siteLocales,\n base = '',\n lang,\n replaceRules = [],\n multiVersion,\n } = docConfig;\n const { versions = [] } = multiVersion || {};\n const hasMultiVersion = versions.length > 0;\n docConfig.themeConfig = docConfig.themeConfig || {};\n const { themeConfig } = docConfig;\n const locales = siteLocales ?? (themeConfig?.locales || []);\n const i18nTextData = getI18nData(docConfig);\n // In following code, we will normalize the theme config reference to the pages data extracted from mdx files\n const normalizeLinkPrefix = (link = '', currentLang = '') => {\n const normalizedLink = slash(link);\n if (\n !currentLang ||\n !link ||\n withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) ||\n isExternalUrl(normalizedLink) ||\n // In multi version case, we have got the complete link prefix in `plugin-auto-nav-sidebar` and does not need to add the lang prefix\n hasMultiVersion\n ) {\n return normalizedLink;\n }\n // if lang exists, we should add the lang prefix to the link\n // such /guide -> /en/guide\n return lang === currentLang\n ? normalizedLink\n : `/${currentLang}${addLeadingSlash(normalizedLink)}`;\n };\n\n const getI18nText = (key = '', currentLang = '') => {\n const text = i18nTextData[key]?.[currentLang];\n return text || key;\n };\n // Normalize sidebar\n const normalizeSidebar = (\n sidebar?: DefaultThemeConfig['sidebar'],\n currentLang = '',\n ): NormalizedDefaultThemeConfig['sidebar'] => {\n const normalizedSidebar: NormalizedDefaultThemeConfig['sidebar'] = {};\n if (!sidebar) {\n return {};\n }\n const normalizeSidebarItem = (\n item:\n | SidebarGroup\n | SidebarItem\n | SidebarDivider\n | SidebarSectionHeader\n | string,\n ):\n | NormalizedSidebarGroup\n | SidebarItem\n | SidebarDivider\n | SidebarSectionHeader => {\n // Meet the divider, return directly\n if (typeof item === 'object' && 'dividerType' in item) {\n return item;\n }\n\n // Meet the section header, return i18n text\n if (typeof item === 'object' && 'sectionHeaderText' in item) {\n item.sectionHeaderText = applyReplaceRules(\n getI18nText(item.sectionHeaderText, currentLang),\n replaceRules,\n );\n return item;\n }\n\n if (typeof item === 'object' && 'items' in item) {\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link),\n collapsed: item.collapsed ?? false,\n collapsible: item.collapsible ?? true,\n tag: item.tag,\n items: item.items.map(subItem => {\n return normalizeSidebarItem(subItem) as\n | NormalizedSidebarGroup\n | SidebarItem;\n }),\n };\n }\n\n if (typeof item === 'string') {\n const normalizedItem = normalizeLinkPrefix(item, currentLang);\n const page = pages.find(\n page => page.routePath === withBase(normalizedItem, base),\n );\n return {\n text: applyReplaceRules(page?.title || '', replaceRules),\n link: normalizedItem,\n _fileKey: page._relativePath.replace(/\\.mdx?$/, ''),\n };\n }\n\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link),\n tag: item.tag,\n };\n };\n\n const normalizeSidebar = (sidebar: Sidebar) => {\n Object.keys(sidebar).forEach(key => {\n const value = sidebar[key];\n normalizedSidebar[key] = value.map(normalizeSidebarItem) as (\n | NormalizedSidebarGroup\n | SidebarItem\n )[];\n });\n };\n\n normalizeSidebar(sidebar);\n\n return normalizedSidebar;\n };\n\n const normalizeNav = (\n nav?: DefaultThemeConfig['nav'],\n currentLang?: string,\n ) => {\n if (!nav) {\n return [];\n }\n const transformNavItem = (navItem: NavItem) => {\n const text = applyReplaceRules(\n getI18nText(navItem.text, currentLang),\n replaceRules,\n );\n if ('link' in navItem) {\n return {\n ...navItem,\n text,\n link: normalizeLinkPrefix(navItem.link, currentLang),\n };\n }\n\n if ('items' in navItem) {\n return {\n ...navItem,\n text,\n items: navItem.items.map((item: NavItemWithLink) => {\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link, currentLang),\n };\n }),\n };\n }\n\n return navItem;\n };\n\n if (Array.isArray(nav)) {\n return nav.map(transformNavItem);\n }\n\n // Multi version case\n return Object.entries(nav).reduce((acc, [key, value]) => {\n acc[key] = value.map(transformNavItem);\n return acc;\n }, {});\n };\n\n /**\n * There are two place the user will define the locales:\n * 1. in the `doc.locales` (the site config)\n * 2. in the `doc.themeConfig.locales`\n * The locales in the theme config will override the locales in the site config.\n *\n * For nav and sidebar, we prefer the locales in the `themeConfig.nav` and `themeConfig.sidebar` if it exists. And the frameowork will generate complete nav and sidebar for each locale and place them in the `themeConfig.locales` field.\n */\n if (locales.length) {\n themeConfig.locales = locales.map(({ lang: currentLang, label }) => {\n const localeInThemeConfig = themeConfig.locales?.find(\n locale => locale.lang === currentLang,\n );\n return {\n lang: currentLang,\n label,\n ...(localeInThemeConfig || {}),\n sidebar: normalizeSidebar(\n localeInThemeConfig?.sidebar ?? themeConfig.sidebar,\n currentLang,\n ),\n nav: normalizeNav(\n localeInThemeConfig?.nav ?? themeConfig.nav,\n currentLang,\n ),\n };\n });\n } else {\n themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar);\n themeConfig.nav = normalizeNav(themeConfig?.nav);\n }\n return themeConfig as NormalizedDefaultThemeConfig;\n}\n","import { join } from 'node:path';\nimport type { UserConfig } from '@rspress/shared';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nconst DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');\n\nexport function getI18nData(docConfig: UserConfig) {\n const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;\n try {\n delete require.cache[i18nSourcePath];\n // eslint-disable-next-line import/no-dynamic-require\n const i18nSource = require(i18nSourcePath);\n return i18nSource;\n } catch (e) {\n return {};\n }\n}\n\nexport function i18nVMPlugin(context: FactoryContext) {\n const { config } = context;\n const i18nData = getI18nData(config);\n return {\n [RuntimeModuleID.I18nText]: `export default ${JSON.stringify(i18nData, null, 2)}`,\n };\n}\n","import chalk from '@rspress/shared/chalk';\nimport { DEFAULT_HIGHLIGHT_LANGUAGES } from '@rspress/shared';\n\nlet supportedLanguages: Set<string>;\n\nexport function handleHighlightLanguages(\n highlightLanguages: Set<string>,\n defaultLanguages: (string | [string, string])[],\n): Record<string, string[]> {\n // Automatically import prism languages\n const aliases: Record<string, string[]> = {};\n if (highlightLanguages.size) {\n if (!supportedLanguages) {\n const langs =\n require('react-syntax-highlighter/dist/cjs/languages/prism/supported-languages').default;\n supportedLanguages = new Set(langs);\n }\n\n // Restore alias to the original name\n let useDeprecatedTypeWarning = true;\n const names: Record<string, string> = {};\n [...DEFAULT_HIGHLIGHT_LANGUAGES, ...defaultLanguages].forEach(lang => {\n if (Array.isArray(lang)) {\n const [alias, name] = lang;\n names[alias] = name;\n } else if (useDeprecatedTypeWarning) {\n // Deprecated warning\n console.log(\n `${chalk.yellowBright(\n 'warning',\n )} Automatic import is supported. \\`highlightLanguages\\` is now used only as alias, and string types will be ignored. \\n`,\n );\n useDeprecatedTypeWarning = false;\n }\n });\n\n [...highlightLanguages.values()].forEach(lang => {\n const name = names[lang];\n if (name && supportedLanguages.has(name)) {\n const temp = aliases[name] || (aliases[name] = []);\n if (!temp.includes(lang)) {\n temp.push(lang);\n }\n\n // delete first, user may config alias to itself like ['go', 'go']\n highlightLanguages.delete(lang);\n highlightLanguages.add(name);\n return;\n }\n\n if (!supportedLanguages.has(lang)) {\n highlightLanguages.delete(lang);\n }\n });\n }\n\n return aliases;\n}\n","import { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function globalUIComponentsVMPlugin(context: FactoryContext) {\n const { config, pluginDriver } = context;\n let index = 0;\n\n const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();\n const globalComponents = [\n ...(config?.globalUIComponents || []),\n ...globalUIComponentsByPlugins,\n ];\n const moduleContent = globalComponents\n .map(source => {\n const name = `Comp_${index}`;\n if (Array.isArray(source)) {\n return `import ${name} from ${JSON.stringify(source[0])};\nconst Props_${index++} = ${JSON.stringify(source[1])};\\n`;\n }\n\n index++;\n return `import ${name} from ${JSON.stringify(source)};\\n`;\n })\n .concat(\n `export default [${Array.from({ length: index }, (_, i) => {\n if (Array.isArray(globalComponents[i])) {\n return `[${`Comp_${i}`}, Props_${i}]`;\n }\n return `Comp_${i}`;\n }).join(', ')}];`,\n )\n .join('');\n\n return {\n [RuntimeModuleID.GlobalComponents]: moduleContent,\n };\n}\n","import fs from '@rspress/shared/fs-extra';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function globalStylesVMPlugin(context: FactoryContext) {\n const { config, pluginDriver } = context;\n const globalStylesByPlugins = pluginDriver.globalStyles();\n\n if (config.globalStyles) {\n // Only patch user config global styles\n const source = config.globalStyles;\n const styleContent = await fs.readFile(source, 'utf-8');\n\n // Patch --modern-abc, .modern-abc global name\n const patchedStyleContent = styleContent\n .replace(/--modern-/g, '--rp-')\n .replace(/\\.modern-doc/g, '.rspress')\n .replace(/\\.modern-/g, '.rspress-');\n\n await fs.writeFile(source, patchedStyleContent, 'utf-8');\n }\n\n const moduleContent = (\n await Promise.all(\n [config?.globalStyles || '', ...globalStylesByPlugins]\n .filter(source => source.length > 0)\n .map(async source => {\n return `import ${JSON.stringify(source)};`;\n }),\n )\n ).join('');\n\n return {\n [RuntimeModuleID.GlobalStyles]: moduleContent,\n };\n}\n","import path from 'node:path';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function searchHookVMPlugin(context: FactoryContext) {\n const { config } = context;\n let content = 'export const onSearch = () => {};';\n let extname = '';\n if (\n typeof config.search === 'object' &&\n typeof config.search.searchHooks === 'string'\n ) {\n content = `export * from '${config.search.searchHooks}'`;\n extname = path.extname(config.search.searchHooks);\n }\n\n return {\n [`${RuntimeModuleID.SearchHooks}${extname}`]: content,\n };\n}\n","import path, { join } from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport chalk from '@rspress/shared/chalk';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport fetch from 'node-fetch';\nimport { type UserConfig, isSCM, SEARCH_INDEX_NAME } from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport { isProduction, OUTPUT_DIR, TEMP_DIR } from './constants';\n\nexport async function writeSearchIndex(config: UserConfig) {\n if (config?.search === false) {\n return;\n }\n const cwd = process.cwd();\n // get all search index files, format is `${SEARCH_INDEX_NAME}.foo.bar.${hash}.json`\n const searchIndexFiles = await fs.readdir(TEMP_DIR);\n const outDir = config?.outDir ?? join(cwd, OUTPUT_DIR);\n\n // For performance, we only stitch the string of search index data instead of big JavaScript object in memory\n let searchIndexData = '[]';\n let scaning = false;\n for (const searchIndexFile of searchIndexFiles) {\n if (\n !searchIndexFile.includes(SEARCH_INDEX_NAME) ||\n !searchIndexFile.endsWith('.json')\n ) {\n continue;\n }\n const source = join(TEMP_DIR, searchIndexFile);\n const target = join(outDir, 'static', searchIndexFile);\n const searchIndex = await fs.readFile(\n join(TEMP_DIR, searchIndexFile),\n 'utf-8',\n );\n searchIndexData = `${searchIndexData.slice(0, -1)}${\n scaning ? ',' : ''\n }${searchIndex.slice(1)}`;\n await fs.move(source, target, { overwrite: true });\n scaning = true;\n }\n\n if (isProduction() && isSCM() && config?.search?.mode === 'remote') {\n const { apiUrl, indexName } = config.search;\n try {\n await fetch(`${apiUrl}?index=${indexName}`, {\n method: 'PUT',\n body: searchIndexData,\n headers: { 'Content-Type': 'application/json' },\n });\n\n logger.info(\n chalk.green(\n `[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`,\n ),\n );\n } catch (e) {\n logger.info(\n chalk.red(\n `[doc-tools] Upload search index \\`${indexName}\\` failed:\\n ${e}`,\n ),\n );\n }\n }\n}\n\ntype RequestHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void;\n\nexport function serveSearchIndexMiddleware(config: UserConfig): RequestHandler {\n return (req, res, next) => {\n const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;\n if (req.url?.includes(searchIndexRequestMatch)) {\n res.setHeader('Content-Type', 'application/json');\n // Get search index name from request url\n const searchIndexFile = req.url?.split('/').pop();\n fs.createReadStream(\n path.join(\n process.cwd(),\n config?.outDir || OUTPUT_DIR,\n 'static',\n searchIndexFile,\n ),\n 'utf-8',\n ).pipe(res, { end: true });\n } else {\n next?.();\n }\n };\n}\n","import path from 'node:path';\nimport type { ComponentType } from 'react';\nimport fs from '@rspress/shared/fs-extra';\nimport {\n addLeadingSlash,\n addTrailingSlash,\n type PageModule,\n type UserConfig,\n type RouteMeta,\n withBase,\n} from '@rspress/shared';\nimport { getPageKey, normalizePath } from '../utils';\nimport type { PluginDriver } from '../PluginDriver';\nimport { PUBLIC_DIR } from '../constants';\n\nexport const DEFAULT_PAGE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'];\n\nexport interface Route {\n path: string;\n element: React.ReactElement;\n filePath: string;\n preload: () => Promise<PageModule<ComponentType<unknown>>>;\n lang: string;\n}\n\nexport interface RouteOptions {\n extensions?: string[];\n include?: string[];\n exclude?: string[];\n}\n\nexport const normalizeRoutePath = (\n routePath: string,\n base: string,\n lang: string,\n version: string,\n langs: string[],\n versions: string[],\n extensions: string[] = DEFAULT_PAGE_EXTENSIONS,\n) => {\n const hasTrailSlash = routePath.endsWith('/');\n let versionPart = '';\n let langPart = '';\n let purePathPart = '';\n const parts: string[] = routePath.split('/').filter(Boolean);\n\n if (version) {\n const versionToMatch = parts[0];\n if (versions.includes(versionToMatch)) {\n if (versionToMatch !== version) {\n versionPart = versionToMatch;\n }\n parts.shift();\n }\n }\n\n if (lang) {\n const langToMatch = parts[0];\n if (langs.includes(langToMatch)) {\n if (langToMatch !== lang) {\n langPart = langToMatch;\n }\n parts.shift();\n }\n }\n purePathPart = parts.join('/');\n\n let normalizedRoutePath = addLeadingSlash(\n [versionPart, langPart, purePathPart].filter(Boolean).join('/'),\n )\n // remove the extension\n .replace(new RegExp(`\\\\.(${extensions.join('|')})$`), '')\n .replace(/\\.html$/, '')\n .replace(/\\/index$/, '/');\n\n // restore the trail slash\n if (hasTrailSlash) {\n normalizedRoutePath = addTrailingSlash(normalizedRoutePath);\n }\n\n return {\n routePath: withBase(normalizedRoutePath, base),\n lang: langPart || lang,\n version: versionPart || version,\n };\n};\n\nexport class RouteService {\n routeData: Map<string, RouteMeta> = new Map();\n\n #scanDir: string;\n\n #defaultLang: string;\n\n #defaultVersion: string = '';\n\n #extensions: string[] = [];\n\n #langs: string[] = [];\n\n #versions: string[] = [];\n\n #include: string[] = [];\n\n #exclude: string[] = [];\n\n #base: string = '';\n\n #tempDir: string = '';\n\n #pluginDriver: PluginDriver;\n\n constructor(\n scanDir: string,\n userConfig: UserConfig,\n tempDir: string,\n pluginDriver: PluginDriver,\n ) {\n const routeOptions = userConfig?.route || {};\n this.#scanDir = scanDir;\n this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;\n this.#include = routeOptions.include || [];\n this.#exclude = routeOptions.exclude || [];\n this.#defaultLang = userConfig?.lang || '';\n this.#langs = (\n userConfig?.locales ??\n userConfig?.themeConfig?.locales ??\n []\n ).map(item => item.lang);\n this.#base = userConfig?.base || '';\n this.#tempDir = tempDir;\n this.#pluginDriver = pluginDriver;\n\n if (userConfig.multiVersion) {\n this.#defaultVersion = userConfig.multiVersion.default || '';\n this.#versions = userConfig.multiVersion.versions || [];\n }\n }\n\n async init() {\n const globby = (\n await import(\n // @ts-expect-error\n // eslint-disable-next-line node/file-extension-in-import\n '../compiled/globby/index.js'\n )\n ).default as typeof import('../../../compiled/globby');\n // 1. internal pages\n const files = (\n await globby([`**/*.{${this.#extensions.join(',')}}`, ...this.#include], {\n cwd: this.#scanDir,\n absolute: true,\n ignore: [\n ...this.#exclude,\n '**/node_modules/**',\n '**/.eslintrc.js',\n '**/.nx-cache/**',\n `./${PUBLIC_DIR}/**`,\n ],\n })\n ).sort();\n files.forEach(filePath => {\n const fileRelativePath = normalizePath(\n path.relative(this.#scanDir, filePath),\n );\n const { routePath, lang, version } =\n this.normalizeRoutePath(fileRelativePath);\n const absolutePath = path.join(this.#scanDir, fileRelativePath);\n\n const routeInfo = {\n routePath,\n absolutePath: normalizePath(absolutePath),\n relativePath: fileRelativePath,\n pageName: getPageKey(fileRelativePath),\n lang,\n version,\n };\n this.addRoute(routeInfo);\n });\n // 2. external pages added by plugins\n const externalPages = await this.#pluginDriver.addPages();\n\n await Promise.all(\n externalPages.map(async (route, index) => {\n const { routePath, content, filepath } = route;\n // case1: specify the filepath\n if (filepath) {\n const routeInfo = this.#generateRouteInfo(routePath, filepath);\n this.addRoute(routeInfo);\n return;\n }\n // case2: specify the content\n if (content) {\n const filepath = await this.#writeTempFile(index, content);\n const routeInfo = this.#generateRouteInfo(routePath, filepath);\n this.addRoute(routeInfo);\n }\n }),\n );\n\n await this.#pluginDriver.routeGenerated(this.getRoutes());\n }\n\n addRoute(routeInfo: RouteMeta) {\n const { routePath, absolutePath } = routeInfo;\n if (this.routeData.has(routePath)) {\n // apply the one with the extension listed first in the array and skip the rest.\n const preRouteExtIndex = this.#extensions.indexOf(\n path.extname(this.routeData.get(routePath)!.absolutePath).slice(1),\n );\n const currRouteExtIndex = this.#extensions.indexOf(\n path.extname(absolutePath).slice(1),\n );\n\n if (\n currRouteExtIndex !== -1 &&\n (currRouteExtIndex < preRouteExtIndex || preRouteExtIndex === -1)\n ) {\n this.routeData.set(routePath, routeInfo);\n }\n } else {\n this.routeData.set(routePath, routeInfo);\n }\n }\n\n removeRoute(filePath: string) {\n const fileRelativePath = path.relative(this.#scanDir, filePath);\n const { routePath } = this.normalizeRoutePath(fileRelativePath);\n this.routeData.delete(routePath);\n }\n\n getRoutes() {\n return Array.from(this.routeData.values());\n }\n\n isExistRoute(routePath: string) {\n const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);\n return this.routeData.get(normalizedRoute);\n }\n\n isEmpty() {\n return this.routeData.size === 0;\n }\n\n generateRoutesCode(isStaticImport = false) {\n return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);\n }\n\n generateRoutesCodeByRouteMeta(\n routeMeta: RouteMeta[],\n isStaticImport: boolean,\n ) {\n // TODO: webpackChunkName need fix https://github.com/web-infra-dev/rspack/issues/4664\n\n return `\nimport React from 'react';\nimport { lazyWithPreload } from \"react-lazy-with-preload\";\n${routeMeta\n .map((route, index) => {\n return isStaticImport\n ? `import * as Route${index} from '${route.absolutePath}';`\n : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`;\n })\n .join('\\n')}\nexport const routes = [\n${routeMeta\n .map((route, index) => {\n // In ssr, we don't need to import component dynamically.\n const preload = isStaticImport\n ? `() => Route${index}`\n : `async () => {\n await Route${index}.preload();\n return import(\"${route.absolutePath}\");\n }`;\n const component = isStaticImport\n ? `Route${index}.default`\n : `Route${index}`;\n /**\n * For SSR, example:\n * {\n * route: '/',\n * element: jsx(Route0),\n * preload: Route0.preload,\n * filePath: '/Users/foo/bar/index.md'\n * }\n *\n * For client render, example:\n * {\n * route: '/',\n * element: jsx(Route0.default),\n * preload: Route0.preload,\n * filePath: '/Users/foo/bar/index.md'\n * }\n */\n return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;\n })\n .join(',\\n')}\n];\n`;\n }\n\n normalizeRoutePath(routePath: string) {\n return normalizeRoutePath(\n routePath,\n this.#base,\n this.#defaultLang,\n this.#defaultVersion,\n this.#langs,\n this.#versions,\n this.#extensions,\n );\n }\n\n async #writeTempFile(index: number, content: string) {\n const tempFilePath = path.join(this.#tempDir, `temp-${index}.mdx`);\n await fs.writeFile(tempFilePath, content);\n return tempFilePath;\n }\n\n #generateRouteInfo(routePath: string, filepath: string): RouteMeta {\n const {\n routePath: normalizedPath,\n lang,\n version,\n } = this.normalizeRoutePath(routePath);\n return {\n routePath: normalizedPath,\n absolutePath: normalizePath(filepath),\n relativePath: normalizePath(path.relative(this.#scanDir, filepath)),\n pageName: getPageKey(routePath),\n lang,\n version,\n };\n }\n}\n","import type { UserConfig } from '@rspress/shared';\nimport type { PluginDriver } from '../PluginDriver';\nimport { RouteService } from './RouteService';\n\ninterface InitOptions {\n scanDir: string;\n config: UserConfig;\n runtimeTempDir: string;\n pluginDriver: PluginDriver;\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeService: RouteService | null = null;\n\n// The factory to create route serveice instance\nexport async function initRouteService(options: InitOptions) {\n const { scanDir, config, runtimeTempDir, pluginDriver } = options;\n routeService = new RouteService(\n scanDir,\n config,\n runtimeTempDir,\n pluginDriver,\n );\n await routeService.init();\n return routeService;\n}\n","import { existsSync } from 'node:fs';\nimport path from 'node:path';\n\nexport const detectCustomIcon = async (customThemeDir: string) => {\n const assetsDir = path.join(customThemeDir, 'assets');\n const alias: Record<string, string> = {};\n\n if (!existsSync(assetsDir)) {\n return alias;\n }\n\n const globby = (\n await import(\n // @ts-expect-error\n // eslint-disable-next-line node/file-extension-in-import\n '../compiled/globby/index.js'\n )\n ).default as typeof import('../../../compiled/globby');\n const files = await globby('*.svg', {\n cwd: assetsDir,\n });\n files.forEach(file => {\n const name = path.basename(file, '.svg');\n alias[`@theme-assets/${name}`] = path.join(assetsDir, file);\n });\n return alias;\n};\n","import type {\n UserConfig,\n PageIndexInfo,\n RspressPlugin,\n RouteMeta,\n} from '@rspress/shared';\nimport { isDevDebugMode } from '@rspress/shared';\nimport { pluginContainerSyntax } from '@rspress/plugin-container-syntax';\n\nexport class PluginDriver {\n #config: UserConfig;\n\n #plugins: RspressPlugin[];\n\n #isProd: boolean;\n\n constructor(config: UserConfig, isProd: boolean) {\n this.#config = config;\n this.#isProd = isProd;\n this.#plugins = [];\n }\n\n // The init function is used to initialize the doc plugins and will execute before the build process.\n async init() {\n // Clear RspressPlugins first, for the watch mode\n this.clearPlugins();\n const config = this.#config;\n const themeConfig = config?.themeConfig || {};\n const enableLastUpdated =\n themeConfig?.lastUpdated ||\n themeConfig?.locales?.some(locale => locale.lastUpdated);\n const mediumZoomConfig = config?.mediumZoom ?? true;\n const haveNavSidebarConfig =\n themeConfig.nav ||\n themeConfig.sidebar ||\n themeConfig.locales?.[0]?.nav ||\n themeConfig.locales?.[0]?.sidebar;\n if (enableLastUpdated) {\n const { pluginLastUpdated } = await import(\n '@rspress/plugin-last-updated'\n );\n this.addPlugin(pluginLastUpdated());\n }\n if (mediumZoomConfig) {\n const { pluginMediumZoom } = await import('@rspress/plugin-medium-zoom');\n this.addPlugin(\n pluginMediumZoom(\n typeof mediumZoomConfig === 'object' ? mediumZoomConfig : undefined,\n ),\n );\n }\n\n // Support the container syntax in markdown/mdx, such as :::tip\n this.addPlugin(pluginContainerSyntax());\n\n if (isDevDebugMode()) {\n const SourceBuildPlugin = await import(\n // @ts-expect-error need moduleResolution: Node16, NodeNext or Bundler to get type declerations work\n '@rspress/theme-default/node/source-build-plugin.js'\n ).then(\n r => r.SourceBuildPlugin,\n () => null as never,\n );\n\n if (SourceBuildPlugin) {\n this.addPlugin(SourceBuildPlugin());\n }\n }\n\n (config.plugins || []).forEach(plugin => {\n this.addPlugin(plugin);\n });\n\n // read _meta.json in the final, allow user's plugin to modify _meta.json\n if (!haveNavSidebarConfig) {\n const { pluginAutoNavSidebar } = await import(\n '@rspress/plugin-auto-nav-sidebar'\n );\n this.addPlugin(pluginAutoNavSidebar());\n }\n }\n\n addPlugin(plugin: RspressPlugin) {\n const existedIndex = this.#plugins.findIndex(\n item => item.name === plugin.name,\n );\n // Avoid the duplicated plugin\n if (existedIndex !== -1) {\n throw new Error(`The plugin \"${plugin.name}\" has been registered`);\n }\n\n this.#plugins.push(plugin);\n }\n\n getPlugins() {\n return this.#plugins;\n }\n\n clearPlugins() {\n this.#plugins = [];\n }\n\n removePlugin(pluginName: string) {\n const index = this.#plugins.findIndex(item => item.name === pluginName);\n if (index !== -1) {\n this.#plugins.splice(index, 1);\n }\n }\n\n async modifyConfig() {\n let config = this.#config;\n\n for (let i = 0; i < this.#plugins.length; i++) {\n const plugin = this.#plugins[i];\n if (typeof plugin.config === 'function') {\n config = await plugin.config(\n config || {},\n {\n addPlugin: this.addPlugin.bind(this),\n removePlugin: (pluginName: string) => {\n const index = this.#plugins.findIndex(\n item => item.name === pluginName,\n );\n this.removePlugin(pluginName);\n if (index <= i && index > 0) {\n i--;\n }\n },\n },\n this.#isProd,\n );\n }\n }\n this.#config = config;\n return this.#config;\n }\n\n async beforeBuild() {\n return this._runParallelAsyncHook(\n 'beforeBuild',\n this.#config || {},\n this.#isProd,\n );\n }\n\n async afterBuild() {\n return this._runParallelAsyncHook(\n 'afterBuild',\n this.#config || {},\n this.#isProd,\n );\n }\n\n async modifySearchIndexData(\n pages: PageIndexInfo[],\n ): Promise<PageIndexInfo[]> {\n return this._runParallelAsyncHook(\n 'modifySearchIndexData',\n pages,\n this.#isProd,\n );\n }\n\n async extendPageData(pageData: PageIndexInfo) {\n return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);\n }\n\n async addPages() {\n // addPages hooks\n const result = await this._runParallelAsyncHook(\n 'addPages',\n this.#config || {},\n this.#isProd,\n );\n return result.flat();\n }\n\n async routeGenerated(routes: RouteMeta[]) {\n return this._runParallelAsyncHook('routeGenerated', routes);\n }\n\n async addRuntimeModules() {\n const result: Record<string, string>[] = await this._runParallelAsyncHook(\n 'addRuntimeModules',\n this.#config || {},\n this.#isProd,\n );\n\n return result.reduce((prev, current) => {\n return {\n ...prev,\n ...current,\n };\n }, {});\n }\n\n async addSSGRoutes() {\n const result = await this._runParallelAsyncHook(\n 'addSSGRoutes',\n this.#config || {},\n this.#isProd,\n );\n\n return result.flat();\n }\n\n globalUIComponents(): (string | [string, object])[] {\n const result = this.#plugins.map(plugin => {\n return plugin.globalUIComponents || [];\n });\n\n return result.flat();\n }\n\n globalStyles(): string[] {\n return this.#plugins\n .filter(plugin => typeof plugin.globalStyles === 'string')\n .map(plugin => {\n return plugin.globalStyles;\n });\n }\n\n _runParallelAsyncHook(hookName: string, ...args: unknown[]) {\n return Promise.all(\n this.#plugins\n .filter(plugin => typeof plugin[hookName] === 'function')\n .map(plugin => {\n return plugin[hookName](...args);\n }),\n );\n }\n\n _runSerialAysncHook(hookName: string, ...args: unknown[]) {\n return this.#plugins.reduce(async (prev, plugin) => {\n if (typeof plugin[hookName] === 'function') {\n await prev;\n return plugin[hookName](...args);\n }\n return prev;\n }, Promise.resolve());\n }\n}\n","import type { UserConfig } from '@rspress/shared';\nimport type { RsbuildConfig } from '@rsbuild/core';\nimport { initRsbuild } from './initRsbuild';\nimport { writeSearchIndex } from './searchIndex';\nimport { PluginDriver } from './PluginDriver';\n\ninterface ServerInstance {\n close: () => Promise<void>;\n}\n\ninterface DevOptions {\n appDirectory: string;\n docDirectory: string;\n config: UserConfig;\n extraBuilderConfig?: RsbuildConfig;\n}\n\nexport async function dev(options: DevOptions): Promise<ServerInstance> {\n const { docDirectory, config, extraBuilderConfig } = options;\n const isProd = false;\n const pluginDriver = new PluginDriver(config, isProd);\n await pluginDriver.init();\n const modifiedConfig = await pluginDriver.modifyConfig();\n\n try {\n await pluginDriver.beforeBuild();\n\n // empty temp dir before build\n // await fs.emptyDir( TEMP_DIR);\n const builder = await initRsbuild(\n docDirectory,\n modifiedConfig,\n pluginDriver,\n false,\n extraBuilderConfig,\n );\n builder.onDevCompileDone(async () => {\n await pluginDriver.afterBuild();\n });\n const { server } = await builder.startDevServer({\n // We will support the following options in the future\n getPortSilently: true,\n });\n\n return server;\n } finally {\n await writeSearchIndex(modifiedConfig);\n }\n}\n","import { dirname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { HelmetData } from 'react-helmet-async';\nimport chalk from '@rspress/shared/chalk';\nimport fs from '@rspress/shared/fs-extra';\nimport {\n type PageData,\n type UserConfig,\n normalizeSlash,\n withBase,\n isDebugMode,\n type SSGConfig,\n} from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport {\n OUTPUT_DIR,\n APP_HTML_MARKER,\n HEAD_MARKER,\n META_GENERATOR,\n HTML_START_TAG,\n BODY_START_TAG,\n TEMP_DIR,\n} from './constants';\nimport { initRsbuild } from './initRsbuild';\nimport { writeSearchIndex } from './searchIndex';\nimport { PluginDriver } from './PluginDriver';\nimport type { Route } from '@/node/route/RouteService';\nimport { routeService } from '@/node/route/init';\nimport { renderFrontmatterHead, renderConfigHead } from './utils/renderHead';\n\ninterface BuildOptions {\n appDirectory: string;\n docDirectory: string;\n config: UserConfig;\n}\n\nexport async function bundle(\n docDirectory: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n enableSSG: boolean,\n) {\n try {\n // if enableSSG, build both client and server bundle\n // else only build client bundle\n const rsbuild = await initRsbuild(\n docDirectory,\n config,\n pluginDriver,\n enableSSG,\n );\n await rsbuild.build();\n } finally {\n await writeSearchIndex(config);\n }\n}\n\nexport interface SSRBundleExports {\n render: (\n url: string,\n helmetContext: object,\n ) => Promise<{ appHtml: string; pageData: PageData }>;\n routes: Route[];\n}\n\nexport async function renderPages(\n appDirectory: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n ssgConfig: SSGConfig,\n) {\n logger.info('Rendering pages...');\n const startTime = Date.now();\n const outputPath = config?.outDir ?? join(appDirectory, OUTPUT_DIR);\n const ssrBundlePath = join(outputPath, 'ssr', 'main.cjs');\n\n try {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n const { version } = await import('../../package.json');\n // There are two cases where we will fallback to CSR:\n // 1. ssr bundle load failed\n // 2. ssr bundle render failed\n // 3. ssg is disabled\n let render = null;\n if (ssgConfig) {\n try {\n const { default: ssrExports } = await import(\n pathToFileURL(ssrBundlePath).toString()\n );\n ({ render } = ssrExports as SSRBundleExports);\n } catch (e) {\n // skip fallback to CSR if ssg config is strict\n // TODO: strict by default in v2\n // see: https://github.com/web-infra-dev/rspress/issues/1317\n if (typeof ssgConfig === 'object' && ssgConfig.strict) {\n logger.error(\n `Failed to load SSG bundle: ${chalk.yellow(ssrBundlePath)}.`,\n );\n throw e;\n }\n\n // fallback to CSR\n logger.error(e);\n logger.warn(\n `Failed to load SSG bundle: ${chalk.yellow(ssrBundlePath)}, fallback to CSR.`,\n );\n }\n }\n\n const routes = routeService.getRoutes();\n const base = config?.base ?? '';\n\n // Get the html generated by builder, as the default ssr template\n const htmlTemplatePath = join(outputPath, 'index.html');\n const htmlTemplate = await fs.readFile(htmlTemplatePath, 'utf-8');\n const additionalRoutes = (await pluginDriver.addSSGRoutes()).map(route => ({\n routePath: withBase(route.path, base),\n }));\n const allRoutes = [...routes, ...additionalRoutes];\n const is404RouteInRoutes = allRoutes.some(\n route => route.routePath === '/404',\n );\n if (!is404RouteInRoutes) {\n allRoutes.push({\n routePath: '/404',\n });\n }\n await Promise.all(\n allRoutes\n .filter(route => {\n // filter the route including dynamic params\n return !route.routePath.includes(':');\n })\n .map(async route => {\n const helmetContext: HelmetData = {\n context: {},\n } as HelmetData;\n const { routePath } = route;\n let appHtml = '';\n if (render) {\n try {\n ({ appHtml } = await render(routePath, helmetContext.context));\n } catch (e) {\n if (typeof ssgConfig === 'object' && ssgConfig.strict) {\n logger.error(\n `Page \"${chalk.yellow(routePath)}\" SSG rendering failed.`,\n );\n throw e;\n }\n\n // fallback to CSR\n logger.warn(\n `Page \"${chalk.yellow(routePath)}\" SSG rendering error: ${e.message}, fallback to CSR.`,\n );\n }\n }\n\n const { helmet } = helmetContext.context;\n let html = htmlTemplate\n // During ssr, we already have the title in react-helmet\n .replace(/<title>(.*?)<\\/title>/gi, '')\n // Don't use `string` as second param\n // To avoid some special characters transformed to the marker, such as `$&`, etc.\n .replace(APP_HTML_MARKER, () => appHtml)\n .replace(\n META_GENERATOR,\n () => `<meta name=\"generator\" content=\"Rspress v${version}\">`,\n )\n .replace(\n HEAD_MARKER,\n [\n await renderConfigHead(config, route),\n helmet?.title?.toString(),\n helmet?.meta?.toString(),\n helmet?.link?.toString(),\n helmet?.style?.toString(),\n helmet?.script?.toString(),\n await renderFrontmatterHead(route),\n ].join(''),\n );\n if (helmet?.htmlAttributes) {\n html = html.replace(\n HTML_START_TAG,\n `${HTML_START_TAG} ${helmet?.htmlAttributes?.toString()}`,\n );\n }\n\n if (helmet?.bodyAttributes) {\n html = html.replace(\n BODY_START_TAG,\n `${BODY_START_TAG} ${helmet?.bodyAttributes?.toString()}`,\n );\n }\n\n const normalizeHtmlFilePath = (path: string) => {\n const normalizedBase = normalizeSlash(config?.base || '/');\n\n if (path.endsWith('/')) {\n return `${path}index.html`.replace(normalizedBase, '');\n }\n\n return `${path}.html`.replace(normalizedBase, '');\n };\n const fileName = normalizeHtmlFilePath(routePath);\n await fs.ensureDir(join(outputPath, dirname(fileName)));\n await fs.writeFile(join(outputPath, fileName), html);\n }),\n );\n // Remove ssr bundle\n if (!isDebugMode()) {\n await fs.remove(join(outputPath, 'ssr'));\n }\n await fs.remove(join(outputPath, 'html'));\n\n const totalTime = Date.now() - startTime;\n logger.success(`Pages rendered in ${chalk.yellow(totalTime)} ms.`);\n } catch (e) {\n logger.error(`Pages render error: ${e.stack}`);\n throw e;\n }\n}\n\nexport async function build(options: BuildOptions) {\n const { docDirectory, appDirectory, config } = options;\n const pluginDriver = new PluginDriver(config, true);\n await pluginDriver.init();\n const modifiedConfig = await pluginDriver.modifyConfig();\n await pluginDriver.beforeBuild();\n const ssgConfig = modifiedConfig.ssg ?? true;\n\n // empty temp dir before build\n await fs.emptyDir(TEMP_DIR);\n\n await bundle(docDirectory, modifiedConfig, pluginDriver, Boolean(ssgConfig));\n await renderPages(appDirectory, modifiedConfig, pluginDriver, ssgConfig);\n await pluginDriver.afterBuild();\n}\n","import type { FrontMatterMeta, RouteMeta, UserConfig } from '@rspress/shared';\nimport fsExtra from '@rspress/shared/fs-extra';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\n\nexport async function renderFrontmatterHead(route: any): Promise<string> {\n if (!isRouteMeta(route)) return '';\n const content = await fsExtra.readFile(route.absolutePath, {\n encoding: 'utf-8',\n });\n const {\n frontmatter: { head },\n } = loadFrontMatter<FrontMatterMeta>(content, route.absolutePath, '', true);\n if (!head || head.length === 0) return '';\n\n return head.map(([tag, attrs]) => `<${tag} ${renderAttrs(attrs)}>`).join('');\n}\n\nexport async function renderConfigHead(\n config: UserConfig,\n route: any,\n): Promise<string> {\n if (!isRouteMeta(route)) return '';\n if (!config.head || config.head.length === 0) return '';\n\n return config.head\n .map(head => {\n if (typeof head === 'string') return head;\n if (typeof head === 'function') {\n const resultHead = head(route);\n if (!resultHead) return '';\n if (typeof resultHead === 'string') return resultHead;\n return `<${resultHead[0]} ${renderAttrs(resultHead[1])}>`;\n }\n return `<${head[0]} ${renderAttrs(head[1])}>`;\n })\n .join('');\n}\n\nfunction renderAttrs(attrs: FrontMatterMeta['head'][number][1]): string {\n return Object.entries(attrs)\n .map(([key, value]) => {\n if (typeof value === 'boolean') return key;\n if (typeof value === 'string' || typeof value === 'number')\n return `${key}=\"${value}\"`;\n throw new Error(\n `Invalid value for attribute ${key}:${JSON.stringify(value)}`,\n );\n })\n .join('');\n}\n\nfunction isRouteMeta(route: any): route is RouteMeta {\n return 'routePath' in route && 'absolutePath' in route;\n}\n","import type { UserConfig } from '@rspress/shared';\nimport { mergeRsbuildConfig } from '@rsbuild/core';\nimport { initRsbuild } from './initRsbuild';\nimport { PluginDriver } from './PluginDriver';\n\ninterface ServeOptions {\n config: UserConfig;\n port?: number;\n host?: string;\n}\n\n// Serve ssg site in production\nexport async function serve(options: ServeOptions) {\n const { config, port: userPort, host: userHost } = options;\n const envPort = process.env.PORT;\n const envHost = process.env.HOST;\n const { builderConfig } = config;\n const port = Number(\n envPort || userPort || builderConfig?.server?.port || 4173,\n );\n const host =\n envHost || userHost || builderConfig?.server?.host || 'localhost';\n\n config.builderConfig = mergeRsbuildConfig(builderConfig, {\n server: {\n port,\n host,\n },\n });\n\n const pluginDriver = new PluginDriver(config, true);\n await pluginDriver.init();\n\n const modifiedConfig = await pluginDriver.modifyConfig();\n\n const builder = await initRsbuild(\n config.root,\n modifiedConfig,\n pluginDriver,\n false,\n );\n\n await builder.preview();\n}\n","export * from './node';\nexport * from '@rspress/shared';\nexport { mergeDocConfig } from '@rspress/shared/node-utils';\n"]}
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,QACP,WAAa;AAAA,MACf;AAAA,MACA,SAAW;AAAA,MACX,MAAQ;AAAA,MACR,iBAAiB;AAAA,MACjB,OAAS;AAAA,MACT,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,QAAU;AAAA,QACZ;AAAA,QACA,YAAY;AAAA,QACZ,kBAAkB;AAA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REGEXP","RSPRESS_TEMP_DIR","fs","routeService","resolver","enhancedResolve","CachedInputFileSystem","ResolverFactory","slash","page","normalizeSidebar","sidebar","domain","join","chalk","SEARCH_INDEX_NAME","logger","addLeadingSlash","withBase","filepath","mergeRsbuildConfig","dirname","isDebugMode","loadFrontMatter"],"ignoreList":[],"sources":["../package.json","../src/node/initRsbuild.ts","../src/node/constants.ts","../src/node/runtimeModule/index.ts","../src/node/runtimeModule/routeData.ts","../src/node/runtimeModule/siteData/index.ts","../src/node/utils/normalizePath.ts","../src/node/utils/getPageKey.ts","../src/node/utils/createHash.ts","../src/node/utils/detectReactVersion.ts","../src/node/utils/flattenMdxContent.ts","../src/node/utils/applyReplaceRules.ts","../src/node/runtimeModule/siteData/extractPageData.ts","../src/node/runtimeModule/siteData/normalizeThemeConfig.ts","../src/node/runtimeModule/i18n.ts","../src/node/runtimeModule/siteData/highlightLanguages.ts","../src/node/runtimeModule/globalUIComponents.ts","../src/node/runtimeModule/globalStyles.ts","../src/node/runtimeModule/searchHooks.ts","../src/node/searchIndex.ts","../src/node/route/RouteService.ts","../src/node/route/init.ts","../src/node/utils/detectCustomIcon.ts","../src/node/PluginDriver.ts","../src/node/dev.ts","../src/node/build.ts","../src/node/utils/renderHead.ts","../src/node/serve.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"@rspress/core\",\n \"version\": \"1.39.0\",\n \"description\": \"The Rspress Documentation Framework\",\n \"bugs\": \"https://github.com/web-infra-dev/rspress/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/web-infra-dev/rspress\",\n \"directory\": \"packages/cli/core\"\n },\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"jsnext:source\": \"./src/index.ts\",\n \"types\": \"./dist/index.d.ts\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/node/index.js\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./dist/*\": \"./dist/*\",\n \"./package.json\": \"./package.json\",\n \"./theme\": {\n \"default\": \"./theme.ts\"\n },\n \"./theme.css\": \"./theme.css\",\n \"./runtime\": {\n \"default\": \"./runtime.ts\"\n }\n },\n \"scripts\": {\n \"dev\": \"modern build -w\",\n \"build\": \"modern build\",\n \"reset\": \"rimraf ./**/node_modules\",\n \"test\": \"vitest run --passWithNoTests\"\n },\n \"engines\": {\n \"node\": \">=14.17.6\"\n },\n \"dependencies\": {\n \"@mdx-js/loader\": \"2.3.0\",\n \"@mdx-js/mdx\": \"2.3.0\",\n \"@mdx-js/react\": \"2.3.0\",\n \"@rsbuild/core\": \"~1.1.12\",\n \"@rsbuild/plugin-less\": \"~1.1.0\",\n \"@rsbuild/plugin-react\": \"~1.1.0\",\n \"@rsbuild/plugin-sass\": \"~1.1.2\",\n \"@rspress/mdx-rs\": \"0.6.4\",\n \"@rspress/plugin-auto-nav-sidebar\": \"workspace:*\",\n \"@rspress/plugin-container-syntax\": \"workspace:*\",\n \"@rspress/plugin-last-updated\": \"workspace:*\",\n \"@rspress/plugin-medium-zoom\": \"workspace:*\",\n \"@rspress/runtime\": \"workspace:*\",\n \"@rspress/shared\": \"workspace:*\",\n \"@rspress/theme-default\": \"workspace:*\",\n \"enhanced-resolve\": \"5.18.0\",\n \"github-slugger\": \"^2.0.0\",\n \"hast-util-from-html\": \"^2.0.3\",\n \"hast-util-heading-rank\": \"^3.0.0\",\n \"html-to-text\": \"^9.0.5\",\n \"htmr\": \"^1.0.2\",\n \"lodash-es\": \"^4.17.21\",\n \"mdast-util-mdxjs-esm\": \"^1.3.1\",\n \"react\": \"^18.3.1\",\n \"react-dom\": \"^18.3.1\",\n \"react-helmet-async\": \"^1.3.0\",\n \"react-lazy-with-preload\": \"^2.2.1\",\n \"react-syntax-highlighter\": \"^15.6.1\",\n \"rehype-external-links\": \"^3.0.0\",\n \"remark\": \"^14.0.3\",\n \"remark-gfm\": \"3.0.1\",\n \"rspack-plugin-virtual-module\": \"0.1.13\",\n \"unified\": \"^10.1.2\",\n \"unist-util-visit\": \"^4.1.2\",\n \"unist-util-visit-children\": \"^3.0.0\"\n },\n \"devDependencies\": {\n \"@modern-js/plugin-tailwindcss\": \"2.63.3\",\n \"@modern-js/tsconfig\": \"2.63.3\",\n \"@types/hast\": \"3.0.4\",\n \"@types/html-to-text\": \"^9.0.4\",\n \"@types/jest\": \"~29.5.14\",\n \"@types/lodash-es\": \"^4.17.12\",\n \"@types/mdast\": \"^4.0.4\",\n \"@types/node\": \"^18.11.17\",\n \"@types/react\": \"^18.3.18\",\n \"@types/react-dom\": \"^18.3.5\",\n \"postcss\": \"8.4.49\",\n \"rehype-stringify\": \"^9.0.4\",\n \"remark-parse\": \"^10.0.2\",\n \"remark-rehype\": \"^10.1.0\",\n \"rimraf\": \"^3.0.2\",\n \"tailwindcss\": \"^3.4.17\",\n \"typescript\": \"^5.5.3\",\n \"vitest\": \"2.1.8\"\n },\n \"sideEffects\": [\n \"*.css\",\n \"*.less\",\n \"*.sass\",\n \"*.scss\",\n \"**/virtual-global-styles.js\",\n \"virtual-global-styles\",\n \"./src/theme-default/styles/index.ts\"\n ],\n \"files\": [\n \"dist\",\n \"src/runtime\",\n \"src/theme-default\",\n \"src/shared\",\n \"index.html\",\n \"runtime.ts\",\n \"theme.ts\",\n \"loader.cjs\",\n \"compiled\"\n ],\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true,\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","import path from 'node:path';\nimport {\n type UserConfig,\n removeLeadingSlash,\n MDX_REGEXP,\n RSPRESS_TEMP_DIR,\n removeTrailingSlash,\n isDebugMode,\n} from '@rspress/shared';\nimport fs from '@rspress/shared/fs-extra';\nimport type {\n RsbuildInstance,\n RsbuildConfig,\n RsbuildPlugin,\n} from '@rsbuild/core';\nimport {\n CLIENT_ENTRY,\n SSR_ENTRY,\n PACKAGE_ROOT,\n OUTPUT_DIR,\n isProduction,\n inlineThemeScript,\n PUBLIC_DIR,\n DEFAULT_TITLE,\n} from './constants';\nimport { rsbuildPluginDocVM } from './runtimeModule';\nimport { serveSearchIndexMiddleware } from './searchIndex';\nimport { detectReactVersion, resolveReactAlias } from './utils';\nimport { initRouteService } from './route/init';\nimport type { PluginDriver } from './PluginDriver';\nimport type { RouteService } from './route/RouteService';\nimport { detectCustomIcon } from './utils/detectCustomIcon';\nimport { PLUGIN_REACT_NAME, pluginReact } from '@rsbuild/plugin-react';\nimport { PLUGIN_SASS_NAME, pluginSass } from '@rsbuild/plugin-sass';\nimport { PLUGIN_LESS_NAME, pluginLess } from '@rsbuild/plugin-less';\n\nexport interface MdxRsLoaderCallbackContext {\n resourcePath: string;\n links: string[];\n root: string;\n base: string;\n}\n\nfunction isPluginIncluded(config: UserConfig, pluginName: string): boolean {\n return (\n config.builderPlugins?.some(plugin => plugin.name === pluginName) ||\n config.builderConfig?.plugins?.some(\n plugin => plugin && (plugin as RsbuildPlugin).name === pluginName,\n )\n );\n}\n\nasync function createInternalBuildConfig(\n userDocRoot: string,\n config: UserConfig,\n enableSSG: boolean,\n routeService: RouteService,\n pluginDriver: PluginDriver,\n runtimeTempDir: string,\n): Promise<RsbuildConfig> {\n const cwd = process.cwd();\n const CUSTOM_THEME_DIR =\n config?.themeDir ?? path.join(process.cwd(), 'theme');\n const baseOutDir = config?.outDir ?? OUTPUT_DIR;\n const csrOutDir = baseOutDir;\n const ssrOutDir = path.join(baseOutDir, 'ssr');\n\n const DEFAULT_THEME = require.resolve('@rspress/theme-default');\n const base = config?.base ?? '';\n\n // In production, we need to add assetPrefix in asset path\n const assetPrefix = isProduction()\n ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base)\n : '';\n const reactVersion = await detectReactVersion();\n\n const normalizeIcon = (icon: string | undefined) => {\n if (!icon) {\n return undefined;\n }\n\n if (path.isAbsolute(icon)) {\n return path.join(userDocRoot, PUBLIC_DIR, icon);\n }\n\n return icon;\n };\n\n const [detectCustomIconAlias, reactCSRAlias, reactSSRAlias] =\n await Promise.all([\n detectCustomIcon(CUSTOM_THEME_DIR),\n resolveReactAlias(reactVersion, false),\n enableSSG ? resolveReactAlias(reactVersion, true) : Promise.resolve({}),\n ]);\n\n return {\n plugins: [\n ...(isPluginIncluded(config, PLUGIN_REACT_NAME) ? [] : [pluginReact()]),\n ...(isPluginIncluded(config, PLUGIN_SASS_NAME) ? [] : [pluginSass()]),\n ...(isPluginIncluded(config, PLUGIN_LESS_NAME) ? [] : [pluginLess()]),\n rsbuildPluginDocVM({\n userDocRoot,\n config,\n runtimeTempDir,\n routeService,\n pluginDriver,\n }),\n ],\n server: {\n port:\n !isProduction() && process.env.PORT\n ? Number(process.env.PORT)\n : undefined,\n printUrls: ({ urls }) => {\n return urls.map(url => `${url}/${removeLeadingSlash(base)}`);\n },\n publicDir: {\n name: path.join(userDocRoot, PUBLIC_DIR),\n },\n },\n dev: {\n progressBar: false,\n // Serve static files\n setupMiddlewares: [\n middlewares => {\n middlewares.unshift(serveSearchIndexMiddleware(config));\n },\n ],\n cliShortcuts: {\n // does not support restart server yet\n custom: shortcuts => shortcuts.filter(({ key }) => key !== 'r'),\n },\n },\n html: {\n title: config?.title ?? DEFAULT_TITLE,\n favicon: normalizeIcon(config?.icon),\n template: path.join(PACKAGE_ROOT, 'index.html'),\n tags: [\n config.themeConfig?.darkMode !== false && {\n tag: 'script',\n children: inlineThemeScript,\n append: false,\n },\n ].filter(Boolean),\n },\n output: {\n assetPrefix,\n distPath: {\n // just for rsbuild preview\n root: csrOutDir,\n },\n },\n resolve: {\n alias: {\n ...detectCustomIconAlias,\n '@mdx-js/react': require.resolve('@mdx-js/react'),\n '@theme': [CUSTOM_THEME_DIR, DEFAULT_THEME],\n '@/theme-default': DEFAULT_THEME,\n '@rspress/core': PACKAGE_ROOT,\n 'react-lazy-with-preload': require.resolve('react-lazy-with-preload'),\n 'react-syntax-highlighter': path.dirname(\n require.resolve('react-syntax-highlighter/package.json'),\n ),\n '@theme-assets': path.join(DEFAULT_THEME, '../assets'),\n },\n },\n source: {\n include: [PACKAGE_ROOT, path.join(cwd, 'node_modules', RSPRESS_TEMP_DIR)],\n define: {\n 'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),\n 'process.env.TEST': JSON.stringify(process.env.TEST),\n },\n },\n performance: {\n chunkSplit: {\n override: {\n cacheGroups: {\n // extract all CSS into a single file\n // ensure CSS in async chunks can be loaded for SSG\n styles: {\n name: 'styles',\n minSize: 0,\n chunks: 'all',\n test: /\\.(?:css|less|sass|scss)$/,\n priority: 99,\n },\n },\n },\n },\n },\n tools: {\n bundlerChain(chain, { CHAIN_ID, target }) {\n const isServer = target === 'node';\n const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);\n\n const swcLoaderOptions = jsModuleRule\n .use(CHAIN_ID.USE.SWC)\n .get('options');\n\n const checkDeadLinks =\n (config?.markdown?.checkDeadLinks && !isServer) ?? false;\n\n chain.module\n .rule('MDX')\n .type('javascript/auto')\n .test(MDX_REGEXP)\n .resolve.merge({\n conditionNames: jsModuleRule.resolve.conditionNames.values(),\n mainFields: jsModuleRule.resolve.mainFields.values(),\n })\n .end()\n .oneOf('MDXCompile')\n .use('builtin:swc-loader')\n .loader('builtin:swc-loader')\n .options(swcLoaderOptions)\n .end()\n .use('mdx-loader')\n .loader(require.resolve('../loader.cjs'))\n .options({\n config,\n docDirectory: userDocRoot,\n checkDeadLinks,\n routeService,\n pluginDriver,\n })\n .end();\n\n if (chain.plugins.has(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH)) {\n chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).tap(options => {\n options[0] ??= {};\n options[0].include = [/\\.([cm]js|[jt]sx?|flow)$/i, MDX_REGEXP];\n return options;\n });\n }\n\n chain.resolve.extensions.prepend('.md').prepend('.mdx').prepend('.mjs');\n\n chain.module\n .rule('css-virtual-module')\n .test(/\\.rspress[\\\\/]runtime[\\\\/]virtual-global-styles/)\n .merge({ sideEffects: true });\n\n if (isServer) {\n chain.output.filename('main.cjs');\n }\n\n const enableIncremental =\n !isProduction() && !process.env.DISABLE_RSPACK_INCREMENTAL;\n if (enableIncremental) {\n chain.merge({ experiments: { incremental: true } });\n }\n },\n },\n environments: {\n web: {\n resolve: {\n alias: reactCSRAlias,\n },\n source: {\n entry: {\n index: CLIENT_ENTRY,\n },\n define: {\n 'process.env.__SSR__': JSON.stringify(false),\n },\n },\n output: {\n target: 'web',\n distPath: {\n root: csrOutDir,\n },\n },\n },\n ...(enableSSG\n ? {\n node: {\n resolve: {\n alias: reactSSRAlias,\n },\n source: {\n entry: {\n index: SSR_ENTRY,\n },\n define: {\n 'process.env.__SSR__': JSON.stringify(true),\n },\n },\n performance: {\n printFileSize: isDebugMode(),\n },\n output: {\n emitAssets: false,\n target: 'node',\n distPath: {\n root: ssrOutDir,\n },\n minify: false,\n },\n },\n }\n : {}),\n },\n };\n}\n\nexport async function initRsbuild(\n rootDir: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n enableSSG: boolean,\n extraRsbuildConfig?: RsbuildConfig,\n): Promise<RsbuildInstance> {\n const cwd = process.cwd();\n const userDocRoot = path.resolve(rootDir || config?.root || cwd);\n const builderPlugins = config?.builderPlugins ?? [];\n // We use a temp dir to store runtime files, so we can separate client and server build\n // and we should empty temp dir before build\n const runtimeTempDir = path.join(RSPRESS_TEMP_DIR, 'runtime');\n const runtimeAbsTempDir = path.join(cwd, 'node_modules', runtimeTempDir);\n await fs.ensureDir(runtimeAbsTempDir);\n\n const routeService = await initRouteService({\n config,\n runtimeTempDir: runtimeAbsTempDir,\n scanDir: userDocRoot,\n pluginDriver,\n });\n const { createRsbuild, mergeRsbuildConfig } = await import('@rsbuild/core');\n\n const internalRsbuildConfig = await createInternalBuildConfig(\n userDocRoot,\n config,\n enableSSG,\n routeService,\n pluginDriver,\n runtimeTempDir,\n );\n\n const rsbuild = await createRsbuild({\n rsbuildConfig: mergeRsbuildConfig(\n internalRsbuildConfig,\n ...(pluginDriver\n .getPlugins()\n ?.map(plugin => plugin.builderConfig ?? {}) || []),\n config?.builderConfig || {},\n extraRsbuildConfig || {},\n ),\n });\n\n rsbuild.addPlugins(builderPlugins);\n\n return rsbuild;\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from '@rspress/shared';\n\nexport const isProduction = () => process.env.NODE_ENV === 'production';\n\n// Keep the quotation marks consistent before and after.\nexport const importStatementRegex =\n /import\\s+(.*?)\\s+from\\s+(['\"])(.*?)(?:\"|');?/gm;\n\n// In the first render, the theme will be set according to the user's system theme\n// - Should be injected into both development and production modes\n// - Class hook (.dark) is set for internal use (Tailwind)\n// - Style hook (colorScheme) is set for external use (CSS media queries or `light-dark()` function)\nexport const inlineThemeScript = `{\n const saved = localStorage.getItem('${APPEARANCE_KEY}')\n const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches\n const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'\n document.documentElement.classList.toggle('dark', isDark)\n document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'\n}`\n .replace(/\\n/g, ';')\n .replace(/\\s{2,}/g, '');\n\nconst dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));\n\nexport const PACKAGE_ROOT = path.join(dirname, '..');\n\nexport const CLIENT_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'clientEntry.js',\n);\n\nexport const SSR_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'ssrEntry.js',\n);\n\nexport const OUTPUT_DIR = 'doc_build';\n\nexport const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';\nexport const HEAD_MARKER = '<!--<?- HEAD ?>-->';\nexport const META_GENERATOR = '<!--<?- GENERATOR ?>-->';\nexport const HTML_START_TAG = '<html';\nexport const BODY_START_TAG = '<body';\n\nexport const DEFAULT_TITLE = 'Rspress';\n\nexport const PUBLIC_DIR = 'public';\nexport const TEMP_DIR = path.join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n);\n","import type { UserConfig } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type { RsbuildPlugin } from '@rsbuild/core';\nimport type { RouteService } from '../route/RouteService';\nimport type { PluginDriver } from '../PluginDriver';\nimport { routeVMPlugin } from './routeData';\nimport { siteDataVMPlugin } from './siteData/index';\nimport { i18nVMPlugin } from './i18n';\nimport { globalUIComponentsVMPlugin } from './globalUIComponents';\nimport { globalStylesVMPlugin } from './globalStyles';\nimport { searchHookVMPlugin } from './searchHooks';\n\nexport interface FactoryContext {\n userDocRoot: string;\n config: UserConfig;\n isSSR: boolean;\n runtimeTempDir: string;\n alias: Record<string, string | string[]>;\n routeService: RouteService;\n pluginDriver: PluginDriver;\n}\n\ntype RuntimeModuleFactory = (\n context: FactoryContext,\n) => Record<string, string> | Promise<Record<string, string>>;\n\nexport const runtimeModuleFactory: RuntimeModuleFactory[] = [\n /**\n * Generate route data for client and server runtime\n */\n routeVMPlugin,\n /**\n * Generate search index and site data for client runtime\n * Also responsible for automatically importing prism languages\n */\n siteDataVMPlugin,\n /**\n * Generate global components from config and plugins\n */\n globalUIComponentsVMPlugin,\n /**\n * Generate global styles from config and plugins\n */\n globalStylesVMPlugin,\n /**\n * Generate i18n text for client runtime\n */\n i18nVMPlugin,\n /**\n * Generate search hook module\n */\n searchHookVMPlugin,\n];\n\n// We will use this plugin to generate runtime module in browser, which is important to ensure the client have access to some compile-time data\nexport function rsbuildPluginDocVM(\n factoryContext: Omit<FactoryContext, 'alias' | 'isSSR'>,\n): RsbuildPlugin {\n const { pluginDriver } = factoryContext;\n return {\n name: 'rsbuild-plugin-doc-vm',\n setup(api) {\n api.modifyBundlerChain(async (bundlerChain, { target }) => {\n const isServer = target === 'node';\n // The order should be sync\n const alias = bundlerChain.resolve.alias.entries();\n const runtimeModule: Record<string, string> = {};\n // Add internal runtime module\n for (const factory of runtimeModuleFactory) {\n const moduleResult = await factory({\n ...factoryContext,\n isSSR: isServer,\n alias: alias as Record<string, string>,\n });\n Object.assign(runtimeModule, moduleResult);\n }\n // Add runtime module from outer plugins\n const modulesByPlugin = await pluginDriver.addRuntimeModules();\n Object.keys(modulesByPlugin).forEach(key => {\n if (runtimeModule[key]) {\n throw new Error(\n `The runtime module ${key} is duplicated, please check your plugin`,\n );\n }\n runtimeModule[key] = modulesByPlugin[key];\n });\n bundlerChain\n .plugin('rspress-runtime-module')\n .use(\n new RspackVirtualModulePlugin(\n runtimeModule,\n factoryContext.runtimeTempDir,\n ),\n );\n });\n },\n };\n}\n\nexport enum RuntimeModuleID {\n GlobalStyles = 'virtual-global-styles',\n GlobalComponents = 'virtual-global-components',\n RouteForClient = 'virtual-routes',\n RouteForSSR = 'virtual-routes-ssr',\n SiteData = 'virtual-site-data',\n SearchIndexHash = 'virtual-search-index-hash',\n I18nText = 'virtual-i18n-text',\n SearchHooks = 'virtual-search-hooks',\n PrismLanguages = 'virtual-prism-languages',\n}\n\nexport const runtimeModuleIDs = [\n RuntimeModuleID.GlobalStyles,\n RuntimeModuleID.GlobalComponents,\n RuntimeModuleID.RouteForClient,\n RuntimeModuleID.RouteForSSR,\n RuntimeModuleID.SiteData,\n RuntimeModuleID.SearchIndexHash,\n RuntimeModuleID.I18nText,\n RuntimeModuleID.SearchHooks,\n];\n","import { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function routeVMPlugin(context: FactoryContext) {\n const { routeService, isSSR } = context;\n\n // client: The components of route is lazy loaded\n if (!isSSR) {\n return {\n [RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),\n };\n }\n\n return {\n [RuntimeModuleID.RouteForClient]: routeService.generateRoutesCode(false),\n [RuntimeModuleID.RouteForSSR]: routeService.generateRoutesCode(true),\n };\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { groupBy } from 'lodash-es';\nimport { SEARCH_INDEX_NAME, type SiteData } from '@rspress/shared';\nimport { createHash } from '@/node/utils';\nimport { TEMP_DIR, isProduction } from '@/node/constants';\nimport { extractPageData } from './extractPageData';\nimport { normalizeThemeConfig } from './normalizeThemeConfig';\nimport { handleHighlightLanguages } from './highlightLanguages';\nimport { type FactoryContext, RuntimeModuleID } from '..';\n\n// How can we let the client runtime access the `indexHash`?\n// We can only do something after the Rspack build process becuase the index hash is generated within Rspack build process.There are two ways to do this:\n// 1. insert window.__INDEX_HASH__ = 'foo' into the html template manually\n// 2. replace the `__INDEX_HASH__` placeholder in the html template with the real index hash after Rspack build\nexport const indexHash = '';\n\nfunction deletePrivateField<T>(obj: T): T {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n const newObj = { ...obj };\n Object.keys(newObj).forEach(key => {\n if (key.startsWith('_')) {\n delete newObj[key];\n }\n });\n return newObj;\n}\n\nexport async function siteDataVMPlugin(context: FactoryContext) {\n const { config, alias, userDocRoot, routeService, pluginDriver } = context;\n const userConfig = config;\n // prevent modify the origin config object\n const tempSearchObj = Object.assign({}, userConfig.search);\n\n // searchHooks is a absolute path which may leak information\n if (tempSearchObj) {\n tempSearchObj.searchHooks = undefined;\n }\n\n const highlightLanguages: Set<string> = new Set();\n const replaceRules = userConfig?.replaceRules || [];\n // If the dev server restart when config file, we will reuse the siteData instead of extracting the siteData from source files again.\n const domain =\n userConfig?.search && userConfig?.search?.mode === 'remote'\n ? (userConfig?.search.domain ?? '')\n : '';\n const pages = await extractPageData(\n replaceRules,\n alias,\n domain,\n userDocRoot,\n routeService,\n highlightLanguages,\n );\n // modify page index by plugins\n await pluginDriver.modifySearchIndexData(pages);\n\n const versioned =\n userConfig.search &&\n userConfig.search.mode !== 'remote' &&\n userConfig.search.versioned;\n\n const groupedPages = groupBy(pages, page => {\n if (page.frontmatter?.pageType === 'home') {\n return 'noindex';\n }\n\n const version = versioned ? page.version : '';\n const lang = page.lang || '';\n\n return `${version}###${lang}`;\n });\n // remove the pages marked as noindex\n delete groupedPages.noindex;\n\n const indexHashByGroup = {} as Record<string, string>;\n\n // Generate search index by different versions & languages, file name is {SEARCH_INDEX_NAME}.{version}.{lang}.{hash}.json\n await Promise.all(\n Object.keys(groupedPages).map(async group => {\n // Avoid writing filepath in compile-time\n const stringifiedIndex = JSON.stringify(\n groupedPages[group].map(deletePrivateField),\n );\n const indexHash = createHash(stringifiedIndex);\n indexHashByGroup[group] = indexHash;\n\n const [version, lang] = group.split('###');\n const indexVersion = version ? `.${version.replace('.', '_')}` : '';\n const indexLang = lang ? `.${lang}` : '';\n\n await fs.ensureDir(TEMP_DIR);\n await fs.writeFile(\n path.join(\n TEMP_DIR,\n `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`,\n ),\n stringifiedIndex,\n );\n }),\n );\n\n // Run extendPageData hook in plugins\n await Promise.all(\n pages.map(async pageData => pluginDriver.extendPageData(pageData)),\n );\n\n const siteData: SiteData = {\n title: userConfig?.title || '',\n description: userConfig?.description || '',\n icon: userConfig?.icon || '',\n route: userConfig?.route,\n themeConfig: normalizeThemeConfig(userConfig, pages),\n base: userConfig?.base || '/',\n lang: userConfig?.lang || '',\n locales: userConfig?.locales || userConfig.themeConfig?.locales || [],\n logo: userConfig?.logo || '',\n logoText: userConfig?.logoText || '',\n ssg: Boolean(userConfig?.ssg) ?? true,\n multiVersion: {\n default: userConfig?.multiVersion?.default || '',\n versions: userConfig?.multiVersion?.versions || [],\n },\n search: tempSearchObj ?? { mode: 'local' },\n pages: pages.map(page => {\n // omit some fields for runtime size\n const { content, id, domain, _filepath, _html, ...rest } = page;\n // In production, we cannot expose the complete filepath for security reasons\n return isProduction() ? rest : { ...rest, _filepath };\n }),\n markdown: {\n showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,\n defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,\n codeHighlighter: userConfig?.markdown?.codeHighlighter || 'prism',\n },\n };\n\n const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};\n\n // @ts-ignore this field is extended in \"plugin-preview\"\n if (siteData.pages[0]?.extraHighlightLanguages?.length) {\n (siteData.pages[0] as any).extraHighlightLanguages.forEach((lang: string) =>\n highlightLanguages.add(lang),\n );\n }\n\n const aliases = handleHighlightLanguages(\n highlightLanguages,\n defaultLanguages,\n );\n const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());\n const sortedHighlightLanguages = Array.from(highlightLanguages).sort();\n\n return {\n [`${RuntimeModuleID.SiteData}.mjs`]: `export default ${JSON.stringify(\n siteData,\n null,\n 2,\n )}`,\n [RuntimeModuleID.SearchIndexHash]: `export default ${JSON.stringify(\n indexHashByGroup,\n null,\n 2,\n )}`,\n [RuntimeModuleID.PrismLanguages]: `export const aliases = ${JSON.stringify(\n sortedAliases,\n null,\n 2,\n )};\n export const languages = {\n ${sortedHighlightLanguages.map(lang => {\n return `\"${lang}\": require(\n \"react-syntax-highlighter/dist/cjs/languages/prism/${lang}\"\n ).default`;\n })}\n }`,\n };\n}\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const isWindows = os.platform() === 'win32';\n\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function normalizePath(id: string): string {\n return path.posix.normalize(isWindows ? slash(id) : id);\n}\n","import { removeLeadingSlash } from '@rspress/shared';\n\nexport function getPageKey(route: string) {\n const cleanRoute = removeLeadingSlash(route);\n return cleanRoute.replace(/\\//g, '_').replace(/\\.[^.]+$/, '') || 'index';\n}\n","import { createHash as createHashFunc } from 'node:crypto';\n\nexport function createHash(str: string) {\n return createHashFunc('sha256').update(str).digest('hex').slice(0, 8);\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { logger } from '@rspress/shared/logger';\nimport { PACKAGE_ROOT } from '../constants';\n\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nconst DEFAULT_REACT_VERSION = 18;\n\nexport async function detectReactVersion(): Promise<number> {\n // Detect react version from current cwd\n // return the major version of react\n // if not found, return 18\n const cwd = process.cwd();\n const reactPath = path.join(cwd, 'node_modules', 'react');\n if (await fs.pathExists(reactPath)) {\n const reactPkg = await fs.readJson(path.join(reactPath, 'package.json'));\n const version = Number(reactPkg.version.split('.')[0]);\n return version;\n }\n\n return DEFAULT_REACT_VERSION;\n}\n\nexport async function resolveReactAlias(reactVersion: number, isSSR: boolean) {\n const basedir =\n reactVersion === DEFAULT_REACT_VERSION ? PACKAGE_ROOT : process.cwd();\n const libPaths = [\n 'react',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n 'react-dom',\n 'react-dom/server',\n ];\n if (reactVersion >= DEFAULT_REACT_VERSION) {\n libPaths.push('react-dom/client');\n }\n const alias: Record<string, string> = {};\n const resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.js'],\n alias,\n conditionNames: isSSR ? ['...'] : ['browser', '...'],\n });\n await Promise.all(\n libPaths.map(async lib => {\n try {\n alias[lib] = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n { importer: basedir },\n basedir,\n lib,\n {},\n (err, filePath) => {\n if (err || filePath === false) {\n return reject(err);\n }\n return resolve(filePath);\n },\n );\n });\n } catch (e) {\n console.log(e);\n logger.warn(`${lib} not found`);\n }\n }),\n );\n return alias;\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { MDX_REGEXP } from '@rspress/shared';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { importStatementRegex } from '../constants';\n\nimport type { Root } from 'hast';\nimport type { Resolver } from 'enhanced-resolve';\n\nlet resolver: Resolver;\nlet startFlatten = false;\n\nconst processor = createProcessor();\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nexport async function resolveDepPath(\n importPath: string,\n importer: string,\n alias: Record<string, string | string[]>,\n) {\n if (!resolver) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md'],\n alias,\n });\n }\n const resolveResult = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n {\n importer,\n },\n importer,\n importPath,\n {},\n (err, filePath) => {\n if (err) {\n return reject(err);\n }\n if (!filePath) {\n return reject(\n new Error(\n `Empty result when resolving ${importPath} from ${importer}`,\n ),\n );\n }\n return resolve(filePath);\n },\n );\n });\n return resolveResult;\n}\n\ninterface ESTree {\n body: {\n type: 'ImportDeclaration';\n specifiers: { local: { name: string } }[];\n source: { value: string };\n }[];\n}\n\nexport async function flattenMdxContent(\n content: string,\n basePath: string,\n alias: Record<string, string | string[]>,\n): Promise<{ flattenContent: string; deps: string[] }> {\n const deps = [];\n // Performance optimization: if the content does not contain any import statement, we can skip the parsing process\n // So we need to check this match\n\n // Create new regExp to avoid the regex cache the last match index\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag\n const regex = new RegExp(importStatementRegex);\n if (!regex.test(content)) {\n return { flattenContent: content, deps };\n }\n\n // We should update the resolver instanceof because the alias should be passed to it\n // If we reuse the resolver instance in `detectReactVersion` method, the resolver will lose the alias info and cannot resolve path correctly in mdx files.\n if (!startFlatten) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md', '.js'],\n alias,\n });\n startFlatten = true;\n }\n\n let ast: Root;\n let result = content;\n\n try {\n ast = processor.parse(content) as Root;\n } catch (e) {\n // Fallback: if mdx parse failed, just return the content\n return { flattenContent: content, deps };\n }\n\n const importNodes = ast.children\n .filter(node => node.type === ('mdxjsEsm' as any))\n .flatMap(node => (node.data?.estree as ESTree)?.body || [])\n .filter(node => node.type === 'ImportDeclaration');\n for (const importNode of importNodes) {\n // import Comp from './a';\n // {id: Comp, importPath: './a'}\n const id = importNode.specifiers[0].local.name;\n const importPath = importNode.source.value;\n\n let absoluteImportPath: string;\n try {\n absoluteImportPath = await resolveDepPath(\n importPath,\n path.dirname(basePath),\n alias,\n );\n } catch (e) {\n continue;\n }\n\n if (MDX_REGEXP.test(absoluteImportPath)) {\n // replace import statement with the content of the imported file\n const importedContent = fs.readFileSync(absoluteImportPath, 'utf-8');\n const { flattenContent: replacedValue, deps: subDeps } =\n await flattenMdxContent(importedContent, absoluteImportPath, alias);\n\n result = result\n .replace(\n new RegExp(`import\\\\s+${id}\\\\s+from\\\\s+['\"](${importPath})['\"];?`),\n '',\n )\n .replace(new RegExp(`<${id}\\\\s*/>`, 'g'), () => replacedValue);\n\n deps.push(...subDeps, absoluteImportPath);\n }\n }\n\n return { flattenContent: result, deps };\n}\n","import type { ReplaceRule } from '@rspress/shared';\n\nexport function applyReplaceRules(\n code = '',\n replaceRules: ReplaceRule[] = [],\n): string {\n let result = code;\n for (const rule of replaceRules) {\n result = result.replace(rule.search, rule.replace);\n }\n return result;\n}\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { htmlToText } from 'html-to-text';\nimport { compile } from '@rspress/mdx-rs';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\nimport {\n type Header,\n MDX_REGEXP,\n type ReplaceRule,\n type PageIndexInfo,\n} from '@rspress/shared';\nimport { flattenMdxContent } from '@/node/utils';\nimport { importStatementRegex } from '@/node/constants';\nimport type { RouteService } from '@/node/route/RouteService';\nimport { applyReplaceRules } from '@/node/utils/applyReplaceRules';\n\nexport function applyReplaceRulesToNestedObject(\n obj: Record<string, any>,\n replaceRules: ReplaceRule[],\n) {\n for (const key in obj) {\n if (typeof obj[key] === 'string') {\n obj[key] = applyReplaceRules(obj[key], replaceRules);\n } else if (typeof obj[key] === 'object') {\n obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);\n }\n }\n\n return obj;\n}\n\nexport async function extractPageData(\n replaceRules: ReplaceRule[],\n alias: Record<string, string | string[]>,\n domain: string,\n root: string,\n routeService: RouteService,\n highlighterLangs: Set<string>,\n): Promise<PageIndexInfo[]> {\n const pageData = await Promise.all(\n routeService\n .getRoutes()\n .map(async (route, index): Promise<PageIndexInfo> => {\n const defaultIndexInfo: PageIndexInfo = {\n id: index,\n title: '',\n content: '',\n _html: '',\n routePath: route.routePath,\n lang: route.lang,\n toc: [],\n domain,\n frontmatter: {},\n version: route.version,\n _filepath: route.absolutePath,\n _relativePath: path.relative(root, route.absolutePath),\n };\n if (!MDX_REGEXP.test(route.absolutePath)) {\n return defaultIndexInfo;\n }\n let content: string = await fs.readFile(route.absolutePath, 'utf8');\n const { frontmatter, content: strippedFrontMatter } = loadFrontMatter(\n content,\n route.absolutePath,\n root,\n );\n\n // 1. Replace rules for frontmatter & content\n applyReplaceRulesToNestedObject(frontmatter, replaceRules);\n\n const { flattenContent } = await flattenMdxContent(\n applyReplaceRules(strippedFrontMatter, replaceRules),\n route.absolutePath,\n alias,\n );\n\n content = flattenContent.replace(importStatementRegex, '');\n\n const {\n html,\n title,\n toc: rawToc,\n languages,\n } = await compile({\n value: content,\n filepath: route.absolutePath,\n development: process.env.NODE_ENV !== 'production',\n root,\n });\n\n if (!title?.length && !frontmatter && !frontmatter.title?.length) {\n return null;\n }\n\n content = htmlToText(String(html), {\n wordwrap: 80,\n selectors: [\n {\n selector: 'a',\n options: {\n ignoreHref: true,\n },\n },\n {\n selector: 'img',\n format: 'skip',\n },\n {\n // Skip code blocks\n selector: 'pre > code',\n format: 'skip',\n },\n ...['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(tag => ({\n selector: tag,\n options: {\n uppercase: false,\n },\n })),\n ],\n tables: true,\n longWordSplit: {\n forceWrapOnLimit: true,\n },\n });\n if (content.startsWith(title)) {\n // Remove the title from the content\n content = content.slice(title.length);\n }\n\n languages.forEach(lang => highlighterLangs.add(lang));\n\n // rawToc comes from mdx compile and it uses `-number` to unique toc of same id\n // We need to find the character index position of each toc in the content thus benefiting for search engines\n const toc: Header[] = rawToc.map(item => {\n const match = item.id.match(/-(\\d+)$/);\n let position = -1;\n if (match) {\n for (let i = 0; i < Number(match[1]); i++) {\n // When text is repeated, the position needs to be determined based on -number\n position = content.indexOf(`\\n${item.text}#\\n\\n`, position + 1);\n\n // If the positions don't match, it means the text itself may exist -number\n if (position === -1) {\n break;\n }\n }\n }\n return {\n ...item,\n charIndex: content.indexOf(`\\n${item.text}#\\n\\n`, position + 1),\n };\n });\n\n return {\n ...defaultIndexInfo,\n title: frontmatter.title || title,\n toc,\n // Stripped frontmatter content\n content,\n _html: html,\n frontmatter: {\n ...frontmatter,\n __content: undefined,\n },\n };\n }),\n );\n return pageData.filter(Boolean);\n}\n","import {\n type UserConfig,\n type DefaultThemeConfig,\n type NormalizedDefaultThemeConfig,\n type SidebarItem,\n type SidebarGroup,\n type NormalizedSidebarGroup,\n type PageIndexInfo,\n type NavItemWithLink,\n withBase,\n addLeadingSlash,\n isExternalUrl,\n withoutBase,\n type NavItem,\n type Sidebar,\n type SidebarDivider,\n slash,\n type SidebarSectionHeader,\n} from '@rspress/shared';\nimport { applyReplaceRules } from '../../utils/applyReplaceRules';\nimport { getI18nData } from '../i18n';\n\nexport function normalizeThemeConfig(\n docConfig: UserConfig,\n pages: PageIndexInfo[] = [],\n): NormalizedDefaultThemeConfig {\n const {\n locales: siteLocales,\n base = '',\n lang,\n replaceRules = [],\n multiVersion,\n } = docConfig;\n const { versions = [] } = multiVersion || {};\n const hasMultiVersion = versions.length > 0;\n docConfig.themeConfig = docConfig.themeConfig || {};\n const { themeConfig } = docConfig;\n const locales = siteLocales ?? (themeConfig?.locales || []);\n const i18nTextData = getI18nData(docConfig);\n // In following code, we will normalize the theme config reference to the pages data extracted from mdx files\n const normalizeLinkPrefix = (link = '', currentLang = '') => {\n const normalizedLink = slash(link);\n if (\n !currentLang ||\n !link ||\n withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) ||\n isExternalUrl(normalizedLink) ||\n // In multi version case, we have got the complete link prefix in `plugin-auto-nav-sidebar` and does not need to add the lang prefix\n hasMultiVersion\n ) {\n return normalizedLink;\n }\n // if lang exists, we should add the lang prefix to the link\n // such /guide -> /en/guide\n return lang === currentLang\n ? normalizedLink\n : `/${currentLang}${addLeadingSlash(normalizedLink)}`;\n };\n\n const getI18nText = (key = '', currentLang = '') => {\n const text = i18nTextData[key]?.[currentLang];\n return text || key;\n };\n // Normalize sidebar\n const normalizeSidebar = (\n sidebar?: DefaultThemeConfig['sidebar'],\n currentLang = '',\n ): NormalizedDefaultThemeConfig['sidebar'] => {\n const normalizedSidebar: NormalizedDefaultThemeConfig['sidebar'] = {};\n if (!sidebar) {\n return {};\n }\n const normalizeSidebarItem = (\n item:\n | SidebarGroup\n | SidebarItem\n | SidebarDivider\n | SidebarSectionHeader\n | string,\n ):\n | NormalizedSidebarGroup\n | SidebarItem\n | SidebarDivider\n | SidebarSectionHeader => {\n // Meet the divider, return directly\n if (typeof item === 'object' && 'dividerType' in item) {\n return item;\n }\n\n // Meet the section header, return i18n text\n if (typeof item === 'object' && 'sectionHeaderText' in item) {\n item.sectionHeaderText = applyReplaceRules(\n getI18nText(item.sectionHeaderText, currentLang),\n replaceRules,\n );\n return item;\n }\n\n if (typeof item === 'object' && 'items' in item) {\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link),\n collapsed: item.collapsed ?? false,\n collapsible: item.collapsible ?? true,\n tag: item.tag,\n items: item.items.map(subItem => {\n return normalizeSidebarItem(subItem) as\n | NormalizedSidebarGroup\n | SidebarItem;\n }),\n };\n }\n\n if (typeof item === 'string') {\n const normalizedItem = normalizeLinkPrefix(item, currentLang);\n const page = pages.find(\n page => page.routePath === withBase(normalizedItem, base),\n );\n return {\n text: applyReplaceRules(page?.title || '', replaceRules),\n link: normalizedItem,\n _fileKey: page._relativePath.replace(/\\.mdx?$/, ''),\n };\n }\n\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link),\n tag: item.tag,\n };\n };\n\n const normalizeSidebar = (sidebar: Sidebar) => {\n Object.keys(sidebar).forEach(key => {\n const value = sidebar[key];\n normalizedSidebar[key] = value.map(normalizeSidebarItem) as (\n | NormalizedSidebarGroup\n | SidebarItem\n )[];\n });\n };\n\n normalizeSidebar(sidebar);\n\n return normalizedSidebar;\n };\n\n const normalizeNav = (\n nav?: DefaultThemeConfig['nav'],\n currentLang?: string,\n ) => {\n if (!nav) {\n return [];\n }\n const transformNavItem = (navItem: NavItem) => {\n const text = applyReplaceRules(\n getI18nText(navItem.text, currentLang),\n replaceRules,\n );\n if ('link' in navItem) {\n return {\n ...navItem,\n text,\n link: normalizeLinkPrefix(navItem.link, currentLang),\n };\n }\n\n if ('items' in navItem) {\n return {\n ...navItem,\n text,\n items: navItem.items.map((item: NavItemWithLink) => {\n return {\n ...item,\n text: applyReplaceRules(\n getI18nText(item.text, currentLang),\n replaceRules,\n ),\n link: normalizeLinkPrefix(item.link, currentLang),\n };\n }),\n };\n }\n\n return navItem;\n };\n\n if (Array.isArray(nav)) {\n return nav.map(transformNavItem);\n }\n\n // Multi version case\n return Object.entries(nav).reduce((acc, [key, value]) => {\n acc[key] = value.map(transformNavItem);\n return acc;\n }, {});\n };\n\n /**\n * There are two place the user will define the locales:\n * 1. in the `doc.locales` (the site config)\n * 2. in the `doc.themeConfig.locales`\n * The locales in the theme config will override the locales in the site config.\n *\n * For nav and sidebar, we prefer the locales in the `themeConfig.nav` and `themeConfig.sidebar` if it exists. And the frameowork will generate complete nav and sidebar for each locale and place them in the `themeConfig.locales` field.\n */\n if (locales.length) {\n themeConfig.locales = locales.map(({ lang: currentLang, label }) => {\n const localeInThemeConfig = themeConfig.locales?.find(\n locale => locale.lang === currentLang,\n );\n return {\n lang: currentLang,\n label,\n ...(localeInThemeConfig || {}),\n sidebar: normalizeSidebar(\n localeInThemeConfig?.sidebar ?? themeConfig.sidebar,\n currentLang,\n ),\n nav: normalizeNav(\n localeInThemeConfig?.nav ?? themeConfig.nav,\n currentLang,\n ),\n };\n });\n } else {\n themeConfig.sidebar = normalizeSidebar(themeConfig?.sidebar);\n themeConfig.nav = normalizeNav(themeConfig?.nav);\n }\n return themeConfig as NormalizedDefaultThemeConfig;\n}\n","import { join } from 'node:path';\nimport type { UserConfig } from '@rspress/shared';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nconst DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');\n\nexport function getI18nData(docConfig: UserConfig) {\n const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;\n try {\n delete require.cache[i18nSourcePath];\n // eslint-disable-next-line import/no-dynamic-require\n const i18nSource = require(i18nSourcePath);\n return i18nSource;\n } catch (e) {\n return {};\n }\n}\n\nexport function i18nVMPlugin(context: FactoryContext) {\n const { config } = context;\n const i18nData = getI18nData(config);\n return {\n [RuntimeModuleID.I18nText]: `export default ${JSON.stringify(i18nData, null, 2)}`,\n };\n}\n","import chalk from '@rspress/shared/chalk';\nimport { DEFAULT_HIGHLIGHT_LANGUAGES } from '@rspress/shared';\n\nlet supportedLanguages: Set<string>;\n\nexport function handleHighlightLanguages(\n highlightLanguages: Set<string>,\n defaultLanguages: (string | [string, string])[],\n): Record<string, string[]> {\n // Automatically import prism languages\n const aliases: Record<string, string[]> = {};\n if (highlightLanguages.size) {\n if (!supportedLanguages) {\n const langs =\n require('react-syntax-highlighter/dist/cjs/languages/prism/supported-languages').default;\n supportedLanguages = new Set(langs);\n }\n\n // Restore alias to the original name\n let useDeprecatedTypeWarning = true;\n const names: Record<string, string> = {};\n [...DEFAULT_HIGHLIGHT_LANGUAGES, ...defaultLanguages].forEach(lang => {\n if (Array.isArray(lang)) {\n const [alias, name] = lang;\n names[alias] = name;\n } else if (useDeprecatedTypeWarning) {\n // Deprecated warning\n console.log(\n `${chalk.yellowBright(\n 'warning',\n )} Automatic import is supported. \\`highlightLanguages\\` is now used only as alias, and string types will be ignored. \\n`,\n );\n useDeprecatedTypeWarning = false;\n }\n });\n\n [...highlightLanguages.values()].forEach(lang => {\n const name = names[lang];\n if (name && supportedLanguages.has(name)) {\n const temp = aliases[name] || (aliases[name] = []);\n if (!temp.includes(lang)) {\n temp.push(lang);\n }\n\n // delete first, user may config alias to itself like ['go', 'go']\n highlightLanguages.delete(lang);\n highlightLanguages.add(name);\n return;\n }\n\n if (!supportedLanguages.has(lang)) {\n highlightLanguages.delete(lang);\n }\n });\n }\n\n return aliases;\n}\n","import { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function globalUIComponentsVMPlugin(context: FactoryContext) {\n const { config, pluginDriver } = context;\n let index = 0;\n\n const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();\n const globalComponents = [\n ...(config?.globalUIComponents || []),\n ...globalUIComponentsByPlugins,\n ];\n const moduleContent = globalComponents\n .map(source => {\n const name = `Comp_${index}`;\n if (Array.isArray(source)) {\n return `import ${name} from ${JSON.stringify(source[0])};\nconst Props_${index++} = ${JSON.stringify(source[1])};\\n`;\n }\n\n index++;\n return `import ${name} from ${JSON.stringify(source)};\\n`;\n })\n .concat(\n `export default [${Array.from({ length: index }, (_, i) => {\n if (Array.isArray(globalComponents[i])) {\n return `[${`Comp_${i}`}, Props_${i}]`;\n }\n return `Comp_${i}`;\n }).join(', ')}];`,\n )\n .join('');\n\n return {\n [RuntimeModuleID.GlobalComponents]: moduleContent,\n };\n}\n","import fs from '@rspress/shared/fs-extra';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function globalStylesVMPlugin(context: FactoryContext) {\n const { config, pluginDriver } = context;\n const globalStylesByPlugins = pluginDriver.globalStyles();\n\n if (config.globalStyles) {\n // Only patch user config global styles\n const source = config.globalStyles;\n const styleContent = await fs.readFile(source, 'utf-8');\n\n // Patch --modern-abc, .modern-abc global name\n const patchedStyleContent = styleContent\n .replace(/--modern-/g, '--rp-')\n .replace(/\\.modern-doc/g, '.rspress')\n .replace(/\\.modern-/g, '.rspress-');\n\n await fs.writeFile(source, patchedStyleContent, 'utf-8');\n }\n\n const moduleContent = (\n await Promise.all(\n [config?.globalStyles || '', ...globalStylesByPlugins]\n .filter(source => source.length > 0)\n .map(async source => {\n return `import ${JSON.stringify(source)};`;\n }),\n )\n ).join('');\n\n return {\n [RuntimeModuleID.GlobalStyles]: moduleContent,\n };\n}\n","import path from 'node:path';\nimport { type FactoryContext, RuntimeModuleID } from '.';\n\nexport async function searchHookVMPlugin(context: FactoryContext) {\n const { config } = context;\n let content = 'export const onSearch = () => {};';\n let extname = '';\n if (\n typeof config.search === 'object' &&\n typeof config.search.searchHooks === 'string'\n ) {\n content = `export * from '${config.search.searchHooks}'`;\n extname = path.extname(config.search.searchHooks);\n }\n\n return {\n [`${RuntimeModuleID.SearchHooks}${extname}`]: content,\n };\n}\n","import path, { join } from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport chalk from '@rspress/shared/chalk';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { type UserConfig, isSCM, SEARCH_INDEX_NAME } from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport { isProduction, OUTPUT_DIR, TEMP_DIR } from './constants';\n\nexport async function writeSearchIndex(config: UserConfig) {\n if (config?.search === false) {\n return;\n }\n const cwd = process.cwd();\n // get all search index files, format is `${SEARCH_INDEX_NAME}.foo.bar.${hash}.json`\n const searchIndexFiles = await fs.readdir(TEMP_DIR);\n const outDir = config?.outDir ?? join(cwd, OUTPUT_DIR);\n\n // For performance, we only stitch the string of search index data instead of big JavaScript object in memory\n let searchIndexData = '[]';\n let scaning = false;\n for (const searchIndexFile of searchIndexFiles) {\n if (\n !searchIndexFile.includes(SEARCH_INDEX_NAME) ||\n !searchIndexFile.endsWith('.json')\n ) {\n continue;\n }\n const source = join(TEMP_DIR, searchIndexFile);\n const target = join(outDir, 'static', searchIndexFile);\n const searchIndex = await fs.readFile(\n join(TEMP_DIR, searchIndexFile),\n 'utf-8',\n );\n searchIndexData = `${searchIndexData.slice(0, -1)}${\n scaning ? ',' : ''\n }${searchIndex.slice(1)}`;\n await fs.move(source, target, { overwrite: true });\n scaning = true;\n }\n\n if (isProduction() && isSCM() && config?.search?.mode === 'remote') {\n const { apiUrl, indexName } = config.search;\n try {\n await fetch(`${apiUrl}?index=${indexName}`, {\n method: 'PUT',\n body: searchIndexData,\n headers: { 'Content-Type': 'application/json' },\n });\n\n logger.info(\n chalk.green(\n `[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`,\n ),\n );\n } catch (e) {\n logger.info(\n chalk.red(\n `[doc-tools] Upload search index \\`${indexName}\\` failed:\\n ${e}`,\n ),\n );\n }\n }\n}\n\ntype RequestHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void;\n\nexport function serveSearchIndexMiddleware(config: UserConfig): RequestHandler {\n return (req, res, next) => {\n const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;\n if (req.url?.includes(searchIndexRequestMatch)) {\n res.setHeader('Content-Type', 'application/json');\n // Get search index name from request url\n const searchIndexFile = req.url?.split('/').pop();\n fs.createReadStream(\n path.join(\n process.cwd(),\n config?.outDir || OUTPUT_DIR,\n 'static',\n searchIndexFile,\n ),\n 'utf-8',\n ).pipe(res, { end: true });\n } else {\n next?.();\n }\n };\n}\n","import path from 'node:path';\nimport type { ComponentType } from 'react';\nimport fs from '@rspress/shared/fs-extra';\nimport {\n addLeadingSlash,\n addTrailingSlash,\n type PageModule,\n type UserConfig,\n type RouteMeta,\n withBase,\n} from '@rspress/shared';\nimport { getPageKey, normalizePath } from '../utils';\nimport type { PluginDriver } from '../PluginDriver';\nimport { PUBLIC_DIR } from '../constants';\n\nexport const DEFAULT_PAGE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'];\n\nexport interface Route {\n path: string;\n element: React.ReactElement;\n filePath: string;\n preload: () => Promise<PageModule<ComponentType<unknown>>>;\n lang: string;\n}\n\nexport interface RouteOptions {\n extensions?: string[];\n include?: string[];\n exclude?: string[];\n}\n\nexport const normalizeRoutePath = (\n routePath: string,\n base: string,\n lang: string,\n version: string,\n langs: string[],\n versions: string[],\n extensions: string[] = DEFAULT_PAGE_EXTENSIONS,\n) => {\n const hasTrailSlash = routePath.endsWith('/');\n let versionPart = '';\n let langPart = '';\n let purePathPart = '';\n const parts: string[] = routePath.split('/').filter(Boolean);\n\n if (version) {\n const versionToMatch = parts[0];\n if (versions.includes(versionToMatch)) {\n if (versionToMatch !== version) {\n versionPart = versionToMatch;\n }\n parts.shift();\n }\n }\n\n if (lang) {\n const langToMatch = parts[0];\n if (langs.includes(langToMatch)) {\n if (langToMatch !== lang) {\n langPart = langToMatch;\n }\n parts.shift();\n }\n }\n purePathPart = parts.join('/');\n\n let normalizedRoutePath = addLeadingSlash(\n [versionPart, langPart, purePathPart].filter(Boolean).join('/'),\n )\n // remove the extension\n .replace(new RegExp(`\\\\.(${extensions.join('|')})$`), '')\n .replace(/\\.html$/, '')\n .replace(/\\/index$/, '/');\n\n // restore the trail slash\n if (hasTrailSlash) {\n normalizedRoutePath = addTrailingSlash(normalizedRoutePath);\n }\n\n return {\n routePath: withBase(normalizedRoutePath, base),\n lang: langPart || lang,\n version: versionPart || version,\n };\n};\n\nexport class RouteService {\n routeData: Map<string, RouteMeta> = new Map();\n\n #scanDir: string;\n\n #defaultLang: string;\n\n #defaultVersion: string = '';\n\n #extensions: string[] = [];\n\n #langs: string[] = [];\n\n #versions: string[] = [];\n\n #include: string[] = [];\n\n #exclude: string[] = [];\n\n #base: string = '';\n\n #tempDir: string = '';\n\n #pluginDriver: PluginDriver;\n\n constructor(\n scanDir: string,\n userConfig: UserConfig,\n tempDir: string,\n pluginDriver: PluginDriver,\n ) {\n const routeOptions = userConfig?.route || {};\n this.#scanDir = scanDir;\n this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;\n this.#include = routeOptions.include || [];\n this.#exclude = routeOptions.exclude || [];\n this.#defaultLang = userConfig?.lang || '';\n this.#langs = (\n userConfig?.locales ??\n userConfig?.themeConfig?.locales ??\n []\n ).map(item => item.lang);\n this.#base = userConfig?.base || '';\n this.#tempDir = tempDir;\n this.#pluginDriver = pluginDriver;\n\n if (userConfig.multiVersion) {\n this.#defaultVersion = userConfig.multiVersion.default || '';\n this.#versions = userConfig.multiVersion.versions || [];\n }\n }\n\n async init() {\n const globby = (\n await import(\n // @ts-expect-error\n // eslint-disable-next-line node/file-extension-in-import\n '../compiled/globby/index.js'\n )\n ).default as typeof import('../../../compiled/globby');\n // 1. internal pages\n const files = (\n await globby([`**/*.{${this.#extensions.join(',')}}`, ...this.#include], {\n cwd: this.#scanDir,\n absolute: true,\n ignore: [\n ...this.#exclude,\n '**/node_modules/**',\n '**/.eslintrc.js',\n '**/.nx-cache/**',\n `./${PUBLIC_DIR}/**`,\n ],\n })\n ).sort();\n files.forEach(filePath => {\n const fileRelativePath = normalizePath(\n path.relative(this.#scanDir, filePath),\n );\n const { routePath, lang, version } =\n this.normalizeRoutePath(fileRelativePath);\n const absolutePath = path.join(this.#scanDir, fileRelativePath);\n\n const routeInfo = {\n routePath,\n absolutePath: normalizePath(absolutePath),\n relativePath: fileRelativePath,\n pageName: getPageKey(fileRelativePath),\n lang,\n version,\n };\n this.addRoute(routeInfo);\n });\n // 2. external pages added by plugins\n const externalPages = await this.#pluginDriver.addPages();\n\n await Promise.all(\n externalPages.map(async (route, index) => {\n const { routePath, content, filepath } = route;\n // case1: specify the filepath\n if (filepath) {\n const routeInfo = this.#generateRouteInfo(routePath, filepath);\n this.addRoute(routeInfo);\n return;\n }\n // case2: specify the content\n if (content) {\n const filepath = await this.#writeTempFile(index, content);\n const routeInfo = this.#generateRouteInfo(routePath, filepath);\n this.addRoute(routeInfo);\n }\n }),\n );\n\n await this.#pluginDriver.routeGenerated(this.getRoutes());\n }\n\n addRoute(routeInfo: RouteMeta) {\n const { routePath, absolutePath } = routeInfo;\n if (this.routeData.has(routePath)) {\n // apply the one with the extension listed first in the array and skip the rest.\n const preRouteExtIndex = this.#extensions.indexOf(\n path.extname(this.routeData.get(routePath)!.absolutePath).slice(1),\n );\n const currRouteExtIndex = this.#extensions.indexOf(\n path.extname(absolutePath).slice(1),\n );\n\n if (\n currRouteExtIndex !== -1 &&\n (currRouteExtIndex < preRouteExtIndex || preRouteExtIndex === -1)\n ) {\n this.routeData.set(routePath, routeInfo);\n }\n } else {\n this.routeData.set(routePath, routeInfo);\n }\n }\n\n removeRoute(filePath: string) {\n const fileRelativePath = path.relative(this.#scanDir, filePath);\n const { routePath } = this.normalizeRoutePath(fileRelativePath);\n this.routeData.delete(routePath);\n }\n\n getRoutes() {\n return Array.from(this.routeData.values());\n }\n\n isExistRoute(routePath: string) {\n const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);\n return this.routeData.get(normalizedRoute);\n }\n\n isEmpty() {\n return this.routeData.size === 0;\n }\n\n generateRoutesCode(isStaticImport = false) {\n return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);\n }\n\n generateRoutesCodeByRouteMeta(\n routeMeta: RouteMeta[],\n isStaticImport: boolean,\n ) {\n // TODO: webpackChunkName need fix https://github.com/web-infra-dev/rspack/issues/4664\n\n return `\nimport React from 'react';\nimport { lazyWithPreload } from \"react-lazy-with-preload\";\n${routeMeta\n .map((route, index) => {\n return isStaticImport\n ? `import * as Route${index} from '${route.absolutePath}';`\n : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`;\n })\n .join('\\n')}\nexport const routes = [\n${routeMeta\n .map((route, index) => {\n // In ssr, we don't need to import component dynamically.\n const preload = isStaticImport\n ? `() => Route${index}`\n : `async () => {\n await Route${index}.preload();\n return import(\"${route.absolutePath}\");\n }`;\n const component = isStaticImport\n ? `Route${index}.default`\n : `Route${index}`;\n /**\n * For SSR, example:\n * {\n * route: '/',\n * element: jsx(Route0),\n * preload: Route0.preload,\n * filePath: '/Users/foo/bar/index.md'\n * }\n *\n * For client render, example:\n * {\n * route: '/',\n * element: jsx(Route0.default),\n * preload: Route0.preload,\n * filePath: '/Users/foo/bar/index.md'\n * }\n */\n return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;\n })\n .join(',\\n')}\n];\n`;\n }\n\n normalizeRoutePath(routePath: string) {\n return normalizeRoutePath(\n routePath,\n this.#base,\n this.#defaultLang,\n this.#defaultVersion,\n this.#langs,\n this.#versions,\n this.#extensions,\n );\n }\n\n async #writeTempFile(index: number, content: string) {\n const tempFilePath = path.join(this.#tempDir, `temp-${index}.mdx`);\n await fs.writeFile(tempFilePath, content);\n return tempFilePath;\n }\n\n #generateRouteInfo(routePath: string, filepath: string): RouteMeta {\n const {\n routePath: normalizedPath,\n lang,\n version,\n } = this.normalizeRoutePath(routePath);\n return {\n routePath: normalizedPath,\n absolutePath: normalizePath(filepath),\n relativePath: normalizePath(path.relative(this.#scanDir, filepath)),\n pageName: getPageKey(routePath),\n lang,\n version,\n };\n }\n}\n","import type { UserConfig } from '@rspress/shared';\nimport type { PluginDriver } from '../PluginDriver';\nimport { RouteService } from './RouteService';\n\ninterface InitOptions {\n scanDir: string;\n config: UserConfig;\n runtimeTempDir: string;\n pluginDriver: PluginDriver;\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeService: RouteService | null = null;\n\n// The factory to create route serveice instance\nexport async function initRouteService(options: InitOptions) {\n const { scanDir, config, runtimeTempDir, pluginDriver } = options;\n routeService = new RouteService(\n scanDir,\n config,\n runtimeTempDir,\n pluginDriver,\n );\n await routeService.init();\n return routeService;\n}\n","import { existsSync } from 'node:fs';\nimport path from 'node:path';\n\nexport const detectCustomIcon = async (customThemeDir: string) => {\n const assetsDir = path.join(customThemeDir, 'assets');\n const alias: Record<string, string> = {};\n\n if (!existsSync(assetsDir)) {\n return alias;\n }\n\n const globby = (\n await import(\n // @ts-expect-error\n // eslint-disable-next-line node/file-extension-in-import\n '../compiled/globby/index.js'\n )\n ).default as typeof import('../../../compiled/globby');\n const files = await globby('*.svg', {\n cwd: assetsDir,\n });\n files.forEach(file => {\n const name = path.basename(file, '.svg');\n alias[`@theme-assets/${name}`] = path.join(assetsDir, file);\n });\n return alias;\n};\n","import type {\n UserConfig,\n PageIndexInfo,\n RspressPlugin,\n RouteMeta,\n} from '@rspress/shared';\nimport { isDevDebugMode } from '@rspress/shared';\nimport { pluginContainerSyntax } from '@rspress/plugin-container-syntax';\n\nexport class PluginDriver {\n #config: UserConfig;\n\n #plugins: RspressPlugin[];\n\n #isProd: boolean;\n\n constructor(config: UserConfig, isProd: boolean) {\n this.#config = config;\n this.#isProd = isProd;\n this.#plugins = [];\n }\n\n // The init function is used to initialize the doc plugins and will execute before the build process.\n async init() {\n // Clear RspressPlugins first, for the watch mode\n this.clearPlugins();\n const config = this.#config;\n const themeConfig = config?.themeConfig || {};\n const enableLastUpdated =\n themeConfig?.lastUpdated ||\n themeConfig?.locales?.some(locale => locale.lastUpdated);\n const mediumZoomConfig = config?.mediumZoom ?? true;\n const haveNavSidebarConfig =\n themeConfig.nav ||\n themeConfig.sidebar ||\n themeConfig.locales?.[0]?.nav ||\n themeConfig.locales?.[0]?.sidebar;\n if (enableLastUpdated) {\n const { pluginLastUpdated } = await import(\n '@rspress/plugin-last-updated'\n );\n this.addPlugin(pluginLastUpdated());\n }\n if (mediumZoomConfig) {\n const { pluginMediumZoom } = await import('@rspress/plugin-medium-zoom');\n this.addPlugin(\n pluginMediumZoom(\n typeof mediumZoomConfig === 'object' ? mediumZoomConfig : undefined,\n ),\n );\n }\n\n // Support the container syntax in markdown/mdx, such as :::tip\n this.addPlugin(pluginContainerSyntax());\n\n if (isDevDebugMode()) {\n const SourceBuildPlugin = await import(\n // @ts-expect-error need moduleResolution: Node16, NodeNext or Bundler to get type declerations work\n '@rspress/theme-default/node/source-build-plugin.js'\n ).then(\n r => r.SourceBuildPlugin,\n () => null as never,\n );\n\n if (SourceBuildPlugin) {\n this.addPlugin(SourceBuildPlugin());\n }\n }\n\n (config.plugins || []).forEach(plugin => {\n this.addPlugin(plugin);\n });\n\n // read _meta.json in the final, allow user's plugin to modify _meta.json\n if (!haveNavSidebarConfig) {\n const { pluginAutoNavSidebar } = await import(\n '@rspress/plugin-auto-nav-sidebar'\n );\n this.addPlugin(pluginAutoNavSidebar());\n }\n }\n\n addPlugin(plugin: RspressPlugin) {\n const existedIndex = this.#plugins.findIndex(\n item => item.name === plugin.name,\n );\n // Avoid the duplicated plugin\n if (existedIndex !== -1) {\n throw new Error(`The plugin \"${plugin.name}\" has been registered`);\n }\n\n this.#plugins.push(plugin);\n }\n\n getPlugins() {\n return this.#plugins;\n }\n\n clearPlugins() {\n this.#plugins = [];\n }\n\n removePlugin(pluginName: string) {\n const index = this.#plugins.findIndex(item => item.name === pluginName);\n if (index !== -1) {\n this.#plugins.splice(index, 1);\n }\n }\n\n async modifyConfig() {\n let config = this.#config;\n\n for (let i = 0; i < this.#plugins.length; i++) {\n const plugin = this.#plugins[i];\n if (typeof plugin.config === 'function') {\n config = await plugin.config(\n config || {},\n {\n addPlugin: this.addPlugin.bind(this),\n removePlugin: (pluginName: string) => {\n const index = this.#plugins.findIndex(\n item => item.name === pluginName,\n );\n this.removePlugin(pluginName);\n if (index <= i && index > 0) {\n i--;\n }\n },\n },\n this.#isProd,\n );\n }\n }\n this.#config = config;\n return this.#config;\n }\n\n async beforeBuild() {\n return this._runParallelAsyncHook(\n 'beforeBuild',\n this.#config || {},\n this.#isProd,\n );\n }\n\n async afterBuild() {\n return this._runParallelAsyncHook(\n 'afterBuild',\n this.#config || {},\n this.#isProd,\n );\n }\n\n async modifySearchIndexData(\n pages: PageIndexInfo[],\n ): Promise<PageIndexInfo[]> {\n return this._runParallelAsyncHook(\n 'modifySearchIndexData',\n pages,\n this.#isProd,\n );\n }\n\n async extendPageData(pageData: PageIndexInfo) {\n return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);\n }\n\n async addPages() {\n // addPages hooks\n const result = await this._runParallelAsyncHook(\n 'addPages',\n this.#config || {},\n this.#isProd,\n );\n return result.flat();\n }\n\n async routeGenerated(routes: RouteMeta[]) {\n return this._runParallelAsyncHook('routeGenerated', routes);\n }\n\n async addRuntimeModules() {\n const result: Record<string, string>[] = await this._runParallelAsyncHook(\n 'addRuntimeModules',\n this.#config || {},\n this.#isProd,\n );\n\n return result.reduce((prev, current) => {\n return {\n ...prev,\n ...current,\n };\n }, {});\n }\n\n async addSSGRoutes() {\n const result = await this._runParallelAsyncHook(\n 'addSSGRoutes',\n this.#config || {},\n this.#isProd,\n );\n\n return result.flat();\n }\n\n globalUIComponents(): (string | [string, object])[] {\n const result = this.#plugins.map(plugin => {\n return plugin.globalUIComponents || [];\n });\n\n return result.flat();\n }\n\n globalStyles(): string[] {\n return this.#plugins\n .filter(plugin => typeof plugin.globalStyles === 'string')\n .map(plugin => {\n return plugin.globalStyles;\n });\n }\n\n _runParallelAsyncHook(hookName: string, ...args: unknown[]) {\n return Promise.all(\n this.#plugins\n .filter(plugin => typeof plugin[hookName] === 'function')\n .map(plugin => {\n return plugin[hookName](...args);\n }),\n );\n }\n\n _runSerialAysncHook(hookName: string, ...args: unknown[]) {\n return this.#plugins.reduce(async (prev, plugin) => {\n if (typeof plugin[hookName] === 'function') {\n await prev;\n return plugin[hookName](...args);\n }\n return prev;\n }, Promise.resolve());\n }\n}\n","import type { UserConfig } from '@rspress/shared';\nimport type { RsbuildConfig } from '@rsbuild/core';\nimport { initRsbuild } from './initRsbuild';\nimport { writeSearchIndex } from './searchIndex';\nimport { PluginDriver } from './PluginDriver';\n\ninterface ServerInstance {\n close: () => Promise<void>;\n}\n\ninterface DevOptions {\n appDirectory: string;\n docDirectory: string;\n config: UserConfig;\n extraBuilderConfig?: RsbuildConfig;\n}\n\nexport async function dev(options: DevOptions): Promise<ServerInstance> {\n const { docDirectory, config, extraBuilderConfig } = options;\n const isProd = false;\n const pluginDriver = new PluginDriver(config, isProd);\n await pluginDriver.init();\n const modifiedConfig = await pluginDriver.modifyConfig();\n\n try {\n await pluginDriver.beforeBuild();\n\n // empty temp dir before build\n // await fs.emptyDir( TEMP_DIR);\n const builder = await initRsbuild(\n docDirectory,\n modifiedConfig,\n pluginDriver,\n false,\n extraBuilderConfig,\n );\n builder.onDevCompileDone(async () => {\n await pluginDriver.afterBuild();\n });\n const { server } = await builder.startDevServer({\n // We will support the following options in the future\n getPortSilently: true,\n });\n\n return server;\n } finally {\n await writeSearchIndex(modifiedConfig);\n }\n}\n","import { dirname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { HelmetData } from 'react-helmet-async';\nimport chalk from '@rspress/shared/chalk';\nimport fs from '@rspress/shared/fs-extra';\nimport {\n type PageData,\n type UserConfig,\n normalizeSlash,\n withBase,\n isDebugMode,\n type SSGConfig,\n} from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport {\n OUTPUT_DIR,\n APP_HTML_MARKER,\n HEAD_MARKER,\n META_GENERATOR,\n HTML_START_TAG,\n BODY_START_TAG,\n TEMP_DIR,\n} from './constants';\nimport { initRsbuild } from './initRsbuild';\nimport { writeSearchIndex } from './searchIndex';\nimport { PluginDriver } from './PluginDriver';\nimport type { Route } from '@/node/route/RouteService';\nimport { routeService } from '@/node/route/init';\nimport { renderFrontmatterHead, renderConfigHead } from './utils/renderHead';\n\ninterface BuildOptions {\n appDirectory: string;\n docDirectory: string;\n config: UserConfig;\n}\n\nexport async function bundle(\n docDirectory: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n enableSSG: boolean,\n) {\n try {\n // if enableSSG, build both client and server bundle\n // else only build client bundle\n const rsbuild = await initRsbuild(\n docDirectory,\n config,\n pluginDriver,\n enableSSG,\n );\n await rsbuild.build();\n } finally {\n await writeSearchIndex(config);\n }\n}\n\nexport interface SSRBundleExports {\n render: (\n url: string,\n helmetContext: object,\n ) => Promise<{ appHtml: string; pageData: PageData }>;\n routes: Route[];\n}\n\nexport async function renderPages(\n appDirectory: string,\n config: UserConfig,\n pluginDriver: PluginDriver,\n ssgConfig: SSGConfig,\n) {\n logger.info('Rendering pages...');\n const startTime = Date.now();\n const outputPath = config?.outDir ?? join(appDirectory, OUTPUT_DIR);\n const ssrBundlePath = join(outputPath, 'ssr', 'main.cjs');\n\n try {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n const { version } = await import('../../package.json');\n // There are two cases where we will fallback to CSR:\n // 1. ssr bundle load failed\n // 2. ssr bundle render failed\n // 3. ssg is disabled\n let render = null;\n if (ssgConfig) {\n try {\n const { default: ssrExports } = await import(\n pathToFileURL(ssrBundlePath).toString()\n );\n ({ render } = ssrExports as SSRBundleExports);\n } catch (e) {\n // skip fallback to CSR if ssg config is strict\n // TODO: strict by default in v2\n // see: https://github.com/web-infra-dev/rspress/issues/1317\n if (typeof ssgConfig === 'object' && ssgConfig.strict) {\n logger.error(\n `Failed to load SSG bundle: ${chalk.yellow(ssrBundlePath)}.`,\n );\n throw e;\n }\n\n // fallback to CSR\n logger.error(e);\n logger.warn(\n `Failed to load SSG bundle: ${chalk.yellow(ssrBundlePath)}, fallback to CSR.`,\n );\n }\n }\n\n const routes = routeService.getRoutes();\n const base = config?.base ?? '';\n\n // Get the html generated by builder, as the default ssr template\n const htmlTemplatePath = join(outputPath, 'index.html');\n const htmlTemplate = await fs.readFile(htmlTemplatePath, 'utf-8');\n const additionalRoutes = (await pluginDriver.addSSGRoutes()).map(route => ({\n routePath: withBase(route.path, base),\n }));\n const allRoutes = [...routes, ...additionalRoutes];\n const is404RouteInRoutes = allRoutes.some(\n route => route.routePath === '/404',\n );\n if (!is404RouteInRoutes) {\n allRoutes.push({\n routePath: '/404',\n });\n }\n await Promise.all(\n allRoutes\n .filter(route => {\n // filter the route including dynamic params\n return !route.routePath.includes(':');\n })\n .map(async route => {\n const helmetContext: HelmetData = {\n context: {},\n } as HelmetData;\n const { routePath } = route;\n let appHtml = '';\n if (render) {\n try {\n ({ appHtml } = await render(routePath, helmetContext.context));\n } catch (e) {\n if (typeof ssgConfig === 'object' && ssgConfig.strict) {\n logger.error(\n `Page \"${chalk.yellow(routePath)}\" SSG rendering failed.`,\n );\n throw e;\n }\n\n // fallback to CSR\n logger.warn(\n `Page \"${chalk.yellow(routePath)}\" SSG rendering error: ${e.message}, fallback to CSR.`,\n );\n }\n }\n\n const { helmet } = helmetContext.context;\n let html = htmlTemplate\n // During ssr, we already have the title in react-helmet\n .replace(/<title>(.*?)<\\/title>/gi, '')\n // Don't use `string` as second param\n // To avoid some special characters transformed to the marker, such as `$&`, etc.\n .replace(APP_HTML_MARKER, () => appHtml)\n .replace(\n META_GENERATOR,\n () => `<meta name=\"generator\" content=\"Rspress v${version}\">`,\n )\n .replace(\n HEAD_MARKER,\n [\n await renderConfigHead(config, route),\n helmet?.title?.toString(),\n helmet?.meta?.toString(),\n helmet?.link?.toString(),\n helmet?.style?.toString(),\n helmet?.script?.toString(),\n await renderFrontmatterHead(route),\n ].join(''),\n );\n if (helmet?.htmlAttributes) {\n html = html.replace(\n HTML_START_TAG,\n `${HTML_START_TAG} ${helmet?.htmlAttributes?.toString()}`,\n );\n }\n\n if (helmet?.bodyAttributes) {\n html = html.replace(\n BODY_START_TAG,\n `${BODY_START_TAG} ${helmet?.bodyAttributes?.toString()}`,\n );\n }\n\n const normalizeHtmlFilePath = (path: string) => {\n const normalizedBase = normalizeSlash(config?.base || '/');\n\n if (path.endsWith('/')) {\n return `${path}index.html`.replace(normalizedBase, '');\n }\n\n return `${path}.html`.replace(normalizedBase, '');\n };\n const fileName = normalizeHtmlFilePath(routePath);\n await fs.ensureDir(join(outputPath, dirname(fileName)));\n await fs.writeFile(join(outputPath, fileName), html);\n }),\n );\n // Remove ssr bundle\n if (!isDebugMode()) {\n await fs.remove(join(outputPath, 'ssr'));\n }\n await fs.remove(join(outputPath, 'html'));\n\n const totalTime = Date.now() - startTime;\n logger.success(`Pages rendered in ${chalk.yellow(totalTime)} ms.`);\n } catch (e) {\n logger.error(`Pages render error: ${e.stack}`);\n throw e;\n }\n}\n\nexport async function build(options: BuildOptions) {\n const { docDirectory, appDirectory, config } = options;\n const pluginDriver = new PluginDriver(config, true);\n await pluginDriver.init();\n const modifiedConfig = await pluginDriver.modifyConfig();\n await pluginDriver.beforeBuild();\n const ssgConfig = modifiedConfig.ssg ?? true;\n\n // empty temp dir before build\n await fs.emptyDir(TEMP_DIR);\n\n await bundle(docDirectory, modifiedConfig, pluginDriver, Boolean(ssgConfig));\n await renderPages(appDirectory, modifiedConfig, pluginDriver, ssgConfig);\n await pluginDriver.afterBuild();\n}\n","import type { FrontMatterMeta, RouteMeta, UserConfig } from '@rspress/shared';\nimport fsExtra from '@rspress/shared/fs-extra';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\n\nexport async function renderFrontmatterHead(route: any): Promise<string> {\n if (!isRouteMeta(route)) return '';\n const content = await fsExtra.readFile(route.absolutePath, {\n encoding: 'utf-8',\n });\n const {\n frontmatter: { head },\n } = loadFrontMatter<FrontMatterMeta>(content, route.absolutePath, '', true);\n if (!head || head.length === 0) return '';\n\n return head.map(([tag, attrs]) => `<${tag} ${renderAttrs(attrs)}>`).join('');\n}\n\nexport async function renderConfigHead(\n config: UserConfig,\n route: any,\n): Promise<string> {\n if (!isRouteMeta(route)) return '';\n if (!config.head || config.head.length === 0) return '';\n\n return config.head\n .map(head => {\n if (typeof head === 'string') return head;\n if (typeof head === 'function') {\n const resultHead = head(route);\n if (!resultHead) return '';\n if (typeof resultHead === 'string') return resultHead;\n return `<${resultHead[0]} ${renderAttrs(resultHead[1])}>`;\n }\n return `<${head[0]} ${renderAttrs(head[1])}>`;\n })\n .join('');\n}\n\nfunction renderAttrs(attrs: FrontMatterMeta['head'][number][1]): string {\n return Object.entries(attrs)\n .map(([key, value]) => {\n if (typeof value === 'boolean') return key;\n if (typeof value === 'string' || typeof value === 'number')\n return `${key}=\"${value}\"`;\n throw new Error(\n `Invalid value for attribute ${key}:${JSON.stringify(value)}`,\n );\n })\n .join('');\n}\n\nfunction isRouteMeta(route: any): route is RouteMeta {\n return 'routePath' in route && 'absolutePath' in route;\n}\n","import type { UserConfig } from '@rspress/shared';\nimport { mergeRsbuildConfig } from '@rsbuild/core';\nimport { initRsbuild } from './initRsbuild';\nimport { PluginDriver } from './PluginDriver';\n\ninterface ServeOptions {\n config: UserConfig;\n port?: number;\n host?: string;\n}\n\n// Serve ssg site in production\nexport async function serve(options: ServeOptions) {\n const { config, port: userPort, host: userHost } = options;\n const envPort = process.env.PORT;\n const envHost = process.env.HOST;\n const { builderConfig } = config;\n const port = Number(\n envPort || userPort || builderConfig?.server?.port || 4173,\n );\n const host =\n envHost || userHost || builderConfig?.server?.host || 'localhost';\n\n config.builderConfig = mergeRsbuildConfig(builderConfig, {\n server: {\n port,\n host,\n },\n });\n\n const pluginDriver = new PluginDriver(config, true);\n await pluginDriver.init();\n\n const modifiedConfig = await pluginDriver.modifyConfig();\n\n const builder = await initRsbuild(\n config.root,\n modifiedConfig,\n pluginDriver,\n false,\n );\n\n await builder.preview();\n}\n","export * from './node';\nexport * from '@rspress/shared';\nexport { mergeDocConfig } from '@rspress/shared/node-utils';\n"]}
package/dist/loader.d.ts CHANGED
@@ -60,6 +60,7 @@ interface LoaderOptions {
60
60
  interface PageMeta {
61
61
  toc: TocItem[];
62
62
  title: string;
63
+ headingTitle: string;
63
64
  frontmatter?: Record<string, any>;
64
65
  }
65
66
  declare function updateSiteDataRuntimeModule(modulePath: string, pageMeta: PageMeta): Promise<void>;
package/dist/loader.js CHANGED
@@ -682,6 +682,7 @@ async function mdxLoader(context, source, callback) {
682
682
  pageMeta = {
683
683
  ...compilationMeta,
684
684
  title: frontmatter.title || compilationMeta.title || "",
685
+ headingTitle: compilationMeta.title,
685
686
  frontmatter
686
687
  };
687
688
  } else {
@@ -696,6 +697,7 @@ async function mdxLoader(context, source, callback) {
696
697
  pageMeta = {
697
698
  toc,
698
699
  title: frontmatter.title || title || "",
700
+ headingTitle: title,
699
701
  frontmatter
700
702
  };
701
703
  if (checkDeadLinks) {
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,OAAOC,SAAQ;AACf,SAAS,qBAAqB;AAC9B,SAAS,mBAAAC,wBAAuB;AACh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AChD,YAAM,QAAQ,MAAM,SAAS,QAAQ;AAAA,QACnC,OAAO;AAAA,QACP,MAAM;AAAA,MACR,CAAC;AAED,sBAAgB,OAAO,KAAK;AAC5B,YAAM,kBAAkB,SAAS,KAAK,UAAU;AAIhD,iBAAW;AAAA,QACT,GAAG;AAAA,QACH,OAAO,YAAY,SAAS,gBAAgB,SAAS;AAAA,QACrD;AAAA,MACF;AAAA,IACF,OAAO;AACL,YAAM,EAAE,QAAQ,IAAI,UAAQ,iBAAiB;AAE7C,YAAM,EAAE,KAAK,OAAO,OAAO,KAAK,IAAI,MAAM,QAAQ;AAAA,QAChD,OAAO;AAAA,QACP;AAAA,QACA,MAAM;AAAA,QACN,aAAa,QAAQ,IAAI,aAAa;AAAA,MACxC,CAAC;AAED,sBAAgB;AAChB,iBAAW;AAAA,QACT;AAAA,QACA,OAAO,YAAY,SAAS,SAAS;AAAA,QACrC;AAAA,MACF;AAEA,UAAI,gBAAgB;AAClB,mBAAW,OAAO,UAAU,cAAc,YAAY;AAAA,MACxD;AAAA,IACF;AAGA,QAAI,CAACC,cAAa,GAAG;AACnB,0BAAoB,UAAU,QAAQ;AAAA,IACxC;AAEA,UAAM,SAAS,uBAAuB,KAAK,UAAU,WAAW,CAAC;AAAA,EACnE,aAAa;AAAA;AAAA;AAAA,kCAGmB;AAAA,MAC5B,cAAcH,MAAK,SAAS,cAAc,QAAQ,CAAC;AAAA,IACrD,CAAC,QAAQ,KAAK,UAAU,QAAQ,CAAC;AAAA;AAEjC,aAAS,MAAM,MAAM;AAAA,EACvB,SAAS,GAAG;AACV,IAAAI,QAAO,MAAM,sBAAsB,EAAE,OAAO,OAAO,QAAQ,EAAE;AAC7D,aAAS,EAAE,SAAS,EAAE,SAAS,MAAM,GAAG,QAAQ,iBAAiB,CAAC;AAAA,EACpE;AACF","names":["path","fs","createProcessor","isProduction","logger","visit","slash"],"ignoreList":[],"sources":["../src/node/mdx/loader.ts","../src/node/mdx/options.ts","../src/node/mdx/remarkPlugins/toc.ts","../src/node/utils/normalizePath.ts","../src/node/constants.ts","../src/node/utils/getASTNodeImport.ts","../src/node/utils/flattenMdxContent.ts","../src/node/utils/applyReplaceRules.ts","../src/node/utils/extractTextAndId.ts","../src/node/utils/escapeHeadingIds.ts","../src/node/mdx/remarkPlugins/builtin.ts","../src/node/mdx/rehypePlugins/codeMeta.ts","../src/node/mdx/rehypePlugins/headerAnchor.ts","../src/node/mdx/remarkPlugins/checkDeadLink.ts","../src/node/mdx/remarkPlugins/normalizeLink.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { pathToFileURL } from 'node:url';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { isProduction } from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\nimport { createMDXOptions } from './options';\nimport type { TocItem } from './remarkPlugins/toc';\nimport { checkLinks } from './remarkPlugins/checkDeadLink';\nimport { TEMP_DIR } from '../constants';\nimport type { PluginDriver } from '../PluginDriver';\nimport { RuntimeModuleID } from '../runtimeModule';\nimport {\n normalizePath,\n escapeMarkdownHeadingIds,\n flattenMdxContent,\n applyReplaceRules,\n} from '../utils';\n\nimport type { Rspack } from '@rsbuild/core';\nimport type { Header, UserConfig } from '@rspress/shared';\nimport type { RouteService } from '../route/RouteService';\n\ninterface LoaderOptions {\n config: UserConfig;\n docDirectory: string;\n checkDeadLinks: boolean;\n routeService: RouteService;\n pluginDriver: PluginDriver;\n}\n\nexport interface PageMeta {\n toc: TocItem[];\n title: string;\n frontmatter?: Record<string, any>;\n}\n\nexport async function updateSiteDataRuntimeModule(\n modulePath: string,\n pageMeta: PageMeta,\n) {\n const siteDataModulePath = path.join(\n TEMP_DIR,\n 'runtime',\n `${RuntimeModuleID.SiteData}.mjs`,\n );\n const { default: siteData } = await import(\n pathToFileURL(siteDataModulePath).href\n );\n await fs.writeFile(\n siteDataModulePath,\n `export default ${JSON.stringify(\n {\n ...siteData,\n timestamp: Date.now().toString(),\n pages: siteData.pages.map(page =>\n // Update page meta if the page is updated\n page._filepath === modulePath ? { ...page, ...pageMeta } : page,\n ),\n },\n null,\n 2,\n )}`,\n );\n}\n\nexport function createCheckPageMetaUpdateFn() {\n const pageMetaMap = new Map<string, string>();\n return (modulePath: string, pageMeta: PageMeta) => {\n const prevMeta = pageMetaMap.get(modulePath);\n const deserializedMeta = JSON.stringify(pageMeta);\n pageMetaMap.set(modulePath, deserializedMeta);\n\n if (!prevMeta) {\n return;\n }\n\n if (prevMeta !== deserializedMeta) {\n setTimeout(async () => {\n logger.info('Page metadata changed, page reloading...');\n await updateSiteDataRuntimeModule(modulePath, pageMeta);\n });\n }\n };\n}\n\nconst checkPageMetaUpdate = createCheckPageMetaUpdateFn();\n\nexport default async function mdxLoader(\n context: Rspack.LoaderContext<LoaderOptions>,\n source: string,\n callback: Rspack.LoaderContext['callback'],\n) {\n context.cacheable(true);\n\n const options = context.getOptions();\n const filepath = context.resourcePath;\n const { alias } = context._compiler.options.resolve;\n const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } =\n options;\n\n // Separate frontmatter and content in MDX source\n const { frontmatter, content } = loadFrontMatter(\n source,\n filepath,\n docDirectory,\n true,\n );\n\n // Replace imported built-in MDX content\n const { flattenContent, deps } = await flattenMdxContent(\n content,\n filepath,\n alias as Record<string, string>,\n );\n\n deps.forEach(dep => context.addDependency(dep));\n\n // Resolve side effects caused by flattenMdxContent.\n // Perhaps this problem should be solved within flattenMdxContent?\n const replacedContent = applyReplaceRules(\n flattenContent,\n config.replaceRules,\n );\n\n // Support custom id like `#hello world {#custom-id}`.\n // TODO > issue: `#hello world {#custom-id}` will also be replaced.\n const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);\n\n // Whether to use the Rust version of the MDX compiler.\n let enableMdxRs: boolean;\n const mdxRs = config?.markdown?.mdxRs ?? true;\n if (typeof mdxRs === 'object') {\n enableMdxRs =\n typeof mdxRs?.include === 'function' ? mdxRs.include(filepath) : true;\n } else {\n enableMdxRs = mdxRs;\n }\n\n try {\n let compileResult: string;\n let pageMeta = { title: '', toc: [] } as PageMeta;\n\n if (!enableMdxRs) {\n const mdxOptions = await createMDXOptions(\n docDirectory,\n config,\n checkDeadLinks,\n routeService,\n filepath,\n pluginDriver,\n );\n const compiler = createProcessor(mdxOptions);\n\n compiler.data('pageMeta', { toc: [], title: '' });\n const vFile = await compiler.process({\n value: preprocessedContent,\n path: filepath,\n });\n\n compileResult = String(vFile);\n const compilationMeta = compiler.data('pageMeta') as {\n toc: Header[];\n title: string;\n };\n pageMeta = {\n ...compilationMeta,\n title: frontmatter.title || compilationMeta.title || '',\n frontmatter,\n } as PageMeta;\n } else {\n const { compile } = require('@rspress/mdx-rs');\n\n const { toc, links, title, code } = await compile({\n value: preprocessedContent,\n filepath,\n root: docDirectory,\n development: process.env.NODE_ENV !== 'production',\n });\n\n compileResult = code;\n pageMeta = {\n toc,\n title: frontmatter.title || title || '',\n frontmatter,\n };\n // We should check dead links in mdx-rs mode\n if (checkDeadLinks) {\n checkLinks(links, filepath, docDirectory, routeService);\n }\n }\n\n // If page meta changed, we trigger page reload to ensure the page is up to date.\n if (!isProduction()) {\n checkPageMetaUpdate(filepath, pageMeta);\n }\n\n const result = `const frontmatter = ${JSON.stringify(frontmatter)};\n${compileResult}\nMDXContent.__RSPRESS_PAGE_META = {};\n\nMDXContent.__RSPRESS_PAGE_META[\"${encodeURIComponent(\n normalizePath(path.relative(docDirectory, filepath)),\n )}\"] = ${JSON.stringify(pageMeta)};\n`;\n callback(null, result);\n } catch (e) {\n logger.error(`MDX compile error: ${e.message} in ${filepath}`);\n callback({ message: e.message, name: `${filepath} compile error` });\n }\n}\n","import path from 'node:path';\nimport remarkGFM from 'remark-gfm';\nimport rehypePluginExternalLinks from 'rehype-external-links';\nimport type { PluggableList } from 'unified';\nimport type { Options } from '@mdx-js/loader';\nimport type { UserConfig } from '@rspress/shared';\nimport { remarkPluginToc } from './remarkPlugins/toc';\nimport { remarkBuiltin } from './remarkPlugins/builtin';\nimport { rehypePluginCodeMeta } from './rehypePlugins/codeMeta';\nimport { rehypeHeaderAnchor } from './rehypePlugins/headerAnchor';\nimport { remarkCheckDeadLinks } from './remarkPlugins/checkDeadLink';\nimport { remarkPluginNormalizeLink } from './remarkPlugins/normalizeLink';\n\nimport type { PluginDriver } from '../PluginDriver';\nimport type { RouteService } from '../route/RouteService';\n\nexport async function createMDXOptions(\n docDirectory: string,\n config: UserConfig,\n checkDeadLinks: boolean,\n routeService: RouteService,\n filepath: string,\n pluginDriver: PluginDriver,\n): Promise<Options> {\n const cleanUrls = Boolean(config?.route?.cleanUrls);\n const {\n remarkPlugins: remarkPluginsFromConfig = [],\n rehypePlugins: rehypePluginsFromConfig = [],\n globalComponents: globalComponentsFromConfig = [],\n } = config?.markdown || {};\n const rspressPlugins = pluginDriver.getPlugins();\n const remarkPluginsFromPlugins = rspressPlugins.flatMap(\n plugin => plugin.markdown?.remarkPlugins || [],\n ) as PluggableList;\n const rehypePluginsFromPlugins = rspressPlugins.flatMap(\n plugin => plugin.markdown?.rehypePlugins || [],\n ) as PluggableList;\n const globalComponents = [\n ...rspressPlugins.flatMap(\n plugin => plugin.markdown?.globalComponents || [],\n ),\n ...globalComponentsFromConfig,\n ];\n const defaultLang = config?.lang || '';\n return {\n providerImportSource: '@mdx-js/react',\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [\n remarkGFM,\n remarkPluginToc,\n [\n remarkPluginNormalizeLink,\n {\n base: config?.base || '',\n cleanUrls,\n defaultLang,\n root: docDirectory,\n },\n ],\n checkDeadLinks && [\n remarkCheckDeadLinks,\n {\n root: docDirectory,\n base: config?.base || '',\n routeService,\n },\n ],\n globalComponents.length && [\n remarkBuiltin,\n {\n globalComponents,\n },\n ],\n ...remarkPluginsFromConfig,\n ...remarkPluginsFromPlugins,\n ].filter(Boolean) as PluggableList,\n rehypePlugins: [\n rehypeHeaderAnchor,\n rehypePluginCodeMeta,\n [\n rehypePluginExternalLinks,\n {\n target: '_blank',\n rel: 'noopener noreferrer',\n },\n ],\n ...rehypePluginsFromConfig,\n ...rehypePluginsFromPlugins,\n ],\n };\n}\n","import type { Plugin } from 'unified';\nimport { visitChildren } from 'unist-util-visit-children';\nimport Slugger from 'github-slugger';\nimport type { Root } from 'hast';\nimport type { Processor } from '@mdx-js/mdx/lib/core';\nimport type { PageMeta } from '../loader';\nimport { extractTextAndId } from '../../utils';\n\nexport interface TocItem {\n id: string;\n text: string;\n depth: number;\n}\n\ninterface ChildNode {\n type: 'link' | 'text' | 'inlineCode' | 'strong';\n value: string;\n children?: ChildNode[];\n}\n\ninterface Heading {\n type: string;\n depth?: number;\n children?: ChildNode[];\n}\n\nexport const parseToc = (tree: Root) => {\n let title = '';\n const toc: TocItem[] = [];\n const slugger = new Slugger();\n visitChildren((node: Heading) => {\n if (node.type !== 'heading' || !node.depth || !node.children) {\n return;\n }\n\n // Collect h1 ~ h4\n if (node.depth >= 1 && node.depth < 5) {\n let customId = '';\n const text = node.children\n .map((child: ChildNode) => {\n if (child.type === 'link') {\n return child.children?.map(item => item.value).join('');\n }\n if (child.type === 'strong') {\n return `**${child.children?.map(item => item.value).join('')}**`;\n }\n if (child.type === 'text') {\n const [textPart, idPart] = extractTextAndId(child.value);\n customId = idPart;\n return textPart;\n }\n if (child.type === 'inlineCode') {\n return `\\`${child.value}\\``;\n }\n return '';\n })\n .join('');\n\n if (node.depth === 1) {\n if (!title) title = text;\n } else {\n const id = customId ? customId : slugger.slug(text);\n const { depth } = node;\n toc.push({ id, text, depth });\n }\n }\n })(tree);\n return {\n title,\n toc,\n };\n};\n\nexport const remarkPluginToc: Plugin<[], Root> = function (this: Processor) {\n const data = this.data() as {\n pageMeta: PageMeta;\n };\n return (tree: Root) => {\n const { toc, title } = parseToc(tree);\n data.pageMeta.toc = toc;\n if (title) {\n data.pageMeta.title = title;\n }\n };\n};\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const isWindows = os.platform() === 'win32';\n\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function normalizePath(id: string): string {\n return path.posix.normalize(isWindows ? slash(id) : id);\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from '@rspress/shared';\n\nexport const isProduction = () => process.env.NODE_ENV === 'production';\n\n// Keep the quotation marks consistent before and after.\nexport const importStatementRegex =\n /import\\s+(.*?)\\s+from\\s+(['\"])(.*?)(?:\"|');?/gm;\n\n// In the first render, the theme will be set according to the user's system theme\n// - Should be injected into both development and production modes\n// - Class hook (.dark) is set for internal use (Tailwind)\n// - Style hook (colorScheme) is set for external use (CSS media queries or `light-dark()` function)\nexport const inlineThemeScript = `{\n const saved = localStorage.getItem('${APPEARANCE_KEY}')\n const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches\n const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'\n document.documentElement.classList.toggle('dark', isDark)\n document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'\n}`\n .replace(/\\n/g, ';')\n .replace(/\\s{2,}/g, '');\n\nconst dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));\n\nexport const PACKAGE_ROOT = path.join(dirname, '..');\n\nexport const CLIENT_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'clientEntry.js',\n);\n\nexport const SSR_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'ssrEntry.js',\n);\n\nexport const OUTPUT_DIR = 'doc_build';\n\nexport const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';\nexport const HEAD_MARKER = '<!--<?- HEAD ?>-->';\nexport const META_GENERATOR = '<!--<?- GENERATOR ?>-->';\nexport const HTML_START_TAG = '<html';\nexport const BODY_START_TAG = '<body';\n\nexport const DEFAULT_TITLE = 'Rspress';\n\nexport const PUBLIC_DIR = 'public';\nexport const TEMP_DIR = path.join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n);\n","import type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\n\n// Construct import statement for AST\n// Such as: import image1 from './test.png'\nexport const getASTNodeImport = (name: string, from: string) =>\n ({\n type: 'mdxjsEsm',\n value: `import ${name} from ${JSON.stringify(from)}`,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ImportDeclaration',\n specifiers: [\n {\n type: 'ImportDefaultSpecifier',\n local: { type: 'Identifier', name },\n },\n ],\n source: {\n type: 'Literal',\n value: from,\n raw: `${JSON.stringify(from)}`,\n },\n },\n ],\n },\n },\n }) as MdxjsEsm;\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { MDX_REGEXP } from '@rspress/shared';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { importStatementRegex } from '../constants';\n\nimport type { Root } from 'hast';\nimport type { Resolver } from 'enhanced-resolve';\n\nlet resolver: Resolver;\nlet startFlatten = false;\n\nconst processor = createProcessor();\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nexport async function resolveDepPath(\n importPath: string,\n importer: string,\n alias: Record<string, string | string[]>,\n) {\n if (!resolver) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md'],\n alias,\n });\n }\n const resolveResult = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n {\n importer,\n },\n importer,\n importPath,\n {},\n (err, filePath) => {\n if (err) {\n return reject(err);\n }\n if (!filePath) {\n return reject(\n new Error(\n `Empty result when resolving ${importPath} from ${importer}`,\n ),\n );\n }\n return resolve(filePath);\n },\n );\n });\n return resolveResult;\n}\n\ninterface ESTree {\n body: {\n type: 'ImportDeclaration';\n specifiers: { local: { name: string } }[];\n source: { value: string };\n }[];\n}\n\nexport async function flattenMdxContent(\n content: string,\n basePath: string,\n alias: Record<string, string | string[]>,\n): Promise<{ flattenContent: string; deps: string[] }> {\n const deps = [];\n // Performance optimization: if the content does not contain any import statement, we can skip the parsing process\n // So we need to check this match\n\n // Create new regExp to avoid the regex cache the last match index\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag\n const regex = new RegExp(importStatementRegex);\n if (!regex.test(content)) {\n return { flattenContent: content, deps };\n }\n\n // We should update the resolver instanceof because the alias should be passed to it\n // If we reuse the resolver instance in `detectReactVersion` method, the resolver will lose the alias info and cannot resolve path correctly in mdx files.\n if (!startFlatten) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md', '.js'],\n alias,\n });\n startFlatten = true;\n }\n\n let ast: Root;\n let result = content;\n\n try {\n ast = processor.parse(content) as Root;\n } catch (e) {\n // Fallback: if mdx parse failed, just return the content\n return { flattenContent: content, deps };\n }\n\n const importNodes = ast.children\n .filter(node => node.type === ('mdxjsEsm' as any))\n .flatMap(node => (node.data?.estree as ESTree)?.body || [])\n .filter(node => node.type === 'ImportDeclaration');\n for (const importNode of importNodes) {\n // import Comp from './a';\n // {id: Comp, importPath: './a'}\n const id = importNode.specifiers[0].local.name;\n const importPath = importNode.source.value;\n\n let absoluteImportPath: string;\n try {\n absoluteImportPath = await resolveDepPath(\n importPath,\n path.dirname(basePath),\n alias,\n );\n } catch (e) {\n continue;\n }\n\n if (MDX_REGEXP.test(absoluteImportPath)) {\n // replace import statement with the content of the imported file\n const importedContent = fs.readFileSync(absoluteImportPath, 'utf-8');\n const { flattenContent: replacedValue, deps: subDeps } =\n await flattenMdxContent(importedContent, absoluteImportPath, alias);\n\n result = result\n .replace(\n new RegExp(`import\\\\s+${id}\\\\s+from\\\\s+['\"](${importPath})['\"];?`),\n '',\n )\n .replace(new RegExp(`<${id}\\\\s*/>`, 'g'), () => replacedValue);\n\n deps.push(...subDeps, absoluteImportPath);\n }\n }\n\n return { flattenContent: result, deps };\n}\n","import type { ReplaceRule } from '@rspress/shared';\n\nexport function applyReplaceRules(\n code = '',\n replaceRules: ReplaceRule[] = [],\n): string {\n let result = code;\n for (const rule of replaceRules) {\n result = result.replace(rule.search, rule.replace);\n }\n return result;\n}\n","/**\n * hello world {#custom-id} -> { text: 'hello world', id: 'custom-id' }\n */\nexport const extractTextAndId = (title: string) => {\n const customIdReg = /{#.*}/;\n const text = title.replace(customIdReg, '').trimEnd();\n const customId = title.match(customIdReg)?.[0]?.slice(2, -1) || '';\n return [text, customId];\n};\n","/**\n * Support custom id like `#hello world {#custom-id}`\n * Avoid https://mdxjs.com/docs/troubleshooting-mdx/#could-not-parse-expression-with-acorn-error\n */\nexport function escapeMarkdownHeadingIds(content: string): string {\n const markdownHeadingRegexp = /(?:^|\\n)#{1,6}(?!#).*/g;\n return content.replace(markdownHeadingRegexp, substring =>\n substring\n .replace('{#', '\\\\{#')\n // prevent duplicate escaping\n .replace('\\\\\\\\{#', '\\\\{#'),\n );\n}\n","import path from 'node:path';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { getASTNodeImport } from '@/node/utils/getASTNodeImport';\n\n/**\n * A remark plugin to import all builtin components.\n * @param options configure the global components.\n * @returns A unified transformer.\n */\nexport const remarkBuiltin: Plugin<[{ globalComponents: string[] }], Root> = ({\n globalComponents,\n}) => {\n return tree => {\n const demos: MdxjsEsm[] = globalComponents.map(componentPath => {\n const filename = path.parse(componentPath).name;\n const componentName = filename[0].toUpperCase() + filename.slice(1);\n return getASTNodeImport(componentName, componentPath);\n });\n\n tree.children.unshift(...demos);\n };\n};\n","import type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'hast';\n\nexport const rehypePluginCodeMeta: Plugin<[], Root> = () => {\n return tree => {\n visit(tree, 'element', node => {\n // <pre><code>...</code></pre>\n // 1. Find pre element\n if (\n node.tagName === 'pre' &&\n node.children[0]?.type === 'element' &&\n node.children[0].tagName === 'code'\n ) {\n const codeNode = node.children[0];\n // language-foo\n const meta = (codeNode.data?.meta as string) || '';\n codeNode.properties.meta = meta;\n }\n });\n };\n};\n","import { headingRank } from 'hast-util-heading-rank';\nimport { visit } from 'unist-util-visit';\nimport GithubSlugger from 'github-slugger';\nimport type { Plugin } from 'unified';\nimport type { Root, Element } from 'hast';\nimport { extractTextAndId } from '../../utils';\n\n/**\n * Generate `id`s for headings and applies to headings with `id`s.\n * same as rehype-slug + rehype-autolink-headings, but support custom id.\n */\nexport const rehypeHeaderAnchor: Plugin<[], Root> = () => {\n const slugger = new GithubSlugger();\n return function (tree) {\n visit(tree, 'element', function (node) {\n if (headingRank(node as any)) {\n // generate id\n if (!node.properties.id) {\n const [text, customId] = collectHeaderText(node);\n node.properties.id = customId || slugger.slug(text);\n }\n // apply to headings\n node.children.unshift(create(node));\n }\n });\n };\n};\n\nexport const collectHeaderText = (node: Element) => {\n let text = '';\n let id = '';\n node.children.forEach(child => {\n if (child.type === 'text') {\n const [textPart, idPart] = extractTextAndId(child.value);\n child.value = textPart;\n text += textPart;\n id = idPart;\n }\n if (child.type === 'element') {\n child.children.forEach(c => {\n if (c.type === 'text') {\n text += c.value;\n }\n });\n }\n });\n return [text, id];\n};\n\n/**\n * Create an `a`.\n *\n * @param {Readonly<Element>} node\n * Related heading.\n * @returns {Element}\n * Link.\n */\nfunction create(node: Element): Element {\n return {\n type: 'element',\n tagName: 'a',\n properties: {\n class: 'header-anchor',\n ariaHidden: 'true',\n href: `#${node.properties.id}`,\n },\n children: [\n {\n type: 'text',\n value: '#',\n },\n ],\n };\n}\n","import path from 'node:path';\nimport { visit } from 'unist-util-visit';\nimport type { Plugin } from 'unified';\nimport { logger } from '@rspress/shared/logger';\nimport { cleanUrl, isProduction } from '@rspress/shared';\nimport type { RouteService } from '@/node/route/RouteService';\nimport { normalizePath } from '@/node/utils';\n\nexport interface DeadLinkCheckOptions {\n root: string;\n base: string;\n routeService: RouteService;\n}\n\nconst IGNORE_REGEXP = /^(https?|mailto|tel|#)/;\n\nexport function checkLinks(\n links: string[],\n filepath: string,\n root: string,\n routeService: RouteService,\n) {\n const errorInfos: string[] = [];\n links\n .filter(link => !IGNORE_REGEXP.test(link))\n .map(link => normalizePath(link))\n .forEach(link => {\n const relativePath = path.relative(root, filepath);\n\n if (!routeService.isExistRoute(cleanUrl(link))) {\n errorInfos.push(\n `Internal link to ${link} is dead, check it in ${relativePath}`,\n );\n }\n });\n // output error info\n if (errorInfos.length > 0) {\n errorInfos?.forEach(err => {\n logger.error(err);\n });\n if (isProduction()) {\n throw new Error('Dead link found');\n }\n }\n}\n\n/**\n * Remark plugin to check dead links\n */\nexport const remarkCheckDeadLinks: Plugin<\n DeadLinkCheckOptions[]\n> = checkLink => {\n const { root, routeService } = checkLink;\n\n return (tree, vfile) => {\n const internalLinks = new Set<string>();\n\n visit(tree, 'link', (node: { url: string }) => {\n const { url } = node;\n if (!url) {\n return;\n }\n if (internalLinks.has(url)) {\n return;\n }\n\n if (!url.startsWith('http') && !url.startsWith('https')) {\n const { routePath: normalizeUrl } = routeService.normalizeRoutePath(\n // fix: windows path\n url.split(path.sep).join('/')?.split('#')[0],\n );\n internalLinks.add(normalizeUrl);\n }\n });\n\n checkLinks(Array.from(internalLinks), vfile.path, root, routeService);\n };\n};\n","import path from 'node:path';\nimport type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { normalizeHref, parseUrl, isExternalUrl, slash } from '@rspress/shared';\nimport { getASTNodeImport } from '@/node/utils/getASTNodeImport';\n\ninterface LinkNode {\n type: string;\n url?: string;\n}\n\n/**\n * Remark plugin to normalize a link href\n */\nexport const remarkPluginNormalizeLink: Plugin<\n [{ base: string; root: string; cleanUrls: boolean }],\n Root\n> =\n ({ base, root, cleanUrls }) =>\n (tree, file) => {\n const images: MdxjsEsm[] = [];\n visit(\n tree,\n (node: LinkNode) => node.type === 'link',\n (node: LinkNode) => {\n if (!node.url) {\n return;\n }\n if (node.url.startsWith('#')) {\n node.url = `#${node.url.slice(1)}`;\n return;\n }\n\n // eslint-disable-next-line prefer-const\n let { url, hash } = parseUrl(node.url);\n\n if (isExternalUrl(url)) {\n node.url = url + (hash ? `#${hash}` : '');\n return;\n }\n\n const extname = path.extname(url);\n\n if (extname === '.md' || extname === '.mdx') {\n url = url.replace(extname, '');\n }\n\n const relativePath = path.relative(root, file.path);\n if (url.startsWith('.')) {\n url = path.posix.join(slash(path.dirname(relativePath)), url);\n }\n\n url = normalizeHref(url, cleanUrls);\n\n if (hash) {\n url += `#${hash}`;\n }\n node.url = path.posix.join(base, url);\n },\n );\n\n const normalizeImageUrl = (imageUrl: string): string => {\n if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) {\n return '';\n }\n\n return imageUrl;\n };\n\n const getMdxSrcAttrbute = (tempVar: string) => {\n return {\n type: 'mdxJsxAttribute',\n name: 'src',\n value: {\n type: 'mdxJsxAttributeValueExpression',\n value: tempVar,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ExpressionStatement',\n expression: {\n type: 'Identifier',\n name: tempVar,\n },\n },\n ],\n },\n },\n },\n };\n };\n\n visit(tree, 'image', node => {\n const { url } = node;\n if (!url) {\n return;\n }\n\n const imagePath = normalizeImageUrl(url);\n if (!imagePath) {\n return;\n }\n // relative path\n const tempVariableName = `image${images.length}`;\n\n Object.assign(node, {\n type: 'mdxJsxFlowElement',\n name: 'img',\n children: [],\n attributes: [\n node.alt && {\n type: 'mdxJsxAttribute',\n name: 'alt',\n value: node.alt,\n },\n getMdxSrcAttrbute(tempVariableName),\n ].filter(Boolean),\n });\n\n images.push(getASTNodeImport(tempVariableName, imagePath));\n });\n\n visit(tree, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node: any) => {\n // get all img src\n if (node.name !== 'img') {\n return;\n }\n\n const src = node.attributes.find((attr: any) => attr.name === 'src');\n\n if (!src?.value || typeof src?.value !== 'string') {\n return;\n }\n\n const imagePath = normalizeImageUrl(src.value);\n\n if (!imagePath) {\n return;\n }\n\n const tempVariableName = `image${images.length}`;\n\n Object.assign(src, getMdxSrcAttrbute(tempVariableName));\n\n images.push(getASTNodeImport(tempVariableName, imagePath));\n });\n\n tree.children.unshift(...images);\n };\n"]}
1
+ {"version":3,"mappings":";;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,OAAOC,SAAQ;AACf,SAAS,qBAAqB;AAC9B,SAAS,mBAAAC,wBAAuB;AAChC,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,UAAAC,eAAc;AACvB,SAAS,uBAAuB;;;ACNhC,OAAOJ,WAAU;AACjB,OAAO,eAAe;AACtB,OAAO,+BAA+B;;;ACDtC,SAAS,qBAAqB;AAC9B,OAAO,aAAa;;;ACFpB,OAAO,QAAQ;AACf,OAAO,UAAU;AAEV,IAAM,YAAY,GAAG,SAAS,MAAM;AAEpC,SAAS,MAAM,GAAmB;AACvC,SAAO,EAAE,QAAQ,OAAO,GAAG;AAC7B;AAEO,SAAS,cAAc,IAAoB;AAChD,SAAO,KAAK,MAAM,UAAU,YAAY,MAAM,EAAE,IAAI,EAAE;AACxD;;;ACXA,OAAOA,WAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,wBAAwB;AAK1C,IAAM,uBACX;AAMK,IAAM,oBAAoB;AAAA,wCACO,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,GAMnD,QAAQ,OAAO,GAAG,EAClB,QAAQ,WAAW,EAAE;AAExB,IAAM,UAAUA,MAAK,QAAQ,cAAc,IAAI,IAAI,YAAY,GAAG,CAAC,CAAC;AAE7D,IAAM,eAAeA,MAAK,KAAK,SAAS,IAAI;AAE5C,IAAM,eAAeA,MAAK;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,YAAYA,MAAK;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;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AK,SAAS,cAAc,QAAQ,CAAC;AAAA,IACrD,CAAC,QAAQ,KAAK,UAAU,QAAQ,CAAC;AAAA;AAEjC,aAAS,MAAM,MAAM;AAAA,EACvB,SAAS,GAAG;AACV,IAAAI,QAAO,MAAM,sBAAsB,EAAE,OAAO,OAAO,QAAQ,EAAE;AAC7D,aAAS,EAAE,SAAS,EAAE,SAAS,MAAM,GAAG,QAAQ,iBAAiB,CAAC;AAAA,EACpE;AACF","names":["path","fs","createProcessor","isProduction","logger","visit","slash"],"ignoreList":[],"sources":["../src/node/mdx/loader.ts","../src/node/mdx/options.ts","../src/node/mdx/remarkPlugins/toc.ts","../src/node/utils/normalizePath.ts","../src/node/constants.ts","../src/node/utils/getASTNodeImport.ts","../src/node/utils/flattenMdxContent.ts","../src/node/utils/applyReplaceRules.ts","../src/node/utils/extractTextAndId.ts","../src/node/utils/escapeHeadingIds.ts","../src/node/mdx/remarkPlugins/builtin.ts","../src/node/mdx/rehypePlugins/codeMeta.ts","../src/node/mdx/rehypePlugins/headerAnchor.ts","../src/node/mdx/remarkPlugins/checkDeadLink.ts","../src/node/mdx/remarkPlugins/normalizeLink.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport { pathToFileURL } from 'node:url';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { isProduction } from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\nimport { createMDXOptions } from './options';\nimport type { TocItem } from './remarkPlugins/toc';\nimport { checkLinks } from './remarkPlugins/checkDeadLink';\nimport { TEMP_DIR } from '../constants';\nimport type { PluginDriver } from '../PluginDriver';\nimport { RuntimeModuleID } from '../runtimeModule';\nimport {\n normalizePath,\n escapeMarkdownHeadingIds,\n flattenMdxContent,\n applyReplaceRules,\n} from '../utils';\n\nimport type { Rspack } from '@rsbuild/core';\nimport type { Header, UserConfig } from '@rspress/shared';\nimport type { RouteService } from '../route/RouteService';\n\ninterface LoaderOptions {\n config: UserConfig;\n docDirectory: string;\n checkDeadLinks: boolean;\n routeService: RouteService;\n pluginDriver: PluginDriver;\n}\n\nexport interface PageMeta {\n toc: TocItem[];\n title: string;\n headingTitle: string;\n frontmatter?: Record<string, any>;\n}\n\nexport async function updateSiteDataRuntimeModule(\n modulePath: string,\n pageMeta: PageMeta,\n) {\n const siteDataModulePath = path.join(\n TEMP_DIR,\n 'runtime',\n `${RuntimeModuleID.SiteData}.mjs`,\n );\n const { default: siteData } = await import(\n pathToFileURL(siteDataModulePath).href\n );\n await fs.writeFile(\n siteDataModulePath,\n `export default ${JSON.stringify(\n {\n ...siteData,\n timestamp: Date.now().toString(),\n pages: siteData.pages.map(page =>\n // Update page meta if the page is updated\n page._filepath === modulePath ? { ...page, ...pageMeta } : page,\n ),\n },\n null,\n 2,\n )}`,\n );\n}\n\nexport function createCheckPageMetaUpdateFn() {\n const pageMetaMap = new Map<string, string>();\n return (modulePath: string, pageMeta: PageMeta) => {\n const prevMeta = pageMetaMap.get(modulePath);\n const deserializedMeta = JSON.stringify(pageMeta);\n pageMetaMap.set(modulePath, deserializedMeta);\n\n if (!prevMeta) {\n return;\n }\n\n if (prevMeta !== deserializedMeta) {\n setTimeout(async () => {\n logger.info('Page metadata changed, page reloading...');\n await updateSiteDataRuntimeModule(modulePath, pageMeta);\n });\n }\n };\n}\n\nconst checkPageMetaUpdate = createCheckPageMetaUpdateFn();\n\nexport default async function mdxLoader(\n context: Rspack.LoaderContext<LoaderOptions>,\n source: string,\n callback: Rspack.LoaderContext['callback'],\n) {\n context.cacheable(true);\n\n const options = context.getOptions();\n const filepath = context.resourcePath;\n const { alias } = context._compiler.options.resolve;\n const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } =\n options;\n\n // Separate frontmatter and content in MDX source\n const { frontmatter, content } = loadFrontMatter(\n source,\n filepath,\n docDirectory,\n true,\n );\n\n // Replace imported built-in MDX content\n const { flattenContent, deps } = await flattenMdxContent(\n content,\n filepath,\n alias as Record<string, string>,\n );\n\n deps.forEach(dep => context.addDependency(dep));\n\n // Resolve side effects caused by flattenMdxContent.\n // Perhaps this problem should be solved within flattenMdxContent?\n const replacedContent = applyReplaceRules(\n flattenContent,\n config.replaceRules,\n );\n\n // Support custom id like `#hello world {#custom-id}`.\n // TODO > issue: `#hello world {#custom-id}` will also be replaced.\n const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);\n\n // Whether to use the Rust version of the MDX compiler.\n let enableMdxRs: boolean;\n const mdxRs = config?.markdown?.mdxRs ?? true;\n if (typeof mdxRs === 'object') {\n enableMdxRs =\n typeof mdxRs?.include === 'function' ? mdxRs.include(filepath) : true;\n } else {\n enableMdxRs = mdxRs;\n }\n\n try {\n let compileResult: string;\n let pageMeta = { title: '', toc: [] } as PageMeta;\n\n if (!enableMdxRs) {\n const mdxOptions = await createMDXOptions(\n docDirectory,\n config,\n checkDeadLinks,\n routeService,\n filepath,\n pluginDriver,\n );\n const compiler = createProcessor(mdxOptions);\n\n compiler.data('pageMeta', { toc: [], title: '' });\n const vFile = await compiler.process({\n value: preprocessedContent,\n path: filepath,\n });\n\n compileResult = String(vFile);\n const compilationMeta = compiler.data('pageMeta') as {\n toc: Header[];\n title: string;\n };\n pageMeta = {\n ...compilationMeta,\n title: frontmatter.title || compilationMeta.title || '',\n headingTitle: compilationMeta.title,\n frontmatter,\n } as PageMeta;\n } else {\n const { compile } = require('@rspress/mdx-rs');\n\n const { toc, links, title, code } = await compile({\n value: preprocessedContent,\n filepath,\n root: docDirectory,\n development: process.env.NODE_ENV !== 'production',\n });\n\n compileResult = code;\n pageMeta = {\n toc,\n title: frontmatter.title || title || '',\n headingTitle: title,\n frontmatter,\n };\n // We should check dead links in mdx-rs mode\n if (checkDeadLinks) {\n checkLinks(links, filepath, docDirectory, routeService);\n }\n }\n\n // If page meta changed, we trigger page reload to ensure the page is up to date.\n if (!isProduction()) {\n checkPageMetaUpdate(filepath, pageMeta);\n }\n\n const result = `const frontmatter = ${JSON.stringify(frontmatter)};\n${compileResult}\nMDXContent.__RSPRESS_PAGE_META = {};\n\nMDXContent.__RSPRESS_PAGE_META[\"${encodeURIComponent(\n normalizePath(path.relative(docDirectory, filepath)),\n )}\"] = ${JSON.stringify(pageMeta)};\n`;\n callback(null, result);\n } catch (e) {\n logger.error(`MDX compile error: ${e.message} in ${filepath}`);\n callback({ message: e.message, name: `${filepath} compile error` });\n }\n}\n","import path from 'node:path';\nimport remarkGFM from 'remark-gfm';\nimport rehypePluginExternalLinks from 'rehype-external-links';\nimport type { PluggableList } from 'unified';\nimport type { Options } from '@mdx-js/loader';\nimport type { UserConfig } from '@rspress/shared';\nimport { remarkPluginToc } from './remarkPlugins/toc';\nimport { remarkBuiltin } from './remarkPlugins/builtin';\nimport { rehypePluginCodeMeta } from './rehypePlugins/codeMeta';\nimport { rehypeHeaderAnchor } from './rehypePlugins/headerAnchor';\nimport { remarkCheckDeadLinks } from './remarkPlugins/checkDeadLink';\nimport { remarkPluginNormalizeLink } from './remarkPlugins/normalizeLink';\n\nimport type { PluginDriver } from '../PluginDriver';\nimport type { RouteService } from '../route/RouteService';\n\nexport async function createMDXOptions(\n docDirectory: string,\n config: UserConfig,\n checkDeadLinks: boolean,\n routeService: RouteService,\n filepath: string,\n pluginDriver: PluginDriver,\n): Promise<Options> {\n const cleanUrls = Boolean(config?.route?.cleanUrls);\n const {\n remarkPlugins: remarkPluginsFromConfig = [],\n rehypePlugins: rehypePluginsFromConfig = [],\n globalComponents: globalComponentsFromConfig = [],\n } = config?.markdown || {};\n const rspressPlugins = pluginDriver.getPlugins();\n const remarkPluginsFromPlugins = rspressPlugins.flatMap(\n plugin => plugin.markdown?.remarkPlugins || [],\n ) as PluggableList;\n const rehypePluginsFromPlugins = rspressPlugins.flatMap(\n plugin => plugin.markdown?.rehypePlugins || [],\n ) as PluggableList;\n const globalComponents = [\n ...rspressPlugins.flatMap(\n plugin => plugin.markdown?.globalComponents || [],\n ),\n ...globalComponentsFromConfig,\n ];\n const defaultLang = config?.lang || '';\n return {\n providerImportSource: '@mdx-js/react',\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [\n remarkGFM,\n remarkPluginToc,\n [\n remarkPluginNormalizeLink,\n {\n base: config?.base || '',\n cleanUrls,\n defaultLang,\n root: docDirectory,\n },\n ],\n checkDeadLinks && [\n remarkCheckDeadLinks,\n {\n root: docDirectory,\n base: config?.base || '',\n routeService,\n },\n ],\n globalComponents.length && [\n remarkBuiltin,\n {\n globalComponents,\n },\n ],\n ...remarkPluginsFromConfig,\n ...remarkPluginsFromPlugins,\n ].filter(Boolean) as PluggableList,\n rehypePlugins: [\n rehypeHeaderAnchor,\n rehypePluginCodeMeta,\n [\n rehypePluginExternalLinks,\n {\n target: '_blank',\n rel: 'noopener noreferrer',\n },\n ],\n ...rehypePluginsFromConfig,\n ...rehypePluginsFromPlugins,\n ],\n };\n}\n","import type { Plugin } from 'unified';\nimport { visitChildren } from 'unist-util-visit-children';\nimport Slugger from 'github-slugger';\nimport type { Root } from 'hast';\nimport type { Processor } from '@mdx-js/mdx/lib/core';\nimport type { PageMeta } from '../loader';\nimport { extractTextAndId } from '../../utils';\n\nexport interface TocItem {\n id: string;\n text: string;\n depth: number;\n}\n\ninterface ChildNode {\n type: 'link' | 'text' | 'inlineCode' | 'strong';\n value: string;\n children?: ChildNode[];\n}\n\ninterface Heading {\n type: string;\n depth?: number;\n children?: ChildNode[];\n}\n\nexport const parseToc = (tree: Root) => {\n let title = '';\n const toc: TocItem[] = [];\n const slugger = new Slugger();\n visitChildren((node: Heading) => {\n if (node.type !== 'heading' || !node.depth || !node.children) {\n return;\n }\n\n // Collect h1 ~ h4\n if (node.depth >= 1 && node.depth < 5) {\n let customId = '';\n const text = node.children\n .map((child: ChildNode) => {\n if (child.type === 'link') {\n return child.children?.map(item => item.value).join('');\n }\n if (child.type === 'strong') {\n return `**${child.children?.map(item => item.value).join('')}**`;\n }\n if (child.type === 'text') {\n const [textPart, idPart] = extractTextAndId(child.value);\n customId = idPart;\n return textPart;\n }\n if (child.type === 'inlineCode') {\n return `\\`${child.value}\\``;\n }\n return '';\n })\n .join('');\n\n if (node.depth === 1) {\n if (!title) title = text;\n } else {\n const id = customId ? customId : slugger.slug(text);\n const { depth } = node;\n toc.push({ id, text, depth });\n }\n }\n })(tree);\n return {\n title,\n toc,\n };\n};\n\nexport const remarkPluginToc: Plugin<[], Root> = function (this: Processor) {\n const data = this.data() as {\n pageMeta: PageMeta;\n };\n return (tree: Root) => {\n const { toc, title } = parseToc(tree);\n data.pageMeta.toc = toc;\n if (title) {\n data.pageMeta.title = title;\n }\n };\n};\n","import os from 'node:os';\nimport path from 'node:path';\n\nexport const isWindows = os.platform() === 'win32';\n\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function normalizePath(id: string): string {\n return path.posix.normalize(isWindows ? slash(id) : id);\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from '@rspress/shared';\n\nexport const isProduction = () => process.env.NODE_ENV === 'production';\n\n// Keep the quotation marks consistent before and after.\nexport const importStatementRegex =\n /import\\s+(.*?)\\s+from\\s+(['\"])(.*?)(?:\"|');?/gm;\n\n// In the first render, the theme will be set according to the user's system theme\n// - Should be injected into both development and production modes\n// - Class hook (.dark) is set for internal use (Tailwind)\n// - Style hook (colorScheme) is set for external use (CSS media queries or `light-dark()` function)\nexport const inlineThemeScript = `{\n const saved = localStorage.getItem('${APPEARANCE_KEY}')\n const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches\n const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'\n document.documentElement.classList.toggle('dark', isDark)\n document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'\n}`\n .replace(/\\n/g, ';')\n .replace(/\\s{2,}/g, '');\n\nconst dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));\n\nexport const PACKAGE_ROOT = path.join(dirname, '..');\n\nexport const CLIENT_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'clientEntry.js',\n);\n\nexport const SSR_ENTRY = path.join(\n PACKAGE_ROOT,\n 'dist',\n 'runtime',\n 'ssrEntry.js',\n);\n\nexport const OUTPUT_DIR = 'doc_build';\n\nexport const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';\nexport const HEAD_MARKER = '<!--<?- HEAD ?>-->';\nexport const META_GENERATOR = '<!--<?- GENERATOR ?>-->';\nexport const HTML_START_TAG = '<html';\nexport const BODY_START_TAG = '<body';\n\nexport const DEFAULT_TITLE = 'Rspress';\n\nexport const PUBLIC_DIR = 'public';\nexport const TEMP_DIR = path.join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n);\n","import type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\n\n// Construct import statement for AST\n// Such as: import image1 from './test.png'\nexport const getASTNodeImport = (name: string, from: string) =>\n ({\n type: 'mdxjsEsm',\n value: `import ${name} from ${JSON.stringify(from)}`,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ImportDeclaration',\n specifiers: [\n {\n type: 'ImportDefaultSpecifier',\n local: { type: 'Identifier', name },\n },\n ],\n source: {\n type: 'Literal',\n value: from,\n raw: `${JSON.stringify(from)}`,\n },\n },\n ],\n },\n },\n }) as MdxjsEsm;\n","import path from 'node:path';\nimport fs from '@rspress/shared/fs-extra';\nimport enhancedResolve from 'enhanced-resolve';\nimport { MDX_REGEXP } from '@rspress/shared';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { importStatementRegex } from '../constants';\n\nimport type { Root } from 'hast';\nimport type { Resolver } from 'enhanced-resolve';\n\nlet resolver: Resolver;\nlet startFlatten = false;\n\nconst processor = createProcessor();\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\n\nexport async function resolveDepPath(\n importPath: string,\n importer: string,\n alias: Record<string, string | string[]>,\n) {\n if (!resolver) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md'],\n alias,\n });\n }\n const resolveResult = await new Promise<string>((resolve, reject) => {\n resolver.resolve(\n {\n importer,\n },\n importer,\n importPath,\n {},\n (err, filePath) => {\n if (err) {\n return reject(err);\n }\n if (!filePath) {\n return reject(\n new Error(\n `Empty result when resolving ${importPath} from ${importer}`,\n ),\n );\n }\n return resolve(filePath);\n },\n );\n });\n return resolveResult;\n}\n\ninterface ESTree {\n body: {\n type: 'ImportDeclaration';\n specifiers: { local: { name: string } }[];\n source: { value: string };\n }[];\n}\n\nexport async function flattenMdxContent(\n content: string,\n basePath: string,\n alias: Record<string, string | string[]>,\n): Promise<{ flattenContent: string; deps: string[] }> {\n const deps = [];\n // Performance optimization: if the content does not contain any import statement, we can skip the parsing process\n // So we need to check this match\n\n // Create new regExp to avoid the regex cache the last match index\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#using_test_on_a_regex_with_the_global_flag\n const regex = new RegExp(importStatementRegex);\n if (!regex.test(content)) {\n return { flattenContent: content, deps };\n }\n\n // We should update the resolver instanceof because the alias should be passed to it\n // If we reuse the resolver instance in `detectReactVersion` method, the resolver will lose the alias info and cannot resolve path correctly in mdx files.\n if (!startFlatten) {\n resolver = ResolverFactory.createResolver({\n fileSystem: new CachedInputFileSystem(fs as any, 0),\n extensions: ['.mdx', '.md', '.js'],\n alias,\n });\n startFlatten = true;\n }\n\n let ast: Root;\n let result = content;\n\n try {\n ast = processor.parse(content) as Root;\n } catch (e) {\n // Fallback: if mdx parse failed, just return the content\n return { flattenContent: content, deps };\n }\n\n const importNodes = ast.children\n .filter(node => node.type === ('mdxjsEsm' as any))\n .flatMap(node => (node.data?.estree as ESTree)?.body || [])\n .filter(node => node.type === 'ImportDeclaration');\n for (const importNode of importNodes) {\n // import Comp from './a';\n // {id: Comp, importPath: './a'}\n const id = importNode.specifiers[0].local.name;\n const importPath = importNode.source.value;\n\n let absoluteImportPath: string;\n try {\n absoluteImportPath = await resolveDepPath(\n importPath,\n path.dirname(basePath),\n alias,\n );\n } catch (e) {\n continue;\n }\n\n if (MDX_REGEXP.test(absoluteImportPath)) {\n // replace import statement with the content of the imported file\n const importedContent = fs.readFileSync(absoluteImportPath, 'utf-8');\n const { flattenContent: replacedValue, deps: subDeps } =\n await flattenMdxContent(importedContent, absoluteImportPath, alias);\n\n result = result\n .replace(\n new RegExp(`import\\\\s+${id}\\\\s+from\\\\s+['\"](${importPath})['\"];?`),\n '',\n )\n .replace(new RegExp(`<${id}\\\\s*/>`, 'g'), () => replacedValue);\n\n deps.push(...subDeps, absoluteImportPath);\n }\n }\n\n return { flattenContent: result, deps };\n}\n","import type { ReplaceRule } from '@rspress/shared';\n\nexport function applyReplaceRules(\n code = '',\n replaceRules: ReplaceRule[] = [],\n): string {\n let result = code;\n for (const rule of replaceRules) {\n result = result.replace(rule.search, rule.replace);\n }\n return result;\n}\n","/**\n * hello world {#custom-id} -> { text: 'hello world', id: 'custom-id' }\n */\nexport const extractTextAndId = (title: string) => {\n const customIdReg = /{#.*}/;\n const text = title.replace(customIdReg, '').trimEnd();\n const customId = title.match(customIdReg)?.[0]?.slice(2, -1) || '';\n return [text, customId];\n};\n","/**\n * Support custom id like `#hello world {#custom-id}`\n * Avoid https://mdxjs.com/docs/troubleshooting-mdx/#could-not-parse-expression-with-acorn-error\n */\nexport function escapeMarkdownHeadingIds(content: string): string {\n const markdownHeadingRegexp = /(?:^|\\n)#{1,6}(?!#).*/g;\n return content.replace(markdownHeadingRegexp, substring =>\n substring\n .replace('{#', '\\\\{#')\n // prevent duplicate escaping\n .replace('\\\\\\\\{#', '\\\\{#'),\n );\n}\n","import path from 'node:path';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { getASTNodeImport } from '@/node/utils/getASTNodeImport';\n\n/**\n * A remark plugin to import all builtin components.\n * @param options configure the global components.\n * @returns A unified transformer.\n */\nexport const remarkBuiltin: Plugin<[{ globalComponents: string[] }], Root> = ({\n globalComponents,\n}) => {\n return tree => {\n const demos: MdxjsEsm[] = globalComponents.map(componentPath => {\n const filename = path.parse(componentPath).name;\n const componentName = filename[0].toUpperCase() + filename.slice(1);\n return getASTNodeImport(componentName, componentPath);\n });\n\n tree.children.unshift(...demos);\n };\n};\n","import type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'hast';\n\nexport const rehypePluginCodeMeta: Plugin<[], Root> = () => {\n return tree => {\n visit(tree, 'element', node => {\n // <pre><code>...</code></pre>\n // 1. Find pre element\n if (\n node.tagName === 'pre' &&\n node.children[0]?.type === 'element' &&\n node.children[0].tagName === 'code'\n ) {\n const codeNode = node.children[0];\n // language-foo\n const meta = (codeNode.data?.meta as string) || '';\n codeNode.properties.meta = meta;\n }\n });\n };\n};\n","import { headingRank } from 'hast-util-heading-rank';\nimport { visit } from 'unist-util-visit';\nimport GithubSlugger from 'github-slugger';\nimport type { Plugin } from 'unified';\nimport type { Root, Element } from 'hast';\nimport { extractTextAndId } from '../../utils';\n\n/**\n * Generate `id`s for headings and applies to headings with `id`s.\n * same as rehype-slug + rehype-autolink-headings, but support custom id.\n */\nexport const rehypeHeaderAnchor: Plugin<[], Root> = () => {\n const slugger = new GithubSlugger();\n return function (tree) {\n visit(tree, 'element', function (node) {\n if (headingRank(node as any)) {\n // generate id\n if (!node.properties.id) {\n const [text, customId] = collectHeaderText(node);\n node.properties.id = customId || slugger.slug(text);\n }\n // apply to headings\n node.children.unshift(create(node));\n }\n });\n };\n};\n\nexport const collectHeaderText = (node: Element) => {\n let text = '';\n let id = '';\n node.children.forEach(child => {\n if (child.type === 'text') {\n const [textPart, idPart] = extractTextAndId(child.value);\n child.value = textPart;\n text += textPart;\n id = idPart;\n }\n if (child.type === 'element') {\n child.children.forEach(c => {\n if (c.type === 'text') {\n text += c.value;\n }\n });\n }\n });\n return [text, id];\n};\n\n/**\n * Create an `a`.\n *\n * @param {Readonly<Element>} node\n * Related heading.\n * @returns {Element}\n * Link.\n */\nfunction create(node: Element): Element {\n return {\n type: 'element',\n tagName: 'a',\n properties: {\n class: 'header-anchor',\n ariaHidden: 'true',\n href: `#${node.properties.id}`,\n },\n children: [\n {\n type: 'text',\n value: '#',\n },\n ],\n };\n}\n","import path from 'node:path';\nimport { visit } from 'unist-util-visit';\nimport type { Plugin } from 'unified';\nimport { logger } from '@rspress/shared/logger';\nimport { cleanUrl, isProduction } from '@rspress/shared';\nimport type { RouteService } from '@/node/route/RouteService';\nimport { normalizePath } from '@/node/utils';\n\nexport interface DeadLinkCheckOptions {\n root: string;\n base: string;\n routeService: RouteService;\n}\n\nconst IGNORE_REGEXP = /^(https?|mailto|tel|#)/;\n\nexport function checkLinks(\n links: string[],\n filepath: string,\n root: string,\n routeService: RouteService,\n) {\n const errorInfos: string[] = [];\n links\n .filter(link => !IGNORE_REGEXP.test(link))\n .map(link => normalizePath(link))\n .forEach(link => {\n const relativePath = path.relative(root, filepath);\n\n if (!routeService.isExistRoute(cleanUrl(link))) {\n errorInfos.push(\n `Internal link to ${link} is dead, check it in ${relativePath}`,\n );\n }\n });\n // output error info\n if (errorInfos.length > 0) {\n errorInfos?.forEach(err => {\n logger.error(err);\n });\n if (isProduction()) {\n throw new Error('Dead link found');\n }\n }\n}\n\n/**\n * Remark plugin to check dead links\n */\nexport const remarkCheckDeadLinks: Plugin<\n DeadLinkCheckOptions[]\n> = checkLink => {\n const { root, routeService } = checkLink;\n\n return (tree, vfile) => {\n const internalLinks = new Set<string>();\n\n visit(tree, 'link', (node: { url: string }) => {\n const { url } = node;\n if (!url) {\n return;\n }\n if (internalLinks.has(url)) {\n return;\n }\n\n if (!url.startsWith('http') && !url.startsWith('https')) {\n const { routePath: normalizeUrl } = routeService.normalizeRoutePath(\n // fix: windows path\n url.split(path.sep).join('/')?.split('#')[0],\n );\n internalLinks.add(normalizeUrl);\n }\n });\n\n checkLinks(Array.from(internalLinks), vfile.path, root, routeService);\n };\n};\n","import path from 'node:path';\nimport type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { normalizeHref, parseUrl, isExternalUrl, slash } from '@rspress/shared';\nimport { getASTNodeImport } from '@/node/utils/getASTNodeImport';\n\ninterface LinkNode {\n type: string;\n url?: string;\n}\n\n/**\n * Remark plugin to normalize a link href\n */\nexport const remarkPluginNormalizeLink: Plugin<\n [{ base: string; root: string; cleanUrls: boolean }],\n Root\n> =\n ({ base, root, cleanUrls }) =>\n (tree, file) => {\n const images: MdxjsEsm[] = [];\n visit(\n tree,\n (node: LinkNode) => node.type === 'link',\n (node: LinkNode) => {\n if (!node.url) {\n return;\n }\n if (node.url.startsWith('#')) {\n node.url = `#${node.url.slice(1)}`;\n return;\n }\n\n // eslint-disable-next-line prefer-const\n let { url, hash } = parseUrl(node.url);\n\n if (isExternalUrl(url)) {\n node.url = url + (hash ? `#${hash}` : '');\n return;\n }\n\n const extname = path.extname(url);\n\n if (extname === '.md' || extname === '.mdx') {\n url = url.replace(extname, '');\n }\n\n const relativePath = path.relative(root, file.path);\n if (url.startsWith('.')) {\n url = path.posix.join(slash(path.dirname(relativePath)), url);\n }\n\n url = normalizeHref(url, cleanUrls);\n\n if (hash) {\n url += `#${hash}`;\n }\n node.url = path.posix.join(base, url);\n },\n );\n\n const normalizeImageUrl = (imageUrl: string): string => {\n if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) {\n return '';\n }\n\n return imageUrl;\n };\n\n const getMdxSrcAttrbute = (tempVar: string) => {\n return {\n type: 'mdxJsxAttribute',\n name: 'src',\n value: {\n type: 'mdxJsxAttributeValueExpression',\n value: tempVar,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ExpressionStatement',\n expression: {\n type: 'Identifier',\n name: tempVar,\n },\n },\n ],\n },\n },\n },\n };\n };\n\n visit(tree, 'image', node => {\n const { url } = node;\n if (!url) {\n return;\n }\n\n const imagePath = normalizeImageUrl(url);\n if (!imagePath) {\n return;\n }\n // relative path\n const tempVariableName = `image${images.length}`;\n\n Object.assign(node, {\n type: 'mdxJsxFlowElement',\n name: 'img',\n children: [],\n attributes: [\n node.alt && {\n type: 'mdxJsxAttribute',\n name: 'alt',\n value: node.alt,\n },\n getMdxSrcAttrbute(tempVariableName),\n ].filter(Boolean),\n });\n\n images.push(getASTNodeImport(tempVariableName, imagePath));\n });\n\n visit(tree, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node: any) => {\n // get all img src\n if (node.name !== 'img') {\n return;\n }\n\n const src = node.attributes.find((attr: any) => attr.name === 'src');\n\n if (!src?.value || typeof src?.value !== 'string') {\n return;\n }\n\n const imagePath = normalizeImageUrl(src.value);\n\n if (!imagePath) {\n return;\n }\n\n const tempVariableName = `image${images.length}`;\n\n Object.assign(src, getMdxSrcAttrbute(tempVariableName));\n\n images.push(getASTNodeImport(tempVariableName, imagePath));\n });\n\n tree.children.unshift(...images);\n };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "1.38.0",
3
+ "version": "1.39.0",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -36,12 +36,12 @@
36
36
  "@mdx-js/loader": "2.3.0",
37
37
  "@mdx-js/mdx": "2.3.0",
38
38
  "@mdx-js/react": "2.3.0",
39
- "@rsbuild/core": "~1.1.9",
39
+ "@rsbuild/core": "~1.1.12",
40
40
  "@rsbuild/plugin-less": "~1.1.0",
41
41
  "@rsbuild/plugin-react": "~1.1.0",
42
42
  "@rsbuild/plugin-sass": "~1.1.2",
43
43
  "@rspress/mdx-rs": "0.6.4",
44
- "enhanced-resolve": "5.17.1",
44
+ "enhanced-resolve": "5.18.0",
45
45
  "github-slugger": "^2.0.0",
46
46
  "hast-util-from-html": "^2.0.3",
47
47
  "hast-util-heading-rank": "^3.0.0",
@@ -49,7 +49,6 @@
49
49
  "htmr": "^1.0.2",
50
50
  "lodash-es": "^4.17.21",
51
51
  "mdast-util-mdxjs-esm": "^1.3.1",
52
- "node-fetch": "3.3.2",
53
52
  "react": "^18.3.1",
54
53
  "react-dom": "^18.3.1",
55
54
  "react-helmet-async": "^1.3.0",
@@ -62,31 +61,31 @@
62
61
  "unified": "^10.1.2",
63
62
  "unist-util-visit": "^4.1.2",
64
63
  "unist-util-visit-children": "^3.0.0",
65
- "@rspress/plugin-auto-nav-sidebar": "1.38.0",
66
- "@rspress/plugin-container-syntax": "1.38.0",
67
- "@rspress/plugin-last-updated": "1.38.0",
68
- "@rspress/plugin-medium-zoom": "1.38.0",
69
- "@rspress/runtime": "1.38.0",
70
- "@rspress/shared": "1.38.0",
71
- "@rspress/theme-default": "1.38.0"
64
+ "@rspress/plugin-auto-nav-sidebar": "1.39.0",
65
+ "@rspress/plugin-container-syntax": "1.39.0",
66
+ "@rspress/plugin-medium-zoom": "1.39.0",
67
+ "@rspress/runtime": "1.39.0",
68
+ "@rspress/theme-default": "1.39.0",
69
+ "@rspress/shared": "1.39.0",
70
+ "@rspress/plugin-last-updated": "1.39.0"
72
71
  },
73
72
  "devDependencies": {
74
- "@modern-js/plugin-tailwindcss": "2.63.1",
75
- "@modern-js/tsconfig": "2.63.1",
73
+ "@modern-js/plugin-tailwindcss": "2.63.3",
74
+ "@modern-js/tsconfig": "2.63.3",
76
75
  "@types/hast": "3.0.4",
77
76
  "@types/html-to-text": "^9.0.4",
78
77
  "@types/jest": "~29.5.14",
79
78
  "@types/lodash-es": "^4.17.12",
80
79
  "@types/mdast": "^4.0.4",
81
80
  "@types/node": "^18.11.17",
82
- "@types/react": "^18.3.14",
83
- "@types/react-dom": "^18.3.2",
81
+ "@types/react": "^18.3.18",
82
+ "@types/react-dom": "^18.3.5",
84
83
  "postcss": "8.4.49",
85
84
  "rehype-stringify": "^9.0.4",
86
85
  "remark-parse": "^10.0.2",
87
86
  "remark-rehype": "^10.1.0",
88
87
  "rimraf": "^3.0.2",
89
- "tailwindcss": "^3.4.16",
88
+ "tailwindcss": "^3.4.17",
90
89
  "typescript": "^5.5.3",
91
90
  "vitest": "2.1.8"
92
91
  },
@@ -25,6 +25,7 @@ export enum QueryStatus {
25
25
 
26
26
  type PageMeta = {
27
27
  title: string;
28
+ headingTitle: string;
28
29
  toc: Header[];
29
30
  frontmatter: Record<string, any>;
30
31
  };