@rspress/core 2.0.22 → 2.1.0-beta.1

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.
Files changed (134) hide show
  1. package/bin/rspress.js +3 -1
  2. package/dist/{v~0.js → b~0.js} +19 -16
  3. package/dist/cli/index.js +2 -2
  4. package/dist/{common-Qw-RoVFD.js → common-Bo3KCGim.js} +4 -1
  5. package/dist/config/loadConfigFile.js +1 -1
  6. package/dist/eject-theme/components/Link/getHref.ts +1 -0
  7. package/dist/eject-theme/components/Link/index.tsx +0 -3
  8. package/dist/eject-theme/components/Link/useLinkNavigate.ts +29 -54
  9. package/dist/eject-theme/components/Search/SearchPanel.tsx +9 -5
  10. package/dist/eject-theme/components/Search/logic/providers/LocalProvider.ts +5 -2
  11. package/dist/eject-theme/components/Search/useSearchPanel.ts +105 -37
  12. package/dist/eject-theme/components/SocialLinks/GithubStars.test.tsx +4 -1
  13. package/dist/eject-theme/components/SocialLinks/GithubStars.tsx +1 -1
  14. package/dist/eject-theme/components/SocialLinks/SocialLink.tsx +2 -2
  15. package/dist/eject-theme/components/SourceCode/index.tsx +1 -1
  16. package/dist/entry/worker.js +1 -1
  17. package/dist/{o~0.js → h~0.js} +18 -29
  18. package/dist/index.d.ts +1 -1
  19. package/dist/node/PluginDriver.js +8 -2
  20. package/dist/node/auto-nav-sidebar/index.js +1 -1
  21. package/dist/node/auto-nav-sidebar/locales.js +1 -1
  22. package/dist/node/auto-nav-sidebar/normalize.js +1 -1
  23. package/dist/node/auto-nav-sidebar/utils.js +1 -1
  24. package/dist/node/auto-nav-sidebar/walk.js +1 -1
  25. package/dist/node/constants.js +1 -1
  26. package/dist/node/eject.js +1 -1
  27. package/dist/node/initRsbuild.js +9 -5
  28. package/dist/node/llms.d.ts +1 -1
  29. package/dist/node/llms.js +2 -2
  30. package/dist/node/logger/hint.d.ts +1 -0
  31. package/dist/node/logger/hint.js +8 -2
  32. package/dist/node/route/RoutePage.js +1 -1
  33. package/dist/node/route/RouteService.js +1 -1
  34. package/dist/node/route/extractPageData.js +1 -1
  35. package/dist/node/route/normalizeRoutePath.js +1 -1
  36. package/dist/node/runtimeModule/DEFAULT_I18N_TEXT.d.ts +28 -0
  37. package/dist/node/runtimeModule/DEFAULT_I18N_TEXT.js +28 -0
  38. package/dist/node/runtimeModule/i18n.js +1 -1
  39. package/dist/node/runtimeModule/pageData/createPageData.js +1 -1
  40. package/dist/node/runtimeModule/pageData/rsbuildPlugin.js +1 -1
  41. package/dist/node/runtimeModule/searchHooks.js +2 -2
  42. package/dist/node/runtimeModule/siteData/createSiteData.js +1 -1
  43. package/dist/node/runtimeModule/siteData/normalizeThemeConfig.js +1 -1
  44. package/dist/node/runtimeModule/siteData/rsbuildPlugin.js +1 -1
  45. package/dist/node/serve.js +1 -1
  46. package/dist/node/sitemap.d.ts +2 -0
  47. package/dist/node/sitemap.js +103 -0
  48. package/dist/node/ssg/alternateLinks.js +1 -1
  49. package/dist/node/ssg/htmlFile.js +1 -1
  50. package/dist/node/ssg/renderHtmlTemplate.js +4 -3
  51. package/dist/node/ssg/renderPage.js +1 -1
  52. package/dist/node/ssg/renderPageWorker.js +1 -1
  53. package/dist/node/ssg/renderPages.js +2 -2
  54. package/dist/node/ssg/rsbuildPluginSSG.js +1 -1
  55. package/dist/node/ssg/ssgEnv.js +1 -1
  56. package/dist/node/ssg-md/llms/emitLlmsTxt.js +1 -1
  57. package/dist/node/ssg-md/llms/llmsTxt.js +1 -1
  58. package/dist/node/ssg-md/renderPage.js +5 -4
  59. package/dist/node/ssg-md/renderPages.js +2 -2
  60. package/dist/node/ssg-md/rsbuildPluginSSGMD.js +1 -1
  61. package/dist/node/utils/checkLanguageParity.js +1 -1
  62. package/dist/node/utils/createHash.js +1 -1
  63. package/dist/node/utils/flattenMdxContent.js +1 -1
  64. package/dist/node/utils/getPageKey.js +1 -1
  65. package/dist/node/utils/reactAlias.js +5 -2
  66. package/dist/n~0.js +11 -10
  67. package/dist/runtime/App.js +15 -27
  68. package/dist/runtime/ClientApp.d.ts +3 -2
  69. package/dist/runtime/ClientApp.js +27 -21
  70. package/dist/runtime/ErrorRoute.d.ts +1 -0
  71. package/dist/runtime/ErrorRoute.js +30 -0
  72. package/dist/runtime/PageRoute.d.ts +2 -0
  73. package/dist/runtime/PageRoute.js +58 -0
  74. package/dist/runtime/createServerRouter.d.ts +4 -0
  75. package/dist/runtime/createServerRouter.js +17 -0
  76. package/dist/runtime/csrClientEntry.js +5 -2
  77. package/dist/runtime/hooks/createExternalStore.d.ts +4 -0
  78. package/dist/runtime/hooks/createExternalStore.js +20 -0
  79. package/dist/runtime/hooks/useGlobalComponents.d.ts +1 -0
  80. package/dist/runtime/hooks/useGlobalComponents.js +10 -0
  81. package/dist/runtime/hooks/useI18n.js +5 -3
  82. package/dist/runtime/hooks/useI18nText.d.ts +1 -0
  83. package/dist/runtime/hooks/useI18nText.js +10 -0
  84. package/dist/runtime/hooks/usePages.d.ts +2 -0
  85. package/dist/runtime/hooks/usePages.js +12 -3
  86. package/dist/runtime/hooks/useSearchHooks.d.ts +8 -0
  87. package/dist/runtime/hooks/useSearchHooks.js +14 -0
  88. package/dist/runtime/hooks/useSite.d.ts +1 -0
  89. package/dist/runtime/hooks/useSite.js +9 -2
  90. package/dist/runtime/hooks/useWebMcp.d.ts +36 -0
  91. package/dist/runtime/hooks/useWebMcp.js +80 -0
  92. package/dist/runtime/index.d.ts +6 -2
  93. package/dist/runtime/index.js +8 -2
  94. package/dist/runtime/initPageData.d.ts +0 -3
  95. package/dist/runtime/initPageData.js +13 -49
  96. package/dist/runtime/pageDataLoader.d.ts +11 -0
  97. package/dist/runtime/pageDataLoader.js +7 -0
  98. package/dist/runtime/route.js +5 -5
  99. package/dist/runtime/ssrClientEntry.js +14 -6
  100. package/dist/runtime/ssrMdServerEntry.js +10 -21
  101. package/dist/runtime/ssrServerEntry.js +10 -21
  102. package/dist/runtime/utils.js +6 -6
  103. package/dist/static/assets/package.json +58 -0
  104. package/dist/theme/components/Link/index.js +0 -4
  105. package/dist/theme/components/Link/useLinkNavigate.d.ts +2 -2
  106. package/dist/theme/components/Link/useLinkNavigate.js +13 -35
  107. package/dist/theme/components/Search/SearchPanel.js +8 -6
  108. package/dist/theme/components/Search/logic/providers/LocalProvider.js +5 -2
  109. package/dist/theme/components/Search/useSearchPanel.js +75 -27
  110. package/dist/theme/components/SocialLinks/GithubStars.js +1 -1
  111. package/dist/theme/components/SocialLinks/SocialLink.js +2 -2
  112. package/dist/theme/components/SourceCode/index.js +1 -1
  113. package/dist/theme/hooks/useWebMcpNavigation.d.ts +6 -0
  114. package/dist/theme/hooks/useWebMcpNavigation.js +123 -0
  115. package/dist/theme/hooks/useWebMcpPageList.d.ts +6 -0
  116. package/dist/theme/hooks/useWebMcpPageList.js +25 -0
  117. package/dist/theme/hooks/useWebMcpPageReading.d.ts +7 -0
  118. package/dist/theme/hooks/useWebMcpPageReading.js +23 -0
  119. package/dist/theme/hooks/useWebMcpSiteInfo.d.ts +6 -0
  120. package/dist/theme/hooks/useWebMcpSiteInfo.js +22 -0
  121. package/dist/theme/index.d.ts +5 -0
  122. package/dist/theme/index.js +5 -0
  123. package/dist/theme/layout/ErrorLayout/index.css +52 -0
  124. package/dist/theme/layout/ErrorLayout/index.d.ts +8 -0
  125. package/dist/theme/layout/ErrorLayout/index.js +76 -0
  126. package/dist/theme/logic/utils.d.ts +0 -2
  127. package/dist/theme/logic/utils.js +56 -6
  128. package/dist/theme/webMcp/tools.d.ts +56 -0
  129. package/dist/theme/webMcp/tools.js +122 -0
  130. package/dist/theme/webMcp/types.d.ts +35 -0
  131. package/dist/theme/webMcp/types.js +0 -0
  132. package/dist/tinypool~0.js +19 -49
  133. package/dist/tu~0.js +3 -0
  134. package/package.json +17 -17
@@ -0,0 +1,76 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { useI18nText } from "@rspress/core/runtime";
3
+ import { useHead } from "@unhead/react";
4
+ import { useEffect, useRef } from "react";
5
+ import { isRouteErrorResponse } from "react-router-dom";
6
+ import "../NotFountLayout/index.css";
7
+ import "./index.css";
8
+ function ErrorLayout({ error, lang, homeHref }) {
9
+ const i18n = useI18nText();
10
+ const title = useRef(null);
11
+ const text = (key, fallback)=>i18n[key]?.[lang] || fallback;
12
+ const heading = text('errorTitleText', 'Something went wrong');
13
+ useHead({
14
+ title: heading
15
+ });
16
+ const response = isRouteErrorResponse(error);
17
+ const details = import.meta.env.DEV ? error instanceof Error ? error.stack || error.message : response ? `${error.status} ${error.statusText}` : 'string' == typeof error ? error : 'Unknown error' : void 0;
18
+ useEffect(()=>{
19
+ title.current?.focus();
20
+ }, [
21
+ heading
22
+ ]);
23
+ return /*#__PURE__*/ jsxs("main", {
24
+ className: "rp-not-found rp-error",
25
+ "aria-labelledby": "rp-error-title",
26
+ children: [
27
+ /*#__PURE__*/ jsx("p", {
28
+ className: "rp-not-found__error-code",
29
+ children: response ? error.status : 'ERROR'
30
+ }),
31
+ /*#__PURE__*/ jsx("h1", {
32
+ className: "rp-not-found__title",
33
+ id: "rp-error-title",
34
+ ref: title,
35
+ tabIndex: -1,
36
+ children: heading
37
+ }),
38
+ /*#__PURE__*/ jsx("div", {
39
+ className: "rp-not-found__divider"
40
+ }),
41
+ /*#__PURE__*/ jsx("p", {
42
+ className: "rp-error__description",
43
+ children: text("errorDescriptionText", 'This page could not be loaded. Try reloading it or return to the home page.')
44
+ }),
45
+ /*#__PURE__*/ jsxs("div", {
46
+ className: "rp-not-found__action rp-error__actions",
47
+ children: [
48
+ /*#__PURE__*/ jsx("button", {
49
+ type: "button",
50
+ className: "rp-not-found__home-link",
51
+ onClick: ()=>window.location.reload(),
52
+ children: text('reloadPageText', 'Reload page')
53
+ }),
54
+ /*#__PURE__*/ jsx("a", {
55
+ className: "rp-not-found__home-link",
56
+ href: homeHref,
57
+ children: text('takeMeHomeText', 'Take me home')
58
+ })
59
+ ]
60
+ }),
61
+ details && /*#__PURE__*/ jsxs("details", {
62
+ className: "rp-error__details",
63
+ open: true,
64
+ children: [
65
+ /*#__PURE__*/ jsx("summary", {
66
+ children: text('errorDetailsText', 'Error details')
67
+ }),
68
+ /*#__PURE__*/ jsx("pre", {
69
+ children: details
70
+ })
71
+ ]
72
+ })
73
+ ]
74
+ });
75
+ }
76
+ export { ErrorLayout };
@@ -16,8 +16,6 @@ export declare function renderHtmlOrText(str?: string | number | null): {
16
16
  * @private
17
17
  */
18
18
  export declare function renderInlineMarkdown(text: string): {
19
- children: string | null;
20
- } | {
21
19
  dangerouslySetInnerHTML: {
22
20
  __html: string;
23
21
  };
@@ -16,12 +16,11 @@ function renderHtmlOrText(str) {
16
16
  children: str.replace(/\\</g, '<').replace(/\\>/g, '>').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
17
17
  };
18
18
  }
19
- const CODE_TEXT_PATTERN = /`(.*?)`/g;
20
19
  const STRONG_TEXT_PATTERN = /\*{2}(?!\*)(.*?)\*{2}(?!\*)/g;
21
20
  const EMPHASIS_TEXT_PATTERN = /\*(?!\*)(.*?)\*(?!\*)/g;
22
21
  const DELETE_TEXT_PATTERN = /~{2}(.*?)~{2}/g;
23
- const INLINE_CODE_PATTERN = /`[^`]+`/g;
24
22
  const HTML_TAG_PATTERN = /<\/?[a-z][^>]*>/gi;
23
+ const HTML_VOID_ELEMENT_PATTERN = /<(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)(?=[\s/>])[^>]*>/gi;
25
24
  const HTML_ENTITY_PATTERN = /&(#\d+|#x[0-9a-f]+|[a-z][0-9a-z]*);/gi;
26
25
  const NAMED_HTML_ENTITIES = {
27
26
  amp: '&',
@@ -40,12 +39,63 @@ function decodeHtmlEntities(text) {
40
39
  return isScalarValue ? String.fromCodePoint(codePoint) : match;
41
40
  });
42
41
  }
42
+ function escapeHtml(text) {
43
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
44
+ }
45
+ function protectInlineMarkdown(text) {
46
+ let marker = '\u0000';
47
+ while(text.includes(marker))marker += '\u0000';
48
+ const fragments = [];
49
+ const protect = (value, html = escapeHtml(value))=>{
50
+ const index = fragments.push({
51
+ text: value,
52
+ html
53
+ }) - 1;
54
+ return `${marker}${index}${marker}`;
55
+ };
56
+ const pattern = /\\([!-/:-@[-`{-~])|`+|<code\b[^>]*>[\s\S]*?<\/code>|&(#\d+|#x[0-9a-f]+|[a-z][0-9a-z]*);/gi;
57
+ const backticks = /`+/g;
58
+ let result = '';
59
+ let offset = 0;
60
+ let match;
61
+ while(match = pattern.exec(text)){
62
+ result += text.slice(offset, match.index);
63
+ if (match[1]) result += protect(match[1]);
64
+ else if (match[0].startsWith('&')) result += protect(decodeHtmlEntities(match[0]), match[0]);
65
+ else if (match[0].startsWith('<')) result += protect(decodeHtmlEntities(match[0].replace(HTML_TAG_PATTERN, '')), match[0]);
66
+ else {
67
+ backticks.lastIndex = pattern.lastIndex;
68
+ let closing;
69
+ while(closing = backticks.exec(text))if (closing[0].length === match[0].length) break;
70
+ if (closing) {
71
+ let value = text.slice(pattern.lastIndex, closing.index).replace(/\r\n?|\n/g, ' ');
72
+ if (value.startsWith(' ') && value.endsWith(' ') && /[^ ]/.test(value)) value = value.slice(1, -1);
73
+ result += protect(value, `<code>${escapeHtml(value)}</code>`);
74
+ pattern.lastIndex = closing.index + closing[0].length;
75
+ } else result += protect(match[0]);
76
+ }
77
+ offset = pattern.lastIndex;
78
+ }
79
+ result += text.slice(offset);
80
+ return {
81
+ text: result,
82
+ restore: (value, format)=>value.replace(new RegExp(`${marker}(\\d+)${marker}`, 'g'), (_, index)=>fragments[Number(index)][format])
83
+ };
84
+ }
43
85
  function renderInlineMarkdown(text) {
44
- const htmlText = text.replace(INLINE_CODE_PATTERN, (match)=>match.replace(/</g, '&lt;')).replace(STRONG_TEXT_PATTERN, '<strong>$1</strong>').replace(EMPHASIS_TEXT_PATTERN, '<em>$1</em>').replace(DELETE_TEXT_PATTERN, '<del>$1</del>').replace(CODE_TEXT_PATTERN, '<code>$1</code>');
45
- return renderHtmlOrText(htmlText);
86
+ const protectedText = protectInlineMarkdown(text);
87
+ const source = renderHtmlOrText(protectedText.text);
88
+ const htmlText = ('children' in source ? escapeHtml(source.children ?? '') : source.dangerouslySetInnerHTML.__html).replace(STRONG_TEXT_PATTERN, '<strong>$1</strong>').replace(EMPHASIS_TEXT_PATTERN, '<em>$1</em>').replace(DELETE_TEXT_PATTERN, '<del>$1</del>');
89
+ return {
90
+ dangerouslySetInnerHTML: {
91
+ __html: protectedText.restore(htmlText, 'html')
92
+ }
93
+ };
46
94
  }
47
95
  function parseInlineMarkdownText(mdx) {
48
- const plainText = mdx.replace(INLINE_CODE_PATTERN, (match)=>match.replace(/</g, '&lt;')).replace(STRONG_TEXT_PATTERN, '$1').replace(EMPHASIS_TEXT_PATTERN, '$1').replace(DELETE_TEXT_PATTERN, '$1').replace(CODE_TEXT_PATTERN, '$1').replace(HTML_TAG_PATTERN, '');
49
- return decodeHtmlEntities(plainText).trim();
96
+ const protectedText = protectInlineMarkdown(mdx);
97
+ const source = renderHtmlOrText(protectedText.text.replace(HTML_VOID_ELEMENT_PATTERN, ''));
98
+ const plainText = ('children' in source ? source.children ?? '' : source.dangerouslySetInnerHTML.__html.replace(HTML_TAG_PATTERN, '')).replace(STRONG_TEXT_PATTERN, '$1').replace(EMPHASIS_TEXT_PATTERN, '$1').replace(DELETE_TEXT_PATTERN, '$1');
99
+ return protectedText.restore(decodeHtmlEntities(plainText), 'text').trim();
50
100
  }
51
101
  export { parseInlineMarkdownText, renderHtmlOrText, renderInlineMarkdown };
@@ -0,0 +1,56 @@
1
+ import type { WebMcpOptions } from '@rspress/core/runtime';
2
+ import type { PageInfo } from './types.js';
3
+ type Field = {
4
+ type: 'string';
5
+ minLength?: number;
6
+ } | {
7
+ type: 'integer';
8
+ minimum: number;
9
+ maximum?: number;
10
+ };
11
+ export declare const queryField: Field;
12
+ export declare const routePathField: Field;
13
+ export declare function toWebMcpSearchResults(groups: {
14
+ group: string;
15
+ result: unknown;
16
+ }[]): {
17
+ group: string;
18
+ results: unknown;
19
+ }[];
20
+ export declare function resolveInternalRoute(value: string, context: {
21
+ origin: string;
22
+ resolveRoute(pathname: string): string | undefined;
23
+ }): string;
24
+ export declare function metadata(page: PageInfo): {
25
+ title: string;
26
+ description: string | undefined;
27
+ routePath: string;
28
+ lang: string;
29
+ version: string;
30
+ };
31
+ export declare function readPage(page: PageInfo, base: string, signal?: AbortSignal, fetcher?: typeof fetch): Promise<{
32
+ title: string;
33
+ description: string | undefined;
34
+ routePath: string;
35
+ lang: string;
36
+ version: string;
37
+ frontmatter: import("@rspress/shared").FrontMatterMeta;
38
+ toc: import("@rspress/shared").Header[];
39
+ markdown: string;
40
+ }>;
41
+ export declare function listPages(pages: PageInfo[], current: Pick<PageInfo, 'lang' | 'version'>, args: Record<string, unknown>): {
42
+ pages: {
43
+ title: string;
44
+ description: string | undefined;
45
+ routePath: string;
46
+ lang: string;
47
+ version: string;
48
+ toc: import("@rspress/shared").Header[];
49
+ }[];
50
+ total: number;
51
+ offset: number;
52
+ limit: number;
53
+ };
54
+ /** Shared validation and defaults for Rspress's built-in tools. */
55
+ export declare function defineTool(name: string, description: string, fields: Record<string, Field>, required: string[], execute: (args: Record<string, unknown>, signal?: AbortSignal) => unknown): WebMcpOptions;
56
+ export {};
@@ -0,0 +1,122 @@
1
+ import { normalizeHref, removeTrailingSlash } from "@rspress/shared";
2
+ const queryField = {
3
+ type: 'string',
4
+ minLength: 1
5
+ };
6
+ const routePathField = {
7
+ type: 'string',
8
+ minLength: 1
9
+ };
10
+ function toWebMcpSearchResults(groups) {
11
+ return groups.flatMap(({ group, result })=>{
12
+ try {
13
+ const json = JSON.stringify(result, (_key, value)=>{
14
+ if ([
15
+ 'function',
16
+ 'symbol',
17
+ 'bigint'
18
+ ].includes(typeof value)) throw new TypeError('Search result is not JSON-serializable.');
19
+ return value;
20
+ });
21
+ return void 0 === json ? [] : [
22
+ {
23
+ group,
24
+ results: JSON.parse(json)
25
+ }
26
+ ];
27
+ } catch {
28
+ return [];
29
+ }
30
+ });
31
+ }
32
+ function argumentsObject(input, fields, required) {
33
+ const value = void 0 === input ? {} : input;
34
+ if (null === value || 'object' != typeof value || Array.isArray(value)) throw new TypeError('Tool arguments must be an object.');
35
+ const args = value;
36
+ for (const key of Object.keys(args))if (!Object.hasOwn(fields, key)) throw new TypeError(`Unknown argument: ${key}`);
37
+ for (const [key, field] of Object.entries(fields)){
38
+ const val = args[key];
39
+ if (void 0 !== val || required.includes(key)) {
40
+ if ('string' === field.type) {
41
+ if ('string' != typeof val || field.minLength && !val.trim()) throw new TypeError(`${key} must be ${field.minLength ? 'a non-empty' : 'a'} string.`);
42
+ } else if ('number' != typeof val || !Number.isSafeInteger(val) || val < field.minimum || void 0 !== field.maximum && val > field.maximum) throw new TypeError(`${key} must be an integer between ${field.minimum} and ${field.maximum ?? Number.MAX_SAFE_INTEGER}.`);
43
+ }
44
+ }
45
+ return args;
46
+ }
47
+ function resolveInternalRoute(value, context) {
48
+ if (!value.startsWith('/') || value.startsWith('//')) throw new TypeError('routePath must be an absolute internal path.');
49
+ const url = new URL(value, context.origin);
50
+ if (url.origin !== context.origin) throw new TypeError('External routes are not allowed.');
51
+ const path = context.resolveRoute(url.pathname);
52
+ if (!path) throw new TypeError(`Unknown internal route: ${url.pathname}`);
53
+ return `${path}${url.search}${url.hash}`;
54
+ }
55
+ function metadata(page) {
56
+ return {
57
+ title: page.title,
58
+ description: page.description,
59
+ routePath: page.routePath,
60
+ lang: page.lang,
61
+ version: page.version
62
+ };
63
+ }
64
+ async function readPage(page, base, signal, fetcher = fetch) {
65
+ const url = `${removeTrailingSlash(base)}${normalizeHref(page.routePath, false).replace(/\.html$/, '.md')}`;
66
+ const response = await fetcher(url, {
67
+ signal
68
+ });
69
+ if (!response.ok) throw new Error(`Failed to read Markdown for ${page.routePath}: ${response.status}`);
70
+ const markdown = await response.text();
71
+ if (response.headers.get('content-type')?.includes('text/html') || /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(markdown)) throw new Error(`Markdown is unavailable for ${page.routePath}. Serve the output of rspress build with llms enabled.`);
72
+ return {
73
+ ...metadata(page),
74
+ frontmatter: page.frontmatter,
75
+ toc: page.toc,
76
+ markdown
77
+ };
78
+ }
79
+ function listPages(pages, current, args) {
80
+ const lang = args.lang ?? current.lang;
81
+ const version = args.version ?? current.version;
82
+ const terms = args.query?.trim().toLowerCase().split(/\s+/) ?? [];
83
+ const matches = pages.filter((page)=>{
84
+ const text = [
85
+ page.title,
86
+ page.description,
87
+ page.routePath,
88
+ ...page.toc.map((item)=>item.text)
89
+ ].join(' ').toLowerCase();
90
+ return page.lang === lang && page.version === version && terms.every((term)=>text.includes(term));
91
+ });
92
+ const limit = args.limit ?? 50;
93
+ const offset = args.offset ?? 0;
94
+ return {
95
+ pages: matches.slice(offset, offset + limit).map((page)=>({
96
+ ...metadata(page),
97
+ toc: page.toc
98
+ })),
99
+ total: matches.length,
100
+ offset,
101
+ limit
102
+ };
103
+ }
104
+ function defineTool(name, description, fields, required, execute) {
105
+ return {
106
+ name: `rspress_${name}`,
107
+ description,
108
+ inputSchema: {
109
+ type: 'object',
110
+ properties: fields,
111
+ required,
112
+ additionalProperties: false
113
+ },
114
+ annotations: {
115
+ readOnlyHint: 'navigate' !== name,
116
+ untrustedContentHint: true
117
+ },
118
+ exposedTo: import.meta.env.WEBMCP_EXPOSED_TO,
119
+ execute: (input, options)=>execute(argumentsObject(input, fields, required), options.signal)
120
+ };
121
+ }
122
+ export { defineTool, listPages, metadata, queryField, readPage, resolveInternalRoute, routePathField, toWebMcpSearchResults };
@@ -0,0 +1,35 @@
1
+ import type { BaseRuntimePageInfo, NavItem, SidebarData } from '@rspress/shared';
2
+ export type PageInfo = Pick<BaseRuntimePageInfo, 'title' | 'description' | 'routePath' | 'lang' | 'version' | 'toc' | 'frontmatter'>;
3
+ export interface SiteInfo {
4
+ title: string;
5
+ description: string;
6
+ base: string;
7
+ siteOrigin: string;
8
+ lang: string;
9
+ version: string;
10
+ locales: {
11
+ lang: string;
12
+ label: string;
13
+ }[];
14
+ versions: string[];
15
+ defaultVersion: string;
16
+ nav: NavItem[];
17
+ sidebar: SidebarData;
18
+ }
19
+ export interface NavigationResult {
20
+ routePath: string;
21
+ page: Pick<PageInfo, 'title' | 'description' | 'lang' | 'version'>;
22
+ sections: {
23
+ title: string;
24
+ depth: number;
25
+ routePath: string;
26
+ }[];
27
+ previousPage: {
28
+ title: string;
29
+ routePath: string;
30
+ } | null;
31
+ nextPage: {
32
+ title: string;
33
+ routePath: string;
34
+ } | null;
35
+ }
File without changes
@@ -1,14 +1,13 @@
1
1
  import { MessageChannel, MessagePort, Worker, receiveMessageOnPort } from "node:worker_threads";
2
2
  import { EventEmitterAsyncResource, once } from "node:events";
3
3
  import { AsyncResource } from "node:async_hooks";
4
- import { URL, fileURLToPath } from "node:url";
5
- import { join } from "node:path";
4
+ import { URL as external_node_url_URL, fileURLToPath } from "node:url";
6
5
  import { inspect, types } from "node:util";
7
6
  import node_assert from "node:assert";
8
7
  import { performance } from "node:perf_hooks";
9
8
  import { readFileSync } from "node:fs";
10
- import node_os from "node:os";
11
- import node_child_process, { fork } from "node:child_process";
9
+ import { availableParallelism } from "node:os";
10
+ import { fork } from "node:child_process";
12
11
  const kMovable = Symbol("Tinypool.kMovable");
13
12
  const kTransferable = Symbol.for("Tinypool.transferable");
14
13
  const kValue = Symbol.for("Tinypool.valueOf");
@@ -27,42 +26,9 @@ function markMovable(value) {
27
26
  value: true
28
27
  });
29
28
  }
30
- function exec(command) {
31
- const output = node_child_process.execSync(command, {
32
- encoding: "utf8",
33
- stdio: [
34
- null,
35
- null,
36
- null
37
- ]
38
- });
39
- return output;
40
- }
41
- let amount;
42
- try {
43
- const platform = node_os.platform();
44
- if ("linux" === platform) {
45
- const output1 = exec("cat /proc/cpuinfo | grep \"physical id\" | sort |uniq | wc -l");
46
- const output2 = exec("cat /proc/cpuinfo | grep \"core id\" | sort | uniq | wc -l");
47
- const physicalCpuAmount = parseInt(output1.trim(), 10);
48
- const physicalCoreAmount = parseInt(output2.trim(), 10);
49
- amount = physicalCpuAmount * physicalCoreAmount;
50
- } else if ("darwin" === platform) {
51
- const output = exec("sysctl -n hw.physicalcpu_max");
52
- amount = parseInt(output.trim(), 10);
53
- } else if ("win32" === platform) throw new Error();
54
- else {
55
- const cores = node_os.cpus().filter(function(cpu, index) {
56
- const hasHyperthreading = cpu.model.includes("Intel");
57
- const isOdd = index % 2 === 1;
58
- return !hasHyperthreading || isOdd;
59
- });
60
- amount = cores.length;
61
- }
62
- } catch {
63
- amount = node_os.cpus().length;
29
+ function withNullPrototype(source) {
30
+ return Object.assign(Object.create(null), source);
64
31
  }
65
- if (0 === amount) amount = node_os.cpus().length;
66
32
  var ThreadWorker = class {
67
33
  name = "ThreadWorker";
68
34
  runtime = "worker_threads";
@@ -194,7 +160,7 @@ var ProcessWorker = class {
194
160
  function hasUnref(stream) {
195
161
  return null != stream && "unref" in stream && "function" == typeof stream.unref;
196
162
  }
197
- const cpuCount = amount;
163
+ const cpuCount = availableParallelism();
198
164
  function onabort(abortSignal, listener) {
199
165
  if ("addEventListener" in abortSignal) abortSignal.addEventListener("abort", listener, {
200
166
  once: true
@@ -285,7 +251,8 @@ var ArrayBufferViewTransferable = class {
285
251
  };
286
252
  let taskIdCounter = 0;
287
253
  function maybeFileURLToPath(filename) {
288
- return filename.startsWith("file:") ? fileURLToPath(new URL(filename)) : filename;
254
+ if ("string" != typeof filename) return "file:" === filename.protocol ? fileURLToPath(filename) : filename.href;
255
+ return filename.startsWith("file:") ? fileURLToPath(new external_node_url_URL(filename)) : filename;
289
256
  }
290
257
  var TaskInfo = class extends AsyncResource {
291
258
  abortListener = null;
@@ -508,12 +475,12 @@ var ThreadPool = class {
508
475
  this.publicInterface = publicInterface;
509
476
  this.taskQueue = options.taskQueue || new ArrayTaskQueue();
510
477
  const filename = options.filename ? maybeFileURLToPath(options.filename) : null;
511
- this.options = {
478
+ this.options = withNullPrototype({
512
479
  ...kDefaultOptions,
513
480
  ...options,
514
481
  filename,
515
482
  maxQueue: 0
516
- };
483
+ });
517
484
  if (void 0 !== options.maxThreads && this.options.minThreads >= options.maxThreads) this.options.minThreads = options.maxThreads;
518
485
  if (void 0 !== options.minThreads && this.options.maxThreads <= options.minThreads) this.options.maxThreads = options.minThreads;
519
486
  if ("auto" === options.maxQueue) this.options.maxQueue = this.options.maxThreads ** 2;
@@ -559,7 +526,8 @@ var ThreadPool = class {
559
526
  tinypoolPrivateData,
560
527
  this.options.workerData
561
528
  ],
562
- trackUnmanagedFds: this.options.trackUnmanagedFds
529
+ trackUnmanagedFds: this.options.trackUnmanagedFds,
530
+ serialization: this.options.serialization
563
531
  });
564
532
  const onMessage = (message$1)=>{
565
533
  const { taskId, result } = message$1;
@@ -649,7 +617,7 @@ var ThreadPool = class {
649
617
  const { transferList = [], signal = null, channel } = options;
650
618
  if (null == filename) filename = this.options.filename;
651
619
  if (null == name) name = this.options.name;
652
- if ("string" != typeof filename) return Promise.reject(Errors.FilenameNotProvided());
620
+ if ("string" != typeof filename && !(filename instanceof external_node_url_URL)) return Promise.reject(Errors.FilenameNotProvided());
653
621
  filename = maybeFileURLToPath(filename);
654
622
  let resolve;
655
623
  let reject;
@@ -731,7 +699,8 @@ var ThreadPool = class {
731
699
  }
732
700
  await Promise.all(exitEvents);
733
701
  }
734
- async recycleWorkers(options = {}) {
702
+ async recycleWorkers(_options = {}) {
703
+ const options = withNullPrototype(_options);
735
704
  const runtimeChanged = options?.runtime && options.runtime !== this.options.runtime;
736
705
  if (options?.runtime) this.options.runtime = options.runtime;
737
706
  if (this.options.isolateWorkers && !runtimeChanged) return;
@@ -748,7 +717,8 @@ var ThreadPool = class {
748
717
  };
749
718
  var Tinypool = class extends EventEmitterAsyncResource {
750
719
  #pool;
751
- constructor(options = {}){
720
+ constructor(_options = {}){
721
+ const options = withNullPrototype(_options);
752
722
  if (void 0 !== options.minThreads && options.minThreads > 0 && options.minThreads < 1) options.minThreads = Math.max(1, Math.floor(options.minThreads * cpuCount));
753
723
  if (void 0 !== options.maxThreads && options.maxThreads > 0 && options.maxThreads < 1) options.maxThreads = Math.max(1, Math.floor(options.maxThreads * cpuCount));
754
724
  super({
@@ -759,7 +729,7 @@ var Tinypool = class extends EventEmitterAsyncResource {
759
729
  this.#pool = new ThreadPool(this, options);
760
730
  }
761
731
  run(task, options = kDefaultRunOptions) {
762
- const { transferList, filename, name, signal, runtime, channel } = options;
732
+ const { transferList, filename, name, signal, runtime, channel } = withNullPrototype(options);
763
733
  return this.#pool.runTask(task, {
764
734
  transferList,
765
735
  filename,
@@ -805,7 +775,7 @@ var Tinypool = class extends EventEmitterAsyncResource {
805
775
  return process.__tinypool_state__?.workerData || void 0;
806
776
  }
807
777
  static get version() {
808
- const { version } = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
778
+ const { version } = JSON.parse(readFileSync(new URL("./static/assets/package.json", import.meta.url), "utf-8"));
809
779
  return version;
810
780
  }
811
781
  static move(val) {
package/dist/tu~0.js ADDED
@@ -0,0 +1,3 @@
1
+ export { stat } from "node:fs/promises";
2
+ export { withBase, withSiteOrigin } from "@rspress/shared";
3
+ export { logger } from "@rspress/shared/logger";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "2.0.22",
3
+ "version": "2.1.0-beta.1",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -60,8 +60,9 @@
60
60
  "dependencies": {
61
61
  "@mdx-js/mdx": "^3.1.1",
62
62
  "@mdx-js/react": "^3.1.1",
63
- "@rsbuild/core": "^2.2.5",
64
- "@rsbuild/plugin-react": "~2.1.0",
63
+ "@rsbuild/core": "^2.2.12",
64
+ "@rsbuild/plugin-react": "~2.1.1",
65
+ "@rspress/shared": "2.1.0-beta.1",
65
66
  "@shikijs/rehype": "^4.2.0",
66
67
  "@types/mdast": "^4.0.4",
67
68
  "@types/react": "^19.2.18",
@@ -80,10 +81,10 @@
80
81
  "react-dom": "^19.2.8",
81
82
  "react-lazy-with-preload": "^2.2.1",
82
83
  "react-render-to-markdown": "19.1.0",
83
- "react-router-dom": "^7.18.3",
84
+ "react-router-dom": "^7.18.4",
84
85
  "rehype-external-links": "^3.0.0",
85
86
  "rehype-raw": "^7.0.0",
86
- "remark-cjk-friendly": "^2.3.1",
87
+ "remark-cjk-friendly": "^2.3.2",
87
88
  "remark-cjk-friendly-gfm-strikethrough": "^2.3.1",
88
89
  "remark-gfm": "^4.0.1",
89
90
  "remark-mdx": "^3.1.1",
@@ -94,35 +95,34 @@
94
95
  "unified": "^11.0.5",
95
96
  "unist-util-visit": "^5.1.0",
96
97
  "unist-util-visit-children": "^3.0.0",
97
- "vfile": "^6.0.3",
98
- "@rspress/shared": "2.0.22"
98
+ "vfile": "^6.0.3"
99
99
  },
100
100
  "devDependencies": {
101
- "@microsoft/api-extractor": "^7.59.0",
101
+ "@microsoft/api-extractor": "^7.59.4",
102
102
  "@rsbuild/plugin-sass": "~2.0.1",
103
103
  "@rsbuild/plugin-svgr": "^2.0.5",
104
+ "@rspress/config": "1.0.0",
104
105
  "@types/body-scroll-lock": "^3.1.2",
105
106
  "@types/hast": "^3.0.5",
106
107
  "@types/node": "^22.8.1",
107
108
  "@types/nprogress": "^0.2.3",
108
109
  "@types/react-dom": "^19.2.7",
109
- "@types/web": "^0.0.355",
110
- "cac": "^7.0.0",
110
+ "@types/web": "^0.0.358",
111
+ "cac": "^7.0.1",
111
112
  "execa": "8.0.1",
112
- "mdast-util-directive": "^3.1.0",
113
+ "mdast-util-directive": "^3.1.1",
113
114
  "mdast-util-mdx-expression": "^2.0.1",
114
- "memfs": "^4.78.0",
115
- "p-map": "^7.0.7",
115
+ "memfs": "^4.80.0",
116
+ "p-map": "^7.0.8",
116
117
  "picocolors": "^1.1.1",
117
- "postcss": "8.5.28",
118
+ "postcss": "8.5.29",
118
119
  "remark-directive": "^4.0.0",
119
120
  "rsbuild-plugin-publint": "^1.0.0",
120
121
  "rsbuild-plugin-virtual-module": "0.4.5",
121
122
  "tinyglobby": "^0.2.17",
122
- "tinypool": "^1.1.1",
123
+ "tinypool": "^2.2.0",
123
124
  "ts-json-schema-generator": "^2.9.0",
124
- "typescript": "^6.0.3",
125
- "@rspress/config": "1.0.0"
125
+ "typescript": "^6.0.3"
126
126
  },
127
127
  "engines": {
128
128
  "node": "^20.19.0 || >=22.12.0"