Compare commits

...

4 Commits

Author SHA1 Message Date
Steven H 2b498cf699 Read only the site's spaces at a site revision, without a live fallback
Other spaces are read live. A missing page or site revision is a real 404,
and OpenAPI specs are always read at the site revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:51:38 +00:00
Steven H 4ee2e16bfb Read the previewed content with mirrored PublishedSiteContent variants
Temporary mirror of the `oneOf` variants from GitbookIO/gitbook-x#27870,
until a published @gitbook/api includes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:33:33 +00:00
Steven H 367247a1b6 Keep site revision previews out of search indexes
Resolution no longer returns `revision` with `siteRevision`, so the site
context carries the site revision and isSiteIndexable checks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:14:15 +00:00
Steven H a8aabe9cb9 Read site revision previews as their site revision pins them
A preview URL resolved to a site revision reads every space and OpenAPI
spec through the site revision endpoints, falling back to live content for
what it doesn't record. A site revision never reports content updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:29:03 +00:00
9 changed files with 296 additions and 49 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
@@ -14,6 +14,11 @@ export async function hasContentBeenUpdated(props: { revisionId: string }) {
const context = await getServerActionBaseContext();
const siteURLData = await getSiteURLDataFromMiddleware();
// A site revision never changes what it shows.
if (siteURLData.siteRevision) {
return false;
}
if (siteURLData.changeRequest) {
const changeRequest = await getDataOrNull(
context.dataFetcher.getChangeRequest({
+25
View File
@@ -44,6 +44,7 @@ import {
getLinkerForSiteSpace,
getLocalizedTitle,
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
/**
@@ -71,6 +72,11 @@ export type SiteURLData = Pick<
*/
imagesContextId: string;
/**
* Site revision being previewed, when the URL previews one. Content is read as it pins it.
*/
siteRevision?: string;
/**
* Whether this request is a fallback rendering.
* We use this when switching variant as we don't know if the page exists in the other variant.
@@ -217,6 +223,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Whether search indexation is blocked for this deployment. */
noIndexSearch: boolean;
/** Site revision the URL previews. Content is read as it pins it. */
siteRevision?: string;
/** Whether the request included a visitor token. */
isLoggedInVisitor: boolean;
@@ -250,6 +259,13 @@ export function getBaseContext(input: {
const dataFetcher = createDataFetcher({
apiToken: siteURLData.apiToken ?? null,
siteRevision: siteURLData.siteRevision
? {
organizationId: siteURLData.organization,
siteId: siteURLData.site,
siteRevisionId: siteURLData.siteRevision,
}
: undefined,
});
const linkerInput: SiteLinkerInput = {
@@ -305,6 +321,7 @@ export async function fetchSiteContextByURLLookup(
contextId: data.contextId,
isFallback: data.isFallback ?? false,
noIndexSearch: data.noIndexSearch ?? false,
siteRevision: data.siteRevision,
isLoggedInVisitor: data.isLoggedInVisitor ?? false,
preview: data.preview ?? false,
displayAgentInstructions: data.displayAgentInstructions,
@@ -329,6 +346,7 @@ export async function fetchSiteContextByIds(
contextId?: string;
isFallback: boolean;
noIndexSearch: boolean;
siteRevision?: string;
isLoggedInVisitor: boolean;
preview: boolean;
displayAgentInstructions?: boolean;
@@ -462,6 +480,12 @@ export async function fetchSiteContextByIds(
return {
...spaceContext,
// Only the site's own spaces are read at the site revision it previews.
dataFetcher: ids.siteRevision
? spaceContext.dataFetcher.withSiteRevisionSpaces(
listAllSiteSpaces(siteStructure).map((entry) => entry.space.id)
)
: spaceContext.dataFetcher,
locale: siteSpace.space.language ?? spaceContext.locale,
linker: getLinkerForSiteSpace(siteLinker, siteSpace, spaceContext.revision.pages),
organizationId: ids.organization,
@@ -477,6 +501,7 @@ export async function fetchSiteContextByIds(
contextId: ids.contextId,
isFallback: ids.isFallback,
noIndexSearch: ids.noIndexSearch,
siteRevision: ids.siteRevision,
isLoggedInVisitor: ids.isLoggedInVisitor,
preview: ids.preview,
displayAgentInstructions: ids.displayAgentInstructions,
+184 -45
View File
@@ -12,7 +12,7 @@ import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-t
import { cache } from '../cache';
import { DataFetcherError, wrapDataFetcherError } from './errors';
import type { GitBookDataFetcher } from './types';
import type { DataFetcherResponse, GitBookDataFetcher } from './types';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
import { trace } from '@/lib/tracing';
@@ -21,6 +21,25 @@ interface DataFetcherInput {
* API token.
*/
apiToken: string | null;
/**
* Site revision being previewed. The site's spaces and OpenAPI specs are read at it.
*/
siteRevision?: DataFetcherSiteRevision;
}
/**
* A site revision, as a preview URL resolves it.
*/
export interface DataFetcherSiteRevision {
organizationId: string;
siteId: string;
siteRevisionId: string;
/**
* Spaces of the site, read at the site revision. Other spaces are read live. Until the site
* structure is known, every space is read at the site revision.
*/
spaceIds?: string[];
}
/**
@@ -46,10 +65,18 @@ export function createDataFetcher(
withToken({ apiToken }) {
return createDataFetcher({
...input,
apiToken,
});
},
withSiteRevisionSpaces(spaceIds) {
return createDataFetcher({
...input,
siteRevision: input.siteRevision ? { ...input.siteRevision, spaceIds } : undefined,
});
},
//
// API that are tied to the token
//
@@ -77,61 +104,106 @@ export function createDataFetcher(
});
},
getRevision(params) {
return getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
});
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}`,
{ metadata: params.metadata ?? false },
() =>
getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
})
);
},
getRevisionPageByPath(params) {
return getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
});
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}/path/${encodeURIComponent(params.path)}`,
{
metadata: params.metadata ?? false,
cachedMetadata: params.cachedMetadata ?? false,
},
() =>
getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
})
);
},
getRevisionPageMarkdown(params) {
return getRevisionPageMarkdown(
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}/page/${params.pageId}`,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
format: 'markdown',
'format.markdown.refs': 'stable',
evaluated: 'deterministic-only',
metadata: false,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
() =>
getRevisionPageMarkdown(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
)
);
},
getRevisionPageDocument(params) {
return getRevisionPageDocument(
return readAtSiteRevision(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
params.spaceId,
`content/${params.spaceId}/page/${params.pageId}/document`,
{ evaluated: 'deterministic-only', dereferenced: 'reusable-contents' },
() =>
getRevisionPageDocument(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
)
);
},
getRevisionReusableContentDocument(params) {
return getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
});
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}/reusable-contents/${params.reusableContentId}/document`,
{ evaluated: 'deterministic-only' },
() =>
getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
})
);
},
getLatestOpenAPISpecVersionContent(params) {
return getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
});
return readAtSiteRevision(input, null, `openapi/${params.slug}/content`, {}, () =>
getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
})
);
},
getSpace(params) {
return getSpace(input, {
@@ -195,15 +267,82 @@ export function createDataFetcher(
},
listRevisionPageMetaLinks(params) {
return listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
});
return readAtSiteRevision(
input,
params.spaceId,
`content/${params.spaceId}/page/${params.pageId}/meta-links`,
{},
() =>
listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
})
);
},
};
}
/**
* Read content at the site revision of the input, with the same query as `live` reads it. Reads
* live when there is no site revision, or for a space outside the site. An OpenAPI spec (no
* space) is always read at the site revision.
*/
async function readAtSiteRevision<T>(
input: DataFetcherInput,
spaceId: string | null,
path: string,
query: Record<string, string | boolean>,
live: () => Promise<DataFetcherResponse<T>>
): Promise<DataFetcherResponse<T>> {
const { siteRevision } = input;
if (!siteRevision || (spaceId && siteRevision.spaceIds?.includes(spaceId) === false)) {
return live();
}
const { spaceIds: _spaceIds, ...cacheableSiteRevision } = siteRevision;
// Typed like the space endpoint it mirrors: the API client doesn't publish these endpoints yet.
return (await getAtSiteRevision(
{ ...input, siteRevision: cacheableSiteRevision },
{ path, query }
)) as DataFetcherResponse<T>;
}
/**
* Get content at a site revision. It never changes, so it is cached forever.
*/
const getAtSiteRevision = cache(
async (
input: DataFetcherInput,
params: { path: string; query: Record<string, string | boolean> }
) => {
'use cache';
return wrapDataFetcherError(async () => {
const { siteRevision } = input;
if (!siteRevision) {
throw new Error('A site revision is required to read content at it');
}
const { organizationId, siteId, siteRevisionId } = siteRevision;
const path = `/orgs/${organizationId}/sites/${siteId}/revisions/${siteRevisionId}/${params.path}`;
return trace(`getAtSiteRevision(${path})`, async () => {
const api = apiClient(input);
const res = await api.request<unknown>({
path,
method: 'GET',
query: params.query,
secure: true,
format: 'json',
...noCacheFetchOptions,
});
cacheTag(...getCacheTagsFromResponse(res));
cacheLife('max');
return res.data;
});
});
}
);
/**
* Infer the cache life from the api response headers.
* @param response The response from the API call.
+1
View File
@@ -6,3 +6,4 @@ export * from './lookup';
export * from './visitor';
export * from './pages';
export * from './revisions';
export * from './siteRevisionTypes';
@@ -0,0 +1,43 @@
// TEMPORARY: mirrors the `PublishedSiteContent` variants of GitbookIO/gitbook-x#27870 until a
// published `@gitbook/api` includes them. Delete this file and import the official types then.
import type * as api from '@gitbook/api';
/** Site content at the live revision of its spaces. */
export type PublishedSiteContentLive = object;
/** Site content previewed at a revision of its space. */
export interface PublishedSiteContentAtRevision {
revision: string;
}
/** Site content previewed in a change request of its space. */
export interface PublishedSiteContentInChangeRequest {
changeRequest: string;
}
/** Site content previewed at a site revision. */
export interface PublishedSiteContentAtSiteRevision {
siteRevision: string;
}
/** Site content a URL resolves to: at most one of `revision`, `changeRequest` and `siteRevision`. */
export type PublishedSiteContentWithSiteRevision = Omit<
api.PublishedSiteContent,
'revision' | 'changeRequest'
> &
(
| PublishedSiteContentLive
| PublishedSiteContentAtRevision
| PublishedSiteContentInChangeRequest
| PublishedSiteContentAtSiteRevision
);
/**
* Read a resolution with the variants of the next `@gitbook/api`: the published type has neither
* `siteRevision` nor the variants, though the API already returns them.
*/
export function asPublishedSiteContentWithSiteRevision(
content: api.PublishedSiteContent
): PublishedSiteContentWithSiteRevision {
return content as PublishedSiteContentWithSiteRevision;
}
+6
View File
@@ -34,6 +34,12 @@ export interface GitBookDataFetcher {
*/
withToken(input: { apiToken: string }): GitBookDataFetcher;
/**
* Create a data fetcher that reads only these spaces at the site revision it previews, and
* other spaces live.
*/
withSiteRevisionSpaces(spaceIds: string[]): GitBookDataFetcher;
/**
* Get a user by its ID.
*/
+6 -2
View File
@@ -29,8 +29,12 @@ export function isSiteIndexable(context: GitBookSiteContext) {
return false;
}
// Prevent indexation of preview of revisions / change-requests
if (context.changeRequest || context.revisionId !== context.space.revision) {
// Prevent indexation of preview of revisions / change-requests / site revisions
if (
context.changeRequest ||
context.siteRevision ||
context.revisionId !== context.space.revision
) {
return false;
}
+21 -2
View File
@@ -32,6 +32,7 @@ import { validateSerializedCustomization } from '@/lib/customization';
import {
DataFetcherError,
apiClient,
asPublishedSiteContentWithSiteRevision,
getVisitorAuthBasePath,
lookupPublishedContentByUrl,
normalizeRequestURL,
@@ -426,8 +427,7 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
basePath: siteURLData.basePath,
space: siteURLData.space,
organization: siteURLData.organization,
changeRequest: siteURLData.changeRequest,
revision: siteURLData.revision,
...getPreviewedContent(siteURLData),
shareKey: siteURLData.shareKey,
preview: siteURLData.preview,
apiToken: siteURLData.apiToken,
@@ -1204,3 +1204,22 @@ function acceptsMarkdown(request: Request): boolean {
const htmlIndex = mediaTypes.findIndex((type) => type === 'text/html' || type === '*/*');
return htmlIndex === -1 || markdownIndex < htmlIndex;
}
/**
* The revision, change request or site revision a URL previews: at most one of them.
*/
function getPreviewedContent(
lookup: PublishedSiteContent
): Pick<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
const content = asPublishedSiteContentWithSiteRevision(lookup);
if ('revision' in content) {
return { revision: content.revision };
}
if ('changeRequest' in content) {
return { changeRequest: content.changeRequest };
}
if ('siteRevision' in content) {
return { siteRevision: content.siteRevision };
}
return {};
}