mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-25 01:33:41 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db88aeac4d | |||
| 4cbbda7fab | |||
| 63a4a98384 | |||
| 060f1f63ca | |||
| 7cee30ecb8 | |||
| a035d196f0 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Serve the published-docs MCP endpoint independently of the Connect with MCP page action.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published site search results visible while visitors refine a query.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published revision URLs out of search results.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Track the displayed position and search request ID when a visitor opens a search result.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Update the GitBook API SDK for site revision responses.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix wide content in Updates blocks overflowing into the page outline.
|
||||
@@ -357,7 +357,7 @@
|
||||
},
|
||||
"catalog": {
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.211.0",
|
||||
"@gitbook/api": "0.213.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
@@ -725,7 +725,7 @@
|
||||
|
||||
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
|
||||
|
||||
"@gitbook/api": ["@gitbook/api@0.211.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-G+rY2m7ZvyR1RA4oilarzrNDABDkYhARoIyfNCE5mYqZQgpgsLShn3rGgzTudO2iqwt/5iK6RcJc2enfj+37Jg=="],
|
||||
"@gitbook/api": ["@gitbook/api@0.213.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-c61/FejKsDJFjLuZVgKplQZm21VyVnC4ahX9NBleRVnYbiN8UJ9lijHCch2sEZ2lR9KM42pi5DVvaMKymli8eg=="],
|
||||
|
||||
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
|
||||
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.211.0",
|
||||
"@gitbook/api": "0.213.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
|
||||
@@ -442,6 +442,48 @@ const searchTestCases: Test[] = [
|
||||
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter opens the visible result while a new query loads',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
})}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
const searchPopup = page.getByTestId('search-popover');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
const initialSearch = await heldSearch('gitbook');
|
||||
const { siteSpaceId } = initialSearch.request().postDataJSON().scope;
|
||||
const topResult = searchPageResult(
|
||||
initialSearch,
|
||||
siteSpaceId,
|
||||
'Headings',
|
||||
'blocks/headings'
|
||||
);
|
||||
await initialSearch.fulfill({ json: [topResult] });
|
||||
const firstResult = searchPopup.getByTestId('search-page-result').first();
|
||||
await expect(firstResult).toHaveAttribute('href', topResult.href);
|
||||
|
||||
await searchInput.pressSequentially(' docs');
|
||||
const pendingSearch = await heldSearch('gitbook docs');
|
||||
await expect(searchPopup.locator('output[aria-busy="true"]')).toBeVisible();
|
||||
await expect(firstResult).toHaveAttribute('href', topResult.href);
|
||||
await expect(searchPopup.locator('[data-search-placeholder-row]')).toHaveCount(0);
|
||||
|
||||
await searchInput.press('Enter');
|
||||
await expect(searchPopup).toBeHidden();
|
||||
await expect
|
||||
.poll(() => new URL(page.url()).pathname)
|
||||
.toBe(new URL(topResult.href, page.url()).pathname);
|
||||
await pendingSearch.abort().catch(() => {});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter opens the result under the mouse',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
|
||||
+3
-1
@@ -14,7 +14,8 @@ const SEARCH_FALLBACK_REASON =
|
||||
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
|
||||
const { asEmbeddable, query, scope, searchId } =
|
||||
(await request.json()) as SearchSiteContentRequest;
|
||||
const [context, siteURLData] = await Promise.all([
|
||||
getServerActionBaseContext({ isEmbeddable: asEmbeddable }),
|
||||
getSiteURLDataFromMiddleware(),
|
||||
@@ -40,6 +41,7 @@ export async function POST(request: NextRequest) {
|
||||
siteId: siteURLData.site,
|
||||
query,
|
||||
scope,
|
||||
searchId,
|
||||
})
|
||||
),
|
||||
throwIfDataError(
|
||||
|
||||
@@ -75,7 +75,7 @@ export function Update(props: BlockProps<DocumentBlockUpdate>) {
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style="flex flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
style="flex min-w-0 flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
/>
|
||||
</FilteredUpdate>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { LinkContext } from '../primitives';
|
||||
import { useIsVisible } from '../VisibilityContext';
|
||||
@@ -37,9 +39,10 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
trackEvent({
|
||||
type: 'search_open',
|
||||
});
|
||||
trackEvent(
|
||||
{ type: 'search_open' },
|
||||
{ pageId: null, displayContext: SiteInsightsDisplayContext.Embed }
|
||||
);
|
||||
}, [trackEvent, isVisible]);
|
||||
|
||||
const tabsRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -56,6 +59,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -79,6 +83,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
|
||||
|
||||
const CONFIGURABLE_PAGE_ACTIONS = [
|
||||
CustomizationPageActionType.Assistant,
|
||||
@@ -29,8 +30,14 @@ export function isPageActionEnabled(
|
||||
* Whether any of the configured page actions is enabled. The RSS feed is not part of them: it is
|
||||
* only offered on pages with an updates block.
|
||||
*/
|
||||
export function hasConfiguredPageActions(customization: GitBookSiteContext['customization']) {
|
||||
return CONFIGURABLE_PAGE_ACTIONS.some((type) => isPageActionEnabled(customization, type));
|
||||
export function hasConfiguredPageActions(context: Pick<GitBookSiteContext, 'customization'>) {
|
||||
const { customization } = context;
|
||||
return CONFIGURABLE_PAGE_ACTIONS.some((type) => {
|
||||
if (type === CustomizationPageActionType.Mcp && !isSiteMcpEnabled(context)) {
|
||||
return false;
|
||||
}
|
||||
return isPageActionEnabled(customization, type);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { PageActionsDropdownURLs } from './PageActionsDropdown';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getPageDocument } from '@/lib/data';
|
||||
import { hasTopLevelBlock } from '@/lib/document';
|
||||
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
|
||||
import { hasAdaptiveMcpEndpoint, isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { getPageRSSURL } from '@/routes/rss';
|
||||
|
||||
/**
|
||||
@@ -51,7 +51,7 @@ export async function getPageActionsURLs(
|
||||
}).toString()}`
|
||||
)
|
||||
: undefined,
|
||||
mcp: getPageActionsMCPURL(context),
|
||||
mcp: isMcpPageActionEnabled(context) ? getPageActionsMCPURL(context) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -139,8 +139,7 @@ export async function PageHeader(props: {
|
||||
// Show page actions if *any* of the configured actions are enabled, or if the RSS feed is
|
||||
// available. RSS is contextual (only on update/blog index pages) and is not part of the
|
||||
// configured `items` list, so it is checked separately.
|
||||
const hasPageActions =
|
||||
pageActionsEnabled && (hasConfiguredPageActions(context.customization) || withRSSFeed);
|
||||
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions(context) || withRSSFeed);
|
||||
|
||||
if (!page.layout.title && !page.layout.description && !hasPageActions) {
|
||||
return null;
|
||||
|
||||
@@ -63,6 +63,7 @@ export function SearchContainer({
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -178,6 +179,7 @@ export function SearchContainer({
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -27,6 +27,7 @@ export function SearchFrame(props: {
|
||||
query: string;
|
||||
results: ResultType[];
|
||||
resultsId: string;
|
||||
resultsQuery: string;
|
||||
resultsRef: React.Ref<SearchResultsRef>;
|
||||
onResultSelect?: () => void;
|
||||
/** Select the result under the mouse, so hover and keyboard share one highlight. */
|
||||
@@ -50,6 +51,7 @@ export function SearchFrame(props: {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
onResultSelect,
|
||||
onResultHover,
|
||||
@@ -78,7 +80,7 @@ export function SearchFrame(props: {
|
||||
fetching ? 'block animate-fade-in' : 'hidden animate-fade-out-slow'
|
||||
)}
|
||||
style={{
|
||||
animationDelay: fetching ? '2s' : undefined,
|
||||
animationDelay: fetching && results.length === 0 ? '2s' : undefined,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -118,7 +120,7 @@ export function SearchFrame(props: {
|
||||
) : (
|
||||
<SearchResults
|
||||
ref={resultsRef}
|
||||
query={query}
|
||||
query={resultsQuery}
|
||||
id={resultsId}
|
||||
fetching={fetching}
|
||||
results={results}
|
||||
|
||||
@@ -135,7 +135,7 @@ export const SearchInput = React.forwardRef<HTMLDivElement, SearchInputProps>(
|
||||
}
|
||||
}
|
||||
trailing={
|
||||
!showAsk && value && resultsCount > 0 ? (
|
||||
!showAsk && !fetching && value && resultsCount > 0 ? (
|
||||
<div className="animate-blur-in mr-2 text-sm text-tint-subtle">
|
||||
{t(language, 'search_results_count', resultsCount.toString())}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useResizeObserver } from '../hooks';
|
||||
import { Tooltip } from '../primitives';
|
||||
import { getPageResultPresentation } from './getPageResultHref';
|
||||
import { HighlightQuery } from './HighlightQuery';
|
||||
import type { ComputedPageResult } from './search-types';
|
||||
import type { ComputedPageResult, SearchResultSource } from './search-types';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -14,13 +14,15 @@ import { tcls } from '@/lib/tailwind';
|
||||
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
|
||||
props: {
|
||||
query: string;
|
||||
item: ComputedPageResult;
|
||||
item: ComputedPageResult & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, style, ...rest } = props;
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const { preview: bestSection, description, href } = getPageResultPresentation(item);
|
||||
@@ -30,7 +32,9 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
|
||||
const insights = {
|
||||
type: 'search_open_result' as const,
|
||||
query,
|
||||
...item.search,
|
||||
position,
|
||||
resultsCount,
|
||||
result: {
|
||||
pageId: item.pageId,
|
||||
spaceId: item.spaceId,
|
||||
|
||||
@@ -4,24 +4,36 @@ import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { Favicon } from '../utils';
|
||||
import { HighlightQuery } from './HighlightQuery';
|
||||
import type { ComputedRecordResult } from './search-types';
|
||||
import type { ComputedRecordResult, SearchResultSource } from './search-types';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
|
||||
export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem(
|
||||
props: {
|
||||
query: string;
|
||||
item: ComputedRecordResult;
|
||||
item: ComputedRecordResult & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, style, ...rest } = props;
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const domain = getDomain(item.href);
|
||||
|
||||
const insights = {
|
||||
type: 'search_open_result' as const,
|
||||
...item.search,
|
||||
position,
|
||||
resultsCount,
|
||||
result: {
|
||||
recordId: item.id,
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<SearchResultItem
|
||||
ref={ref}
|
||||
@@ -36,13 +48,7 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
|
||||
fallback={<Icon icon="memo" className="size-4" />}
|
||||
/>
|
||||
}
|
||||
insights={{
|
||||
type: 'search_open_result',
|
||||
query,
|
||||
result: {
|
||||
recordId: item.id,
|
||||
},
|
||||
}}
|
||||
insights={insights}
|
||||
aria-label={tString(language, 'search_page_result_title', item.title)}
|
||||
style={{ ...style }}
|
||||
{...rest}
|
||||
|
||||
@@ -72,7 +72,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
|
||||
const language = useLanguage();
|
||||
const { siteSpaceId } = useCurrentContent();
|
||||
const shouldAnimateResults = !query || fetching;
|
||||
const shouldAnimateResults = !query;
|
||||
const previousCursor = React.useRef<number | null>(cursor);
|
||||
const seenResultKeys = React.useRef(new Set<string>());
|
||||
const lastQuery = React.useRef(query);
|
||||
@@ -228,9 +228,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
// users should keep their place in it.
|
||||
if (navigatesCurrentWindow(event)) {
|
||||
event.currentTarget.blur();
|
||||
onResultSelect?.();
|
||||
}
|
||||
|
||||
onResultSelect?.();
|
||||
};
|
||||
const resultItemProps = {
|
||||
'aria-posinset': index + 1,
|
||||
@@ -272,6 +271,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
}}
|
||||
query={query}
|
||||
item={item}
|
||||
position={index + 1}
|
||||
resultsCount={results.length}
|
||||
active={index === cursor}
|
||||
style={{
|
||||
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
|
||||
@@ -341,6 +342,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
key={itemKey}
|
||||
query={query}
|
||||
item={item}
|
||||
position={index + 1}
|
||||
resultsCount={results.length}
|
||||
active={index === cursor}
|
||||
style={{
|
||||
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
|
||||
@@ -359,15 +362,11 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
{!fetching && results.length === 0 ? noResults : null}
|
||||
</>
|
||||
)}
|
||||
{fetching ? (
|
||||
{fetching && results.length === 0 ? (
|
||||
<div
|
||||
role="status"
|
||||
aria-busy="true"
|
||||
className={tcls(
|
||||
results.length > 0 ? 'mt-1' : '',
|
||||
'flex flex-col gap-1',
|
||||
'animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] motion-reduce:animate-none'
|
||||
)}
|
||||
className="flex animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] flex-col gap-1 motion-reduce:animate-none"
|
||||
>
|
||||
<SearchResultsPlaceholder />
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import type { OrderedComputedResult } from './search-types';
|
||||
|
||||
describe('computeFilterSiteSpaceIds', () => {
|
||||
@@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterResultsBySiteSpaces', () => {
|
||||
describe('getDisplayedSearchResults', () => {
|
||||
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
|
||||
type: 'page',
|
||||
id,
|
||||
@@ -52,7 +52,7 @@ describe('filterResultsBySiteSpaces', () => {
|
||||
|
||||
it('keeps the server order and drops pages outside the scope', () => {
|
||||
const results = [page('a', 'current'), page('b', 'other'), page('c', 'current'), page('d')];
|
||||
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
|
||||
expect(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([
|
||||
'a',
|
||||
'c',
|
||||
]);
|
||||
@@ -60,6 +60,24 @@ describe('filterResultsBySiteSpaces', () => {
|
||||
|
||||
it('returns every result when the scope is unrestricted', () => {
|
||||
const results = [page('b', 'other'), page('a', 'current')];
|
||||
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
|
||||
expect(getDisplayedSearchResults(results, undefined)).toBe(results);
|
||||
});
|
||||
|
||||
it('caps the displayed list after applying the site space filter', () => {
|
||||
const pages = Array.from({ length: 10 }, (_, index) => page(`page-${index}`, 'current'));
|
||||
const records = Array.from({ length: 11 }, (_, index): OrderedComputedResult => ({
|
||||
type: 'record',
|
||||
id: `record-${index}`,
|
||||
title: `Record ${index}`,
|
||||
description: undefined,
|
||||
href: `/record-${index}`,
|
||||
score: 1,
|
||||
}));
|
||||
const results = [page('hidden', 'other'), ...pages, ...records];
|
||||
|
||||
expect(getDisplayedSearchResults(results, ['current'])).toEqual([
|
||||
...pages,
|
||||
...records.slice(0, 10),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { OrderedComputedResult } from './search-types';
|
||||
import type { SearchScope } from './useSearch';
|
||||
|
||||
// Keep aligned with SiteInsightsSearchResultNumber in the GitBook API schema.
|
||||
const MAX_DISPLAYED_SEARCH_RESULTS = 20;
|
||||
|
||||
/**
|
||||
* Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction.
|
||||
*
|
||||
@@ -29,20 +32,20 @@ export function computeFilterSiteSpaceIds(
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
|
||||
export function filterResultsBySiteSpaces(
|
||||
results: OrderedComputedResult[],
|
||||
/** Keep the first results in server order within the selected site spaces. */
|
||||
export function getDisplayedSearchResults<Result extends OrderedComputedResult>(
|
||||
results: Result[],
|
||||
allowedSiteSpaceIds: string[] | undefined
|
||||
): OrderedComputedResult[] {
|
||||
if (!allowedSiteSpaceIds) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const allowed = new Set(allowedSiteSpaceIds);
|
||||
|
||||
return results.filter(
|
||||
(result) =>
|
||||
result.type === 'record' ||
|
||||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
|
||||
);
|
||||
): Result[] {
|
||||
const allowed = allowedSiteSpaceIds && new Set(allowedSiteSpaceIds);
|
||||
const matching = allowed
|
||||
? results.filter(
|
||||
(result) =>
|
||||
result.type === 'record' ||
|
||||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
|
||||
)
|
||||
: results;
|
||||
return matching.length > MAX_DISPLAYED_SEARCH_RESULTS
|
||||
? matching.slice(0, MAX_DISPLAYED_SEARCH_RESULTS)
|
||||
: matching;
|
||||
}
|
||||
|
||||
@@ -124,11 +124,12 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
|
||||
const search = async (input: {
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope: SearchSiteContentScope;
|
||||
signal: AbortSignal;
|
||||
asEmbeddable: boolean;
|
||||
}): Promise<DirectSearchOutcome> => {
|
||||
const { query, scope, signal, asEmbeddable } = input;
|
||||
const { query, searchId, scope, signal, asEmbeddable } = input;
|
||||
if (!directSearch) {
|
||||
return { type: 'route' };
|
||||
}
|
||||
@@ -163,7 +164,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope)),
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
|
||||
credentials: 'omit',
|
||||
signal: request.signal,
|
||||
});
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { IconName } from '@gitbook/icons';
|
||||
|
||||
export type OrderedComputedResult = ComputedPageResult | ComputedRecordResult;
|
||||
|
||||
export type SearchResultSource = {
|
||||
search: { query: string; searchId: string | undefined };
|
||||
};
|
||||
|
||||
export type BaseComputedResult = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -55,6 +59,7 @@ export type SearchSiteContentScope =
|
||||
|
||||
export interface SearchSiteContentRequest {
|
||||
asEmbeddable?: boolean;
|
||||
searchId?: string;
|
||||
query: string;
|
||||
scope: SearchSiteContentScope;
|
||||
}
|
||||
|
||||
@@ -141,7 +141,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey: string;
|
||||
flush: () => void;
|
||||
resultsRef: React.RefObject<SearchResultsRef | null>;
|
||||
abort: () => void;
|
||||
askCount: number;
|
||||
onAskSelect: (index: number) => void;
|
||||
}) {
|
||||
@@ -154,7 +153,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect,
|
||||
} = props;
|
||||
@@ -190,8 +188,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
|
||||
if (resultsRef.current?.select()) {
|
||||
// Stop any in-flight search request only when activating a result.
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -207,7 +203,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
results.length,
|
||||
onAskSelect,
|
||||
resultsRef,
|
||||
abort,
|
||||
query,
|
||||
fetching,
|
||||
requestKey,
|
||||
@@ -229,13 +224,11 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
pendingOpenRef.current = null;
|
||||
if (results.length > 0) {
|
||||
if (resultsRef.current?.selectFirst()) {
|
||||
abort();
|
||||
}
|
||||
resultsRef.current?.selectFirst();
|
||||
} else if (!error && askCount > 0) {
|
||||
onAskSelect(0);
|
||||
}
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, askCount, onAskSelect]);
|
||||
|
||||
return {
|
||||
cursor,
|
||||
@@ -379,9 +372,10 @@ export function useSearchController(
|
||||
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
|
||||
|
||||
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
|
||||
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
const { results, resultsQuery, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
asEmbeddable,
|
||||
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
|
||||
disabled: options.requestsEnabled === false || showAsk || !(normalizedQuery || withAI),
|
||||
retainPreviousResults: Boolean(state?.open),
|
||||
query: normalizedQuery,
|
||||
siteSpaceId: siteSpace.id,
|
||||
siteSpaceIds,
|
||||
@@ -442,7 +436,6 @@ export function useSearchController(
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect: askInAssistant,
|
||||
});
|
||||
@@ -463,6 +456,7 @@ export function useSearchController(
|
||||
query: normalizedQuery,
|
||||
results,
|
||||
resultsId: searchResultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
|
||||
@@ -8,22 +8,36 @@ import {
|
||||
createRecommendedQuestionResult,
|
||||
getEmptySearchResults,
|
||||
} from './empty-search-results';
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import { useRecentSearchQueries } from './recent-queries';
|
||||
import { computeRemoteSearchScope } from './remote-scope';
|
||||
import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store';
|
||||
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
|
||||
import type {
|
||||
OrderedComputedResult,
|
||||
SearchResultSource,
|
||||
SearchSiteContentScope,
|
||||
} from './search-types';
|
||||
import { streamRecommendedQuestions } from './server-actions';
|
||||
import { type SearchScope, useSearchPass } from './useSearch';
|
||||
import { useAI } from '@/components/AI';
|
||||
|
||||
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
|
||||
export type ResultType = RemoteSearchResult | RecommendedQuestionResult;
|
||||
|
||||
const SEARCH_ID_BYTES = 16;
|
||||
|
||||
type RemoteSearchResult = OrderedComputedResult & SearchResultSource;
|
||||
|
||||
type SearchAnswer = {
|
||||
scopeKey: string;
|
||||
query: string;
|
||||
results: RemoteSearchResult[];
|
||||
};
|
||||
|
||||
type RemoteSearchState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
|
||||
| { status: 'error' };
|
||||
| { status: 'loading'; requestKey: string; answer?: SearchAnswer }
|
||||
| { status: 'ready'; requestKey: string; answer: SearchAnswer }
|
||||
| { status: 'error'; requestKey: string };
|
||||
|
||||
/**
|
||||
* We cache the recommended questions globally to avoid calling the API multiple times
|
||||
@@ -37,6 +51,7 @@ export function useSearchResults(props: {
|
||||
asEmbeddable?: boolean;
|
||||
disabled: boolean;
|
||||
query: string;
|
||||
retainPreviousResults: boolean;
|
||||
siteSpaceId: string;
|
||||
siteSpaceIds: string[];
|
||||
selectedSectionSiteSpaceIds?: string[];
|
||||
@@ -53,6 +68,7 @@ export function useSearchResults(props: {
|
||||
asEmbeddable,
|
||||
disabled,
|
||||
query,
|
||||
retainPreviousResults,
|
||||
siteSpaceId,
|
||||
siteSpaceIds,
|
||||
selectedSectionSiteSpaceIds,
|
||||
@@ -83,8 +99,15 @@ export function useSearchResults(props: {
|
||||
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
|
||||
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
|
||||
);
|
||||
// Identifies the answer the UI needs now; an answer for any other key is never shown as current.
|
||||
const requestKey = JSON.stringify([query, remoteScope]);
|
||||
const scopeKey = JSON.stringify([
|
||||
searchURL,
|
||||
asEmbeddable,
|
||||
siteSpaceId,
|
||||
scope,
|
||||
remoteScope,
|
||||
filterSiteSpaceIds,
|
||||
]);
|
||||
const requestKey = JSON.stringify([scopeKey, query]);
|
||||
|
||||
const [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
|
||||
|
||||
@@ -100,6 +123,7 @@ export function useSearchResults(props: {
|
||||
|
||||
React.useEffect(() => {
|
||||
if (disabled) {
|
||||
setRemoteState({ status: 'idle' });
|
||||
return;
|
||||
}
|
||||
if (!query) {
|
||||
@@ -126,7 +150,7 @@ export function useSearchResults(props: {
|
||||
// We currently have a bug where the same question can be returned multiple times.
|
||||
// This is a workaround to avoid that.
|
||||
const questions = new Set<string>();
|
||||
const recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
let recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
|
||||
if (suggestions && suggestions.length > 0) {
|
||||
suggestions.forEach((question) => {
|
||||
@@ -153,7 +177,10 @@ export function useSearchResults(props: {
|
||||
}
|
||||
|
||||
questions.add(question);
|
||||
recommendedQuestions.push(createRecommendedQuestionResult(question, question));
|
||||
recommendedQuestions = [
|
||||
...recommendedQuestions,
|
||||
createRecommendedQuestionResult(question, question),
|
||||
];
|
||||
cachedRecommendedQuestions.set(siteSpaceId, recommendedQuestions);
|
||||
|
||||
if (!cancelled) {
|
||||
@@ -168,14 +195,19 @@ export function useSearchResults(props: {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}
|
||||
setRemoteState({ status: 'loading' });
|
||||
setRemoteState((state) => {
|
||||
const answer = 'answer' in state ? state.answer : undefined;
|
||||
return answer?.scopeKey === scopeKey
|
||||
? { status: 'loading', requestKey, answer }
|
||||
: { status: 'loading', requestKey };
|
||||
});
|
||||
let cancelled = false;
|
||||
const abortController = new AbortController();
|
||||
const send = async () => {
|
||||
flushRef.current = null;
|
||||
const fetchSearch = (
|
||||
scope: Parameters<typeof fetchSearchResults>[1]
|
||||
): Promise<OrderedComputedResult[]> =>
|
||||
): Promise<RemoteSearchResult[]> =>
|
||||
fetchSearchResults(
|
||||
searchURL,
|
||||
scope,
|
||||
@@ -188,25 +220,29 @@ export function useSearchResults(props: {
|
||||
try {
|
||||
const resultsPromise = fetchSearch(remoteScope);
|
||||
|
||||
const onResults = (results: OrderedComputedResult[]) => {
|
||||
const onResults = (results: RemoteSearchResult[]) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!results) {
|
||||
// Can happen when the route cannot be found and returns the page's html.
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoteState({ status: 'ready', requestKey, results });
|
||||
setRemoteState({
|
||||
status: 'ready',
|
||||
requestKey,
|
||||
answer: { scopeKey, query, results },
|
||||
});
|
||||
trackEvent({ type: 'search_type_query', query });
|
||||
};
|
||||
const onError = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
};
|
||||
|
||||
await resultsPromise.then(onResults, onError);
|
||||
@@ -215,7 +251,7 @@ export function useSearchResults(props: {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
}
|
||||
};
|
||||
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
|
||||
@@ -241,6 +277,7 @@ export function useSearchResults(props: {
|
||||
query,
|
||||
remoteScope,
|
||||
requestKey,
|
||||
scopeKey,
|
||||
trackEvent,
|
||||
withAI,
|
||||
siteSpaceId,
|
||||
@@ -252,6 +289,16 @@ export function useSearchResults(props: {
|
||||
searchPass,
|
||||
]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!retainPreviousResults) {
|
||||
setRemoteState((state) =>
|
||||
state.status === 'loading' && state.answer
|
||||
? { status: 'loading', requestKey: state.requestKey }
|
||||
: state
|
||||
);
|
||||
}
|
||||
}, [retainPreviousResults, requestKey]);
|
||||
|
||||
const flush = React.useCallback(() => {
|
||||
flushRef.current?.();
|
||||
}, []);
|
||||
@@ -262,10 +309,20 @@ export function useSearchResults(props: {
|
||||
setRemoteState((prev) => (prev.status === 'loading' ? { status: 'idle' } : prev));
|
||||
}, []);
|
||||
|
||||
const answer = 'answer' in remoteState ? remoteState.answer : undefined;
|
||||
const visibleAnswer =
|
||||
query &&
|
||||
!disabled &&
|
||||
answer?.scopeKey === scopeKey &&
|
||||
(answer.query === query || retainPreviousResults)
|
||||
? answer
|
||||
: undefined;
|
||||
|
||||
const streamedQuestions = cachedRecommendedQuestions.get(siteSpaceId);
|
||||
const results = React.useMemo<ResultType[]>(() => {
|
||||
if (!query) {
|
||||
const recommendedQuestions =
|
||||
cachedRecommendedQuestions.get(siteSpaceId) ??
|
||||
streamedQuestions ??
|
||||
suggestions?.map((question, index) =>
|
||||
createRecommendedQuestionResult(`recommended-question-${index}`, question)
|
||||
) ??
|
||||
@@ -278,27 +335,32 @@ export function useSearchResults(props: {
|
||||
});
|
||||
}
|
||||
|
||||
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
|
||||
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
|
||||
return visibleAnswer
|
||||
? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds)
|
||||
: [];
|
||||
}, [
|
||||
remoteState,
|
||||
requestKey,
|
||||
visibleAnswer,
|
||||
query,
|
||||
filterSiteSpaceIds,
|
||||
withAI,
|
||||
siteSpaceId,
|
||||
streamedQuestions,
|
||||
suggestions,
|
||||
recentQueries,
|
||||
]);
|
||||
|
||||
// Between a query change and its loading state, the previous answer must still read as loading.
|
||||
const isOutdated = remoteState.status === 'ready' && remoteState.requestKey !== requestKey;
|
||||
|
||||
return {
|
||||
results,
|
||||
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
|
||||
error: remoteState.status === 'error',
|
||||
resultsQuery: visibleAnswer?.query ?? query,
|
||||
fetching:
|
||||
Boolean(query) &&
|
||||
!disabled &&
|
||||
(remoteState.status === 'loading' ||
|
||||
(remoteState.status !== 'idle' && remoteState.requestKey !== requestKey)),
|
||||
error:
|
||||
Boolean(query) &&
|
||||
!disabled &&
|
||||
remoteState.status === 'error' &&
|
||||
remoteState.requestKey === requestKey,
|
||||
requestKey,
|
||||
flush,
|
||||
abort,
|
||||
@@ -315,17 +377,21 @@ async function fetchSearchResults(
|
||||
signal: AbortSignal,
|
||||
asEmbeddable: boolean | undefined,
|
||||
searchPass: SearchPassStore | null
|
||||
): Promise<OrderedComputedResult[]> {
|
||||
): Promise<RemoteSearchResult[]> {
|
||||
const directSearchId = generateSearchId();
|
||||
const direct = await searchPass?.search({
|
||||
query,
|
||||
searchId: directSearchId,
|
||||
scope,
|
||||
signal,
|
||||
asEmbeddable: Boolean(asEmbeddable),
|
||||
});
|
||||
if (direct?.type === 'results') {
|
||||
return direct.results;
|
||||
const search = { query, searchId: directSearchId };
|
||||
return direct.results.map((result) => ({ ...result, search }));
|
||||
}
|
||||
|
||||
const searchId = direct ? generateSearchId() : directSearchId;
|
||||
const response = await fetch(searchURL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -335,6 +401,7 @@ async function fetchSearchResults(
|
||||
body: JSON.stringify({
|
||||
asEmbeddable,
|
||||
query,
|
||||
searchId,
|
||||
scope,
|
||||
}),
|
||||
signal,
|
||||
@@ -344,5 +411,12 @@ async function fetchSearchResults(
|
||||
throw new Error(`Search request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<OrderedComputedResult[]>;
|
||||
const results: OrderedComputedResult[] = await response.json();
|
||||
const search = { query, searchId };
|
||||
return results.map((result) => ({ ...result, search }));
|
||||
}
|
||||
|
||||
function generateSearchId() {
|
||||
const bytes = globalThis.crypto?.getRandomValues(new Uint8Array(SEARCH_ID_BYTES));
|
||||
return bytes && Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@ export function useSearchResultsCursor(props: {
|
||||
}, [query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (fetching && resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
if (fetching) {
|
||||
if (resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import Script from 'next/script';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
|
||||
import { CustomizationDefaultThemeMode } from '@gitbook/api';
|
||||
|
||||
import { AIContextProvider } from '../AI';
|
||||
import { LLMsTxtDirective } from './LLMsTxtDirective';
|
||||
@@ -20,6 +20,7 @@ import { buildVersion } from '@/lib/build';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@/lib/env';
|
||||
import { getResizedImageURL } from '@/lib/images';
|
||||
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { removeTrailingSlash } from '@/lib/paths';
|
||||
import { isSiteIndexable } from '@/lib/seo';
|
||||
import { getOpenSearchURL } from '@/routes/opensearch';
|
||||
@@ -127,7 +128,7 @@ export async function SiteLayout(props: {
|
||||
</AIContextProvider>
|
||||
|
||||
<LoadIntegrations />
|
||||
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
|
||||
{isMcpPageActionEnabled(context) ? (
|
||||
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
|
||||
) : null}
|
||||
{scripts.map(({ script }) =>
|
||||
|
||||
@@ -24,6 +24,7 @@ function makeContext(
|
||||
siteId?: string;
|
||||
visibility?: SiteVisibility;
|
||||
pageActions?: CustomizationPageActionType[];
|
||||
mcpEnabled?: boolean;
|
||||
} = {}
|
||||
): GitBookSiteContext {
|
||||
const {
|
||||
@@ -32,11 +33,16 @@ function makeContext(
|
||||
siteId = 'site_123',
|
||||
visibility = SiteVisibility.Public,
|
||||
pageActions = [CustomizationPageActionType.Mcp],
|
||||
mcpEnabled,
|
||||
} = options;
|
||||
|
||||
return {
|
||||
site: { id: siteId, title: 'Acme', visibility },
|
||||
customization: { pageActions: { items: pageActions } },
|
||||
customization: {
|
||||
pageActions: { items: pageActions },
|
||||
// DO NOT MERGE - mocking type for development
|
||||
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
|
||||
},
|
||||
linker: createLinker({ host, siteBasePath, spaceBasePath: siteBasePath }),
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
@@ -160,6 +166,14 @@ describe('serveSiteAiCatalog', () => {
|
||||
}
|
||||
);
|
||||
|
||||
it('does not advertise the MCP server when the page action is off', () => {
|
||||
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: true, pageActions: [] }))).toBeNull();
|
||||
});
|
||||
|
||||
it('does not advertise the MCP server when the endpoint is off', () => {
|
||||
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: false }))).toBeNull();
|
||||
});
|
||||
|
||||
it('does not serve a catalog when there is nothing to advertise', async () => {
|
||||
const res = await serveSiteAiCatalog(makeContext({ pageActions: [] }), catalogRequest());
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { serveDiscoveryDocument } from '@/lib/discoveryDocument';
|
||||
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
|
||||
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { MCP_SERVER_CARD_PATH } from '@/lib/mcp/paths';
|
||||
import { SERVER_CARD_MEDIA_TYPE } from '@/lib/mcp/serverCard';
|
||||
|
||||
@@ -45,7 +45,7 @@ export function buildSiteAiCatalog(context: GitBookSiteContext): AiCatalog | nul
|
||||
|
||||
const entries: AiCatalogEntry[] = [];
|
||||
|
||||
if (isSiteMcpEnabled(context)) {
|
||||
if (isMcpPageActionEnabled(context)) {
|
||||
entries.push({
|
||||
identifier: buildCatalogIdentifier(context, 'mcp', site.id),
|
||||
type: SERVER_CARD_MEDIA_TYPE,
|
||||
|
||||
@@ -5,7 +5,6 @@ import { assert } from 'ts-essentials';
|
||||
import type {
|
||||
ChangeRequest,
|
||||
CustomizationDefaultThemeMode,
|
||||
PublishedSiteContent,
|
||||
Revision,
|
||||
RevisionPageDocument,
|
||||
Site,
|
||||
@@ -32,6 +31,7 @@ import { isPublishedPreviewAllowed } from './preview';
|
||||
import type { AskVisitorAgent } from '@/lib/ask-visitor';
|
||||
import {
|
||||
type GitBookDataFetcher,
|
||||
type PublishedSiteContent,
|
||||
createDataFetcher,
|
||||
getDataOrNull,
|
||||
throwIfDataError,
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
GitBookAPI,
|
||||
type HttpResponse,
|
||||
type RenderIntegrationUI,
|
||||
type SiteSearchScope,
|
||||
} from '@gitbook/api';
|
||||
import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
|
||||
|
||||
@@ -14,6 +13,7 @@ import { cache } from '../cache';
|
||||
import { DataFetcherError, wrapDataFetcherError } from './errors';
|
||||
import type { GitBookDataFetcher } from './types';
|
||||
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
|
||||
import { toSearchSiteContentBody } from '@/lib/search-results';
|
||||
import { trace } from '@/lib/tracing';
|
||||
|
||||
interface DataFetcherInput {
|
||||
@@ -793,25 +793,12 @@ async function searchSiteContent(
|
||||
return trace(
|
||||
`searchSiteContent(${params.organizationId}, ${params.siteId}, ${params.query})`,
|
||||
async () => {
|
||||
const { organizationId, siteId, query, scope } = params;
|
||||
const { organizationId, siteId, query, scope, searchId } = params;
|
||||
const api = apiClient(input);
|
||||
const res = await api.orgs.searchSiteContent(
|
||||
organizationId,
|
||||
siteId,
|
||||
{
|
||||
query,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
// and the published @gitbook/api types don't include it yet.
|
||||
scope: {
|
||||
mode: 'default',
|
||||
currentSiteSpace: scope.siteSpaceId,
|
||||
restrictTo: scope.restrictTo,
|
||||
} as SiteSearchScope,
|
||||
}
|
||||
: scope),
|
||||
},
|
||||
toSearchSiteContentBody(query, scope, searchId),
|
||||
{},
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitBookAPI, PublishedSiteContentLookup, SiteVisitorPayload } from '@gitbook/api';
|
||||
import type * as API from '@gitbook/api';
|
||||
|
||||
import { apiClient } from './api';
|
||||
import { getExposableError } from './errors';
|
||||
@@ -8,13 +8,16 @@ import { tryCatch } from '@/lib/async';
|
||||
import { isPreviewRequest } from '@/lib/preview';
|
||||
import { trace } from '@/lib/tracing';
|
||||
|
||||
type ResolveBody = Parameters<GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
type ResolveBody = Parameters<API.GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
|
||||
export type PublishedSiteContent = API.PublishedSiteContent &
|
||||
Partial<API.PublishedSiteContentAtRevision & API.PublishedSiteContentInChangeRequest>;
|
||||
|
||||
interface LookupPublishedContentByUrlInput {
|
||||
url: string;
|
||||
redirectOnError: boolean;
|
||||
apiToken: string | null;
|
||||
visitorPayload: SiteVisitorPayload;
|
||||
visitorPayload: API.SiteVisitorPayload;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,7 +25,7 @@ interface LookupPublishedContentByUrlInput {
|
||||
*/
|
||||
export async function lookupPublishedContentByUrl(
|
||||
input: LookupPublishedContentByUrlInput
|
||||
): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
|
||||
): Promise<DataFetcherResponse<PublishedSiteContent | API.PublishedContentRedirect>> {
|
||||
const lookupURL = new URL(input.url);
|
||||
const lookup = getURLLookup(stripURLSearch(lookupURL));
|
||||
|
||||
@@ -61,7 +64,11 @@ export async function lookupPublishedContentByUrl(
|
||||
data: { data },
|
||||
} = callResult;
|
||||
|
||||
if ('redirect' in data && data.target === 'application' && isPreviewRequest(lookupURL)) {
|
||||
if (!('redirect' in data)) {
|
||||
return { data };
|
||||
}
|
||||
|
||||
if (data.target === 'application' && isPreviewRequest(lookupURL)) {
|
||||
// The cached lookup omits the query params needed after login.
|
||||
const redirect = new URL(data.redirect);
|
||||
redirect.searchParams.set('redirect', lookupURL.toString());
|
||||
|
||||
@@ -180,6 +180,7 @@ export interface GitBookDataFetcher {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope:
|
||||
| { mode: 'all' }
|
||||
| {
|
||||
|
||||
@@ -3,12 +3,31 @@ import { CustomizationPageActionType, SiteVisibility } from '@gitbook/api';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
/**
|
||||
* Whether the site publishes an MCP server at all. Gates the endpoint and everything describing it.
|
||||
* Whether the site serves its MCP endpoint. Falls back to the `mcp` page action for cached
|
||||
* customizations that predate the setting.
|
||||
*/
|
||||
export function isSiteMcpEnabled(context: GitBookSiteContext): boolean {
|
||||
export function isSiteMcpEnabled(context: Pick<GitBookSiteContext, 'customization'>): boolean {
|
||||
// DO NOT MERGE - mocking type for development
|
||||
const mcp = (context.customization as { mcp?: { enabled: boolean } }).mcp;
|
||||
if (mcp) {
|
||||
return mcp.enabled;
|
||||
}
|
||||
return context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the site advertises its MCP server to visitors: the endpoint is served and the
|
||||
* "Connect with MCP server" page action is enabled for this visitor.
|
||||
*/
|
||||
export function isMcpPageActionEnabled(
|
||||
context: Pick<GitBookSiteContext, 'customization'>
|
||||
): boolean {
|
||||
return (
|
||||
isSiteMcpEnabled(context) &&
|
||||
context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `~gitbook/mcp` endpoint requires auth for the site (i.e VA site).
|
||||
*/
|
||||
|
||||
@@ -31,6 +31,7 @@ function makeContext(
|
||||
adaptiveContent?: boolean;
|
||||
aiMode?: CustomizationAIMode;
|
||||
pageActions?: CustomizationPageActionType[];
|
||||
mcpEnabled?: boolean;
|
||||
} = {}
|
||||
): GitBookSiteContext {
|
||||
const {
|
||||
@@ -43,6 +44,7 @@ function makeContext(
|
||||
adaptiveContent = true,
|
||||
aiMode = CustomizationAIMode.Search,
|
||||
pageActions = [CustomizationPageActionType.Mcp],
|
||||
mcpEnabled,
|
||||
} = options;
|
||||
|
||||
return {
|
||||
@@ -59,6 +61,8 @@ function makeContext(
|
||||
customization: {
|
||||
ai: { mode: aiMode },
|
||||
pageActions: { items: pageActions },
|
||||
// DO NOT MERGE - mocking type for development
|
||||
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
|
||||
},
|
||||
linker: createLinker({ host, siteBasePath, spaceBasePath }),
|
||||
} as unknown as GitBookSiteContext;
|
||||
@@ -384,6 +388,29 @@ describe('serveSiteMcpServerCard', () => {
|
||||
expect(card.$schema).toBe(SERVER_CARD_SCHEMA_URL);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
scenario: 'the endpoint is on and the page action is off',
|
||||
options: { mcpEnabled: true, pageActions: [] },
|
||||
status: 200,
|
||||
},
|
||||
{
|
||||
scenario: 'the endpoint is off and the page action is on',
|
||||
options: { mcpEnabled: false },
|
||||
status: 404,
|
||||
},
|
||||
{ scenario: 'the setting is missing and the page action is on', options: {}, status: 200 },
|
||||
{
|
||||
scenario: 'the setting is missing and the page action is off',
|
||||
options: { pageActions: [] },
|
||||
status: 404,
|
||||
},
|
||||
])('answers $status when $scenario', async ({ options, status }) => {
|
||||
const res = await serveSiteMcpServerCard(makeContext(options), cardRequest());
|
||||
|
||||
expect(res.status).toBe(status);
|
||||
});
|
||||
|
||||
it('answers a preflight with a 204', async () => {
|
||||
const res = await serveSiteMcpServerCard(makeContext(), cardRequest({ method: 'OPTIONS' }));
|
||||
|
||||
|
||||
@@ -76,3 +76,7 @@ export function getExtension(path: string): string {
|
||||
export function isGitBookInternalPath(path: string): boolean {
|
||||
return /(^|\/)~gitbook(\/|$)/.test(path);
|
||||
}
|
||||
|
||||
export function hasRevisionSelector(path: string): boolean {
|
||||
return /(?:^|\/)~\/revisions\/[^/]+/.test(path);
|
||||
}
|
||||
|
||||
@@ -52,10 +52,12 @@ export type DirectSearchProps = {
|
||||
*/
|
||||
export function toSearchSiteContentBody(
|
||||
query: string,
|
||||
scope: SearchSiteContentScope
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] {
|
||||
scope: SearchSiteContentScope,
|
||||
searchId?: string
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] & { searchId?: string } {
|
||||
return {
|
||||
query,
|
||||
searchId,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type RevisionPageDocument, type RevisionPageGroup, SiteVisibility } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { hasRevisionSelector } from '@/lib/paths';
|
||||
|
||||
/**
|
||||
* Return true if a page is indexable in search.
|
||||
@@ -29,8 +30,11 @@ export function isSiteIndexable(context: GitBookSiteContext) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prevent indexation of preview of revisions / change-requests
|
||||
if (context.changeRequest || context.revisionId !== context.space.revision) {
|
||||
if (
|
||||
context.changeRequest ||
|
||||
context.revisionId !== context.space.revision ||
|
||||
hasRevisionSelector(context.linker.spaceBasePath)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
ContentType,
|
||||
CustomizationDefaultThemeMode,
|
||||
CustomizationThemeMode,
|
||||
type PublishedSiteContent,
|
||||
SiteInsightsDisplayContext,
|
||||
type SiteInsightsEventLocation,
|
||||
SiteInsightsLLMSVariant,
|
||||
@@ -31,6 +30,7 @@ import { getContentSecurityPolicy } from '@/lib/csp';
|
||||
import { validateSerializedCustomization } from '@/lib/customization';
|
||||
import {
|
||||
DataFetcherError,
|
||||
type PublishedSiteContent,
|
||||
apiClient,
|
||||
getVisitorAuthBasePath,
|
||||
lookupPublishedContentByUrl,
|
||||
@@ -51,7 +51,7 @@ import {
|
||||
isOAuthProtectedResourceMetadataRequestForAuthEndpoint,
|
||||
isOAuthProtectedResourceRequest,
|
||||
} from '@/lib/oauth-protected';
|
||||
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
|
||||
import { hasRevisionSelector, removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
|
||||
import {
|
||||
getPreviewCookieResponse,
|
||||
getPreviewRequestIdentifier,
|
||||
@@ -85,6 +85,8 @@ export const config = {
|
||||
|
||||
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
|
||||
|
||||
const REVISION_ROBOTS_TAG = 'noindex, nofollow';
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
try {
|
||||
const requestURL = new URL(request.url);
|
||||
@@ -168,6 +170,20 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = await serveSiteRequest(requestURL, request, match);
|
||||
if (
|
||||
response &&
|
||||
hasRevisionSelector(match.url.pathname) &&
|
||||
!response.headers.has('x-robots-tag')
|
||||
) {
|
||||
const revisionResponse = new Response(response.body, response);
|
||||
revisionResponse.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
|
||||
return revisionResponse;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
|
||||
const { url: siteRequestURL, mode } = match;
|
||||
|
||||
if (isAITrainingOrIndexingRequest(request)) {
|
||||
@@ -180,6 +196,13 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
// Normalize URL after extracting the URL from the request to make sure the client is redirected to the proper one
|
||||
const normalization = normalizeRequestURL(siteRequestURL, mode);
|
||||
if (normalization instanceof Response) {
|
||||
const location = normalization.headers.get('location');
|
||||
if (location && hasRevisionSelector(new URL(location).pathname)) {
|
||||
return NextResponse.redirect(location, {
|
||||
status: normalization.status,
|
||||
headers: { 'x-robots-tag': REVISION_ROBOTS_TAG },
|
||||
});
|
||||
}
|
||||
return normalization;
|
||||
}
|
||||
const isNormalizedURL = normalization.isNormalized;
|
||||
@@ -622,6 +645,8 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
// noindex search/assistant deep links, kept crawlable so Google sees the directive.
|
||||
if (rewrittenURL.searchParams.has('ask') || rewrittenURL.searchParams.has('q')) {
|
||||
response.headers.set('x-robots-tag', 'none');
|
||||
} else if (hasRevisionSelector(siteURLData.basePath)) {
|
||||
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
|
||||
}
|
||||
|
||||
// Allow cross-origin requests from the same parent domain as the site.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import { type RevisionPageDocument, SiteVisibility } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { createLinker } from '@/lib/links';
|
||||
@@ -26,7 +26,7 @@ function createContext(options: {
|
||||
return {
|
||||
displayAgentInstructions: false,
|
||||
organizationId: 'org-1',
|
||||
site: { id: 'site-1' },
|
||||
site: { id: 'site-1', visibility: SiteVisibility.Public },
|
||||
siteSpace: { id: 'site-space-1' },
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
revisionId: 'revision-1',
|
||||
@@ -66,6 +66,23 @@ describe('servePageMarkdown', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('serves the current revision by selector with a noindex header for AI agents', async () => {
|
||||
const context = createContext({});
|
||||
const response = await servePageMarkdown(
|
||||
{
|
||||
...context,
|
||||
isAiAgent: true,
|
||||
linker: context.linker.fork({
|
||||
spaceBasePath: `/docs/~/revisions/${context.revisionId}/`,
|
||||
}),
|
||||
},
|
||||
'new-page'
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('X-Robots-Tag')).toBe('noindex, nofollow');
|
||||
});
|
||||
|
||||
it('redirects to the markdown version of a site redirect target', async () => {
|
||||
const context = createContext({
|
||||
siteRedirect: { target: 'https://docs.example.com/docs/new-page', permanent: true },
|
||||
|
||||
Reference in New Issue
Block a user