Compare commits

...

3 Commits

Author SHA1 Message Date
Peter White 8de6282de2 Resolve missing search placements in GBO 2026-11-24 08:10:50 +00:00
Peter White 1e591d5505 changeset 2026-11-24 07:18:01 +00:00
Peter White e10facd6b1 Resolve hidden-space hits in browser search 2026-11-24 07:17:32 +00:00
8 changed files with 204 additions and 38 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Use the search pass for matches in spaces hidden from navigation, including on share-link sites.
@@ -6,7 +6,7 @@ import type { SiteURLData } from '@/lib/context';
import { type SearchRouteReason, throwIfDataError } from '@/lib/data';
import { getLogger } from '@/lib/logger';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { transformSitePageResult } from '@/lib/search';
import { getSearchSpaceLookup, transformSitePageResult } from '@/lib/search';
import { computeSearchResults } from '@/lib/search-results';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
@@ -14,6 +14,34 @@ import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
const SEARCH_FALLBACK_REASON =
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
export async function GET(request: NextRequest) {
const spaceIds = request.nextUrl.searchParams.getAll('space');
if (
spaceIds.length === 0 ||
spaceIds.length > 100 ||
spaceIds.some((id) => !/^[A-Za-z0-9_-]{1,128}$/.test(id))
) {
return new NextResponse(null, { status: 400 });
}
const site = await getSiteURLDataFromMiddleware();
if (site.preview || site.revision || site.changeRequest) {
return new NextResponse(null, { status: 404 });
}
const { dataFetcher } = await getServerActionBaseContext();
const { structure } = await throwIfDataError(
dataFetcher.getPublishedContentSite({
organizationId: site.organization,
siteId: site.site,
siteShareKey: site.shareKey,
})
);
return NextResponse.json(getSearchSpaceLookup(structure, spaceIds), {
headers: { 'Cache-Control': 'private, no-store' },
});
}
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope, searchId } =
(await request.json()) as SearchSiteContentRequest;
@@ -60,6 +60,62 @@ describe('createSearchPassStore', () => {
let restore: (() => void) | undefined;
afterEach(() => restore?.());
it('refreshes placements for mixed hits and reuses the search response', async () => {
const urls: string[] = [];
const visible = {
siteSpaceId: 'ss_visible',
spaceURL: 'https://docs.example.com/old/',
breadcrumbs: [],
};
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (input) => {
const url = String(input);
urls.push(url);
if (url === directSearch.passURL) {
return Response.json({ token: 'pass', expiresIn: 300_000 });
}
if (url === endpoint) {
return Response.json({
items: [
{
type: 'space',
id: 'space_hidden',
pages: [{ id: 'page', path: 'reference', rank: 1, ancestors: [] }],
},
{
type: 'space',
id: 'space_visible',
pages: [{ id: 'intro', path: 'intro', rank: 2, ancestors: [] }],
},
],
});
}
return Response.json({
space_hidden: {
siteSpaceId: 'ss_hidden',
spaceURL: 'https://docs.example.com/legacy/',
breadcrumbs: [],
},
space_visible: { ...visible, spaceURL: 'https://docs.example.com/current/' },
});
}) as typeof fetch);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore({
...directSearch,
spaces: { space_visible: visible },
});
await store.requestPass();
expect(await search(store)).toMatchObject({
type: 'results',
results: [{ href: '/legacy/reference' }, { href: '/current/intro' }],
});
expect(urls).toEqual([
directSearch.passURL,
endpoint,
'/~gitbook/search?space=space_hidden&space=space_visible',
]);
});
it('stays on the route for the rest of the page after a 403', async () => {
const { authorizations, fetchSpy } = mockFetch([403]);
restore = () => fetchSpy.mockRestore();
@@ -7,7 +7,9 @@ import { getEmbeddableLinker } from '@/lib/embeddable-linker';
import { createSiteLinker } from '@/lib/links';
import {
type DirectSearchProps,
type SearchSpaceLookup,
computePublishedSearchResults,
getSearchResultSpaceIds,
toSearchSiteContentBody,
} from '@/lib/search-results';
@@ -195,12 +197,31 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
const { items } = (await response.json()) as {
items: (SearchSpaceResult | SearchRecordResult)[];
};
const linker = createSiteLinker(directSearch.linker);
let linker = createSiteLinker(directSearch.linker);
let spaces = directSearch.spaces;
const spaceIds = getSearchResultSpaceIds(items);
if (spaceIds.some((id) => !Object.hasOwn(spaces, id))) {
const params = new URLSearchParams();
for (const id of spaceIds) {
params.append('space', id);
}
const searchURL = linker.toPathInSpace('~gitbook/search');
const placements = await fetch(`${searchURL}?${params}`, {
signal: request.signal,
});
if (!placements.ok) {
return fallBack('unknown_space');
}
spaces = (await placements.json()) as SearchSpaceLookup;
}
if (asEmbeddable) {
linker = getEmbeddableLinker(linker);
}
results = computePublishedSearchResults({
asEmbeddable,
linker: asEmbeddable ? getEmbeddableLinker(linker) : linker,
linker,
searchResults: items,
spaces: directSearch.spaces,
spaces,
});
} catch (error) {
if (signal.aborted) {
@@ -23,7 +23,7 @@ function siteSpace(id: string, title: string, published: string, extra: Partial<
path: '',
default: false,
draft: false,
space: { id: `space_${id}`, title, language: 'en' },
space: { id: `space_${id}`, title, language: 'en', permissions: { view: true } },
urls: { published },
...extra,
} as SiteSpace;
@@ -102,6 +102,7 @@ const items: (SearchSpaceResult | SearchRecordResult)[] = [
{ id: 'status', path: 'https://status.example.com/', rank: 3 },
]),
space('v1', 1, [{ id: 'legacy', path: 'legacy/authentication', rank: 4 }]),
space('v0', 1, [{ id: 'reference', path: 'reference', rank: 5 }]),
{
type: 'record',
id: 'record_1',
@@ -135,8 +136,12 @@ describe('computePublishedSearchResults', () => {
urlMode,
});
const directSearch = context.directSearch!;
const embed = (linker: typeof context.linker) =>
asEmbeddable ? getEmbeddableLinker(linker) : linker;
const embed = (linker: typeof context.linker) => {
if (asEmbeddable) {
return getEmbeddableLinker(linker);
}
return linker;
};
const route = computeSearchResults(items, (spaceItem, pageItem) => {
const found = findSiteSpaceBy(structure, (s) => s.space.id === spaceItem.id);
@@ -150,11 +155,13 @@ describe('computePublishedSearchResults', () => {
siteSectionGroup: found?.siteSectionGroup ?? undefined,
});
});
const spaces = getSearchSpaceLookup(structure);
expect(spaces.space_v0).toBeUndefined();
const browser = computePublishedSearchResults({
asEmbeddable,
linker: embed(createSiteLinker(directSearch.linker)),
searchResults: items,
spaces: getSearchSpaceLookup(structure),
spaces: { ...spaces, ...getSearchSpaceLookup(structure, ['space_v0']) },
});
expect(JSON.stringify(directSearch)).not.toContain('page-token');
@@ -164,14 +171,13 @@ describe('computePublishedSearchResults', () => {
'space_v2/auth',
'space_guides/status',
'space_v1/legacy',
'space_v0/reference',
'record_1',
]);
});
it('leaves hidden variants out of the lookup, so their results go to the route', () => {
it.each(['v0', 'unknown'])('falls back when a result has no placement (%s)', (spaceId) => {
const spaces = getSearchSpaceLookup(structure);
expect(Object.keys(spaces).sort()).toEqual(['space_guides', 'space_v1', 'space_v2']);
expect(JSON.stringify(spaces)).not.toContain('/api/v0/');
const linker = createSiteLinker({
urlMode: 'url-host',
@@ -180,9 +186,32 @@ describe('computePublishedSearchResults', () => {
spaceBasePath: '/api/',
gitbookURL: undefined,
});
const searchResults = [...items, space('v0', 1, [{ id: 'draft', path: 'draft', rank: 5 }])];
const searchResults = [space(spaceId, 1, [{ id: 'page', path: 'page', rank: 1 }])];
expect(
computePublishedSearchResults({ asEmbeddable: false, linker, searchResults, spaces })
).toBeNull();
});
it('only resolves requested placements the visitor can read', () => {
const hidden = siteSpace('hidden', 'Older docs', 'https://docs.example.com/key/old/', {
hidden: true,
});
const denied = siteSpace('denied', 'Denied', 'https://docs.example.com/key/denied/');
denied.space.permissions.view = false;
const draft = siteSpace('draft', 'Draft', 'https://docs.example.com/key/draft/', {
draft: true,
});
const unrequested = siteSpace('other', 'Other', 'https://docs.example.com/key/other/');
const result = getSearchSpaceLookup(
{ type: 'siteSpaces', structure: [hidden, denied, draft, unrequested] },
['space_hidden', 'space_denied', 'space_draft', 'space_unknown']
);
expect(result).toEqual({
space_hidden: {
siteSpaceId: hidden.id,
spaceURL: hidden.urls.published,
breadcrumbs: [],
},
});
});
});
+15 -7
View File
@@ -109,7 +109,7 @@ export function computeSearchResults(
}
/**
* Compute the results of the published content of a site, resolving spaces from a lookup.
* Compute published search results using the space lookup.
* Returns null when a page result belongs to a space missing from the lookup.
*/
export function computePublishedSearchResults(input: {
@@ -119,16 +119,12 @@ export function computePublishedSearchResults(input: {
spaces: SearchSpaceLookup;
}): OrderedComputedResult[] | null {
const { asEmbeddable, linker, searchResults, spaces } = input;
const hasUnknownSpace = searchResults.some(
(item) => item.type === 'space' && item.pages.length > 0 && !spaces[item.id]
);
if (hasUnknownSpace) {
if (getSearchResultSpaceIds(searchResults).some((id) => !Object.hasOwn(spaces, id))) {
return null;
}
return computeSearchResults(searchResults, (spaceItem, pageItem) => {
const entry: SearchSpaceEntry | undefined = spaces[spaceItem.id];
const entry = spaces[spaceItem.id];
const toHref = (pagePath: string) =>
getPublishedPageHref({ asEmbeddable, linker, pagePath, spaceURL: entry?.spaceURL });
@@ -142,6 +138,18 @@ export function computePublishedSearchResults(input: {
});
}
export function getSearchResultSpaceIds(
results: (SearchSpaceResult | SearchRecordResult)[]
): string[] {
const ids = new Set<string>();
for (const item of results) {
if (item.type === 'space' && item.pages.length > 0) {
ids.add(item.id);
}
}
return [...ids];
}
/**
* Build the result for a page, with its best section.
*/
+22 -13
View File
@@ -80,25 +80,34 @@ export function transformSitePageResult(args: {
});
}
/**
* Index the visible site spaces by space, resolving each space as the search route does.
*/
export function getSearchSpaceLookup(structure: SiteStructure): SearchSpaceLookup {
/** Index visible spaces by default, or resolve specific readable published spaces. */
export function getSearchSpaceLookup(
structure: SiteStructure,
requestedSpaceIds?: string[]
): SearchSpaceLookup {
const lookup: SearchSpaceLookup = {};
const ids = requestedSpaceIds ?? listAllSiteSpaces(structure).map(({ space }) => space.id);
for (const { space } of listAllSiteSpaces(structure)) {
if (lookup[space.id]) {
for (const id of new Set(ids)) {
const found = findSiteSpaceBy(structure, (siteSpace) => siteSpace.space.id === id);
if (!found) {
continue;
}
const found = findSiteSpaceBy(structure, (siteSpace) => siteSpace.space.id === space.id);
if (found && !found.siteSpace.hidden) {
lookup[space.id] = getSearchSpaceEntry({
siteSpace: found.siteSpace,
siteSection: found.siteSection ?? undefined,
siteSectionGroup: found.siteSectionGroup ?? undefined,
});
const { siteSpace, siteSection, siteSectionGroup } = found;
if (requestedSpaceIds) {
if (siteSpace.draft || !siteSpace.space.permissions.view || !siteSpace.urls.published) {
continue;
}
} else if (siteSpace.hidden) {
continue;
}
lookup[id] = getSearchSpaceEntry({
siteSpace,
siteSection: siteSection ?? undefined,
siteSectionGroup: siteSectionGroup ?? undefined,
});
}
return lookup;
+16 -6
View File
@@ -649,11 +649,16 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
}
// Allow cross-origin requests from the same parent domain as the site.
const allowedOrigin = getAllowedCORSOrigin(request, siteCanonicalURL);
if (allowedOrigin) {
response.headers.set('access-control-allow-origin', allowedOrigin);
response.headers.set('access-control-allow-credentials', 'true');
const isSearchPlacementLookup =
pathname === '~gitbook/search' &&
(request.method === 'GET' || request.method === 'HEAD');
if (!isSearchPlacementLookup) {
// Allow cross-origin requests from the same parent domain as the site.
const allowedOrigin = getAllowedCORSOrigin(request, siteCanonicalURL);
if (allowedOrigin) {
response.headers.set('access-control-allow-origin', allowedOrigin);
response.headers.set('access-control-allow-credentials', 'true');
}
}
// AI related headers
@@ -665,7 +670,12 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
// When we use adaptive content, we want to ensure that the cache is not used at all on the client side.
// Vercel already set this header, this is needed in OpenNext.
if (siteURLData.contextId && !siteRequestURL.pathname.endsWith('~gitbook/site-index')) {
if (isSearchPlacementLookup) {
response.headers.set('cache-control', 'private, no-store');
} else if (
siteURLData.contextId &&
!siteRequestURL.pathname.endsWith('~gitbook/site-index')
) {
response.headers.set('cache-control', 'public, max-age=0, must-revalidate');
}