Compare commits

...

9 Commits

Author SHA1 Message Date
Peter White af08c4ac08 Prefetch search results on hover or keyboard selection 2026-11-22 18:03:00 +00:00
Peter White e9890dfa4c changeset 2026-11-22 17:40:20 +00:00
Peter White 5c2986e1c5 Prefetch search results on hover or keyboard selection 2026-11-22 17:40:08 +00:00
Peter White 1ecd2ca65a Keep integration dependency errors inside their blocks (#4820) 2026-11-21 10:11:45 +01:00
conico974 b0f3822342 Bump OpenNext to aws 4.2.0 and cloudflare 1.20.18 (#4817)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:19:25 +01:00
Peter White 7e2658a7a2 Reduce site search debounce to 100 ms (#4816) 2026-11-20 10:35:34 +00:00
spastorelli a10eff9e0a Make the page actions menu load its own data (#4808) 2026-11-20 11:32:44 +01:00
Johan Preynat 13c0ff0803 Update to GitBook API SDK 0.211.0 (#4814) 2026-11-19 22:43:29 +01:00
Peter White d2c56e5f0e Redirect change request links to the site preview when public previews are off (#4813) 2026-11-19 20:38:15 +00:00
31 changed files with 449 additions and 571 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Handle optional emoji and icon values when rendering tags.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Reduce the wait after typing in site search to 100 ms.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Keep published pages available when an integration block needs its connection or settings checked.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Reduce background downloads during search by prefetching the result visitors hover or select.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
+6 -6
View File
@@ -128,8 +128,8 @@
"@gitbook/react-openapi": "workspace:*",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"@modelcontextprotocol/sdk": "1.17.5",
"@opennextjs/aws": "4.1.16",
"@opennextjs/cloudflare": "1.20.17",
"@opennextjs/aws": "4.2.0",
"@opennextjs/cloudflare": "1.20.18",
"@panzoom/panzoom": "^4.6.1",
"@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1",
@@ -357,7 +357,7 @@
},
"catalog": {
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.210.0",
"@gitbook/api": "0.211.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.210.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-qxroJUFDreoJNU7X28Gz+2Nbjg8PCiE4GtJkwscHYfmWHLM29NsVVt3ap8x+bz53j6mg+SaobVjeRsXdA1EbXA=="],
"@gitbook/api": ["@gitbook/api@0.211.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-G+rY2m7ZvyR1RA4oilarzrNDABDkYhARoIyfNCE5mYqZQgpgsLShn3rGgzTudO2iqwt/5iK6RcJc2enfj+37Jg=="],
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
@@ -935,9 +935,9 @@
"@octokit/types": ["@octokit/types@14.1.0", "", { "dependencies": { "@octokit/openapi-types": "^25.1.0" } }, "sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g=="],
"@opennextjs/aws": ["@opennextjs/aws@4.1.16", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-eHb6/LCrpr+3DmbmE+/q5GkcrbSs5IRpO/O0kcay7FK5WYDhcML0K5NhO7I9H62z42wscVIi75Hv3ASsXDeEGw=="],
"@opennextjs/aws": ["@opennextjs/aws@4.2.0", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-uWWER/P66CphCM+L0WlN9DSj3LauN/HjfK64V0+Hs+hjzKuQLGII/Q7FhkU1j/BEG4zbjIvkuJorzIyFwVWZiQ=="],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.17", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.1.16", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "glob": "^13.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-jGEC9ue8LLHvOFXp62LjDUSSz7JpD+PQB+Y3r0lU78PtQ84wI16+EMF9TXEDkTek3g3fGWTLTI07pbZt8/gj8w=="],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.18", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.2.0", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "esbuild": "0.28.2", "glob": "^13.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-6hy3RJHP7+OMxUxYLRCgzQipuJJ1n7JowszTHn/i2KGxPXccQuvs42YI5ZchV7Fd0JGrtIDj0lhgvw+dp7yMrg=="],
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+1 -1
View File
@@ -48,7 +48,7 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.210.0",
"@gitbook/api": "0.211.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
-5
View File
@@ -443,11 +443,6 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://help.openloyalty.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'retrozia.gitbook.io/retrozia',
contentBaseURL: 'https://retrozia.gitbook.io',
tests: [{ name: 'Home', url: '/retrozia' }],
},
{
name: 'helpcenter.channable.com',
contentBaseURL: 'https://helpcenter.channable.com',
+2 -2
View File
@@ -20,8 +20,8 @@
"@gitbook/react-openapi": "workspace:*",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"@modelcontextprotocol/sdk": "1.17.5",
"@opennextjs/aws": "4.1.16",
"@opennextjs/cloudflare": "1.20.17",
"@opennextjs/aws": "4.2.0",
"@opennextjs/cloudflare": "1.20.18",
"@panzoom/panzoom": "^4.6.1",
"@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1",
@@ -1,4 +1,5 @@
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { ContentKitOutput } from '@gitbook/react-contentkit';
import type { BlockProps } from '../Block';
@@ -53,6 +54,7 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
{
integrationName: block.data.integration,
request: initialInput,
allowFailedDependency: true,
}
);
@@ -66,12 +68,29 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
// Integration output can render blocks with generated keys.
{...getCommentAnchorProps(context, block.key)}
{...getCommentMarkerProps(context, 'data-comment-block')}
className={tcls(style)}
role="note"
className={tcls(
'flex items-start gap-3 p-4 text-sm',
'rounded-corners:rounded-md circular-corners:rounded-xl',
'bg-warning border-warning text-neutral-strong',
style
)}
>
<pre>
Unexpected error with integration {block.data.integration}:{' '}
{initialResponse.error.message}
</pre>
<Icon
icon="circle-exclamation"
className="mt-0.5 size-4 shrink-0 text-warning-subtle contrast-more:text-warning"
aria-hidden="true"
/>
<div className="wrap-anywhere min-w-0">
<p className="font-medium">
Could not load the {block.data.integration} integration
</p>
<p>
{initialResponse.error.code === 424
? 'Ask an administrator to check its connection and settings.'
: initialResponse.error.message}
</p>
</div>
</div>
);
}
@@ -11,9 +11,11 @@ export async function fetchSafeIntegrationUI(
{
integrationName,
request,
allowFailedDependency = false,
}: {
integrationName: string;
request: RenderIntegrationUI;
allowFailedDependency?: boolean;
}
) {
const output = await ignoreDataFetcherErrors(
@@ -27,6 +29,7 @@ export async function fetchSafeIntegrationUI(
404, // Integration has been uninstalled
400, // Integration is rejecting its own request
422, // Integration is triggering an invalid request, failing at the validation step
...(allowFailedDependency ? [424] : []),
502, // Integration is failing in an unexpected way
]
);
@@ -0,0 +1,31 @@
import type { RevisionPageDocument } from '@gitbook/api';
import { PageActionsDropdown } from './PageActionsDropdown';
import { getPageActionsURLs } from './pageActionsURLs';
import type { GitBookSiteContext } from '@/lib/context';
/**
* Menu of the page actions. It loads what it shows from the context and the page alone, so it can be
* rendered and cached apart from the page body.
*/
export async function PageActionsMenu(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
}) {
const { context, page } = props;
const { linker, revision } = context;
return (
<PageActionsDropdown
siteTitle={context.site.title}
urls={await getPageActionsURLs(context, page)}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
);
}
@@ -0,0 +1,101 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getPageGitMetadata } = await import('./pageActionsData');
const page = {
id: 'page-1',
title: 'Introduction',
kind: 'sheet',
type: 'document',
path: 'readme',
slug: 'readme',
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('getPageGitMetadata', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result).toEqual(git);
});
it('does not fetch Git metadata already on the page', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, { ...page, git });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
@@ -0,0 +1,63 @@
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
const CONFIGURABLE_PAGE_ACTIONS = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
];
/**
* Whether a given built-in page action is enabled.
*/
export function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* 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));
}
/**
* Get the Git metadata of a page for the Edit on Git action, or nothing when that action is not shown.
*/
export async function getPageGitMetadata(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<RevisionPageDocument['git']> {
if (
!context.space.gitSync?.url ||
!isPageActionEnabled(context.customization, CustomizationPageActionType.Git)
) {
return undefined;
}
if (page.git) {
return page.git;
}
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
return pageWithMetadata?.type === 'document' ? pageWithMetadata.git : undefined;
}
@@ -0,0 +1,66 @@
import urlJoin from 'url-join';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import { getPDFURLSearchParams } from '../PDF';
import { getPageGitMetadata, isPageActionEnabled } from './pageActionsData';
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 { getPageRSSURL } from '@/routes/rss';
/**
* Return the URLs for the page actions. The page's Git path and RSS feed are loaded here, so the
* page actions depend on the context and the page alone.
*/
export async function getPageActionsURLs(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<PageActionsDropdownURLs> {
const [document, git] = await Promise.all([
getPageDocument(context, page),
getPageGitMetadata(context, page),
]);
// Update blocks can only be at the top level of the document, so we optimize the check.
const withRSSFeed = document
? hasTopLevelBlock(document, (block) => block.type === 'updates')
: false;
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
const { gitSync } = context.space;
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
gitSync?.url && git
? {
provider: gitSync.installationProvider,
url: urlJoin(gitSync.url, git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -1,24 +1,19 @@
import assertNever from 'assert-never';
import urlJoin from 'url-join';
import {
CustomizationPageActionType,
type RevisionPage,
type RevisionPageDocument,
type SiteSection,
type SiteSectionGroup,
import type {
RevisionPage,
RevisionPageDocument,
SiteSection,
SiteSectionGroup,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { SpacesDropdownMenuItems, type VariantSpace } from '../Header/SpacesDropdownMenuItem';
import { CONTENT_STYLE, CONTENT_STYLE_REDUCED } from '../layout';
import {
PageActionsDropdown,
type PageActionsDropdownURLs,
} from '../PageActions/PageActionsDropdown';
import { hasConfiguredPageActions } from '../PageActions/pageActionsData';
import { PageActionsMenu } from '../PageActions/PageActionsMenu';
import { PageAsideToggleButton } from '../PageAside/PageAsideButton';
import { PageIcon } from '../PageIcon';
import { getPDFURLSearchParams } from '../PDF';
import {
findBestTargetURL,
getTargetURLForSiteSpace,
@@ -27,11 +22,9 @@ import { categorizeVariants } from '../SpaceLayout/categorizeVariants';
import { BreadcrumbItemDropdown, type BreadcrumbSibling } from './BreadcrumbItemDropdown';
import { PageTags } from './PageTags';
import type { GitBookSiteContext, SiteStructureNode } from '@/lib/context';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { type AncestorRevisionPage, resolveFirstDocument } from '@/lib/pages';
import { getLocalizedTitle } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
export async function PageHeader(props: {
context: GitBookSiteContext;
@@ -146,15 +139,8 @@ 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 hasConfiguredPageActions = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
].some((type) => isPageActionEnabled(context.customization, type));
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions || withRSSFeed);
const hasPageActions =
pageActionsEnabled && (hasConfiguredPageActions(context.customization) || withRSSFeed);
if (!page.layout.title && !page.layout.description && !hasPageActions) {
return null;
@@ -181,19 +167,7 @@ export async function PageHeader(props: {
]
)}
>
{hasPageActions ? (
<PageActionsDropdown
siteTitle={context.site.title}
urls={getPageActionsURLs({ context, page, withRSSFeed })}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
) : null}
{hasPageActions ? <PageActionsMenu context={context} page={page} /> : null}
<PageAsideToggleButton />
</div>
);
@@ -520,67 +494,3 @@ function BreadcrumbSeparator() {
/>
);
}
/**
* Return the URLs for the page actions.
*/
function getPageActionsURLs({
context,
page,
withRSSFeed,
}: {
context: GitBookSiteContext;
page: RevisionPageDocument;
withRSSFeed: boolean;
}): PageActionsDropdownURLs {
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
isPageActionEnabled(context.customization, CustomizationPageActionType.Git) &&
context.space.gitSync?.url &&
page.git
? {
provider: context.space?.gitSync?.installationProvider,
url: urlJoin(context.space.gitSync.url, page.git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Whether a given built-in page action is enabled.
*/
function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -8,6 +8,7 @@ import { getPageResultPresentation } from './getPageResultHref';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedPageResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { usePrefetchWhenActive } from './usePrefetchWhenActive';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
@@ -24,6 +25,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
const language = useLanguage();
const { preview: bestSection, description, href } = getPageResultPresentation(item);
usePrefetchWhenActive(href, active);
const preview = bestSection
? [bestSection.title, bestSection.body].filter(Boolean).join(' · ')
: undefined;
@@ -50,6 +52,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
...style,
}}
{...rest}
prefetch={false}
>
<Breadcrumbs breadcrumbs={item.breadcrumbs} />
<p className="line-clamp-1 font-heading text-base font-semibold leading-snug text-tint-strong">
@@ -6,6 +6,7 @@ import { Favicon } from '../utils';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedRecordResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { usePrefetchWhenActive } from './usePrefetchWhenActive';
import { tString, useLanguage } from '@/intl/client';
export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem(
@@ -20,6 +21,7 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
usePrefetchWhenActive(item.href, active);
const domain = getDomain(item.href);
return (
@@ -46,6 +48,7 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
aria-label={tString(language, 'search_page_result_title', item.title)}
style={{ ...style }}
{...rest}
prefetch={false}
>
<p className="line-clamp-2 text-base font-semibold leading-snug text-tint-strong">
<HighlightQuery query={query} text={item.title} />
@@ -0,0 +1,32 @@
import { PrefetchKind } from 'next/dist/client/components/router-reducer/router-reducer-types';
import { useRouter } from 'next/navigation';
import React from 'react';
import { defaultIsExternalClient, hasSideEffectQueryParams, LinkContext } from '../primitives';
import { isExternalLink, isSiteAuthLink } from '../utils/link';
const RESULT_PREFETCH_DELAY_MS = 200;
export function usePrefetchWhenActive(href: string, active: boolean) {
const router = useRouter();
const { isExternalServer = isExternalLink, isExternalClient = defaultIsExternalClient } =
React.useContext(LinkContext);
React.useEffect(() => {
if (
!active ||
isExternalServer(href) ||
isSiteAuthLink(href) ||
hasSideEffectQueryParams(href) ||
(window.self !== window.top && isExternalClient(href))
) {
return;
}
const timeout = setTimeout(
() => router.prefetch(href, { kind: PrefetchKind.FULL }),
RESULT_PREFETCH_DELAY_MS
);
return () => clearTimeout(timeout);
}, [active, href, isExternalClient, isExternalServer, router]);
}
@@ -218,7 +218,7 @@ export function useSearchResults(props: {
setRemoteState({ status: 'error' });
}
};
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 150);
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
flushRef.current = () => {
clearTimeout(timeout);
void send();
@@ -1,17 +1,13 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const {
fetchPageData,
getLowercasePathnameRedirect,
resolveMissingPagePath,
resolveSitePageFromURL,
} = await import('./fetch');
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
await import('./fetch');
const { normalizeURL } = await import('@/lib/data/urls');
const { createLinker } = await import('@/lib/links');
@@ -25,81 +21,6 @@ const page = {
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revision: { pages: [page] },
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('fetchPageData', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result.pageTarget?.page.git).toEqual(git);
expect(result.context.page?.git).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
});
describe('resolveMissingPagePath', () => {
function createRedirectContext(options: {
siteRedirect?: { source?: string; target: string; permanent?: boolean };
@@ -1,7 +1,6 @@
import { permanentRedirect, redirect } from 'next/navigation';
import {
CustomizationPageActionType,
type RevisionPageDocument,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
@@ -30,34 +29,7 @@ export type PageParams = PagePathParams | PageIdParams;
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
let pageTarget = await resolvePage(context, params);
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
if (
pageTarget &&
!pageTarget.page.git &&
context.space.gitSync?.url &&
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
) {
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: pageTarget.page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
pageTarget = {
...pageTarget,
page: {
...pageTarget.page,
git: pageWithMetadata.git,
},
};
}
}
const pageTarget = await resolvePage(context, params);
return {
context: {
+2 -2
View File
@@ -36,11 +36,11 @@ export function Tag(props: { tag: RevisionTag; className?: string }) {
export function TagIcon(props: { tag: RevisionTag }) {
const { tag } = props;
if ('emoji' in tag) {
if ('emoji' in tag && tag.emoji !== undefined) {
return <Emoji code={tag.emoji} style="shrink-0" />;
}
if (tag.icon) {
if ('icon' in tag && tag.icon) {
return <Icon icon={tag.icon as IconName} className={tcls('size-[1em]', 'shrink-0')} />;
}
@@ -74,7 +74,7 @@ function getTargetProps(
/**
* Check if the link is external with the origin.
*/
function defaultIsExternalClient(href: string) {
export function defaultIsExternalClient(href: string) {
return isExternalLink(href, window.location.origin);
}
@@ -183,7 +183,7 @@ export function Link(props: LinkProps) {
* NextLink automatically prefetches links (RSC requests) on hover/viewport, which would fire those
* side effects without any user intent, so such links should not be prefetched.
*/
function hasSideEffectQueryParams(href: string): boolean {
export function hasSideEffectQueryParams(href: string): boolean {
const baseURL = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';
const linkURL = URL.canParse(href) ? new URL(href) : new URL(href, baseURL);
+23 -50
View File
@@ -1,7 +1,5 @@
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
import type { PublishedSiteContentLookup } from '@gitbook/api';
import { GITBOOK_PREVIEW_BASE_URL } from '../env';
import * as api from './api';
import { DataFetcherError } from './errors';
@@ -50,64 +48,39 @@ describe('preview auth redirects', () => {
expect(redirect.origin + redirect.pathname).toBe(authURL.toString());
expect(redirect.searchParams.get('redirect')).toBe(requestURL.toString());
});
});
it.each([
{
name: 'non-preview application redirects',
requestURL: 'https://docs.example.com/~/changes/66',
target: 'application',
redirect: 'https://app.gitbook.com/o/org_foo/sites/site_foo',
expectedRedirect: 'https://app.gitbook.com/o/org_foo/sites/site_foo',
},
{
name: 'preview content redirects with a remaining page path',
requestURL: new URL(
'site_foo/~/changes/66/hello%20world',
GITBOOK_PREVIEW_BASE_URL
).toString(),
target: 'content',
redirect: 'https://docs.example.com/section?theme=dark',
expectedRedirect: 'https://docs.example.com/section/hello%20world?theme=dark',
},
{
name: 'preview external redirects with a remaining page path',
requestURL: new URL(
'site_foo/~/revisions/revision_123/hello%20world',
GITBOOK_PREVIEW_BASE_URL
).toString(),
target: 'external',
redirect: 'https://auth.example.com/login?location=%2Fsection&state=keep',
expectedRedirect:
'https://auth.example.com/login?location=%2Fsection%2Fhello%2520world&state=keep',
},
] as const)(
'preserves handling of $name',
async ({ requestURL, target, redirect, expectedRedirect }) => {
const data: PublishedSiteContentLookup =
target === 'external'
? { target, redirect, site: 'site_foo' }
: { target, redirect };
apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
urls: {
async resolvePublishedContentByUrl() {
return { data };
},
describe('lookup URL', () => {
it('sends change request URLs in full and keeps the redirect of the API', async () => {
const urls: string[] = [];
const redirect = new URL(
'site_foo/section/~/changes/66/hello%20world',
GITBOOK_PREVIEW_BASE_URL
).toString();
const apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
urls: {
async resolvePublishedContentByUrl({ url }: { url: string }) {
urls.push(url);
return { data: { target: 'content', redirect } };
},
} as unknown as ReturnType<typeof api.apiClient>);
},
} as unknown as ReturnType<typeof api.apiClient>);
try {
const result = await lookupPublishedContentByUrl({
url: requestURL,
url: 'https://docs.example.com/section/~/changes/66/hello%20world?jwt_token=abc',
apiToken: null,
redirectOnError: false,
visitorPayload: {},
});
expect(result).toEqual({ data: { ...data, redirect: expectedRedirect } });
expect(result).toEqual({ data: { target: 'content', redirect } });
} finally {
apiClientSpy.mockRestore();
}
);
});
describe('lookup URL', () => {
expect(urls).toEqual(['https://docs.example.com/section/~/changes/66/hello%20world']);
});
it('resolves the full URL without search params in a single call', async () => {
const urls: string[] = [];
const apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
+9 -45
View File
@@ -3,9 +3,8 @@ import type { GitBookAPI, PublishedSiteContentLookup, SiteVisitorPayload } from
import { apiClient } from './api';
import { getExposableError } from './errors';
import type { DataFetcherResponse } from './types';
import { getURLLookup, getURLLookupPathname, stripURLSearch } from './urls';
import { getURLLookup, stripURLSearch } from './urls';
import { tryCatch } from '@/lib/async';
import { joinPath, joinPathWithBaseURL } from '@/lib/paths';
import { isPreviewRequest } from '@/lib/preview';
import { trace } from '@/lib/tracing';
@@ -40,12 +39,12 @@ export async function lookupPublishedContentByUrl(
const callResult = await trace(
{
operation: 'resolvePublishedContentByUrl',
name: lookup.url,
name: lookup,
},
() =>
tryCatch(
api.urls.resolvePublishedContentByUrl({
url: lookup.url,
url: lookup,
...(input.visitorPayload ? { visitor: input.visitorPayload } : {}),
redirectOnError: input.redirectOnError,
} as ResolveBody) //TODO: remove cast when we are sure that everything is good
@@ -62,47 +61,12 @@ export async function lookupPublishedContentByUrl(
data: { data },
} = callResult;
if ('redirect' in data) {
if (data.target === 'application' && isPreviewRequest(lookupURL)) {
// The cached lookup omits content selectors and query params needed after login.
const redirect = new URL(data.redirect);
redirect.searchParams.set('redirect', lookupURL.toString());
return { data: { ...data, redirect: redirect.toString() } };
}
// Append the path to the redirect URL
// because we resolved a shorter path and the redirect is relative to it
if (lookup.extraPath) {
if (data.target === 'content') {
const redirect = new URL(data.redirect);
redirect.pathname = joinPath(redirect.pathname, lookup.extraPath);
data.redirect = redirect.toString();
} else {
const redirect = new URL(data.redirect);
if (redirect.searchParams.has('location')) {
redirect.searchParams.set(
'location',
joinPath(redirect.searchParams.get('location') ?? '', lookup.extraPath)
);
data.redirect = redirect.toString();
}
}
}
return { data };
if ('redirect' in data && 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());
return { data: { ...data, redirect: redirect.toString() } };
}
const changeRequest = data.changeRequest ?? lookup.changeRequest;
const revision = data.revision ?? lookup.revision;
return {
data: {
...data,
canonicalUrl: joinPathWithBaseURL(data.canonicalUrl, lookup.extraPath),
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
pathname: getURLLookupPathname(lookup, data),
...(changeRequest ? { changeRequest } : {}),
...(revision ? { revision } : {}),
},
};
return { data };
}
+15 -139
View File
@@ -1,88 +1,6 @@
import { describe, expect, it } from 'bun:test';
import { getURLLookup, getURLLookupPathname, normalizeRequestURL, normalizeURL } from './urls';
describe('getURLLookupPathname', () => {
const previewRoot = 'https://sites.gitbook.com/preview/site_example/section';
const pagePath = 'guides/access/setup';
const homepagePath = '/welcome/overview';
it.each(['revisions', 'changes'])(
'resolves a page in a %s preview from the site-space root',
(kind) => {
const lookup = getURLLookup(
new URL(`${previewRoot}/~/${kind}/revision-id/${pagePath}`)
)!;
expect(
getURLLookupPathname(lookup, {
basePath: '/preview/site_example/section/',
pathname: homepagePath,
})
).toBe(`/${pagePath}`);
}
);
it.each(['revisions', 'changes'])(
'preserves the custom homepage at a %s preview root',
(kind) => {
const lookup = getURLLookup(new URL(`${previewRoot}/~/${kind}/revision-id/`))!;
expect(
getURLLookupPathname(lookup, {
basePath: '/preview/site_example/section/',
pathname: homepagePath,
})
).toBe(`${homepagePath}/`);
}
);
it('uses the resolved pathname for a full URL lookup', () => {
const lookup = getURLLookup(new URL(`https://docs.example.com/section/${pagePath}`))!;
expect(
getURLLookupPathname(lookup, {
basePath: '/section/',
pathname: `/${pagePath}`,
})
).toBe(`/${pagePath}/`);
});
it('preserves page resolution without a custom homepage', () => {
const lookup = getURLLookup(new URL(`${previewRoot}/~/revisions/revision-id/${pagePath}`))!;
expect(
getURLLookupPathname(lookup, {
basePath: '/preview/site_example/section/',
pathname: '/',
})
).toBe(`/${pagePath}`);
});
it.each(['/section/variant', '/section/variant/'])(
'recognizes a root lookup with base path %s',
(basePath) => {
expect(
getURLLookupPathname(
{
url: 'https://docs.example.com/section/variant/',
extraPath: 'guide/page',
},
{ basePath, pathname: homepagePath }
)
).toBe('/guide/page');
}
);
it('preserves a legitimate page prefix for a non-root lookup', () => {
expect(
getURLLookupPathname(
{ url: 'https://docs.example.com/section/guide', extraPath: 'page' },
{ basePath: '/section/', pathname: '/guide' }
)
).toBe('/guide/page');
});
});
import { getURLLookup, normalizeRequestURL, normalizeURL } from './urls';
describe('getURLLookup', () => {
it.each([
@@ -98,68 +16,26 @@ describe('getURLLookup', () => {
'https://docs.mycompany.com/section/blog/rss.xml',
'https://docs.mycompany.com/a/b/intro.md',
'https://proxy.gitbook.site/sites/site_foo/hello/world',
'https://docs.mycompany.com/~/revisions/id/a/b/c',
'https://docs.mycompany.com/~/changes/id/hello',
'https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c',
'https://docs.mycompany.com/~/revisions/id/a/~gitbook/ogimage/pageId',
])('looks up the full URL %s', (url) => {
expect(getURLLookup(new URL(url))).toEqual({ url, extraPath: '' });
expect(getURLLookup(new URL(url))).toBe(url);
});
it('looks up the normalized URL', () => {
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toEqual({
url: 'https://docs.mycompany.com/hello',
extraPath: '',
});
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toBe(
'https://docs.mycompany.com/hello'
);
});
it('should not match before a revision ID', () => {
expect(getURLLookup(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c'))).toEqual({
url: 'https://docs.mycompany.com/',
extraPath: 'a/b/c',
basePath: '~/revisions/id',
revision: 'id',
});
});
it('should not match before a change request ID', () => {
expect(getURLLookup(new URL('https://docs.mycompany.com/~/changes/id/hello'))).toEqual({
url: 'https://docs.mycompany.com/',
extraPath: 'hello',
basePath: '~/changes/id',
changeRequest: 'id',
});
});
it('should match a revision in a variant in a share-link', () => {
expect(
getURLLookup(
new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c')
)
).toEqual({
url: 'https://test.gitbook.io/sharelink/v/variant',
extraPath: 'a/b/c',
basePath: '~/revisions/id',
revision: 'id',
});
});
it('should keep the revision base path for an internal path', () => {
expect(
getURLLookup(
new URL('https://docs.mycompany.com/~/revisions/id/a/~gitbook/ogimage/pageId')
)
).toEqual({
url: 'https://docs.mycompany.com/',
extraPath: 'a/~gitbook/ogimage/pageId',
basePath: '~/revisions/id',
revision: 'id',
});
});
it.each([
'https://proxy.gitbook.site/',
'https://proxy.gitbook.site/sites',
'https://proxy.gitbook.site/sites/~/changes/id/hello',
])('should skip the proxy root URL %s', (url) => {
expect(getURLLookup(new URL(url))).toBeNull();
});
it.each(['https://proxy.gitbook.site/', 'https://proxy.gitbook.site/sites'])(
'should skip the proxy root URL %s',
(url) => {
expect(getURLLookup(new URL(url))).toBeNull();
}
);
});
describe('normalizeRequestURL', () => {
+2 -96
View File
@@ -1,107 +1,13 @@
import { joinPath, removeTrailingSlash } from '../paths';
import { isProxyRequest, isProxyRootRequest } from '../proxy';
import { DataFetcherError, getExposableError } from './errors';
/**
* Paths served by our own routes rather than by site content. They can never be part of a
* site URL, so a revision or change marker is never searched for inside them.
* Kept in sync with the site route handlers and `encodePathInSiteContent` in the middleware.
*/
const INTERNAL_PATHS = [
// Simple `~gitbook` endpoints. `image`, `__evt` and `visitor` are served by the middleware
// before the lookup, but are listed so this stays a complete registry.
/^~gitbook\/(pdf|search|search-prewarm|icon|site-index|image|__evt|visitor)$/,
/^~gitbook\/ogimage\/[^/]+$/,
/^~gitbook\/auth\/(login|logout)$/,
/^~gitbook\/oauth2\/v1\/[^/]+\/authorize$/,
/^~gitbook\/embed(\/(assistant|search|demo|script\.js|page(\/.*)?))?$/,
/^~gitbook\/markdown\/.+$/,
/^~gitbook\/markdown-ask\/[^/]+(\/[^/]+)?$/,
/^~gitbook\/rss\/.+$/,
// Site root files, including the `llms.txt` aliases from `PATH_ALIASES`.
/^llms\.txt$/,
/^llms-full\.txt(\/\d+)?$/,
/^(\.well-known\/)?sitemap\.md$/,
/^robots\.txt$/,
/^sitemap(-pages)?\.xml$/,
/^rss\.xml$/,
];
/**
* Return the leading segments that can be part of the site URL, dropping the internal path
* (if any) that follows them.
*/
function getContentPathSegments(pathSegments: string[]): string[] {
for (let index = 0; index < pathSegments.length; index++) {
const remaining = pathSegments.slice(index).join('/');
if (INTERNAL_PATHS.some((regex) => regex.test(remaining))) {
return pathSegments.slice(0, index);
}
}
return pathSegments;
}
/**
* For a given GitBook URL, return the URL to resolve with the API.
*
* The full URL is resolved as-is, except for revisions and changes in the path
* (`~/revisions/<id>/` or `~/changes/<id>/`): these are resolved up to the tilde,
* and the rest of the path goes in the extraPath.
*
* Returns `null` for the root proxy URLs, which can never resolve to a site.
*/
export function getURLLookup(input: URL): {
url: string;
extraPath: string;
basePath?: string;
changeRequest?: string;
revision?: string;
} | null {
export function getURLLookup(input: URL): string | null {
const url = normalizeURL(input);
const pathSegments = url.pathname.slice(1).split('/');
// A `~` in an internal path (like `~gitbook/...`) is not a revision or change marker.
const contentSegments = getContentPathSegments(pathSegments);
const tildeIndex = contentSegments.indexOf('~');
const kind = tildeIndex >= 0 ? contentSegments[tildeIndex + 1] : undefined;
if (kind !== 'revisions' && kind !== 'changes') {
return isProxyRootRequest(url) ? null : { url: url.toString(), extraPath: '' };
}
const idIndex = tildeIndex + 2;
const id = contentSegments[idIndex];
const contentURL = new URL(url);
contentURL.pathname = contentSegments.slice(0, tildeIndex).join('/');
if (isProxyRootRequest(contentURL)) {
return null;
}
return {
url: contentURL.toString(),
extraPath: pathSegments.slice(idIndex + 1).join('/'),
basePath: contentSegments.slice(tildeIndex, idIndex + 1).join('/'),
...(kind === 'revisions' ? { revision: id } : { changeRequest: id }),
};
}
/** Combine a resolved lookup with the remaining requested page path. */
export function getURLLookupPathname(
alternative: { url: string; extraPath: string },
resolved: { basePath: string; pathname: string }
) {
if (
alternative.extraPath &&
removeTrailingSlash(new URL(alternative.url).pathname) ===
removeTrailingSlash(resolved.basePath)
) {
// A root lookup can resolve to a custom homepage, which is not a prefix for other pages.
return joinPath('/', alternative.extraPath);
}
return joinPath(resolved.pathname, alternative.extraPath);
return isProxyRootRequest(url) ? null : url.toString();
}
/**
+11 -6
View File
@@ -40,6 +40,7 @@ import {
import { GITBOOK_DISABLE_INSIGHTS, isGitBookAssetsHostURL, isGitBookHostURL } from '@/lib/env';
import { getImageResizingContextId } from '@/lib/images';
import { isAITrainingOrIndexingRequest } from '@/lib/indexing-crawlers';
import { getLogger } from '@/lib/logger';
import { MCP_SERVER_CARD_PATH, MCP_SERVER_CARD_WELL_KNOWN_PATH } from '@/lib/mcp/paths';
import { MiddlewareHeaders } from '@/lib/middleware';
import {
@@ -316,21 +317,25 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
// oxlint-disable-next-line no-console
console.log('redirect', siteURLData.redirect);
if (siteURLData.target === 'content') {
let contentRedirect = new URL(siteURLData.redirect, request.url);
const redirectURL = new URL(siteURLData.redirect, request.url);
let contentRedirect = new URL(redirectURL);
// For content redirects, we redirect using the /url/:url format
// during development and testing in 'url' mode.
if (mode === 'url') {
const urlObject = new URL(siteURLData.redirect);
contentRedirect = new URL(
`/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`,
`/url/${redirectURL.host}${redirectURL.pathname}${redirectURL.search}`,
request.url
);
}
// Keep the same search params as the original request
// as it might contain a VA token
contentRedirect.search = request.nextUrl.search;
if (!isPreviewRequest(siteRequestURL) && isPreviewRequest(redirectURL)) {
getLogger().info('Redirected disabled published preview to the preview domain');
} else {
// Keep the same search params as the original request
// as it might contain a VA token
contentRedirect.search = request.nextUrl.search;
}
return createRedirectResponse(contentRedirect.toString());
}