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

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.
@@ -0,0 +1,777 @@
1
+ import node_path from "node:path";
2
+ import { createProcessor, nodeTypes } from "@mdx-js/mdx";
3
+ import { extractTextAndId, getNodeAttribute, loadFrontMatter } from "@rspress/shared/node-utils";
4
+ import node_os from "node:os";
5
+ import rehype from "@shikijs/rehype";
6
+ import rehype_external_links from "rehype-external-links";
7
+ import rehype_raw from "rehype-raw";
8
+ import remark_gfm from "remark-gfm";
9
+ import { visit } from "unist-util-visit";
10
+ import github_slugger from "github-slugger";
11
+ import { headingRank } from "hast-util-heading-rank";
12
+ import { createCssVariablesTheme } from "shiki";
13
+ import { readFile as promises_readFile } from "node:fs/promises";
14
+ import { logger as logger_logger } from "@rspress/shared/logger";
15
+ import picocolors_0 from "picocolors";
16
+ import { addLeadingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, withBase } from "@rspress/shared";
17
+ import { visitChildren } from "unist-util-visit-children";
18
+ function applyReplaceRules(code = '', replaceRules = []) {
19
+ let result = code;
20
+ for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
21
+ return result;
22
+ }
23
+ function escapeMarkdownHeadingIds(content) {
24
+ const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
25
+ return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
26
+ }
27
+ const isWindows = 'win32' === node_os.platform();
28
+ function slash(p) {
29
+ return p.replace(/\\/g, '/');
30
+ }
31
+ function normalizePath(id) {
32
+ return node_path.posix.normalize(isWindows ? slash(id) : id);
33
+ }
34
+ const rehypeCodeMeta = ()=>(tree)=>{
35
+ visit(tree, 'element', (node)=>{
36
+ if ('pre' === node.tagName && node.children[0]?.type === 'element' && 'code' === node.children[0].tagName) {
37
+ const codeNode = node.children[0];
38
+ codeNode.properties.metastring = codeNode.data?.meta;
39
+ }
40
+ });
41
+ };
42
+ const rehypeHeaderAnchor = ()=>{
43
+ const slugger = new github_slugger();
44
+ return (tree)=>{
45
+ visit(tree, 'element', (node)=>{
46
+ if (!headingRank(node)) return;
47
+ if (!node.properties?.id) {
48
+ const [text, customId] = collectHeaderText(node);
49
+ node.properties ??= {};
50
+ node.properties.id = customId || slugger.slug(text.trim());
51
+ }
52
+ node.children.unshift(create(node));
53
+ });
54
+ };
55
+ };
56
+ const collectHeaderText = (node)=>{
57
+ let text = '';
58
+ let id = '';
59
+ node.children.forEach((child)=>{
60
+ if ('text' === child.type) {
61
+ const [textPart, idPart] = extractTextAndId(child.value);
62
+ child.value = textPart;
63
+ text += textPart;
64
+ id = idPart;
65
+ } else if ('element' === child.type) child.children.forEach((c)=>{
66
+ if ('text' === c.type) text += c.value;
67
+ });
68
+ });
69
+ return [
70
+ text,
71
+ id
72
+ ];
73
+ };
74
+ function create(node) {
75
+ return {
76
+ type: 'element',
77
+ tagName: 'a',
78
+ properties: {
79
+ class: 'header-anchor',
80
+ ariaHidden: 'true',
81
+ href: `#${node.properties.id}`
82
+ },
83
+ children: [
84
+ {
85
+ type: 'text',
86
+ value: '#'
87
+ }
88
+ ]
89
+ };
90
+ }
91
+ const SHIKI_TRANSFORMER_LINE_NUMBER = 'shiki-transformer:line-number';
92
+ function transformerLineNumber(options = {}) {
93
+ const { classActiveLine = 'line-number', classActivePre = 'has-line-number' } = options;
94
+ return {
95
+ name: SHIKI_TRANSFORMER_LINE_NUMBER,
96
+ pre (pre) {
97
+ return this.addClassToHast(pre, classActivePre);
98
+ },
99
+ line (node) {
100
+ this.addClassToHast(node, classActiveLine);
101
+ }
102
+ };
103
+ }
104
+ const SHIKI_TRANSFORMER_ADD_TITLE = 'shiki-transformer:add-title';
105
+ function parseTitleFromMeta(meta) {
106
+ if (!meta) return '';
107
+ const kvList = meta.split(' ').filter(Boolean);
108
+ for (const item of kvList){
109
+ const [k, v = ''] = item.split('=').filter(Boolean);
110
+ if ('title' === k && v.length > 0) return v.replace(/["'`]/g, '');
111
+ }
112
+ return '';
113
+ }
114
+ function transformerAddTitle() {
115
+ return {
116
+ name: SHIKI_TRANSFORMER_ADD_TITLE,
117
+ pre (pre) {
118
+ const title = parseTitleFromMeta(this.options.meta?.__raw);
119
+ if (title.length > 0) pre.properties = {
120
+ ...pre.properties,
121
+ title
122
+ };
123
+ return pre;
124
+ }
125
+ };
126
+ }
127
+ const cssVariablesTheme = createCssVariablesTheme({
128
+ name: 'css-variables',
129
+ variablePrefix: '--shiki-',
130
+ variableDefaults: {},
131
+ fontStyle: true
132
+ });
133
+ function createRehypeShikiOptions(showLineNumbers, options) {
134
+ const { transformers = [], ...restOptions } = options || {};
135
+ const newTransformers = [
136
+ transformerAddTitle(),
137
+ ...transformers
138
+ ];
139
+ if (showLineNumbers && !newTransformers.some((transformerItem)=>transformerItem.name === SHIKI_TRANSFORMER_LINE_NUMBER)) newTransformers.push(transformerLineNumber());
140
+ return {
141
+ theme: cssVariablesTheme,
142
+ defaultLanguage: 'txt',
143
+ lazy: true,
144
+ langs: [
145
+ 'tsx',
146
+ 'ts',
147
+ 'js'
148
+ ],
149
+ ...restOptions,
150
+ addLanguageClass: true,
151
+ transformers: newTransformers
152
+ };
153
+ }
154
+ const getASTNodeImport = (name, from)=>({
155
+ type: 'mdxjsEsm',
156
+ value: `import ${name} from ${JSON.stringify(from)}`,
157
+ data: {
158
+ estree: {
159
+ type: 'Program',
160
+ sourceType: 'module',
161
+ body: [
162
+ {
163
+ type: 'ImportDeclaration',
164
+ specifiers: [
165
+ {
166
+ type: 'ImportDefaultSpecifier',
167
+ local: {
168
+ type: 'Identifier',
169
+ name
170
+ }
171
+ }
172
+ ],
173
+ source: {
174
+ type: 'Literal',
175
+ value: from,
176
+ raw: `${JSON.stringify(from)}`
177
+ }
178
+ }
179
+ ]
180
+ }
181
+ }
182
+ });
183
+ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
184
+ const demos = globalComponents.map((componentPath)=>{
185
+ const filename = node_path.parse(componentPath).name;
186
+ const componentName = filename[0].toUpperCase() + filename.slice(1);
187
+ return getASTNodeImport(componentName, componentPath);
188
+ });
189
+ tree.children.unshift(...demos);
190
+ };
191
+ const DIRECTIVE_TYPES = [
192
+ 'tip',
193
+ 'note',
194
+ 'warning',
195
+ 'caution',
196
+ 'danger',
197
+ 'info',
198
+ 'details'
199
+ ];
200
+ const REGEX_BEGIN = /^\s*:::\s*(\w+)\s*(.*)?/;
201
+ const REGEX_END = /\s*:::$/;
202
+ const REGEX_GH_BEGIN = /^\s*\s*\[!(\w+)\]\s*(.*)?/;
203
+ const TITLE_REGEX_IN_MD = /{\s*title=["']?(.+)}\s*/;
204
+ const TITLE_REGEX_IN_MDX = /\s*title=["']?(.+)\s*/;
205
+ const trimTailingQuote = (str)=>str.replace(/['"]$/g, '');
206
+ const parseTitle = (rawTitle = '', isMDX = false)=>{
207
+ const matched = rawTitle?.match(isMDX ? TITLE_REGEX_IN_MDX : TITLE_REGEX_IN_MD);
208
+ return trimTailingQuote(matched?.[1] || rawTitle);
209
+ };
210
+ const createContainer = (type, title, children)=>{
211
+ const isDetails = 'details' === type;
212
+ const rootHName = isDetails ? 'details' : 'div';
213
+ const titleHName = isDetails ? 'summary' : 'div';
214
+ return {
215
+ type: 'containerDirective',
216
+ name: type,
217
+ data: {
218
+ hName: rootHName,
219
+ hProperties: {
220
+ class: `rspress-directive ${type}`
221
+ }
222
+ },
223
+ children: [
224
+ {
225
+ type: 'paragraph',
226
+ data: {
227
+ hName: titleHName,
228
+ hProperties: {
229
+ class: 'rspress-directive-title'
230
+ }
231
+ },
232
+ children: [
233
+ {
234
+ type: 'text',
235
+ value: title || type.toUpperCase()
236
+ }
237
+ ]
238
+ },
239
+ {
240
+ type: 'paragraph',
241
+ data: {
242
+ hName: 'div',
243
+ hProperties: {
244
+ class: 'rspress-directive-content'
245
+ }
246
+ },
247
+ children: children
248
+ }
249
+ ]
250
+ };
251
+ };
252
+ function transformer(tree) {
253
+ let i = 0;
254
+ try {
255
+ while(i < tree.children.length){
256
+ const node = tree.children[i];
257
+ if ('children' in node) transformer(node);
258
+ if ('containerDirective' === node.type) {
259
+ const type = node.name;
260
+ if (DIRECTIVE_TYPES.includes(type)) tree.children.splice(i, 1, createContainer(type, node.attributes?.title ?? type.toUpperCase(), node.children));
261
+ } else if ('blockquote' === node.type && node.children[0]?.type === 'paragraph' && node.children[0].children?.[0] && 'value' in node.children[0].children[0]) {
262
+ const initiatorTag = node.children[0].children[0].value;
263
+ const match = initiatorTag.match(REGEX_GH_BEGIN);
264
+ if (match) {
265
+ const [, type] = match;
266
+ if (!DIRECTIVE_TYPES.includes(type.toLowerCase())) {
267
+ i++;
268
+ continue;
269
+ }
270
+ if (1 === node.children.length && 'paragraph' === node.children[0].type) node.children[0].children[0].value = match[2] ?? '';
271
+ const newChild = createContainer(type.toLowerCase(), type.toUpperCase(), 0 === node.children.slice(1).length ? node.children.slice(0) : node.children.slice(1));
272
+ tree.children.splice(i, 1, newChild);
273
+ }
274
+ }
275
+ if ('paragraph' !== node.type || 'text' !== node.children[0].type) {
276
+ i++;
277
+ continue;
278
+ }
279
+ const firstTextNode = node.children[0];
280
+ const text = firstTextNode.value;
281
+ const metaText = text.split('\n')[0];
282
+ const content = text.slice(metaText.length);
283
+ const match = metaText.match(REGEX_BEGIN);
284
+ if (!match) {
285
+ i++;
286
+ continue;
287
+ }
288
+ const [, type, rawTitle] = match;
289
+ let title = parseTitle(rawTitle);
290
+ const titleExpressionNode = node.children[1] && 'mdxTextExpression' === node.children[1].type ? node.children[1] : null;
291
+ if (titleExpressionNode) {
292
+ title = parseTitle(titleExpressionNode.value, true);
293
+ node.children.splice(1, 1);
294
+ }
295
+ if (!DIRECTIVE_TYPES.includes(type)) {
296
+ i++;
297
+ continue;
298
+ }
299
+ const wrappedChildren = [];
300
+ if (content?.endsWith(':::')) {
301
+ wrappedChildren.push({
302
+ type: 'paragraph',
303
+ children: [
304
+ {
305
+ type: 'text',
306
+ value: content.replace(REGEX_END, '')
307
+ }
308
+ ]
309
+ });
310
+ const newChild = createContainer(type, title, wrappedChildren);
311
+ tree.children.splice(i, 1, newChild);
312
+ } else {
313
+ const paragraphChild = {
314
+ type: 'paragraph',
315
+ children: []
316
+ };
317
+ wrappedChildren.push(paragraphChild);
318
+ if (content.length) paragraphChild.children.push({
319
+ type: 'text',
320
+ value: content
321
+ });
322
+ paragraphChild.children.push(...node.children.slice(1, -1));
323
+ if (0 === paragraphChild.children.length) wrappedChildren.pop();
324
+ const lastChildInNode = node.children[node.children.length - 1];
325
+ if ('text' === lastChildInNode.type && REGEX_END.test(lastChildInNode.value)) {
326
+ const lastChildInNodeText = lastChildInNode.value;
327
+ const matchedEndContent = lastChildInNodeText.slice(0, -3).trimEnd();
328
+ if (wrappedChildren.length) wrappedChildren[0].children.push({
329
+ type: 'text',
330
+ value: matchedEndContent
331
+ });
332
+ else if (matchedEndContent) wrappedChildren.push({
333
+ type: 'paragraph',
334
+ children: [
335
+ {
336
+ type: 'text',
337
+ value: matchedEndContent
338
+ }
339
+ ]
340
+ });
341
+ const newChild = createContainer(type, title, wrappedChildren);
342
+ tree.children.splice(i, 1, newChild);
343
+ i++;
344
+ continue;
345
+ }
346
+ if (lastChildInNode !== firstTextNode && wrappedChildren.length) wrappedChildren[0].children.push(lastChildInNode);
347
+ let j = i + 1;
348
+ while(j < tree.children.length){
349
+ const currentParagraph = tree.children[j];
350
+ if ('paragraph' !== currentParagraph.type) {
351
+ wrappedChildren.push(currentParagraph);
352
+ j++;
353
+ continue;
354
+ }
355
+ const lastChild = currentParagraph.children[currentParagraph.children.length - 1];
356
+ if (lastChild === firstTextNode || 'text' === lastChild.type && REGEX_END.test(lastChild.value)) {
357
+ const lastChildText = lastChild.value;
358
+ const matchedEndContent = lastChildText.slice(0, -3).trimEnd();
359
+ const filteredChildren = currentParagraph.children.filter((child)=>child !== firstTextNode && child !== lastChild);
360
+ if (matchedEndContent) wrappedChildren.push({
361
+ type: 'paragraph',
362
+ children: [
363
+ ...filteredChildren,
364
+ {
365
+ type: 'text',
366
+ value: matchedEndContent
367
+ }
368
+ ]
369
+ });
370
+ else wrappedChildren.push(...filteredChildren);
371
+ const newChild = createContainer(type, title, wrappedChildren);
372
+ tree.children.splice(i, j - i + 1, newChild);
373
+ break;
374
+ }
375
+ wrappedChildren.push({
376
+ ...currentParagraph,
377
+ children: currentParagraph.children.filter((child)=>child !== firstTextNode)
378
+ });
379
+ j++;
380
+ }
381
+ }
382
+ i++;
383
+ }
384
+ } catch (e) {
385
+ console.log(e);
386
+ throw e;
387
+ }
388
+ }
389
+ const remarkContainerSyntax = ()=>transformer;
390
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
391
+ function parseFileFromMeta(meta) {
392
+ if (!meta) return '';
393
+ const kvList = meta.split(' ').filter(Boolean);
394
+ for (const item of kvList){
395
+ const [k, v = ''] = item.split('=');
396
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
397
+ }
398
+ return '';
399
+ }
400
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
401
+ const promiseList = [];
402
+ visit(tree, 'code', (node)=>{
403
+ const { meta, value, lang } = node;
404
+ const file = parseFileFromMeta(meta ?? '');
405
+ if (!file) return;
406
+ const originalMetaForErrorInfo = picocolors_0.cyan(`\`\`\`${lang} ${meta}`);
407
+ if (file.startsWith('./') || file.startsWith('../')) {
408
+ const resolvedFilePath = node_path.join(node_path.dirname(filepath), file);
409
+ if ('' !== value.trim()) {
410
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
411
+
412
+ \`\`\`tsx file="./filename"
413
+ content
414
+ \`\`\`
415
+
416
+ this usage is not allowed, please use below:
417
+
418
+ \`\`\`tsx file="./filename"
419
+ \`\`\`
420
+ `);
421
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
422
+ }
423
+ const promise = promises_readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
424
+ addDependency?.(resolvedFilePath);
425
+ node.value = fileContent;
426
+ }).catch((e)=>{
427
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
428
+ logger_logger.error(message);
429
+ e.message = `${message}\n${e.message}`;
430
+ throw e;
431
+ });
432
+ promiseList.push(promise);
433
+ return;
434
+ }
435
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
436
+ Please use below:
437
+
438
+ \`\`\`tsx file="./filename"
439
+ \`\`\`
440
+ `);
441
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
442
+ });
443
+ await Promise.all(promiseList);
444
+ };
445
+ const normalizeImageUrl = (imageUrl)=>{
446
+ if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
447
+ return imageUrl;
448
+ };
449
+ const remarkImage = ()=>(tree, _file)=>{
450
+ const images = [];
451
+ const getMdxSrcAttribute = (tempVar)=>({
452
+ type: 'mdxJsxAttribute',
453
+ name: 'src',
454
+ value: {
455
+ type: 'mdxJsxAttributeValueExpression',
456
+ value: tempVar,
457
+ data: {
458
+ estree: {
459
+ type: 'Program',
460
+ sourceType: 'module',
461
+ body: [
462
+ {
463
+ type: 'ExpressionStatement',
464
+ expression: {
465
+ type: 'Identifier',
466
+ name: tempVar
467
+ }
468
+ }
469
+ ]
470
+ }
471
+ }
472
+ }
473
+ });
474
+ visit(tree, 'image', (node)=>{
475
+ const { alt, url } = node;
476
+ if (!url) return;
477
+ const imagePath = normalizeImageUrl(url);
478
+ if (!imagePath) return;
479
+ const tempVariableName = `image${images.length}`;
480
+ Object.assign(node, {
481
+ type: 'mdxJsxFlowElement',
482
+ name: 'img',
483
+ children: [],
484
+ attributes: [
485
+ alt && {
486
+ type: 'mdxJsxAttribute',
487
+ name: 'alt',
488
+ value: alt
489
+ },
490
+ getMdxSrcAttribute(tempVariableName)
491
+ ].filter(Boolean)
492
+ });
493
+ images.push(getASTNodeImport(tempVariableName, imagePath));
494
+ });
495
+ visit(tree, (node)=>{
496
+ if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
497
+ const srcAttr = getNodeAttribute(node, 'src', true);
498
+ if ('string' != typeof srcAttr?.value) return;
499
+ const imagePath = normalizeImageUrl(srcAttr.value);
500
+ if (!imagePath) return;
501
+ const tempVariableName = `image${images.length}`;
502
+ Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
503
+ images.push(getASTNodeImport(tempVariableName, imagePath));
504
+ });
505
+ tree.children.unshift(...images);
506
+ };
507
+ let isLogged = false;
508
+ function hintRelativeMarkdownLink() {
509
+ if (isLogged) return;
510
+ isLogged = true;
511
+ logger_logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
512
+ }
513
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, filePath) {
514
+ const errorInfos = [];
515
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
516
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
517
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
518
+ let possibleBreakingChange = false;
519
+ [
520
+ ...internalLinks.entries()
521
+ ].forEach(([nodeUrl, link])=>{
522
+ if (excludesUrl?.has(nodeUrl)) return;
523
+ if (excludesFn?.(nodeUrl)) return;
524
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
525
+ errorInfos.push([
526
+ nodeUrl,
527
+ link
528
+ ]);
529
+ });
530
+ if (errorInfos.length > 0) {
531
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
532
+ logger_logger.error(`Dead links found in ${picocolors_0.cyan(filePath)}:
533
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors_0.green(`"[..](${nodeUrl})"`)} ${picocolors_0.gray(link)}`).join('\n')}`);
534
+ if (isProduction()) throw new Error('Dead link found');
535
+ }
536
+ }
537
+ function looseMarkdownLink(url, routeService, filePath) {
538
+ if (!routeService.isInDocsDir(filePath)) return url;
539
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
540
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
541
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
542
+ if ('' === versionPart) {
543
+ if ('' === langPart) return addLeadingSlash(`${[
544
+ versionPartCurrFile,
545
+ langPartCurrFile
546
+ ].filter(Boolean).join('/')}${addLeadingSlash(pureRoute.replace(/^\/*/, ''))}`);
547
+ return addLeadingSlash(`${[
548
+ versionPartCurrFile,
549
+ langPart
550
+ ].filter(Boolean).join('/')}${addLeadingSlash(pureRoute.replace(/^\/*/, ''))}`);
551
+ }
552
+ return url;
553
+ }
554
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, deadLinks, __base) {
555
+ if (!nodeUrl) return '';
556
+ if (nodeUrl.startsWith('#')) return nodeUrl;
557
+ let { url, hash } = parseUrl(nodeUrl);
558
+ if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
559
+ if (!routeService) return nodeUrl;
560
+ if (url.startsWith('/')) {
561
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
562
+ const { routePath } = routeService.normalizeRoutePath(url);
563
+ url = routePath;
564
+ } else {
565
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
566
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
567
+ }
568
+ if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
569
+ else {
570
+ url = normalizeHref(url, false);
571
+ url = url.replace(/\.html$/, cleanUrls);
572
+ }
573
+ if (!routeService.isExistRoute(url)) {
574
+ deadLinks.set(nodeUrl, url);
575
+ return nodeUrl;
576
+ }
577
+ if (hash) url += `#${hash}`;
578
+ if (__base) url = withBase(url, __base);
579
+ return url;
580
+ }
581
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, __base })=>(tree, file)=>{
582
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
583
+ const deadLinks = new Map();
584
+ visit(tree, 'link', (node)=>{
585
+ const { url: nodeUrl } = node;
586
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
587
+ node.url = link;
588
+ });
589
+ visit(tree, 'definition', (node)=>{
590
+ const { url: nodeUrl } = node;
591
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, deadLinks, __base);
592
+ node.url = link;
593
+ });
594
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, deadLinks, file.path);
595
+ };
596
+ const parseToc = (tree)=>{
597
+ let title = '';
598
+ const toc = [];
599
+ const slugger = new github_slugger();
600
+ visitChildren((node)=>{
601
+ if ('heading' !== node.type || !node.depth || !node.children) return;
602
+ if (node.depth >= 1 && node.depth < 5) {
603
+ let customId = '';
604
+ const text = node.children.map((child)=>{
605
+ if ('link' === child.type) return child.children?.map((item)=>item.value).join('');
606
+ if ('strong' === child.type) return `**${child.children?.map((item)=>item.value).join('')}**`;
607
+ if ('emphasis' === child.type) return `*${child.children?.map((item)=>item.value).join('')}*`;
608
+ if ('delete' === child.type) return `~~${child.children?.map((item)=>item.value).join('')}~~`;
609
+ if ('text' === child.type) {
610
+ const [textPart, idPart] = extractTextAndId(child.value);
611
+ customId = idPart;
612
+ return textPart;
613
+ }
614
+ if ('inlineCode' === child.type) return `\`${child.value}\``;
615
+ return '';
616
+ }).join('');
617
+ if (1 === node.depth) {
618
+ if (!title) title = text;
619
+ } else {
620
+ const id = customId ? customId : slugger.slug(text.trim());
621
+ const { depth } = node;
622
+ toc.push({
623
+ id,
624
+ text,
625
+ depth
626
+ });
627
+ }
628
+ }
629
+ })(tree);
630
+ return {
631
+ title,
632
+ toc
633
+ };
634
+ };
635
+ const remarkToc = function() {
636
+ const data = this.data();
637
+ return (tree)=>{
638
+ const { toc, title } = parseToc(tree);
639
+ data.pageMeta.toc = toc;
640
+ if (title) data.pageMeta.title = title;
641
+ };
642
+ };
643
+ async function createMDXOptions(options) {
644
+ const { docDirectory, config, routeService, filepath, pluginDriver, addDependency } = options;
645
+ const remarkLinkOptions = config?.markdown?.link;
646
+ const format = node_path.extname(filepath).slice(1);
647
+ const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [], showLineNumbers = false, shiki } = config?.markdown || {};
648
+ const rspressPlugins = pluginDriver?.getPlugins() ?? [];
649
+ const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.remarkPlugins || []);
650
+ const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.rehypePlugins || []);
651
+ const globalComponents = [
652
+ ...rspressPlugins.flatMap((plugin)=>plugin.markdown?.globalComponents || []),
653
+ ...globalComponentsFromConfig
654
+ ];
655
+ return {
656
+ providerImportSource: '@mdx-js/react',
657
+ format,
658
+ remarkPlugins: [
659
+ remark_gfm,
660
+ remarkToc,
661
+ remarkContainerSyntax,
662
+ [
663
+ remarkFileCodeBlock,
664
+ {
665
+ filepath,
666
+ addDependency
667
+ }
668
+ ],
669
+ [
670
+ remarkLink,
671
+ {
672
+ cleanUrls: false,
673
+ root: docDirectory,
674
+ routeService,
675
+ remarkLinkOptions
676
+ }
677
+ ],
678
+ remarkImage,
679
+ globalComponents.length && [
680
+ remarkBuiltin,
681
+ {
682
+ globalComponents
683
+ }
684
+ ],
685
+ ...remarkPluginsFromConfig,
686
+ ...remarkPluginsFromPlugins
687
+ ].filter(Boolean),
688
+ rehypePlugins: [
689
+ rehypeHeaderAnchor,
690
+ ...'md' === format ? [
691
+ rehypeCodeMeta,
692
+ [
693
+ rehype_raw,
694
+ {
695
+ passThrough: nodeTypes
696
+ }
697
+ ]
698
+ ] : [],
699
+ [
700
+ rehype,
701
+ createRehypeShikiOptions(showLineNumbers, shiki)
702
+ ],
703
+ [
704
+ rehype_external_links,
705
+ {
706
+ target: '_blank',
707
+ rel: 'noopener noreferrer'
708
+ }
709
+ ],
710
+ ...rehypePluginsFromConfig,
711
+ ...rehypePluginsFromPlugins
712
+ ]
713
+ };
714
+ }
715
+ async function compile(options) {
716
+ const { source, filepath, docDirectory, config, routeService, pluginDriver, addDependency } = options;
717
+ const mdxOptions = await createMDXOptions({
718
+ config,
719
+ docDirectory,
720
+ filepath,
721
+ pluginDriver,
722
+ routeService,
723
+ addDependency
724
+ });
725
+ const { frontmatter, emptyLinesSource } = loadFrontMatter(source, filepath, docDirectory, true);
726
+ const { replaceRules } = config ?? {};
727
+ const replacedSource = applyReplaceRules(emptyLinesSource, replaceRules);
728
+ const preprocessedContent = escapeMarkdownHeadingIds(replacedSource);
729
+ try {
730
+ let pageMeta = {
731
+ title: '',
732
+ toc: [],
733
+ headingTitle: ''
734
+ };
735
+ const frontmatterTitle = extractTextAndId(frontmatter.title)[0];
736
+ const compiler = createProcessor(mdxOptions);
737
+ compiler.data('pageMeta', {
738
+ toc: [],
739
+ title: ''
740
+ });
741
+ const vFile = await compiler.process({
742
+ value: preprocessedContent,
743
+ path: filepath
744
+ });
745
+ const compileResult = String(vFile);
746
+ const compilationMeta = compiler.data('pageMeta');
747
+ const headingTitle = extractTextAndId(compilationMeta.title)[0];
748
+ pageMeta = {
749
+ ...compilationMeta,
750
+ title: frontmatterTitle || headingTitle,
751
+ headingTitle,
752
+ frontmatter
753
+ };
754
+ const result = `${compileResult}
755
+
756
+ MDXContent.__RSPRESS_PAGE_META = {};
757
+ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(node_path.relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
758
+ `;
759
+ return result;
760
+ } catch (e) {
761
+ if (e instanceof Error) throw e;
762
+ throw new Error(`MDX compile error: ${e} in ${filepath}`);
763
+ }
764
+ }
765
+ const cache = new Map();
766
+ async function compileWithCrossCompilerCache(options) {
767
+ const filepath = options.filepath;
768
+ const task = cache.get(filepath);
769
+ if (task) {
770
+ cache.delete(filepath);
771
+ return task;
772
+ }
773
+ const promise = compile(options);
774
+ cache.set(filepath, promise);
775
+ return promise;
776
+ }
777
+ export { compile, compileWithCrossCompilerCache };