@rspress/core 1.41.1 → 1.41.3

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/loader.js CHANGED
@@ -1,729 +1,591 @@
1
- import { createRequire } from "module";
2
- const { url } = import.meta;
3
- const require = createRequire(url);
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined")
8
- return require.apply(this, arguments);
9
- throw Error('Dynamic require of "' + x + '" is not supported');
10
- });
11
-
12
- // src/node/mdx/loader.ts
13
- import fs2 from "fs/promises";
14
- import path8 from "path";
15
- import { pathToFileURL } from "url";
16
- import { createProcessor as createProcessor2 } from "@mdx-js/mdx";
17
- import { isProduction as isProduction2 } from "@rspress/shared";
18
- import { logger as logger2 } from "@rspress/shared/logger";
19
- import { loadFrontMatter } from "@rspress/shared/node-utils";
20
-
21
- // src/node/constants.ts
22
- import path from "path";
23
- import { fileURLToPath } from "url";
24
- import { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from "@rspress/shared";
25
- var importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
26
- var inlineThemeScript = `{
27
- const saved = localStorage.getItem('${APPEARANCE_KEY}')
1
+ import __rslib_shim_module__ from 'module';
2
+ /*#__PURE__*/ import.meta.url;
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
6
+ import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
8
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__ from "@rspress/shared/logger";
9
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
10
+ import "rspack-plugin-virtual-module";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
12
+ import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
13
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
14
+ import * as __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__ from "rehype-external-links";
15
+ import * as __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__ from "remark-gfm";
16
+ import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
17
+ import * as __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__ from "github-slugger";
18
+ import * as __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__ from "hast-util-heading-rank";
19
+ import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__ from "unist-util-visit-children";
20
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
21
+ `{
22
+ const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
28
23
  const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
29
24
  const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
30
25
  document.documentElement.classList.toggle('dark', isDark)
31
26
  document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
32
- }`.replace(/\n/g, ";").replace(/\s{2,}/g, "");
33
- var dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));
34
- var PACKAGE_ROOT = path.join(dirname, "..");
35
- var CLIENT_ENTRY = path.join(
36
- PACKAGE_ROOT,
37
- "dist",
38
- "runtime",
39
- "clientEntry.js"
40
- );
41
- var SSR_ENTRY = path.join(
42
- PACKAGE_ROOT,
43
- "dist",
44
- "runtime",
45
- "ssrEntry.js"
46
- );
47
- var TEMP_DIR = path.join(
48
- process.cwd(),
49
- "node_modules",
50
- RSPRESS_TEMP_DIR
51
- );
52
-
53
- // src/node/utils/normalizePath.ts
54
- import os from "os";
55
- import path2 from "path";
56
- var isWindows = os.platform() === "win32";
57
- function slash(p) {
58
- return p.replace(/\\/g, "/");
59
- }
60
- function normalizePath(id) {
61
- return path2.posix.normalize(isWindows ? slash(id) : id);
62
- }
63
-
64
- // src/node/utils/getASTNodeImport.ts
65
- var getASTNodeImport = (name, from) => ({
66
- type: "mdxjsEsm",
67
- value: `import ${name} from ${JSON.stringify(from)}`,
68
- data: {
69
- estree: {
70
- type: "Program",
71
- sourceType: "module",
72
- body: [
73
- {
74
- type: "ImportDeclaration",
75
- specifiers: [
76
- {
77
- type: "ImportDefaultSpecifier",
78
- local: { type: "Identifier", name }
79
- }
80
- ],
81
- source: {
82
- type: "Literal",
83
- value: from,
84
- raw: `${JSON.stringify(from)}`
85
- }
86
- }
87
- ]
88
- }
89
- }
90
- });
91
-
92
- // src/node/utils/flattenMdxContent.ts
93
- import fs from "fs";
94
- import path3 from "path";
95
- import { createProcessor } from "@mdx-js/mdx";
96
- import { MDX_REGEXP } from "@rspress/shared";
97
- import enhancedResolve from "enhanced-resolve";
98
- var resolver;
99
- var startFlatten = false;
100
- var processor = createProcessor();
101
- var { CachedInputFileSystem, ResolverFactory } = enhancedResolve;
27
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
28
+ const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
29
+ const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
30
+ __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'clientEntry.js');
31
+ __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrEntry.js');
32
+ const TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
33
+ var runtimeModule_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
34
+ RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
35
+ RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
36
+ RuntimeModuleID["RouteForClient"] = "virtual-routes";
37
+ RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
38
+ RuntimeModuleID["SiteData"] = "virtual-site-data";
39
+ RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
40
+ RuntimeModuleID["I18nText"] = "virtual-i18n-text";
41
+ RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
42
+ RuntimeModuleID["PrismLanguages"] = "virtual-prism-languages";
43
+ return RuntimeModuleID;
44
+ }({});
45
+ let resolver;
46
+ let startFlatten = false;
47
+ const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
48
+ const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
102
49
  async function resolveDepPath(importPath, importer, alias) {
103
- if (!resolver) {
104
- resolver = ResolverFactory.createResolver({
105
- fileSystem: new CachedInputFileSystem(fs, 0),
106
- extensions: [".mdx", ".md"],
107
- alias
50
+ if (!resolver) resolver = ResolverFactory.createResolver({
51
+ fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
52
+ extensions: [
53
+ '.mdx',
54
+ '.md'
55
+ ],
56
+ alias
108
57
  });
109
- }
110
- const resolveResult = await new Promise((resolve, reject) => {
111
- resolver.resolve(
112
- {
113
- importer
114
- },
115
- importer,
116
- importPath,
117
- {},
118
- (err, filePath) => {
119
- if (err) {
120
- return reject(err);
121
- }
122
- if (!filePath) {
123
- return reject(
124
- new Error(
125
- `Empty result when resolving ${importPath} from ${importer}`
126
- )
127
- );
128
- }
129
- return resolve(filePath);
130
- }
131
- );
132
- });
133
- return resolveResult;
58
+ const resolveResult = await new Promise((resolve, reject)=>{
59
+ resolver.resolve({
60
+ importer
61
+ }, importer, importPath, {}, (err, filePath)=>{
62
+ if (err) return reject(err);
63
+ if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
64
+ return resolve(filePath);
65
+ });
66
+ });
67
+ return resolveResult;
134
68
  }
135
69
  async function flattenMdxContent(content, basePath, alias) {
136
- const deps = [];
137
- const regex = new RegExp(importStatementRegex);
138
- if (!regex.test(content)) {
139
- return { flattenContent: content, deps };
140
- }
141
- if (!startFlatten) {
142
- resolver = ResolverFactory.createResolver({
143
- fileSystem: new CachedInputFileSystem(fs, 0),
144
- extensions: [".mdx", ".md", ".js"],
145
- alias
146
- });
147
- startFlatten = true;
148
- }
149
- let ast;
150
- let result = content;
151
- try {
152
- ast = processor.parse(content);
153
- } catch (e) {
154
- return { flattenContent: content, deps };
155
- }
156
- const importNodes = ast.children.filter((node) => node.type === "mdxjsEsm").flatMap((node) => node.data?.estree?.body || []).filter((node) => node.type === "ImportDeclaration");
157
- for (const importNode of importNodes) {
158
- const id = importNode.specifiers[0].local.name;
159
- const importPath = importNode.source.value;
160
- let absoluteImportPath;
70
+ const deps = [];
71
+ const regex = new RegExp(importStatementRegex);
72
+ if (!regex.test(content)) return {
73
+ flattenContent: content,
74
+ deps
75
+ };
76
+ if (!startFlatten) {
77
+ resolver = ResolverFactory.createResolver({
78
+ fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
79
+ extensions: [
80
+ '.mdx',
81
+ '.md',
82
+ '.js'
83
+ ],
84
+ alias
85
+ });
86
+ startFlatten = true;
87
+ }
88
+ let ast;
89
+ let result = content;
161
90
  try {
162
- absoluteImportPath = await resolveDepPath(
163
- importPath,
164
- path3.dirname(basePath),
165
- alias
166
- );
91
+ ast = processor.parse(content);
167
92
  } catch (e) {
168
- continue;
93
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug('flattenMdxContent parse failed: \n', e);
94
+ return {
95
+ flattenContent: content,
96
+ deps
97
+ };
169
98
  }
170
- if (MDX_REGEXP.test(absoluteImportPath)) {
171
- const importedContent = fs.readFileSync(absoluteImportPath, "utf-8");
172
- const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
173
- result = result.replace(
174
- new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`),
175
- ""
176
- ).replace(new RegExp(`<${id}\\s*/>`, "g"), () => replacedValue);
177
- deps.push(...subDeps, absoluteImportPath);
99
+ const importNodes = ast.children.filter((node)=>'mdxjsEsm' === node.type).flatMap((node)=>{
100
+ var _node_data_estree, _node_data;
101
+ return (null === (_node_data = node.data) || void 0 === _node_data ? void 0 : null === (_node_data_estree = _node_data.estree) || void 0 === _node_data_estree ? void 0 : _node_data_estree.body) || [];
102
+ }).filter((node)=>'ImportDeclaration' === node.type);
103
+ for (const importNode of importNodes){
104
+ const id = importNode.specifiers[0].local.name;
105
+ const importPath = importNode.source.value;
106
+ let absoluteImportPath;
107
+ try {
108
+ absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
109
+ } catch (e) {
110
+ continue;
111
+ }
112
+ if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_REGEXP.test(absoluteImportPath)) {
113
+ const importedContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(absoluteImportPath, 'utf-8');
114
+ const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
115
+ result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
116
+ deps.push(...subDeps, absoluteImportPath);
117
+ }
178
118
  }
179
- }
180
- return { flattenContent: result, deps };
119
+ return {
120
+ flattenContent: result,
121
+ deps
122
+ };
181
123
  }
182
-
183
- // src/node/utils/applyReplaceRules.ts
184
- function applyReplaceRules(code = "", replaceRules = []) {
185
- let result = code;
186
- for (const rule of replaceRules) {
187
- result = result.replace(rule.search, rule.replace);
188
- }
189
- return result;
124
+ function applyReplaceRules(code = '', replaceRules = []) {
125
+ let result = code;
126
+ for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
127
+ return result;
190
128
  }
191
-
192
- // src/node/utils/extractTextAndId.ts
193
- var extractTextAndId = (title) => {
194
- const customIdReg = /{#.*}/;
195
- const text = title.replace(customIdReg, "").trimEnd();
196
- const customId = title.match(customIdReg)?.[0]?.slice(2, -1) || "";
197
- return [text, customId];
198
- };
199
-
200
- // src/node/utils/escapeHeadingIds.ts
201
129
  function escapeMarkdownHeadingIds(content) {
202
- const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
203
- return content.replace(
204
- markdownHeadingRegexp,
205
- (substring) => substring.replace("{#", "\\{#").replace("\\\\{#", "\\{#")
206
- );
130
+ const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
131
+ return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
207
132
  }
208
-
209
- // src/node/mdx/options.ts
210
- import path7 from "path";
211
- import rehypePluginExternalLinks from "rehype-external-links";
212
- import remarkGFM from "remark-gfm";
213
-
214
- // src/node/mdx/rehypePlugins/codeMeta.ts
215
- import { visit } from "unist-util-visit";
216
- var rehypePluginCodeMeta = () => {
217
- return (tree) => {
218
- visit(tree, "element", (node) => {
219
- if (node.tagName === "pre" && node.children[0]?.type === "element" && node.children[0].tagName === "code") {
220
- const codeNode = node.children[0];
221
- const meta = codeNode.data?.meta || "";
222
- codeNode.properties.meta = meta;
223
- }
224
- });
225
- };
133
+ const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
134
+ function slash(p) {
135
+ return p.replace(/\\/g, '/');
136
+ }
137
+ function normalizePath(id) {
138
+ return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
139
+ }
140
+ const rehypePluginCodeMeta = ()=>(tree)=>{
141
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
142
+ var _node_children_;
143
+ if ('pre' === node.tagName && (null === (_node_children_ = node.children[0]) || void 0 === _node_children_ ? void 0 : _node_children_.type) === 'element' && 'code' === node.children[0].tagName) {
144
+ var _codeNode_data;
145
+ const codeNode = node.children[0];
146
+ const meta = (null === (_codeNode_data = codeNode.data) || void 0 === _codeNode_data ? void 0 : _codeNode_data.meta) || '';
147
+ codeNode.properties.meta = meta;
148
+ }
149
+ });
150
+ };
151
+ const extractTextAndId = (title)=>{
152
+ var _title_match_, _title_match;
153
+ const customIdReg = /{#.*}/;
154
+ const text = title.replace(customIdReg, '').trimEnd();
155
+ const customId = (null === (_title_match = title.match(customIdReg)) || void 0 === _title_match ? void 0 : null === (_title_match_ = _title_match[0]) || void 0 === _title_match_ ? void 0 : _title_match_.slice(2, -1)) || '';
156
+ return [
157
+ text,
158
+ customId
159
+ ];
226
160
  };
227
-
228
- // src/node/mdx/rehypePlugins/headerAnchor.ts
229
- import GithubSlugger from "github-slugger";
230
- import { headingRank } from "hast-util-heading-rank";
231
- import { visit as visit2 } from "unist-util-visit";
232
- var rehypeHeaderAnchor = () => {
233
- const slugger = new GithubSlugger();
234
- return function(tree) {
235
- visit2(tree, "element", function(node) {
236
- if (headingRank(node)) {
237
- if (!node.properties.id) {
238
- const [text, customId] = collectHeaderText(node);
239
- node.properties.id = customId || slugger.slug(text);
240
- }
241
- node.children.unshift(create(node));
242
- }
243
- });
244
- };
161
+ const rehypeHeaderAnchor = ()=>{
162
+ const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
163
+ return function(tree) {
164
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', function(node) {
165
+ if ((0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) {
166
+ if (!node.properties.id) {
167
+ const [text, customId] = collectHeaderText(node);
168
+ node.properties.id = customId || slugger.slug(text);
169
+ }
170
+ node.children.unshift(create(node));
171
+ }
172
+ });
173
+ };
245
174
  };
246
- var collectHeaderText = (node) => {
247
- let text = "";
248
- let id = "";
249
- node.children.forEach((child) => {
250
- if (child.type === "text") {
251
- const [textPart, idPart] = extractTextAndId(child.value);
252
- child.value = textPart;
253
- text += textPart;
254
- id = idPart;
255
- }
256
- if (child.type === "element") {
257
- child.children.forEach((c) => {
258
- if (c.type === "text") {
259
- text += c.value;
175
+ const collectHeaderText = (node)=>{
176
+ let text = '';
177
+ let id = '';
178
+ node.children.forEach((child)=>{
179
+ if ('text' === child.type) {
180
+ const [textPart, idPart] = extractTextAndId(child.value);
181
+ child.value = textPart;
182
+ text += textPart;
183
+ id = idPart;
260
184
  }
261
- });
262
- }
263
- });
264
- return [text, id];
185
+ if ('element' === child.type) child.children.forEach((c)=>{
186
+ if ('text' === c.type) text += c.value;
187
+ });
188
+ });
189
+ return [
190
+ text,
191
+ id
192
+ ];
265
193
  };
266
194
  function create(node) {
267
- return {
268
- type: "element",
269
- tagName: "a",
270
- properties: {
271
- class: "header-anchor",
272
- ariaHidden: "true",
273
- href: `#${node.properties.id}`
274
- },
275
- children: [
276
- {
277
- type: "text",
278
- value: "#"
279
- }
280
- ]
281
- };
195
+ return {
196
+ type: 'element',
197
+ tagName: 'a',
198
+ properties: {
199
+ class: 'header-anchor',
200
+ ariaHidden: 'true',
201
+ href: `#${node.properties.id}`
202
+ },
203
+ children: [
204
+ {
205
+ type: 'text',
206
+ value: '#'
207
+ }
208
+ ]
209
+ };
282
210
  }
283
-
284
- // src/node/mdx/remarkPlugins/builtin.ts
285
- import path4 from "path";
286
- var remarkBuiltin = ({
287
- globalComponents
288
- }) => {
289
- return (tree) => {
290
- const demos = globalComponents.map((componentPath) => {
291
- const filename = path4.parse(componentPath).name;
292
- const componentName = filename[0].toUpperCase() + filename.slice(1);
293
- return getASTNodeImport(componentName, componentPath);
211
+ const getASTNodeImport = (name, from)=>({
212
+ type: 'mdxjsEsm',
213
+ value: `import ${name} from ${JSON.stringify(from)}`,
214
+ data: {
215
+ estree: {
216
+ type: 'Program',
217
+ sourceType: 'module',
218
+ body: [
219
+ {
220
+ type: 'ImportDeclaration',
221
+ specifiers: [
222
+ {
223
+ type: 'ImportDefaultSpecifier',
224
+ local: {
225
+ type: 'Identifier',
226
+ name
227
+ }
228
+ }
229
+ ],
230
+ source: {
231
+ type: 'Literal',
232
+ value: from,
233
+ raw: `${JSON.stringify(from)}`
234
+ }
235
+ }
236
+ ]
237
+ }
238
+ }
294
239
  });
295
- tree.children.unshift(...demos);
296
- };
297
- };
298
-
299
- // src/node/mdx/remarkPlugins/checkDeadLink.ts
300
- import path5 from "path";
301
- import { cleanUrl, isProduction } from "@rspress/shared";
302
- import { logger } from "@rspress/shared/logger";
303
- import { visit as visit3 } from "unist-util-visit";
304
- var IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
240
+ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
241
+ const demos = globalComponents.map((componentPath)=>{
242
+ const filename = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].parse(componentPath).name;
243
+ const componentName = filename[0].toUpperCase() + filename.slice(1);
244
+ return getASTNodeImport(componentName, componentPath);
245
+ });
246
+ tree.children.unshift(...demos);
247
+ };
248
+ const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
305
249
  function checkLinks(links, filepath, root, routeService) {
306
- const errorInfos = [];
307
- links.filter((link) => !IGNORE_REGEXP.test(link)).map((link) => normalizePath(link)).forEach((link) => {
308
- const relativePath = path5.relative(root, filepath);
309
- if (!routeService.isExistRoute(cleanUrl(link))) {
310
- errorInfos.push(
311
- `Internal link to ${link} is dead, check it in ${relativePath}`
312
- );
313
- }
314
- });
315
- if (errorInfos.length > 0) {
316
- errorInfos?.forEach((err) => {
317
- logger.error(err);
250
+ const errorInfos = [];
251
+ links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
252
+ const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, filepath);
253
+ if (!routeService.isExistRoute((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.cleanUrl)(link))) errorInfos.push(`Internal link to ${link} is dead, check it in ${relativePath}`);
318
254
  });
319
- if (isProduction()) {
320
- throw new Error("Dead link found");
255
+ if (errorInfos.length > 0) {
256
+ null == errorInfos || errorInfos.forEach((err)=>{
257
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(err);
258
+ });
259
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) throw new Error('Dead link found');
321
260
  }
322
- }
323
261
  }
324
- var remarkCheckDeadLinks = (checkLink) => {
325
- const { root, routeService } = checkLink;
326
- return (tree, vfile) => {
327
- const internalLinks = /* @__PURE__ */ new Set();
328
- visit3(tree, "link", (node) => {
329
- const { url } = node;
330
- if (!url) {
331
- return;
332
- }
333
- if (internalLinks.has(url)) {
334
- return;
335
- }
336
- if (!url.startsWith("http") && !url.startsWith("https")) {
337
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(
338
- // fix: windows path
339
- url.split(path5.sep).join("/")?.split("#")[0]
340
- );
341
- internalLinks.add(normalizeUrl);
342
- }
343
- });
344
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
345
- };
262
+ const remarkCheckDeadLinks = (checkLink)=>{
263
+ const { root, routeService } = checkLink;
264
+ return (tree, vfile)=>{
265
+ const internalLinks = new Set();
266
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
267
+ const { url } = node;
268
+ if (!url) return;
269
+ if (internalLinks.has(url)) return;
270
+ if (!url.startsWith('http') && !url.startsWith('https')) {
271
+ var _url_split_join;
272
+ const { routePath: normalizeUrl } = routeService.normalizeRoutePath(null === (_url_split_join = url.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')) || void 0 === _url_split_join ? void 0 : _url_split_join.split('#')[0]);
273
+ internalLinks.add(normalizeUrl);
274
+ }
275
+ });
276
+ checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
277
+ };
346
278
  };
347
-
348
- // src/node/mdx/remarkPlugins/normalizeLink.ts
349
- import path6 from "path";
350
- import { isExternalUrl, normalizeHref, parseUrl, slash as slash2 } from "@rspress/shared";
351
- import { visit as visit4 } from "unist-util-visit";
352
- var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
353
- const images = [];
354
- visit4(
355
- tree,
356
- (node) => node.type === "link",
357
- (node) => {
358
- if (!node.url) {
359
- return;
360
- }
361
- if (node.url.startsWith("#")) {
362
- node.url = `#${node.url.slice(1)}`;
363
- return;
364
- }
365
- let { url, hash } = parseUrl(node.url);
366
- if (isExternalUrl(url)) {
367
- node.url = url + (hash ? `#${hash}` : "");
368
- return;
369
- }
370
- const extname = path6.extname(url);
371
- if (extname === ".md" || extname === ".mdx") {
372
- url = url.replace(extname, "");
373
- }
374
- const relativePath = path6.relative(root, file.path);
375
- if (url.startsWith(".")) {
376
- url = path6.posix.join(slash2(path6.dirname(relativePath)), url);
377
- }
378
- url = normalizeHref(url, cleanUrls);
379
- if (hash) {
380
- url += `#${hash}`;
381
- }
382
- node.url = path6.posix.join(base, url);
383
- }
384
- );
385
- const normalizeImageUrl = (imageUrl) => {
386
- if (isExternalUrl(imageUrl) || imageUrl.startsWith("/")) {
387
- return "";
388
- }
389
- return imageUrl;
390
- };
391
- const getMdxSrcAttribute = (tempVar) => {
392
- return {
393
- type: "mdxJsxAttribute",
394
- name: "src",
395
- value: {
396
- type: "mdxJsxAttributeValueExpression",
397
- value: tempVar,
398
- data: {
399
- estree: {
400
- type: "Program",
401
- sourceType: "module",
402
- body: [
403
- {
404
- type: "ExpressionStatement",
405
- expression: {
406
- type: "Identifier",
407
- name: tempVar
279
+ const remarkPluginNormalizeLink = ({ base, root, cleanUrls })=>(tree, file)=>{
280
+ const images = [];
281
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>'link' === node.type, (node)=>{
282
+ if (!node.url) return;
283
+ if (node.url.startsWith('#')) {
284
+ node.url = `#${node.url.slice(1)}`;
285
+ return;
286
+ }
287
+ let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(node.url);
288
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) {
289
+ node.url = url + (hash ? `#${hash}` : '');
290
+ return;
291
+ }
292
+ const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
293
+ if ('.md' === extname || '.mdx' === extname) url = url.replace(extname, '');
294
+ const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
295
+ if (url.startsWith('.')) url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(relativePath)), url);
296
+ url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
297
+ if (hash) url += `#${hash}`;
298
+ node.url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join(base, url);
299
+ });
300
+ const normalizeImageUrl = (imageUrl)=>{
301
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
302
+ return imageUrl;
303
+ };
304
+ const getMdxSrcAttribute = (tempVar)=>({
305
+ type: 'mdxJsxAttribute',
306
+ name: 'src',
307
+ value: {
308
+ type: 'mdxJsxAttributeValueExpression',
309
+ value: tempVar,
310
+ data: {
311
+ estree: {
312
+ type: 'Program',
313
+ sourceType: 'module',
314
+ body: [
315
+ {
316
+ type: 'ExpressionStatement',
317
+ expression: {
318
+ type: 'Identifier',
319
+ name: tempVar
320
+ }
321
+ }
322
+ ]
323
+ }
324
+ }
408
325
  }
409
- }
410
- ]
411
- }
412
- }
413
- }
326
+ });
327
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
328
+ const { url } = node;
329
+ if (!url) return;
330
+ const imagePath = normalizeImageUrl(url);
331
+ if (!imagePath) return;
332
+ const tempVariableName = `image${images.length}`;
333
+ Object.assign(node, {
334
+ type: 'mdxJsxFlowElement',
335
+ name: 'img',
336
+ children: [],
337
+ attributes: [
338
+ node.alt && {
339
+ type: 'mdxJsxAttribute',
340
+ name: 'alt',
341
+ value: node.alt
342
+ },
343
+ getMdxSrcAttribute(tempVariableName)
344
+ ].filter(Boolean)
345
+ });
346
+ images.push(getASTNodeImport(tempVariableName, imagePath));
347
+ });
348
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, [
349
+ 'mdxJsxFlowElement',
350
+ 'mdxJsxTextElement'
351
+ ], (node)=>{
352
+ if ('img' !== node.name) return;
353
+ const src = node.attributes.find((attr)=>'src' === attr.name);
354
+ if (!(null == src ? void 0 : src.value) || 'string' != typeof (null == src ? void 0 : src.value)) return;
355
+ const imagePath = normalizeImageUrl(src.value);
356
+ if (!imagePath) return;
357
+ const tempVariableName = `image${images.length}`;
358
+ Object.assign(src, getMdxSrcAttribute(tempVariableName));
359
+ images.push(getASTNodeImport(tempVariableName, imagePath));
360
+ });
361
+ tree.children.unshift(...images);
414
362
  };
415
- };
416
- visit4(tree, "image", (node) => {
417
- const { url } = node;
418
- if (!url) {
419
- return;
420
- }
421
- const imagePath = normalizeImageUrl(url);
422
- if (!imagePath) {
423
- return;
424
- }
425
- const tempVariableName = `image${images.length}`;
426
- Object.assign(node, {
427
- type: "mdxJsxFlowElement",
428
- name: "img",
429
- children: [],
430
- attributes: [
431
- node.alt && {
432
- type: "mdxJsxAttribute",
433
- name: "alt",
434
- value: node.alt
435
- },
436
- getMdxSrcAttribute(tempVariableName)
437
- ].filter(Boolean)
438
- });
439
- images.push(getASTNodeImport(tempVariableName, imagePath));
440
- });
441
- visit4(tree, ["mdxJsxFlowElement", "mdxJsxTextElement"], (node) => {
442
- if (node.name !== "img") {
443
- return;
444
- }
445
- const src = node.attributes.find((attr) => attr.name === "src");
446
- if (!src?.value || typeof src?.value !== "string") {
447
- return;
448
- }
449
- const imagePath = normalizeImageUrl(src.value);
450
- if (!imagePath) {
451
- return;
452
- }
453
- const tempVariableName = `image${images.length}`;
454
- Object.assign(src, getMdxSrcAttribute(tempVariableName));
455
- images.push(getASTNodeImport(tempVariableName, imagePath));
456
- });
457
- tree.children.unshift(...images);
458
- };
459
-
460
- // src/node/mdx/remarkPlugins/toc.ts
461
- import Slugger from "github-slugger";
462
- import { visitChildren } from "unist-util-visit-children";
463
- var parseToc = (tree) => {
464
- let title = "";
465
- const toc = [];
466
- const slugger = new Slugger();
467
- visitChildren((node) => {
468
- if (node.type !== "heading" || !node.depth || !node.children) {
469
- return;
470
- }
471
- if (node.depth >= 1 && node.depth < 5) {
472
- let customId = "";
473
- const text = node.children.map((child) => {
474
- if (child.type === "link") {
475
- return child.children?.map((item) => item.value).join("");
476
- }
477
- if (child.type === "strong") {
478
- return `**${child.children?.map((item) => item.value).join("")}**`;
479
- }
480
- if (child.type === "text") {
481
- const [textPart, idPart] = extractTextAndId(child.value);
482
- customId = idPart;
483
- return textPart;
484
- }
485
- if (child.type === "inlineCode") {
486
- return `\`${child.value}\``;
363
+ const parseToc = (tree)=>{
364
+ let title = '';
365
+ const toc = [];
366
+ const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
367
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__.visitChildren)((node)=>{
368
+ if ('heading' !== node.type || !node.depth || !node.children) return;
369
+ if (node.depth >= 1 && node.depth < 5) {
370
+ let customId = '';
371
+ const text = node.children.map((child)=>{
372
+ if ('link' === child.type) {
373
+ var _child_children;
374
+ return null === (_child_children = child.children) || void 0 === _child_children ? void 0 : _child_children.map((item)=>item.value).join('');
375
+ }
376
+ if ('strong' === child.type) {
377
+ var _child_children1;
378
+ return `**${null === (_child_children1 = child.children) || void 0 === _child_children1 ? void 0 : _child_children1.map((item)=>item.value).join('')}**`;
379
+ }
380
+ if ('emphasis' === child.type) {
381
+ var _child_children2;
382
+ return `*${null === (_child_children2 = child.children) || void 0 === _child_children2 ? void 0 : _child_children2.map((item)=>item.value).join('')}*`;
383
+ }
384
+ if ('delete' === child.type) {
385
+ var _child_children3;
386
+ return `~~${null === (_child_children3 = child.children) || void 0 === _child_children3 ? void 0 : _child_children3.map((item)=>item.value).join('')}~~`;
387
+ }
388
+ if ('text' === child.type) {
389
+ const [textPart, idPart] = extractTextAndId(child.value);
390
+ customId = idPart;
391
+ return textPart;
392
+ }
393
+ if ('inlineCode' === child.type) return `\`${child.value}\``;
394
+ return '';
395
+ }).join('');
396
+ if (1 === node.depth) {
397
+ if (!title) title = text;
398
+ } else {
399
+ const id = customId ? customId : slugger.slug(text);
400
+ const { depth } = node;
401
+ toc.push({
402
+ id,
403
+ text,
404
+ depth
405
+ });
406
+ }
487
407
  }
488
- return "";
489
- }).join("");
490
- if (node.depth === 1) {
491
- if (!title)
492
- title = text;
493
- } else {
494
- const id = customId ? customId : slugger.slug(text);
495
- const { depth } = node;
496
- toc.push({ id, text, depth });
497
- }
498
- }
499
- })(tree);
500
- return {
501
- title,
502
- toc
503
- };
408
+ })(tree);
409
+ return {
410
+ title,
411
+ toc
412
+ };
504
413
  };
505
- var remarkPluginToc = function() {
506
- const data = this.data();
507
- return (tree) => {
508
- const { toc, title } = parseToc(tree);
509
- data.pageMeta.toc = toc;
510
- if (title) {
511
- data.pageMeta.title = title;
512
- }
513
- };
414
+ const remarkPluginToc = function() {
415
+ const data = this.data();
416
+ return (tree)=>{
417
+ const { toc, title } = parseToc(tree);
418
+ data.pageMeta.toc = toc;
419
+ if (title) data.pageMeta.title = title;
420
+ };
514
421
  };
515
-
516
- // src/node/mdx/options.ts
517
422
  async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
518
- const cleanUrls = Boolean(config?.route?.cleanUrls);
519
- const {
520
- remarkPlugins: remarkPluginsFromConfig = [],
521
- rehypePlugins: rehypePluginsFromConfig = [],
522
- globalComponents: globalComponentsFromConfig = []
523
- } = config?.markdown || {};
524
- const rspressPlugins = pluginDriver.getPlugins();
525
- const remarkPluginsFromPlugins = rspressPlugins.flatMap(
526
- (plugin) => plugin.markdown?.remarkPlugins || []
527
- );
528
- const rehypePluginsFromPlugins = rspressPlugins.flatMap(
529
- (plugin) => plugin.markdown?.rehypePlugins || []
530
- );
531
- const globalComponents = [
532
- ...rspressPlugins.flatMap(
533
- (plugin) => plugin.markdown?.globalComponents || []
534
- ),
535
- ...globalComponentsFromConfig
536
- ];
537
- const defaultLang = config?.lang || "";
538
- return {
539
- providerImportSource: "@mdx-js/react",
540
- format: path7.extname(filepath).slice(1),
541
- remarkPlugins: [
542
- remarkGFM,
543
- remarkPluginToc,
544
- [
545
- remarkPluginNormalizeLink,
546
- {
547
- base: config?.base || "",
548
- cleanUrls,
549
- defaultLang,
550
- root: docDirectory
551
- }
552
- ],
553
- checkDeadLinks && [
554
- remarkCheckDeadLinks,
555
- {
556
- root: docDirectory,
557
- base: config?.base || "",
558
- routeService
559
- }
560
- ],
561
- globalComponents.length && [
562
- remarkBuiltin,
563
- {
564
- globalComponents
565
- }
566
- ],
567
- ...remarkPluginsFromConfig,
568
- ...remarkPluginsFromPlugins
569
- ].filter(Boolean),
570
- rehypePlugins: [
571
- rehypeHeaderAnchor,
572
- rehypePluginCodeMeta,
573
- [
574
- rehypePluginExternalLinks,
575
- {
576
- target: "_blank",
577
- rel: "noopener noreferrer"
578
- }
579
- ],
580
- ...rehypePluginsFromConfig,
581
- ...rehypePluginsFromPlugins
582
- ]
583
- };
423
+ var _config_route;
424
+ const cleanUrls = Boolean(null == config ? void 0 : null === (_config_route = config.route) || void 0 === _config_route ? void 0 : _config_route.cleanUrls);
425
+ const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [] } = (null == config ? void 0 : config.markdown) || {};
426
+ const rspressPlugins = pluginDriver.getPlugins();
427
+ const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>{
428
+ var _plugin_markdown;
429
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.remarkPlugins) || [];
430
+ });
431
+ const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>{
432
+ var _plugin_markdown;
433
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.rehypePlugins) || [];
434
+ });
435
+ const globalComponents = [
436
+ ...rspressPlugins.flatMap((plugin)=>{
437
+ var _plugin_markdown;
438
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.globalComponents) || [];
439
+ }),
440
+ ...globalComponentsFromConfig
441
+ ];
442
+ const defaultLang = (null == config ? void 0 : config.lang) || '';
443
+ return {
444
+ providerImportSource: '@mdx-js/react',
445
+ format: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(filepath).slice(1),
446
+ remarkPlugins: [
447
+ __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__["default"],
448
+ remarkPluginToc,
449
+ [
450
+ remarkPluginNormalizeLink,
451
+ {
452
+ base: (null == config ? void 0 : config.base) || '',
453
+ cleanUrls,
454
+ defaultLang,
455
+ root: docDirectory
456
+ }
457
+ ],
458
+ checkDeadLinks && [
459
+ remarkCheckDeadLinks,
460
+ {
461
+ root: docDirectory,
462
+ base: (null == config ? void 0 : config.base) || '',
463
+ routeService
464
+ }
465
+ ],
466
+ globalComponents.length && [
467
+ remarkBuiltin,
468
+ {
469
+ globalComponents
470
+ }
471
+ ],
472
+ ...remarkPluginsFromConfig,
473
+ ...remarkPluginsFromPlugins
474
+ ].filter(Boolean),
475
+ rehypePlugins: [
476
+ rehypeHeaderAnchor,
477
+ rehypePluginCodeMeta,
478
+ [
479
+ __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__["default"],
480
+ {
481
+ target: '_blank',
482
+ rel: 'noopener noreferrer'
483
+ }
484
+ ],
485
+ ...rehypePluginsFromConfig,
486
+ ...rehypePluginsFromPlugins
487
+ ]
488
+ };
584
489
  }
585
-
586
- // src/node/mdx/loader.ts
587
490
  async function updateSiteDataRuntimeModule(modulePath, pageMeta) {
588
- const siteDataModulePath = path8.join(
589
- TEMP_DIR,
590
- "runtime",
591
- `${"virtual-site-data" /* SiteData */}.mjs`
592
- );
593
- const { default: siteData } = await import(pathToFileURL(siteDataModulePath).href);
594
- await fs2.writeFile(
595
- siteDataModulePath,
596
- `export default ${JSON.stringify(
597
- {
491
+ const siteDataModulePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(TEMP_DIR, 'runtime', `${runtimeModule_RuntimeModuleID.SiteData}.mjs`);
492
+ const { default: siteData } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(siteDataModulePath).href);
493
+ await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(siteDataModulePath, `export default ${JSON.stringify({
598
494
  ...siteData,
599
495
  timestamp: Date.now().toString(),
600
- pages: siteData.pages.map(
601
- (page) => (
602
- // Update page meta if the page is updated
603
- page._filepath === modulePath ? { ...page, ...pageMeta } : page
604
- )
605
- )
606
- },
607
- null,
608
- 2
609
- )}`
610
- );
496
+ pages: siteData.pages.map((page)=>page._filepath === modulePath ? {
497
+ ...page,
498
+ ...pageMeta
499
+ } : page)
500
+ }, null, 2)}`);
611
501
  }
612
502
  function createCheckPageMetaUpdateFn() {
613
- const pageMetaMap = /* @__PURE__ */ new Map();
614
- return (modulePath, pageMeta) => {
615
- const prevMeta = pageMetaMap.get(modulePath);
616
- const deserializedMeta = JSON.stringify(pageMeta);
617
- pageMetaMap.set(modulePath, deserializedMeta);
618
- if (!prevMeta) {
619
- return;
620
- }
621
- if (prevMeta !== deserializedMeta) {
622
- setTimeout(async () => {
623
- logger2.info("Page metadata changed, page reloading...");
624
- await updateSiteDataRuntimeModule(modulePath, pageMeta);
625
- });
626
- }
627
- };
503
+ const pageMetaMap = new Map();
504
+ return (modulePath, pageMeta)=>{
505
+ const prevMeta = pageMetaMap.get(modulePath);
506
+ const deserializedMeta = JSON.stringify(pageMeta);
507
+ pageMetaMap.set(modulePath, deserializedMeta);
508
+ if (!prevMeta) return;
509
+ if (prevMeta !== deserializedMeta) setTimeout(async ()=>{
510
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Page metadata changed, page reloading...');
511
+ await updateSiteDataRuntimeModule(modulePath, pageMeta);
512
+ });
513
+ };
628
514
  }
629
- var checkPageMetaUpdate = createCheckPageMetaUpdateFn();
515
+ const checkPageMetaUpdate = createCheckPageMetaUpdateFn();
630
516
  async function mdxLoader(source) {
631
- this.cacheable(true);
632
- const callback = this.async();
633
- const options = this.getOptions();
634
- const filepath = this.resourcePath;
635
- const { alias } = this._compiler.options.resolve;
636
- const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
637
- const { frontmatter, content } = loadFrontMatter(
638
- source,
639
- filepath,
640
- docDirectory,
641
- true
642
- );
643
- const { flattenContent, deps } = await flattenMdxContent(
644
- content,
645
- filepath,
646
- alias
647
- );
648
- deps.forEach((dep) => this.addDependency(dep));
649
- const replacedContent = applyReplaceRules(
650
- flattenContent,
651
- config.replaceRules
652
- );
653
- const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
654
- let enableMdxRs;
655
- const mdxRs = config?.markdown?.mdxRs ?? true;
656
- if (typeof mdxRs === "object") {
657
- enableMdxRs = typeof mdxRs?.include === "function" ? mdxRs.include(filepath) : true;
658
- } else {
659
- enableMdxRs = mdxRs;
660
- }
661
- try {
662
- let compileResult;
663
- let pageMeta = { title: "", toc: [] };
664
- if (!enableMdxRs) {
665
- const mdxOptions = await createMDXOptions(
666
- docDirectory,
667
- config,
668
- checkDeadLinks,
669
- routeService,
670
- filepath,
671
- pluginDriver
672
- );
673
- const compiler = createProcessor2(mdxOptions);
674
- compiler.data("pageMeta", { toc: [], title: "" });
675
- const vFile = await compiler.process({
676
- value: preprocessedContent,
677
- path: filepath
678
- });
679
- compileResult = String(vFile);
680
- const compilationMeta = compiler.data("pageMeta");
681
- pageMeta = {
682
- ...compilationMeta,
683
- title: frontmatter.title || compilationMeta.title || "",
684
- headingTitle: compilationMeta.title,
685
- frontmatter
686
- };
687
- } else {
688
- const { compile } = __require("@rspress/mdx-rs");
689
- const { toc, links, title, code } = await compile({
690
- value: preprocessedContent,
691
- filepath,
692
- root: docDirectory,
693
- development: process.env.NODE_ENV !== "production"
694
- });
695
- compileResult = code;
696
- pageMeta = {
697
- toc,
698
- title: frontmatter.title || title || "",
699
- headingTitle: title,
700
- frontmatter
701
- };
702
- if (checkDeadLinks) {
703
- checkLinks(links, filepath, docDirectory, routeService);
704
- }
705
- }
706
- if (!isProduction2()) {
707
- checkPageMetaUpdate(filepath, pageMeta);
708
- }
709
- const result = `const frontmatter = ${JSON.stringify(frontmatter)};
517
+ var _config_markdown;
518
+ this.cacheable(true);
519
+ const callback = this.async();
520
+ const options = this.getOptions();
521
+ const filepath = this.resourcePath;
522
+ const { alias } = this._compiler.options.resolve;
523
+ const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
524
+ const { frontmatter, content } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(source, filepath, docDirectory, true);
525
+ const { flattenContent, deps } = await flattenMdxContent(content, filepath, alias);
526
+ deps.forEach((dep)=>this.addDependency(dep));
527
+ const replacedContent = applyReplaceRules(flattenContent, config.replaceRules);
528
+ const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
529
+ let enableMdxRs;
530
+ const mdxRs = (null == config ? void 0 : null === (_config_markdown = config.markdown) || void 0 === _config_markdown ? void 0 : _config_markdown.mdxRs) ?? true;
531
+ enableMdxRs = 'object' == typeof mdxRs ? 'function' != typeof (null == mdxRs ? void 0 : mdxRs.include) || mdxRs.include(filepath) : mdxRs;
532
+ try {
533
+ let compileResult;
534
+ let pageMeta = {
535
+ title: '',
536
+ toc: []
537
+ };
538
+ if (enableMdxRs) {
539
+ const { compile } = await import("@rspress/mdx-rs");
540
+ const { toc, links, title, code } = await compile({
541
+ value: preprocessedContent,
542
+ filepath,
543
+ root: docDirectory,
544
+ development: 'production' !== process.env.NODE_ENV
545
+ });
546
+ compileResult = code;
547
+ pageMeta = {
548
+ toc,
549
+ title: frontmatter.title || title || '',
550
+ headingTitle: title,
551
+ frontmatter
552
+ };
553
+ if (checkDeadLinks) checkLinks(links, filepath, docDirectory, routeService);
554
+ } else {
555
+ const mdxOptions = await createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver);
556
+ const compiler = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)(mdxOptions);
557
+ compiler.data('pageMeta', {
558
+ toc: [],
559
+ title: ''
560
+ });
561
+ const vFile = await compiler.process({
562
+ value: preprocessedContent,
563
+ path: filepath
564
+ });
565
+ compileResult = String(vFile);
566
+ const compilationMeta = compiler.data('pageMeta');
567
+ pageMeta = {
568
+ ...compilationMeta,
569
+ title: frontmatter.title || compilationMeta.title || '',
570
+ headingTitle: compilationMeta.title,
571
+ frontmatter
572
+ };
573
+ }
574
+ if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) checkPageMetaUpdate(filepath, pageMeta);
575
+ const result = `const frontmatter = ${JSON.stringify(frontmatter)};
710
576
  ${compileResult}
711
577
  MDXContent.__RSPRESS_PAGE_META = {};
712
578
 
713
- MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(
714
- normalizePath(path8.relative(docDirectory, filepath))
715
- )}"] = ${JSON.stringify(pageMeta)};
579
+ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
716
580
  `;
717
- callback(null, result);
718
- } catch (e) {
719
- logger2.error(`MDX compile error: ${e.message} in ${filepath}`);
720
- callback({ message: e.message, name: `${filepath} compile error` });
721
- }
581
+ callback(null, result);
582
+ } catch (e) {
583
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
584
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
585
+ callback({
586
+ message: e.message,
587
+ name: `${filepath} compile error`
588
+ });
589
+ }
722
590
  }
723
- export {
724
- createCheckPageMetaUpdateFn,
725
- mdxLoader as default,
726
- updateSiteDataRuntimeModule
727
- };
728
-
729
- //# sourceMappingURL=loader.js.map
591
+ export { createCheckPageMetaUpdateFn, mdxLoader as default, updateSiteDataRuntimeModule };