@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
package/bin/rspress.js CHANGED
@@ -4,7 +4,9 @@ import nodeModule from 'node:module';
4
4
  // enable on-disk code caching of all modules loaded by Node.js
5
5
  // requires Nodejs >= 22.8.0
6
6
  const { enableCompileCache } = nodeModule;
7
- if (enableCompileCache) {
7
+ const isCI = Boolean(process.env.CI) && process.env.CI !== 'false';
8
+ // Skip CI, where the cache is unlikely to be reused.
9
+ if (enableCompileCache && !isCI) {
8
10
  try {
9
11
  enableCompileCache();
10
12
  } catch {
@@ -1,6 +1,4 @@
1
- var package_namespaceObject = {
2
- rE: "2.0.22"
3
- };
1
+ var package_namespaceObject = /*#__PURE__*/ JSON.parse('{"rE":"2.1.0-beta.1"}');
4
2
  async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
5
3
  return new Promise((resolve_, reject_)=>{
6
4
  if (void 0 === iterable[Symbol.iterator] && void 0 === iterable[Symbol.asyncIterator]) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
@@ -14,7 +12,7 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
14
12
  let isIterableDone = false;
15
13
  let resolvingCount = 0;
16
14
  let currentIndex = 0;
17
- const iterator = void 0 === iterable[Symbol.iterator] ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
15
+ const iterator = void 0 === iterable[Symbol.asyncIterator] ? iterable[Symbol.iterator]() : iterable[Symbol.asyncIterator]();
18
16
  const signalListener = ()=>{
19
17
  reject(signal.reason);
20
18
  };
@@ -26,10 +24,12 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
26
24
  cleanup();
27
25
  };
28
26
  const reject = (reason)=>{
27
+ if (isResolved) return;
29
28
  isRejected = true;
30
29
  isResolved = true;
31
30
  reject_(reason);
32
31
  cleanup();
32
+ if (!isIterableDone) closeIterator(iterator);
33
33
  };
34
34
  if (signal) {
35
35
  if (signal.aborted) return void reject(signal.reason);
@@ -39,7 +39,9 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
39
39
  }
40
40
  const next = async ()=>{
41
41
  if (isResolved) return;
42
- const nextItem = await iterator.next();
42
+ const nextItem = isIterableDone ? {
43
+ done: true
44
+ } : await iterator.next();
43
45
  const index = currentIndex;
44
46
  currentIndex++;
45
47
  if (nextItem.done) {
@@ -62,19 +64,15 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
62
64
  const value = await mapper(element, index);
63
65
  if (value === pMapSkip) skippedIndexesMap.set(index, value);
64
66
  result[index] = value;
65
- resolvingCount--;
67
+ } catch (error) {
68
+ if (stopOnError) return void reject(error);
69
+ errors.push(error);
70
+ }
71
+ resolvingCount--;
72
+ try {
66
73
  await next();
67
74
  } catch (error) {
68
- if (stopOnError) reject(error);
69
- else {
70
- errors.push(error);
71
- resolvingCount--;
72
- try {
73
- await next();
74
- } catch (error) {
75
- reject(error);
76
- }
77
- }
75
+ reject(error);
78
76
  }
79
77
  })();
80
78
  };
@@ -92,6 +90,11 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
92
90
  });
93
91
  }
94
92
  const pMapSkip = Symbol('skip');
93
+ async function closeIterator(iterator) {
94
+ try {
95
+ await iterator.return?.();
96
+ } catch {}
97
+ }
95
98
  export { getDefaultDarkModeValue, isDarkModeSwitchEnabled } from "@rspress/shared";
96
99
  export { createRequire } from "node:module";
97
100
  export { default as node_path, isAbsolute, posix, relative, resolve as external_node_path_resolve } from "node:path";
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { logger, cac } from "../o~0.js";
2
- import { package_namespaceObject } from "../v~0.js";
1
+ import { logger, cac } from "../h~0.js";
2
+ import { package_namespaceObject } from "../b~0.js";
3
3
  import { loadConfigFile, resolveDocRoot } from "../config/loadConfigFile.js";
4
4
  import { dev } from "../node/dev.js";
5
5
  import { build } from "../node/build.js";
@@ -16,10 +16,13 @@ function markMovable(value) {
16
16
  value: true
17
17
  });
18
18
  }
19
+ function withNullPrototype(source) {
20
+ return Object.assign(Object.create(null), source);
21
+ }
19
22
  function isTaskQueue(value) {
20
23
  return "object" == typeof value && null !== value && "size" in value && "function" == typeof value.shift && "function" == typeof value.remove && "function" == typeof value.push;
21
24
  }
22
25
  const kRequestCountField = 0;
23
26
  const kResponseCountField = 1;
24
27
  const kFieldCount = 2;
25
- export { isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable };
28
+ export { isMovable, isTaskQueue, isTransferable, kFieldCount, kQueueOptions, kRequestCountField, kResponseCountField, kTransferable, kValue, markMovable, withNullPrototype };
@@ -1,4 +1,4 @@
1
- import { node_path, logger, DEFAULT_CONFIG_NAME, DEFAULT_CONFIG_EXTENSIONS } from "../o~0.js";
1
+ import { node_path, logger, DEFAULT_CONFIG_NAME, DEFAULT_CONFIG_EXTENSIONS } from "../h~0.js";
2
2
  async function loadConfigFile(customConfigFile) {
3
3
  const { loadConfig } = await import("@rsbuild/core");
4
4
  const result = await loadConfig({
@@ -1,4 +1,5 @@
1
1
  import { cleanUrl, isExternalUrl } from '@rspress/shared';
2
+ // eslint-disable-next-line no-restricted-imports -- Existing cross-directory dependency; retained until this component is eject-safe.
2
3
  import { cleanUrlByConfig, removeBase, withBase } from '../../../runtime/utils';
3
4
 
4
5
  type LinkType = 'external' | 'hashOnly' | 'relative' | 'internal';
@@ -1,6 +1,5 @@
1
1
  import { preloadLink } from '@rspress/core/runtime';
2
2
  import clsx from 'clsx';
3
- import nprogress from 'nprogress';
4
3
  import type React from 'react';
5
4
  import type { ComponentProps, TransitionStartFunction } from 'react';
6
5
  import { forwardRef } from 'react';
@@ -35,8 +34,6 @@ export interface LinkProps extends ComponentProps<'a'> {
35
34
  startTransition?: TransitionStartFunction;
36
35
  }
37
36
 
38
- nprogress.configure({ showSpinner: false });
39
-
40
37
  /**
41
38
  * What's the difference between <Link> and <a>?
42
39
  * Link can tell whether it's in current site or external site.
@@ -1,35 +1,24 @@
1
1
  import {
2
- initPageData,
3
2
  isActive,
4
3
  pathnameToRouteService,
5
4
  useLocation,
6
- useNavigate as useNavigateInner,
5
+ useNavigate,
7
6
  useSite,
8
- warmPageData,
9
7
  } from '@rspress/core/runtime';
10
- import nprogress from 'nprogress';
11
- import {
12
- startTransition as reactStartTransition,
13
- type TransitionStartFunction,
14
- useCallback,
15
- } from 'react';
8
+ import { type TransitionStartFunction, useCallback } from 'react';
16
9
  import { getHref } from './getHref';
17
10
 
18
- nprogress.configure({ showSpinner: false });
19
-
20
11
  /**
21
- * For import { Link } from '@rspress/core/theme';
22
- * useNavigate with preload logic
12
+ * Navigate with Rspress link normalization. The router loader handles page
13
+ * loading for both this helper and the native useNavigate hook.
23
14
  */
24
- export function useLinkNavigate(
25
- {
26
- startTransition = reactStartTransition,
27
- }: { startTransition?: TransitionStartFunction } = {
28
- startTransition: reactStartTransition,
29
- },
30
- ): (href: string) => Promise<void> {
31
- const { pathname: currPagePathname } = useLocation();
32
- const navigate = useNavigateInner();
15
+ export function useLinkNavigate({
16
+ startTransition,
17
+ }: { startTransition?: TransitionStartFunction } = {}): (
18
+ href: string,
19
+ ) => Promise<void> {
20
+ const { pathname } = useLocation();
21
+ const navigate = useNavigate();
33
22
  const { site } = useSite();
34
23
  const useTransitions = site?.route?.useTransitions;
35
24
 
@@ -41,41 +30,27 @@ export function useLinkNavigate(
41
30
  window.location.assign(href);
42
31
  return;
43
32
  }
33
+ // Keep same-page links client-side, including on a 404 page, so clicking
34
+ // a parent menu link does not reload the document and close its submenu.
35
+ if (
36
+ !isActive(removeBaseHref, pathname) &&
37
+ !pathnameToRouteService(routePath)
38
+ ) {
39
+ window.location.assign(withBaseHref);
40
+ return;
41
+ }
44
42
 
45
- const isTransitionable = !!(useTransitions && startTransition);
46
- const preloadChunkThenNavigate = async () => {
47
- const inCurrPage = isActive(removeBaseHref, currPagePathname);
48
-
49
- if (!import.meta.env.SSR && !inCurrPage) {
50
- const matchedRoute = pathnameToRouteService(routePath);
51
- if (matchedRoute) {
52
- const timer = setTimeout(() => {
53
- nprogress.start();
54
- }, 200);
55
- const data = await initPageData(routePath);
56
- warmPageData(routePath, data);
57
- clearTimeout(timer);
58
- nprogress.done();
59
- } else {
60
- window.location.assign(withBaseHref);
61
- return;
62
- }
63
- }
64
- if (isTransitionable) {
65
- startTransition(() => {
66
- return navigate(removeBaseHref, { replace: false });
67
- });
68
- } else {
69
- navigate(removeBaseHref, { replace: false });
70
- }
71
- };
72
-
73
- if (isTransitionable) {
74
- startTransition(preloadChunkThenNavigate);
43
+ if (useTransitions && startTransition) {
44
+ let navigation: void | Promise<void> = undefined;
45
+ startTransition(() => {
46
+ navigation = navigate(removeBaseHref);
47
+ return navigation;
48
+ });
49
+ await navigation;
75
50
  } else {
76
- preloadChunkThenNavigate();
51
+ await navigate(removeBaseHref);
77
52
  }
78
53
  },
79
- [useTransitions, currPagePathname, navigate, startTransition],
54
+ [useTransitions, pathname, navigate, startTransition],
80
55
  );
81
56
  }
@@ -1,4 +1,4 @@
1
- import { Head, useI18n } from '@rspress/core/runtime';
1
+ import { Head, useI18n, useSearchHooks } from '@rspress/core/runtime';
2
2
  import {
3
3
  IconClose,
4
4
  IconSearch,
@@ -9,7 +9,7 @@ import {
9
9
  } from '@rspress/core/theme';
10
10
  import { useEffect, useRef, useState } from 'react';
11
11
  import { createPortal } from 'react-dom';
12
- import * as userSearchHooks from 'virtual-search-hooks';
12
+
13
13
  import type {
14
14
  DefaultMatchResult,
15
15
  DefaultMatchResultItem,
@@ -99,6 +99,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
99
99
  }
100
100
  };
101
101
  const t = useI18n();
102
+ const userSearchHooks = useSearchHooks();
102
103
  const navigate = useLinkNavigate();
103
104
 
104
105
  const {
@@ -182,6 +183,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
182
183
  return;
183
184
  }
184
185
  if (
186
+ focused &&
185
187
  currentSuggestionIndex >= 0 &&
186
188
  currentRenderType === RenderType.Default
187
189
  ) {
@@ -190,8 +192,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
190
192
  normalizeSuggestions(currentSuggestions).values(),
191
193
  ).flat();
192
194
  const suggestion = flatSuggestions[currentSuggestionIndex];
193
- navigate(suggestion.link);
194
- clearSearchState();
195
+ if (suggestion) {
196
+ navigate(suggestion.link);
197
+ clearSearchState();
198
+ }
195
199
  }
196
200
  break;
197
201
  case KEY_CODE.ESC:
@@ -242,7 +246,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
242
246
  {item.renderType === RenderType.Default &&
243
247
  renderSearchResultItem(item.result)}
244
248
  {item.renderType === RenderType.Custom &&
245
- userSearchHooks[renderKey](item.result)}
249
+ userSearchHooks[renderKey]?.(item.result)}
246
250
  </Tab>
247
251
  ))}
248
252
  </Tabs>
@@ -15,7 +15,7 @@ import {
15
15
  type DocumentValue,
16
16
  type EnrichedDocumentSearchResults,
17
17
  } from 'flexsearch';
18
- import { searchIndexHash } from 'virtual-page-data';
18
+ import { searchIndexHash } from '@rspress/core/runtime';
19
19
  import { LOCAL_INDEX, type Provider, type SearchQuery } from '../Provider';
20
20
  import type { SearchOptions } from '../types';
21
21
  import { normalizeTextCase } from '../util';
@@ -124,7 +124,10 @@ export class LocalProvider implements Provider {
124
124
  this.#fetchPromise = this.#getPages(
125
125
  currentLang,
126
126
  versioned ? currentVersion : '',
127
- );
127
+ ).catch(error => {
128
+ this.#fetchPromise = undefined;
129
+ throw error;
130
+ });
128
131
 
129
132
  return this.#fetchPromise;
130
133
  }
@@ -1,4 +1,4 @@
1
- import { usePageData } from '@rspress/core/runtime';
1
+ import { usePageData, useSearchHooks, useWebMcp } from '@rspress/core/runtime';
2
2
  import type { LocalSearchOptions } from '@rspress/core';
3
3
  import { debounce } from '@rspress/shared/lodash-es';
4
4
  import {
@@ -8,7 +8,7 @@ import {
8
8
  useState,
9
9
  type RefObject,
10
10
  } from 'react';
11
- import * as userSearchHooks from 'virtual-search-hooks';
11
+
12
12
  import { getSearchIndexURL } from './logic/providers/LocalProvider';
13
13
  import { PageSearcher } from './logic/search';
14
14
  import type {
@@ -18,6 +18,12 @@ import type {
18
18
  PageSearcherConfig,
19
19
  } from './logic/types';
20
20
  import { RenderType } from './logic/types';
21
+ // eslint-disable-next-line no-restricted-imports -- Existing cross-directory dependency; retained until this component is eject-safe.
22
+ import {
23
+ defineTool,
24
+ queryField,
25
+ toWebMcpSearchResults,
26
+ } from '../../webMcp/tools';
21
27
 
22
28
  const useDebounce = <T extends (...args: any[]) => any>(cb: T) => {
23
29
  const cbRef = useRef(cb);
@@ -42,6 +48,7 @@ export function useSearchPanel({
42
48
  siteData,
43
49
  page: { lang, version },
44
50
  } = usePageData();
51
+ const userSearchHooks = useSearchHooks();
45
52
  const { search, title: siteTitle } = siteData;
46
53
  const [query, setQuery] = useState('');
47
54
  const [searchResult, setSearchResult] = useState<MatchResult>([]);
@@ -54,6 +61,10 @@ export function useSearchPanel({
54
61
  const [searchError, setSearchError] = useState<string>();
55
62
  const pageSearcherRef = useRef<PageSearcher | null>(null);
56
63
  const pageSearcherConfigRef = useRef<PageSearcherConfig | null>(null);
64
+ const pageSearcherURLRef = useRef<string | undefined>(undefined);
65
+ const initializationRef = useRef<
66
+ { searcher: PageSearcher; promise: Promise<void> } | undefined
67
+ >(undefined);
57
68
  const searchEnabled = search !== false;
58
69
  const searchOptions: LocalSearchOptions = search === false ? {} : search;
59
70
  const versionedSearch = searchEnabled && (search?.versioned ?? true);
@@ -65,7 +76,13 @@ export function useSearchPanel({
65
76
  ];
66
77
 
67
78
  const createSearcher = () => {
68
- if (pageSearcherRef.current) {
79
+ const previous = pageSearcherConfigRef.current;
80
+ if (
81
+ pageSearcherRef.current &&
82
+ previous?.currentLang === lang &&
83
+ (!versionedSearch || previous.currentVersion === version) &&
84
+ pageSearcherURLRef.current === searchIndexURL
85
+ ) {
69
86
  return pageSearcherRef.current;
70
87
  }
71
88
  const pageSearcherConfig = { currentLang: lang, currentVersion: version };
@@ -76,9 +93,75 @@ export function useSearchPanel({
76
93
  });
77
94
  pageSearcherRef.current = pageSearcher;
78
95
  pageSearcherConfigRef.current = pageSearcherConfig;
96
+ pageSearcherURLRef.current = searchIndexURL;
79
97
  return pageSearcher;
80
98
  };
81
99
 
100
+ // UI searches and agent calls initialize the same provider once, on demand.
101
+ const initializeSearcher = (searcher: PageSearcher) => {
102
+ if (initializationRef.current?.searcher === searcher)
103
+ return initializationRef.current.promise;
104
+ const promise = searcher.init().catch(error => {
105
+ if (initializationRef.current?.searcher === searcher)
106
+ initializationRef.current = undefined;
107
+ throw error;
108
+ });
109
+ initializationRef.current = { searcher, promise };
110
+ return promise;
111
+ };
112
+
113
+ const searchDocs = async (value: string, limit?: number) => {
114
+ const searcher = createSearcher();
115
+ let newQuery = value;
116
+ const result: MatchResult = [];
117
+ if (userSearchHooks.beforeSearch) {
118
+ const transformedQuery = await userSearchHooks.beforeSearch(newQuery);
119
+ if (transformedQuery) newQuery = transformedQuery;
120
+ }
121
+ await initializeSearcher(searcher);
122
+ const defaultSearchResult = await searcher.match(newQuery, limit);
123
+ result.push(...defaultSearchResult);
124
+ if (userSearchHooks.onSearch) {
125
+ const customSearchResult = await userSearchHooks.onSearch(
126
+ newQuery,
127
+ result as DefaultMatchResult[],
128
+ );
129
+ if (customSearchResult)
130
+ result.push(
131
+ ...customSearchResult.map(
132
+ item =>
133
+ ({ renderType: RenderType.Custom, ...item }) as CustomMatchResult,
134
+ ),
135
+ );
136
+ }
137
+ await userSearchHooks.afterSearch?.(newQuery, result);
138
+ return result;
139
+ };
140
+
141
+ // Build-time gating keeps tool code out of sites that do not enable WebMCP.
142
+ if (import.meta.env.ENABLE_WEBMCP) {
143
+ useWebMcp({
144
+ ...defineTool(
145
+ 'search_docs',
146
+ 'Search documentation through the active local search component.',
147
+ {
148
+ query: queryField,
149
+ limit: { type: 'integer', minimum: 1, maximum: 20 },
150
+ },
151
+ ['query'],
152
+ async args =>
153
+ toWebMcpSearchResults(
154
+ await searchDocs(
155
+ args.query as string,
156
+ (args.limit as number | undefined) ?? 10,
157
+ ),
158
+ ),
159
+ ),
160
+ enabled:
161
+ searchEnabled && Boolean(searchIndexURL || userSearchHooks.onSearch),
162
+ });
163
+ }
164
+
82
165
  const initSearch = async () => {
83
166
  if (initStatus !== 'initial') {
84
167
  return;
@@ -87,7 +170,7 @@ export function useSearchPanel({
87
170
  setSearchError(undefined);
88
171
  setInitStatus('initing');
89
172
  try {
90
- await searcher.init();
173
+ await initializeSearcher(searcher);
91
174
  } catch (error) {
92
175
  if (pageSearcherRef.current !== searcher) {
93
176
  return;
@@ -134,52 +217,37 @@ export function useSearchPanel({
134
217
  const { currentLang, currentVersion } = pageSearcherConfigRef.current ?? {};
135
218
  const isLangChanged = lang !== currentLang;
136
219
  const isVersionChanged = versionedSearch && version !== currentVersion;
137
- if (isLangChanged || isVersionChanged) {
220
+ const isIndexChanged = pageSearcherURLRef.current !== searchIndexURL;
221
+ if (isLangChanged || isVersionChanged || isIndexChanged) {
138
222
  setInitStatus('initial');
139
223
  setSearchError(undefined);
140
224
  setIsSearching(false);
141
225
  pageSearcherRef.current = null;
142
- createSearcher()
143
- .fetchSearchIndex()
144
- .catch(() => {});
145
226
  }
146
- }, [lang, version, versionedSearch, searchEnabled]);
227
+ }, [lang, version, versionedSearch, searchEnabled, searchIndexURL]);
147
228
 
148
229
  const handleQueryChangedImpl = async (value: string) => {
149
- let newQuery = value;
230
+ const newQuery = value;
150
231
  setQuery(newQuery);
151
232
  if (!newQuery) {
152
233
  setIsSearching(false);
153
234
  return;
154
235
  }
155
- const result: MatchResult = [];
156
- if ('beforeSearch' in userSearchHooks) {
157
- const transformedQuery = await userSearchHooks.beforeSearch(newQuery);
158
- if (transformedQuery) newQuery = transformedQuery;
159
- }
160
- const defaultSearchResult = await pageSearcherRef.current?.match(newQuery);
161
- if (defaultSearchResult) result.push(...defaultSearchResult);
162
- if ('onSearch' in userSearchHooks) {
163
- const customSearchResult = await userSearchHooks.onSearch(
164
- newQuery,
165
- result as DefaultMatchResult[],
166
- );
167
- if (customSearchResult) {
168
- result.push(
169
- ...customSearchResult.map(
170
- item =>
171
- ({ renderType: RenderType.Custom, ...item }) as CustomMatchResult,
172
- ),
173
- );
236
+ try {
237
+ const result = await searchDocs(value);
238
+ if (searchInputRef.current?.value === newQuery) {
239
+ setSearchError(undefined);
240
+ setInitStatus('inited');
241
+ setCurrentSuggestionIndex(0);
242
+ setSearchResult(result || DEFAULT_RESULT);
243
+ setIsSearching(false);
244
+ }
245
+ } catch (error) {
246
+ if (searchInputRef.current?.value === newQuery) {
247
+ setSearchError(error instanceof Error ? error.message : String(error));
248
+ setInitStatus('error');
249
+ setIsSearching(false);
174
250
  }
175
- }
176
- if ('afterSearch' in userSearchHooks) {
177
- await userSearchHooks.afterSearch(newQuery, result);
178
- }
179
- if (searchInputRef.current?.value === newQuery) {
180
- setCurrentSuggestionIndex(0);
181
- setSearchResult(result || DEFAULT_RESULT);
182
- setIsSearching(false);
183
251
  }
184
252
  };
185
253
 
@@ -1,7 +1,10 @@
1
- import { afterEach, describe, expect, it } from '@rstest/core';
1
+ import { afterEach, describe, expect, it, rs } from '@rstest/core';
2
2
  import { renderToStaticMarkup } from 'react-dom/server';
3
+ import { useStorageValue } from '../../logic/useStorageValue';
3
4
  import { GithubStars } from './GithubStars';
4
5
 
6
+ rs.mock('@rspress/core/theme', () => ({ useStorageValue }));
7
+
5
8
  const originalLocalStorage = Object.getOwnPropertyDescriptor(
6
9
  globalThis,
7
10
  'localStorage',
@@ -1,5 +1,5 @@
1
+ import { useStorageValue } from '@rspress/core/theme';
1
2
  import { type ReactNode, useEffect, useState } from 'react';
2
- import { useStorageValue } from '../../logic/useStorageValue';
3
3
 
4
4
  const TTL_MS = 60 * 60 * 1000;
5
5
 
@@ -1,5 +1,5 @@
1
1
  import type { SocialLink as ISocialLink } from '@rspress/core';
2
- import iconMap from 'virtual-social-links';
2
+ import { socialLinks } from '@rspress/core/runtime';
3
3
  import './index.scss';
4
4
  import { GithubStars } from './GithubStars';
5
5
  import { useHoverGroup } from '../HoverGroup/useHoverGroup';
@@ -18,7 +18,7 @@ export const SocialLink = (props: SocialLinkProps) => {
18
18
 
19
19
  let IconComp: React.ReactElement = <></>;
20
20
  if (icon) {
21
- const html = typeof icon === 'string' ? iconMap[icon] : icon.svg;
21
+ const html = typeof icon === 'string' ? socialLinks[icon] : icon.svg;
22
22
  IconComp = (
23
23
  <div
24
24
  className="rp-social-links__icon"
@@ -11,7 +11,7 @@ export function SourceCode(props: SourceCodeProps) {
11
11
  const { href, platform = 'github' } = props;
12
12
  const t = useI18n();
13
13
  return (
14
- <div className="rp-not-doc rp-source-code">
14
+ <div className="rp-not-doc rp-source-code rp-toc-exclude">
15
15
  <a href={href} target="_blank" className="rp-source-code__link">
16
16
  <span className="rp-source-code__icon">
17
17
  {
@@ -1,4 +1,4 @@
1
- import { isMovable, kRequestCountField, kResponseCountField, kTransferable, kValue } from "../common-Qw-RoVFD.js";
1
+ import { isMovable, kRequestCountField, kResponseCountField, kTransferable, kValue } from "../common-Bo3KCGim.js";
2
2
  import { stderr, stdout } from "../utils-De75vAgL.js";
3
3
  import { getHandler, throwInNextTick } from "../utils-B--2TaWv.js";
4
4
  import { parentPort, receiveMessageOnPort, workerData } from "node:worker_threads";