@rspress/core 1.20.1 → 1.21.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/loader.d.ts CHANGED
@@ -1,6 +1,12 @@
1
- import { Rspack } from '@rsbuild/core';
2
1
  import * as _rspress_shared from '@rspress/shared';
3
2
  import { UserConfig, RspressPlugin, PageIndexInfo, RouteMeta } from '@rspress/shared';
3
+ import { Rspack } from '@rsbuild/core';
4
+
5
+ interface TocItem {
6
+ id: string;
7
+ text: string;
8
+ depth: number;
9
+ }
4
10
 
5
11
  declare class PluginDriver {
6
12
  #private;
@@ -44,12 +50,6 @@ declare class RouteService {
44
50
  };
45
51
  }
46
52
 
47
- interface TocItem {
48
- id: string;
49
- text: string;
50
- depth: number;
51
- }
52
-
53
53
  interface LoaderOptions {
54
54
  config: UserConfig;
55
55
  docDirectory: string;
package/dist/loader.js CHANGED
@@ -11,12 +11,21 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
11
11
 
12
12
  // src/node/mdx/loader.ts
13
13
  import path8 from "path";
14
+ import fs2 from "@rspress/shared/fs-extra";
14
15
  import { pathToFileURL } from "url";
15
16
  import { createProcessor as createProcessor2 } from "@mdx-js/mdx";
16
17
  import { isProduction as isProduction2 } from "@rspress/shared";
17
18
  import { logger as logger2 } from "@rspress/shared/logger";
18
19
  import { loadFrontMatter } from "@rspress/shared/node-utils";
19
- import fs2 from "@rspress/shared/fs-extra";
20
+
21
+ // src/node/mdx/options.ts
22
+ import path7 from "path";
23
+ import remarkGFM from "remark-gfm";
24
+ import rehypePluginExternalLinks from "rehype-external-links";
25
+
26
+ // src/node/mdx/remarkPlugins/toc.ts
27
+ import { visitChildren } from "unist-util-visit-children";
28
+ import Slugger from "github-slugger";
20
29
 
21
30
  // src/node/utils/normalizePath.ts
22
31
  import os from "os";
@@ -91,18 +100,18 @@ var getASTNodeImport = (name, from) => ({
91
100
 
92
101
  // src/node/utils/flattenMdxContent.ts
93
102
  import path3 from "path";
94
- import enhancedResolve from "enhanced-resolve";
95
103
  import fs from "@rspress/shared/fs-extra";
96
- import { createProcessor } from "@mdx-js/mdx";
104
+ import enhancedResolve from "enhanced-resolve";
97
105
  import { MDX_REGEXP } from "@rspress/shared";
98
- var { CachedInputFileSystem, ResolverFactory } = enhancedResolve;
99
- var processor = createProcessor();
106
+ import { createProcessor } from "@mdx-js/mdx";
100
107
  var resolver;
101
108
  var startFlatten = false;
109
+ var processor = createProcessor();
110
+ var { CachedInputFileSystem, ResolverFactory } = enhancedResolve;
102
111
  async function resolveDepPath(importPath, importer, alias) {
103
112
  if (!resolver) {
104
113
  resolver = ResolverFactory.createResolver({
105
- fileSystem: new CachedInputFileSystem(fs),
114
+ fileSystem: new CachedInputFileSystem(fs, 0),
106
115
  extensions: [".mdx", ".md"],
107
116
  alias
108
117
  });
@@ -138,24 +147,22 @@ async function flattenMdxContent(content, basePath, alias) {
138
147
  if (!regex.test(content)) {
139
148
  return { flattenContent: content, deps };
140
149
  }
141
- let result = content;
142
150
  if (!startFlatten) {
143
151
  resolver = ResolverFactory.createResolver({
144
- fileSystem: new CachedInputFileSystem(fs),
152
+ fileSystem: new CachedInputFileSystem(fs, 0),
145
153
  extensions: [".mdx", ".md", ".js"],
146
154
  alias
147
155
  });
148
156
  startFlatten = true;
149
157
  }
150
158
  let ast;
159
+ let result = content;
151
160
  try {
152
161
  ast = processor.parse(content);
153
162
  } catch (e) {
154
163
  return { flattenContent: content, deps };
155
164
  }
156
- const importNodes = ast.children.filter((node) => node.type === "mdxjsEsm").map((node) => {
157
- return node.data?.estree?.body || [];
158
- }).flat().filter((node) => node.type === "ImportDeclaration");
165
+ const importNodes = ast.children.filter((node) => node.type === "mdxjsEsm").flatMap((node) => node.data?.estree?.body || []).filter((node) => node.type === "ImportDeclaration");
159
166
  for (const importNode of importNodes) {
160
167
  const id = importNode.specifiers[0].local.name;
161
168
  const importPath = importNode.source.value;
@@ -208,14 +215,7 @@ function escapeMarkdownHeadingIds(content) {
208
215
  );
209
216
  }
210
217
 
211
- // src/node/mdx/options.ts
212
- import path7 from "path";
213
- import remarkGFM from "remark-gfm";
214
- import rehypePluginExternalLinks from "rehype-external-links";
215
-
216
218
  // src/node/mdx/remarkPlugins/toc.ts
217
- import { visitChildren } from "unist-util-visit-children";
218
- import Slugger from "github-slugger";
219
219
  var parseToc = (tree) => {
220
220
  let title = "";
221
221
  const toc = [];
@@ -269,6 +269,21 @@ var remarkPluginToc = function() {
269
269
  };
270
270
  };
271
271
 
272
+ // src/node/mdx/remarkPlugins/builtin.ts
273
+ import path4 from "path";
274
+ var remarkBuiltin = ({
275
+ globalComponents
276
+ }) => {
277
+ return (tree) => {
278
+ const demos = globalComponents.map((componentPath) => {
279
+ const filename = path4.parse(componentPath).name;
280
+ const componentName = filename[0].toUpperCase() + filename.slice(1);
281
+ return getASTNodeImport(componentName, componentPath);
282
+ });
283
+ tree.children.unshift(...demos);
284
+ };
285
+ };
286
+
272
287
  // src/node/mdx/rehypePlugins/codeMeta.ts
273
288
  import { visit } from "unist-util-visit";
274
289
  var rehypePluginCodeMeta = () => {
@@ -339,13 +354,62 @@ function create(node) {
339
354
  };
340
355
  }
341
356
 
342
- // src/node/mdx/remarkPlugins/normalizeLink.ts
343
- import path4 from "path";
357
+ // src/node/mdx/remarkPlugins/checkDeadLink.ts
358
+ import path5 from "path";
344
359
  import { visit as visit3 } from "unist-util-visit";
360
+ import { logger } from "@rspress/shared/logger";
361
+ import { cleanUrl, isProduction } from "@rspress/shared";
362
+ var IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
363
+ function checkLinks(links, filepath, root, routeService) {
364
+ const errorInfos = [];
365
+ links.filter((link) => !IGNORE_REGEXP.test(link)).map((link) => normalizePath(link)).forEach((link) => {
366
+ const relativePath = path5.relative(root, filepath);
367
+ if (!routeService.isExistRoute(cleanUrl(link))) {
368
+ errorInfos.push(
369
+ `Internal link to ${link} is dead, check it in ${relativePath}`
370
+ );
371
+ }
372
+ });
373
+ if (errorInfos.length > 0) {
374
+ errorInfos?.forEach((err) => {
375
+ logger.error(err);
376
+ });
377
+ if (isProduction()) {
378
+ throw new Error("Dead link found");
379
+ }
380
+ }
381
+ }
382
+ var remarkCheckDeadLinks = (checkLink) => {
383
+ const { root, routeService } = checkLink;
384
+ return (tree, vfile) => {
385
+ const internalLinks = /* @__PURE__ */ new Set();
386
+ visit3(tree, "link", (node) => {
387
+ const { url } = node;
388
+ if (!url) {
389
+ return;
390
+ }
391
+ if (internalLinks.has(url)) {
392
+ return;
393
+ }
394
+ if (!url.startsWith("http") && !url.startsWith("https")) {
395
+ const { routePath: normalizeUrl } = routeService.normalizeRoutePath(
396
+ // fix: windows path
397
+ url.split(path5.sep).join("/")?.split("#")[0]
398
+ );
399
+ internalLinks.add(normalizeUrl);
400
+ }
401
+ });
402
+ checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
403
+ };
404
+ };
405
+
406
+ // src/node/mdx/remarkPlugins/normalizeLink.ts
407
+ import path6 from "path";
408
+ import { visit as visit4 } from "unist-util-visit";
345
409
  import { normalizeHref, parseUrl, isExternalUrl, slash as slash2 } from "@rspress/shared";
346
410
  var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
347
411
  const images = [];
348
- visit3(
412
+ visit4(
349
413
  tree,
350
414
  (node) => node.type === "link",
351
415
  (node) => {
@@ -361,19 +425,19 @@ var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
361
425
  node.url = url + (hash ? `#${hash}` : "");
362
426
  return;
363
427
  }
364
- const extname = path4.extname(url);
428
+ const extname = path6.extname(url);
365
429
  if (extname === ".md" || extname === ".mdx") {
366
430
  url = url.replace(extname, "");
367
431
  }
368
- const relativePath = path4.relative(root, file.path);
432
+ const relativePath = path6.relative(root, file.path);
369
433
  if (url.startsWith(".")) {
370
- url = path4.posix.join(slash2(path4.dirname(relativePath)), url);
434
+ url = path6.posix.join(slash2(path6.dirname(relativePath)), url);
371
435
  }
372
436
  url = normalizeHref(url, cleanUrls);
373
437
  if (hash) {
374
438
  url += `#${hash}`;
375
439
  }
376
- node.url = path4.posix.join(base, url);
440
+ node.url = path6.posix.join(base, url);
377
441
  }
378
442
  );
379
443
  const normalizeImageUrl = (imageUrl) => {
@@ -407,7 +471,7 @@ var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
407
471
  }
408
472
  };
409
473
  };
410
- visit3(tree, "image", (node) => {
474
+ visit4(tree, "image", (node) => {
411
475
  const { url } = node;
412
476
  if (!url) {
413
477
  return;
@@ -432,7 +496,7 @@ var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
432
496
  });
433
497
  images.push(getASTNodeImport(tempVariableName, imagePath));
434
498
  });
435
- visit3(tree, ["mdxJsxFlowElement", "mdxJsxTextElement"], (node) => {
499
+ visit4(tree, ["mdxJsxFlowElement", "mdxJsxTextElement"], (node) => {
436
500
  if (node.name !== "img") {
437
501
  return;
438
502
  }
@@ -451,70 +515,6 @@ var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
451
515
  tree.children.unshift(...images);
452
516
  };
453
517
 
454
- // src/node/mdx/remarkPlugins/checkDeadLink.ts
455
- import path5 from "path";
456
- import { visit as visit4 } from "unist-util-visit";
457
- import { logger } from "@rspress/shared/logger";
458
- import { cleanUrl, isProduction } from "@rspress/shared";
459
- var IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
460
- function checkLinks(links, filepath, root, routeService) {
461
- const errorInfos = [];
462
- links.filter((link) => !IGNORE_REGEXP.test(link)).map((link) => normalizePath(link)).forEach((link) => {
463
- const relativePath = path5.relative(root, filepath);
464
- if (!routeService.isExistRoute(cleanUrl(link))) {
465
- errorInfos.push(
466
- `Internal link to ${link} is dead, check it in ${relativePath}`
467
- );
468
- }
469
- });
470
- if (errorInfos.length > 0) {
471
- errorInfos?.forEach((err) => {
472
- logger.error(err);
473
- });
474
- if (isProduction()) {
475
- throw new Error("Dead link found");
476
- }
477
- }
478
- }
479
- var remarkCheckDeadLinks = (checkLink) => {
480
- const { root, routeService } = checkLink;
481
- return (tree, vfile) => {
482
- const internalLinks = /* @__PURE__ */ new Set();
483
- visit4(tree, "link", (node) => {
484
- const { url } = node;
485
- if (!url) {
486
- return;
487
- }
488
- if (internalLinks.has(url)) {
489
- return;
490
- }
491
- if (!url.startsWith("http") && !url.startsWith("https")) {
492
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(
493
- // fix: windows path
494
- url.split(path5.sep).join("/")?.split("#")[0]
495
- );
496
- internalLinks.add(normalizeUrl);
497
- }
498
- });
499
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
500
- };
501
- };
502
-
503
- // src/node/mdx/remarkPlugins/builtin.ts
504
- import path6 from "path";
505
- var remarkBuiltin = ({
506
- globalComponents
507
- }) => {
508
- return (tree) => {
509
- const demos = globalComponents.map((componentPath) => {
510
- const filename = path6.parse(componentPath).name;
511
- const componentName = filename[0].toUpperCase() + filename.slice(1);
512
- return getASTNodeImport(componentName, componentPath);
513
- });
514
- tree.children.unshift(...demos);
515
- };
516
- };
517
-
518
518
  // src/node/mdx/options.ts
519
519
  async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
520
520
  const cleanUrls = Boolean(config?.route?.cleanUrls);
@@ -628,14 +628,10 @@ function createCheckPageMetaUpdateFn() {
628
628
  }
629
629
  var checkPageMetaUpdate = createCheckPageMetaUpdateFn();
630
630
  async function mdxLoader(context, source, callback) {
631
+ context.cacheable(true);
631
632
  const options = context.getOptions();
632
633
  const filepath = context.resourcePath;
633
634
  const { alias } = context._compiler.options.resolve;
634
- context.cacheable(true);
635
- let pageMeta = {
636
- title: "",
637
- toc: []
638
- };
639
635
  const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
640
636
  const { frontmatter, content } = loadFrontMatter(
641
637
  source,
@@ -648,12 +644,12 @@ async function mdxLoader(context, source, callback) {
648
644
  filepath,
649
645
  alias
650
646
  );
647
+ deps.forEach((dep) => context.addDependency(dep));
651
648
  const replacedContent = applyReplaceRules(
652
649
  flattenContent,
653
650
  config.replaceRules
654
651
  );
655
652
  const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
656
- deps.forEach((dep) => context.addDependency(dep));
657
653
  let enableMdxRs;
658
654
  const mdxRs = config?.markdown?.mdxRs ?? true;
659
655
  if (typeof mdxRs === "object") {
@@ -663,6 +659,7 @@ async function mdxLoader(context, source, callback) {
663
659
  }
664
660
  try {
665
661
  let compileResult;
662
+ let pageMeta = { title: "", toc: [] };
666
663
  if (!enableMdxRs) {
667
664
  const mdxOptions = await createMDXOptions(
668
665
  docDirectory,
@@ -673,10 +670,7 @@ async function mdxLoader(context, source, callback) {
673
670
  pluginDriver
674
671
  );
675
672
  const compiler = createProcessor2(mdxOptions);
676
- compiler.data("pageMeta", {
677
- toc: [],
678
- title: ""
679
- });
673
+ compiler.data("pageMeta", { toc: [], title: "" });
680
674
  const vFile = await compiler.process({
681
675
  value: preprocessedContent,
682
676
  path: filepath
@@ -1 +1 @@
1
- {"version":3,"mappings":";;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,SAAS,qBAAqB;AAE9B,SAAS,mBAAAC,wBAAuB;AAChC,SAAS,gBAAAC,qBAAkD;AAC3D,SAAS,UAAAC,eAAc;AACvB,SAAS,uBAAuB;AAChC,OAAOC,SAAQ;;;ACPf,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,OAAOJ,WAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,wBAAwB;AAK1C,IAAM,uBACX;AAMK,IAAM,oBAAoB;AAAA,wCACO,cAAc;A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AA,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,cAAcF,MAAK,SAAS,cAAc,QAAQ,CAAC;AAAA,IACrD,CAAC,QAAQ,KAAK,UAAU,QAAQ,CAAC;AAAA;AAEjC,aAAS,MAAM,MAAM;AAAA,EACvB,SAAS,GAAG;AACV,IAAAG,QAAO,MAAM,sBAAsB,EAAE,OAAO,OAAO,QAAQ,EAAE;AAC7D,aAAS,EAAE,SAAS,EAAE,SAAS,MAAM,GAAG,QAAQ,iBAAiB,CAAC;AAAA,EACpE;AACF","names":["path","createProcessor","isProduction","logger","fs","visit","slash"],"ignoreList":[],"sources":["../src/node/mdx/loader.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/options.ts","../src/node/mdx/remarkPlugins/toc.ts","../src/node/mdx/rehypePlugins/codeMeta.ts","../src/node/mdx/rehypePlugins/headerAnchor.ts","../src/node/mdx/remarkPlugins/normalizeLink.ts","../src/node/mdx/remarkPlugins/checkDeadLink.ts","../src/node/mdx/remarkPlugins/builtin.ts"],"sourcesContent":["import path from 'path';\nimport { pathToFileURL } from 'url';\nimport type { Rspack } from '@rsbuild/core';\nimport { createProcessor } from '@mdx-js/mdx';\nimport { isProduction, type Header, type UserConfig } from '@rspress/shared';\nimport { logger } from '@rspress/shared/logger';\nimport { loadFrontMatter } from '@rspress/shared/node-utils';\nimport fs from '@rspress/shared/fs-extra';\nimport type { RouteService } from '../route/RouteService';\nimport {\n normalizePath,\n escapeMarkdownHeadingIds,\n flattenMdxContent,\n applyReplaceRules,\n} from '../utils';\nimport { PluginDriver } from '../PluginDriver';\nimport { TEMP_DIR } from '../constants';\nimport { RuntimeModuleID } from '../runtimeModule';\nimport { createMDXOptions } from './options';\nimport { TocItem } from './remarkPlugins/toc';\nimport { checkLinks } from './remarkPlugins/checkDeadLink';\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 ...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 );\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(\n '⭐️ Page metadata changed, rspress will trigger page reload...',\n );\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 const options = context.getOptions();\n const filepath = context.resourcePath;\n const { alias } = context._compiler.options.resolve;\n context.cacheable(true);\n let pageMeta = {\n title: '',\n toc: [],\n } as PageMeta;\n\n const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } =\n options;\n\n const { frontmatter, content } = loadFrontMatter(\n source,\n filepath,\n docDirectory,\n true,\n );\n\n const { flattenContent, deps } = await flattenMdxContent(\n content,\n filepath,\n alias as Record<string, string>,\n );\n // replace content\n const replacedContent = applyReplaceRules(\n flattenContent,\n config.replaceRules,\n );\n // preprocessor\n const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);\n\n deps.forEach(dep => context.addDependency(dep));\n\n let enableMdxRs;\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 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', {\n toc: [],\n title: '',\n });\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 // TODO: Cannot get correct toc from mdx which has internal components\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 os from 'os';\nimport path from '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 'path';\nimport { fileURLToPath } from '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\n// @ts-expect-error\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 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 'path';\nimport enhancedResolve from 'enhanced-resolve';\nimport type { Resolver } from 'enhanced-resolve';\nimport fs from '@rspress/shared/fs-extra';\nimport { createProcessor } from '@mdx-js/mdx';\nimport type { Root } from 'hast';\nimport { MDX_REGEXP } from '@rspress/shared';\nimport { importStatementRegex } from '../constants';\n\nconst { CachedInputFileSystem, ResolverFactory } = enhancedResolve;\nconst processor = createProcessor();\nlet resolver: Resolver;\nlet startFlatten = false;\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),\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 ImportNode {\n type: 'ImportDeclaration';\n specifiers: { local: { name: string } }[];\n source: { value: string };\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 let result = content;\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),\n extensions: ['.mdx', '.md', '.js'],\n alias,\n });\n startFlatten = true;\n }\n let ast: Root;\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 const importNodes = ast.children\n .filter(node => node.type === 'mdxjsEsm')\n .map(node => {\n return (node.data?.estree as { body: ImportNode[] })?.body || [];\n })\n .flat()\n .filter(node => node.type === 'ImportDeclaration');\n for (const importNode of importNodes) {\n // import Comp from './a';\n // id: Comp\n // 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 { 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 'path';\nimport remarkGFM from 'remark-gfm';\nimport { Options } from '@mdx-js/loader';\nimport { UserConfig } from '@rspress/shared';\nimport { PluggableList } from 'unified';\nimport rehypePluginExternalLinks from 'rehype-external-links';\nimport type { RouteService } from '../route/RouteService';\nimport type { PluginDriver } from '../PluginDriver';\nimport { remarkPluginToc } from './remarkPlugins/toc';\nimport { rehypePluginCodeMeta } from './rehypePlugins/codeMeta';\nimport { rehypeHeaderAnchor } from './rehypePlugins/headerAnchor';\nimport { remarkPluginNormalizeLink } from './remarkPlugins/normalizeLink';\nimport { remarkCheckDeadLinks } from './remarkPlugins/checkDeadLink';\nimport { remarkBuiltin } from './remarkPlugins/builtin';\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 { Processor } from '@mdx-js/mdx/lib/core';\nimport { 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 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 '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","import path from '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 '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"]}
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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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 'path';\nimport fs from '@rspress/shared/fs-extra';\nimport { pathToFileURL } from '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 { TocItem } from './remarkPlugins/toc';\nimport { checkLinks } from './remarkPlugins/checkDeadLink';\nimport { TEMP_DIR } from '../constants';\nimport { 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 ...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 );\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(\n '⭐️ Page metadata changed, rspress will trigger page reload...',\n );\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 'path';\nimport remarkGFM from 'remark-gfm';\nimport rehypePluginExternalLinks from 'rehype-external-links';\nimport { PluggableList } from 'unified';\nimport { Options } from '@mdx-js/loader';\nimport { 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 { Processor } from '@mdx-js/mdx/lib/core';\nimport { 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 'os';\nimport path from '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 'path';\nimport { fileURLToPath } from '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 '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 { 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 '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 '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 '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.20.1",
3
+ "version": "1.21.0",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -37,10 +37,10 @@
37
37
  "@mdx-js/loader": "2.3.0",
38
38
  "@mdx-js/mdx": "2.3.0",
39
39
  "@mdx-js/react": "2.3.0",
40
- "@modern-js/utils": "2.49.2",
40
+ "@modern-js/utils": "2.49.3",
41
41
  "@rsbuild/core": "0.6.13",
42
42
  "@rsbuild/plugin-react": "0.6.13",
43
- "@rspress/mdx-rs": "0.5.4",
43
+ "@rspress/mdx-rs": "0.5.5",
44
44
  "body-scroll-lock": "4.0.0-beta.0",
45
45
  "copy-to-clipboard": "^3.3.3",
46
46
  "enhanced-resolve": "5.16.0",
@@ -74,18 +74,18 @@
74
74
  "unist-util-visit": "^4.1.1",
75
75
  "unist-util-visit-children": "^2.0.1",
76
76
  "yaml-front-matter": "^4.1.1",
77
- "@rspress/theme-default": "1.20.1",
78
- "@rspress/runtime": "1.20.1",
79
- "@rspress/plugin-medium-zoom": "1.20.1",
80
- "@rspress/plugin-last-updated": "1.20.1",
81
- "@rspress/plugin-auto-nav-sidebar": "1.20.1",
82
- "@rspress/plugin-container-syntax": "1.20.1",
83
- "@rspress/shared": "1.20.1"
77
+ "@rspress/theme-default": "1.21.0",
78
+ "@rspress/runtime": "1.21.0",
79
+ "@rspress/plugin-medium-zoom": "1.21.0",
80
+ "@rspress/plugin-last-updated": "1.21.0",
81
+ "@rspress/plugin-auto-nav-sidebar": "1.21.0",
82
+ "@rspress/plugin-container-syntax": "1.21.0",
83
+ "@rspress/shared": "1.21.0"
84
84
  },
85
85
  "devDependencies": {
86
86
  "tailwindcss": "^3.4.3",
87
- "@modern-js/plugin-tailwindcss": "2.49.2",
88
- "@modern-js/tsconfig": "2.49.2",
87
+ "@modern-js/plugin-tailwindcss": "2.49.3",
88
+ "@modern-js/tsconfig": "2.49.3",
89
89
  "@types/body-scroll-lock": "^3.1.0",
90
90
  "@types/hast": "3.0.3",
91
91
  "@types/html-to-text": "^8.1.1",