mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-26 02:02:32 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c50ba2d5d | |||
| 84ba78bd4d | |||
| 5d60c2a7c7 | |||
| bca0b711d8 | |||
| ea375ecefc |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Handle optional emoji and icon values when rendering tags.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Point agents to the site MCP server from Markdown pages, the page HTML, llms.txt and llms-full.txt.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Serve the site AI Catalog as specification version 0.9, with identifiers in its `urn:air:{publisher}:{name}:{kind}` format.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Name a site's MCP server as docs, such as "Acme Docs MCP Server", in AI clients and in the install commands and links, so it is not confused with a product's own MCP server.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Reduce the wait after typing in site search to 100 ms.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published pages available when an integration block needs its connection or settings checked.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published site search results visible while visitors refine a query.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Apply the default language-aware search scope to legacy search links.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"gitbook": minor
|
||||
"@gitbook/react-openapi": minor
|
||||
---
|
||||
|
||||
Replace the Scalar API client behind "Test it" with a lightweight Try it panel.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Count only MCP tool calls in the MCP request insights event.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Answer GET requests to the MCP endpoint with an `Allow: POST` header.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Support MCP protocol version 2025-11-25 on published site MCP servers.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published revision URLs out of search results.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Render a page's search keywords in its metadata.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"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.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Track the displayed position and search request ID when a visitor opens a search result.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Run the Cloudflare server worker next to the GitBook API.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Start the requests a site page needs as soon as their inputs are known, instead of when each component renders.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Update the GitBook API SDK for site revision responses.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix wide content in Updates blocks overflowing into the page outline.
|
||||
@@ -30,7 +30,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: deployments status --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -49,7 +49,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ steps.extract_current_version.outputs.version_id }}@100% ${{ inputs.serverVersionId }}@0% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -61,7 +61,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ inputs.middlewareVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
|
||||
|
||||
@@ -71,7 +71,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ inputs.serverVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: deploy --config ./packages/gitbook/openNext/customWorkers/doWrangler.jsonc
|
||||
|
||||
@@ -89,7 +89,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -112,7 +112,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.80.0'
|
||||
wranglerVersion: '4.43.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
|
||||
|
||||
|
||||
+1
-2
@@ -48,8 +48,7 @@
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.214.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@gitbook/api": "0.210.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"assert-never": "^1.4.0",
|
||||
|
||||
@@ -443,6 +443,11 @@ 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',
|
||||
|
||||
@@ -442,48 +442,6 @@ 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({
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
"observability": {
|
||||
"enabled": false,
|
||||
},
|
||||
// Run the server next to the GitBook API so its request waterfall stays short; the middleware stays at the edge.
|
||||
"placement": { "region": "gcp:us-central1" },
|
||||
"vars": {
|
||||
"NEXT_CACHE_DO_QUEUE_DISABLE_SQLITE": "true",
|
||||
},
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
"@gitbook/react-math": "workspace:*",
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@mermaid-js/mermaid-zenuml": "^0.2.2",
|
||||
"@modelcontextprotocol/sdk": "1.26.0",
|
||||
"@opennextjs/aws": "4.2.0",
|
||||
"@opennextjs/cloudflare": "1.20.18",
|
||||
"@modelcontextprotocol/sdk": "1.17.5",
|
||||
"@opennextjs/aws": "4.1.16",
|
||||
"@opennextjs/cloudflare": "1.20.17",
|
||||
"@panzoom/panzoom": "^4.6.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
@@ -40,7 +40,7 @@
|
||||
"jsontoxml": "^1.0.1",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"leven": "^4.1.0",
|
||||
"mcp-handler": "^1.1.0",
|
||||
"mcp-handler": "^1.0.2",
|
||||
"mdast-util-from-markdown": "^2.0.2",
|
||||
"mdast-util-frontmatter": "^2.0.1",
|
||||
"mdast-util-gfm": "^3.1.0",
|
||||
@@ -82,14 +82,13 @@
|
||||
"url-join": "^5.0.0",
|
||||
"usehooks-ts": "catalog:",
|
||||
"warn-once": "^0.1.1",
|
||||
"zod": "^3.25",
|
||||
"zod": "^3",
|
||||
"zod-to-json-schema": "^3.25.1",
|
||||
"zustand": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^7.2.0",
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@scalar/api-client-react": "catalog:",
|
||||
"@tailwindcss/postcss": "^4.1.11",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
@@ -119,9 +118,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "./scripts/generate.sh",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/download-fonts.ts",
|
||||
"generate:fonts": "bun ./scripts/generate-font-faces.ts",
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts",
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/fonts",
|
||||
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
|
||||
"build": "bun run generate:assets && next build --webpack",
|
||||
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { build } from 'bun';
|
||||
import { mkdir, rename, rm } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { SCALAR_RUNTIME_PATH } from '../src/components/DocumentView/OpenAPI/scalar-runtime-path';
|
||||
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const outputDir = join(scriptDir, '../public/~gitbook/static/scalar');
|
||||
const temporaryDir = join(outputDir, '.build');
|
||||
const scalarPackage = createRequire(import.meta.url)('@scalar/api-client-react/package.json') as {
|
||||
version: string;
|
||||
};
|
||||
|
||||
if (SCALAR_RUNTIME_PATH !== `scalar/scalar-api-client@${scalarPackage.version}.mjs`) {
|
||||
throw new Error(
|
||||
'Update SCALAR_RUNTIME_PATH for the installed @scalar/api-client-react version'
|
||||
);
|
||||
}
|
||||
|
||||
const reactShim = `
|
||||
const react = () => globalThis.__gitbookScalarReact;
|
||||
export const createContext = (...args) => react().createContext(...args);
|
||||
export const useContext = (...args) => react().useContext(...args);
|
||||
export const useEffect = (...args) => react().useEffect(...args);
|
||||
export const useRef = (...args) => react().useRef(...args);
|
||||
export const useSyncExternalStore = (...args) => react().useSyncExternalStore(...args);
|
||||
`;
|
||||
|
||||
const jsxRuntimeShim = `
|
||||
const runtime = () => globalThis.__gitbookScalarJSXRuntime;
|
||||
export const jsx = (...args) => runtime().jsx(...args);
|
||||
export const jsxs = (...args) => runtime().jsxs(...args);
|
||||
`;
|
||||
|
||||
await rm(outputDir, { force: true, recursive: true });
|
||||
await mkdir(temporaryDir, { recursive: true });
|
||||
|
||||
const result = await build({
|
||||
entrypoints: [join(scriptDir, 'scalar-runtime.ts')],
|
||||
format: 'esm',
|
||||
minify: true,
|
||||
outdir: temporaryDir,
|
||||
plugins: [
|
||||
{
|
||||
name: 'scalar-react-shims',
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^react$/ }, () => ({
|
||||
namespace: 'scalar-runtime',
|
||||
path: 'react',
|
||||
}));
|
||||
build.onResolve({ filter: /^react\/jsx-runtime$/ }, () => ({
|
||||
namespace: 'scalar-runtime',
|
||||
path: 'react-jsx-runtime',
|
||||
}));
|
||||
build.onLoad({ filter: /^react$/, namespace: 'scalar-runtime' }, () => ({
|
||||
contents: reactShim,
|
||||
loader: 'js',
|
||||
}));
|
||||
build.onLoad(
|
||||
{ filter: /^react-jsx-runtime$/, namespace: 'scalar-runtime' },
|
||||
() => ({
|
||||
contents: jsxRuntimeShim,
|
||||
loader: 'js',
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
target: 'browser',
|
||||
});
|
||||
|
||||
const [output] = result.outputs;
|
||||
if (!result.success || !output || result.outputs.length !== 1) {
|
||||
throw new Error(`Unable to build Scalar runtime: ${result.logs.join('\n')}`);
|
||||
}
|
||||
|
||||
const outputPath = join(outputDir, SCALAR_RUNTIME_PATH.replace('scalar/', ''));
|
||||
await rename(output.path, outputPath);
|
||||
await rm(temporaryDir, { force: true, recursive: true });
|
||||
@@ -1 +0,0 @@
|
||||
export { ApiClientModalProvider, useApiClientModal } from '@scalar/api-client-react';
|
||||
+1
-4
@@ -5,7 +5,6 @@ import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
startSitePagePlan,
|
||||
} from '@/components/SitePage';
|
||||
|
||||
type PageProps = {
|
||||
@@ -22,9 +21,7 @@ export default async function Page(props: PageProps) {
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const params = await props.params;
|
||||
const { context } = await getDynamicSiteContext(params);
|
||||
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
|
||||
const { context } = await getDynamicSiteContext(await props.params);
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
|
||||
+15
-24
@@ -19,37 +19,28 @@ export async function handleMcpRequest(
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
|
||||
// The server is stateless, so it has no notification stream for a GET to open. `Allow` tells
|
||||
// clients to stop asking, as the Streamable HTTP transport expects.
|
||||
if (rawRequest.method === 'GET') {
|
||||
return new Response('Method Not Allowed', { status: 405, headers: { Allow: 'POST' } });
|
||||
}
|
||||
|
||||
// Next.js request.url is the original URL and not the rewritten one from the middleware
|
||||
const requestURL = new URL(context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint)));
|
||||
requestURL.search = rawRequest.nextUrl.search;
|
||||
const request = new Request(requestURL, rawRequest);
|
||||
|
||||
trackMcpEvent({
|
||||
organizationId: context.organizationId,
|
||||
siteId: context.site.id,
|
||||
events: [
|
||||
{
|
||||
type: 'mcp_request',
|
||||
location: {
|
||||
displayContext: SiteInsightsDisplayContext.Server,
|
||||
},
|
||||
},
|
||||
],
|
||||
request,
|
||||
});
|
||||
|
||||
const mcpHandler = createMcpHandler(
|
||||
(server) => {
|
||||
registerSiteMcpTools(server, createSiteMcpTools(context, { request }), {
|
||||
// Connecting, listing tools and notifications are protocol overhead, several
|
||||
// requests per client session: only tool calls count as usage.
|
||||
onToolCall: () =>
|
||||
trackMcpEvent({
|
||||
organizationId: context.organizationId,
|
||||
siteId: context.site.id,
|
||||
events: [
|
||||
{
|
||||
type: 'mcp_request',
|
||||
location: {
|
||||
displayContext: SiteInsightsDisplayContext.Server,
|
||||
},
|
||||
},
|
||||
],
|
||||
request,
|
||||
}),
|
||||
});
|
||||
registerSiteMcpTools(server, createSiteMcpTools(context, { request }));
|
||||
},
|
||||
{
|
||||
// The same identity the server card republishes, so the card and the handshake agree.
|
||||
|
||||
+2
-41
@@ -2,8 +2,7 @@ import { type NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { SEARCH_FALLBACK_HEADER } from '@/components/Search/search-pass-store';
|
||||
import type { SearchSiteContentRequest } from '@/components/Search/search-types';
|
||||
import type { SiteURLData } from '@/lib/context';
|
||||
import { type SearchRouteReason, throwIfDataError } from '@/lib/data';
|
||||
import { throwIfDataError } from '@/lib/data';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
|
||||
import { transformSitePageResult } from '@/lib/search';
|
||||
@@ -15,8 +14,7 @@ const SEARCH_FALLBACK_REASON =
|
||||
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { asEmbeddable, query, scope, searchId } =
|
||||
(await request.json()) as SearchSiteContentRequest;
|
||||
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
|
||||
const [context, siteURLData] = await Promise.all([
|
||||
getServerActionBaseContext({ isEmbeddable: asEmbeddable }),
|
||||
getSiteURLDataFromMiddleware(),
|
||||
@@ -42,8 +40,6 @@ export async function POST(request: NextRequest) {
|
||||
siteId: siteURLData.site,
|
||||
query,
|
||||
scope,
|
||||
searchId,
|
||||
routeReason: getSearchRouteReason(siteURLData, fallback),
|
||||
})
|
||||
),
|
||||
throwIfDataError(
|
||||
@@ -92,38 +88,3 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
return NextResponse.json(results);
|
||||
}
|
||||
|
||||
function getSearchRouteReason(
|
||||
siteURLData: SiteURLData,
|
||||
fallback: string | null
|
||||
): SearchRouteReason {
|
||||
if (siteURLData.changeRequest) {
|
||||
return 'change_request';
|
||||
}
|
||||
if (siteURLData.revision) {
|
||||
return 'revision';
|
||||
}
|
||||
if (siteURLData.preview) {
|
||||
return 'preview';
|
||||
}
|
||||
|
||||
switch (fallback) {
|
||||
case null:
|
||||
case 'expired':
|
||||
case 'pass_request':
|
||||
return 'no_pass';
|
||||
case '401':
|
||||
case '403':
|
||||
case '429':
|
||||
case 'network':
|
||||
case 'timeout':
|
||||
case 'invalid':
|
||||
case 'unknown_space':
|
||||
return `fallback:${fallback}`;
|
||||
default:
|
||||
if (/^5\d{2}$/.test(fallback)) {
|
||||
return 'fallback:5xx';
|
||||
}
|
||||
return /^\d{3}$/.test(fallback) ? 'fallback:http' : 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
+1
-4
@@ -5,7 +5,6 @@ import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
startSitePagePlan,
|
||||
} from '@/components/SitePage';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
@@ -23,9 +22,7 @@ export default async function Page(props: PageProps) {
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const params = await props.params;
|
||||
const { context } = await getStaticSiteContext(params);
|
||||
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
|
||||
const { context } = await getStaticSiteContext(await props.params);
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { ContentKitOutput } from '@gitbook/react-contentkit';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
@@ -54,7 +53,6 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
|
||||
{
|
||||
integrationName: block.data.integration,
|
||||
request: initialInput,
|
||||
allowFailedDependency: true,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -68,29 +66,12 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
|
||||
// Integration output can render blocks with generated keys.
|
||||
{...getCommentAnchorProps(context, block.key)}
|
||||
{...getCommentMarkerProps(context, 'data-comment-block')}
|
||||
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
|
||||
)}
|
||||
className={tcls(style)}
|
||||
>
|
||||
<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>
|
||||
<pre>
|
||||
Unexpected error with integration {block.data.integration}:{' '}
|
||||
{initialResponse.error.message}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,11 +11,9 @@ export async function fetchSafeIntegrationUI(
|
||||
{
|
||||
integrationName,
|
||||
request,
|
||||
allowFailedDependency = false,
|
||||
}: {
|
||||
integrationName: string;
|
||||
request: RenderIntegrationUI;
|
||||
allowFailedDependency?: boolean;
|
||||
}
|
||||
) {
|
||||
const output = await ignoreDataFetcherErrors(
|
||||
@@ -29,7 +27,6 @@ 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
|
||||
]
|
||||
);
|
||||
|
||||
@@ -38,7 +38,6 @@ export type OpenAPIBlockClientContextProps = {
|
||||
/** Rendered on the server: both go through the async document pipeline. */
|
||||
headingNode: React.ReactNode;
|
||||
descriptionNode: React.ReactNode;
|
||||
scalarRuntimeURL: string;
|
||||
};
|
||||
|
||||
type OpenAPIBlockVariant =
|
||||
@@ -70,7 +69,6 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
|
||||
renderDocument: () => descriptionNode,
|
||||
renderHeading: () => headingNode,
|
||||
resolveProxyUrl: proxyUrl ? () => proxyUrl : undefined,
|
||||
scalarRuntimeURL: props.scalarRuntimeURL,
|
||||
};
|
||||
|
||||
switch (props.variant) {
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type OpenAPISchemasData,
|
||||
type OpenAPIWebhookData,
|
||||
checkIsValidLocale,
|
||||
extractOrigin,
|
||||
getAllServerOrigins,
|
||||
getOperationTitle,
|
||||
getSchemasHeading,
|
||||
@@ -17,9 +16,7 @@ import { PlainCodeBlock } from '../CodeBlock';
|
||||
import { DocumentView } from '../DocumentView';
|
||||
import { Heading } from '../Heading';
|
||||
import type { OpenAPIBlockClientContextProps } from './OpenAPIBlockClient';
|
||||
import { SCALAR_RUNTIME_PATH } from './scalar-runtime-path';
|
||||
import { DEFAULT_LOCALE, getSpaceLocale } from '@/intl/server';
|
||||
import { getAssetURL } from '@/lib/assets';
|
||||
import type { GitBookAnyContext } from '@/lib/context';
|
||||
import { GITBOOK_URL } from '@/lib/env';
|
||||
import { buildSignedProxyUrl } from '@/lib/openapi/proxy-token';
|
||||
@@ -124,7 +121,6 @@ export function getOpenAPIContext(args: {
|
||||
expandAllResponses: expandAllResponses || props.context.mode === 'print',
|
||||
expandAllModelSections: expandAllModelSections || props.context.mode === 'print',
|
||||
headless,
|
||||
scalarRuntimeURL: getAssetURL(SCALAR_RUNTIME_PATH),
|
||||
id: block.meta?.id,
|
||||
blockKey: block.key,
|
||||
locale,
|
||||
@@ -145,7 +141,7 @@ export function getOpenAPIBlockClientProps(args: {
|
||||
expandAllModelSections?: boolean;
|
||||
headless?: boolean;
|
||||
}): OpenAPIBlockClientContextProps {
|
||||
const { props, data, schemas, specUrl, context } = args;
|
||||
const { props, data, schemas, context } = args;
|
||||
const serverContext = getOpenAPIContext(args);
|
||||
const { renderCodeBlock, renderDocument, renderHeading, resolveProxyUrl, ...serializable } =
|
||||
serverContext;
|
||||
@@ -158,10 +154,6 @@ export function getOpenAPIBlockClientProps(args: {
|
||||
const descriptionDocument = data?.operation['x-gitbook-description-document'];
|
||||
|
||||
const origins = data ? getAllServerOrigins(data.servers) : [];
|
||||
const specOrigin = specUrl ? extractOrigin(specUrl) : null;
|
||||
if (specOrigin) {
|
||||
origins.push(specOrigin);
|
||||
}
|
||||
|
||||
return {
|
||||
...serializable,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export const SCALAR_RUNTIME_PATH = 'scalar/scalar-api-client@1.3.46.mjs';
|
||||
@@ -1,360 +0,0 @@
|
||||
/* The vendor stylesheet is imported by ScalarApiModal so it ships with the lazy client chunk:
|
||||
its `group-has-*` rules make every DOM change restyle the whole document. */
|
||||
@reference "../../RootLayout/globals.css";
|
||||
|
||||
html,
|
||||
body {
|
||||
/** Override Scalar's overscroll-behavior */
|
||||
@apply !overscroll-auto;
|
||||
}
|
||||
|
||||
.light .scalar-modal-layout,
|
||||
.light .scalar-app,
|
||||
.light .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-300, 180 180 180)),
|
||||
rgb(var(--tint-12, 23 23 23)) 96%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.72)
|
||||
);
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-accent: #007d9c;
|
||||
|
||||
--scalar-background-1: rgb(var(--tint-1, 255 255 255));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 96%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 90%
|
||||
);
|
||||
--scalar-background-accent: #007d9c1f;
|
||||
--scalar-code-language-color-supersede: var(--scalar-color-1);
|
||||
--scalar-code-languages-background-supersede: var(--scalar-background-1);
|
||||
--scalar-border-color: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.08)
|
||||
);
|
||||
|
||||
--scalar-color-green: #0a6355;
|
||||
--scalar-color-red: #dc1b19;
|
||||
--scalar-color-yellow: #ffc90d;
|
||||
--scalar-color-blue: rgb(var(--primary-9, 52 109 219));
|
||||
--scalar-color-orange: #ff8d4d;
|
||||
--scalar-color-purple: #8250df;
|
||||
|
||||
--scalar-scrollbar-color: rgba(255, 255, 255, 0.24);
|
||||
--scalar-scrollbar-color-active: rgba(255, 255, 255, 0.48);
|
||||
|
||||
--scalar-button-1: rgb(49 53 56);
|
||||
--scalar-button-1-color: #fff;
|
||||
--scalar-button-1-hover: rgb(28 31 33);
|
||||
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
|
||||
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
|
||||
#eeeeed 0px 0 0 1px;
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--tint-12, 22 22 22));
|
||||
}
|
||||
.dark .scalar-modal-layout,
|
||||
.dark .scalar-app,
|
||||
.dark .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-700, 70 70 70)),
|
||||
rgb(var(--tint-12, 255 255 255)) 100%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.64)
|
||||
);
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-accent: #50b7e0;
|
||||
|
||||
--scalar-background-1: rgb(var(--tint-1, 22 22 22));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 92%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 88%
|
||||
);
|
||||
--scalar-background-accent: #8ab4f81f;
|
||||
--scalar-code-languages-background-supersede: var(--scalar-background-1);
|
||||
--scalar-border-color: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.08)
|
||||
);
|
||||
|
||||
--scalar-color-green: #56b6c2;
|
||||
--scalar-color-red: rgb(245 124 97);
|
||||
--scalar-color-yellow: #edbe20;
|
||||
--scalar-color-blue: rgb(var(--primary-9, 93 138 226));
|
||||
--scalar-color-orange: #d19a66;
|
||||
--scalar-color-purple: #5203d1;
|
||||
|
||||
--scalar-scrollbar-color: rgba(0, 0, 0, 0.18);
|
||||
--scalar-scrollbar-color-active: rgba(0, 0, 0, 0.36);
|
||||
|
||||
--scalar-button-1: #f6f6f6;
|
||||
--scalar-button-1-color: #000;
|
||||
--scalar-button-1-hover: #e7e7e7;
|
||||
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
|
||||
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px, 0 0 0
|
||||
1px rgba(255, 255, 255, 0.1);
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--tint-12, 255 255 255));
|
||||
}
|
||||
.scalar-modal-layout,
|
||||
.scalar-app,
|
||||
.scalar {
|
||||
--scalar-font: initial;
|
||||
--scalar-font-code: var(--font-mono);
|
||||
|
||||
--scalar-paragraph: 16px;
|
||||
--scalar-small: 14px;
|
||||
--scalar-mini: 13px;
|
||||
--scalar-micro: 12px;
|
||||
|
||||
--scalar-bold: 600;
|
||||
--scalar-semibold: 500;
|
||||
--scalar-regular: 400;
|
||||
|
||||
/* Font sizes for interactive applications (not rendered text content) */
|
||||
--scalar-font-size-1: 24px;
|
||||
--scalar-font-size-2: 16px;
|
||||
--scalar-font-size-3: 14px;
|
||||
--scalar-font-size-4: 13px;
|
||||
--scalar-font-size-5: 12px;
|
||||
|
||||
--scalar-line-height-1: 32px;
|
||||
--scalar-line-height-2: 24px;
|
||||
--scalar-line-height-3: 20px;
|
||||
--scalar-line-height-4: 18px;
|
||||
--scalar-line-height-5: 16px;
|
||||
|
||||
--scalar-app-header-height: 35px;
|
||||
}
|
||||
.scalar input::placeholder {
|
||||
color: var(--scalar-color-3);
|
||||
}
|
||||
.scalar .scalar-app-header {
|
||||
width: 100%;
|
||||
z-index: 1000;
|
||||
padding: 6px 12px 6px 12px;
|
||||
border-radius: 0.25rem 0.25rem 0 0;
|
||||
font-size: 14px;
|
||||
height: var(--scalar-app-header-height);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: 6px;
|
||||
}
|
||||
.scalar .scalar-api-client {
|
||||
max-height: calc(100dvh - (100px + var(--scalar-app-header-height))) !important;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.scalar-api-client__close {
|
||||
appearance: none;
|
||||
border: none;
|
||||
outline: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: transparent;
|
||||
color: var(--scalar-color-1);
|
||||
font-size: var(--scalar-small);
|
||||
font-weight: var(--scalar-semibold);
|
||||
}
|
||||
.scalar-api-client__close:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
.scalar .scalar-app-layout {
|
||||
background: var(--scalar-background-3);
|
||||
height: calc(100dvh - 100px);
|
||||
max-width: 1280px;
|
||||
width: 100%;
|
||||
margin: auto;
|
||||
opacity: 0;
|
||||
animation: scalarapiclientfadein 0.35s forwards;
|
||||
z-index: 1002;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@keyframes scalarapiclientfadein {
|
||||
from {
|
||||
transform: translate3d(0, 20px, 0) scale(0.985);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translate3d(0, 0, 0) scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.scalar .scalar-app-exit {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.62);
|
||||
transition: all 0.3s ease-in-out;
|
||||
z-index: 1000;
|
||||
cursor: pointer;
|
||||
animation: scalardrawerexitfadein 0.35s forwards;
|
||||
}
|
||||
@keyframes scalardrawerexitfadein {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.scalar-container {
|
||||
overflow: hidden;
|
||||
visibility: visible;
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.scalar .url-form-input {
|
||||
min-height: auto !important;
|
||||
}
|
||||
|
||||
.scalar .scalar-container {
|
||||
line-height: normal;
|
||||
}
|
||||
.scalar .scalar-app-header span {
|
||||
color: var(--scalar-color-3);
|
||||
}
|
||||
.scalar .scalar-app-header a {
|
||||
color: var(--scalar-color-1);
|
||||
}
|
||||
.scalar .scalar-app-header a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.scalar-activate {
|
||||
width: fit-content;
|
||||
line-height: 24px;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.scalar-activate-button {
|
||||
@apply flex gap-2 items-center;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
|
||||
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
|
||||
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
|
||||
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
|
||||
@apply grow-0 shrink-0 truncate;
|
||||
@apply text-[13px] px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
|
||||
}
|
||||
|
||||
.scalar-activate-button svg {
|
||||
@apply size-2.5;
|
||||
}
|
||||
|
||||
/* Same size as the play icon it replaces, so the button doesn't shift while loading. */
|
||||
.scalar-activate-button .scalar-activate-spinner {
|
||||
@apply animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
.scalar-app-loading {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.scalar .request-method {
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* Use :where to lower specificity to 0 */
|
||||
.scalar .custom-scroll {
|
||||
overflow-y: auto;
|
||||
scrollbar-color: transparent transparent;
|
||||
scrollbar-width: thin;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.scalar .custom-scroll:hover {
|
||||
scrollbar-color: rgba(0, 0, 0, 0.24) transparent;
|
||||
}
|
||||
.dark .scalar .custom-scroll:hover {
|
||||
scrollbar-color: rgba(255, 255, 255, 0.24) transparent;
|
||||
}
|
||||
.scalar .custom-scroll:hover::-webkit-scrollbar-thumb {
|
||||
background: var(--scalar-scrollbar-color, var(--default-theme-scrollbar-color));
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-thumb:active {
|
||||
background: var(--scalar-scrollbar-color-active, var(--default-theme-scrollbar-color-active));
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar {
|
||||
height: 12px;
|
||||
width: 12px;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-thumb {
|
||||
border-radius: 20px;
|
||||
background: transparent;
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.scalar .custom-scroll {
|
||||
padding-right: 12px;
|
||||
}
|
||||
}
|
||||
.dark .scalar .client-wrapper-bg-color {
|
||||
background: linear-gradient(
|
||||
color-mix(in srgb, var(--tw-bg-base) 6%, transparent) 1%,
|
||||
color-mix(in srgb, var(--scalar-background-1) 30%, black) 9%
|
||||
);
|
||||
}
|
||||
.light .scalar .client-wrapper-bg-color {
|
||||
background-color: var(--scalar-background-2) !important;
|
||||
}
|
||||
.scalar .gitbook-show {
|
||||
display: block !important;
|
||||
}
|
||||
.scalar .gitbook-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
@reference "../../RootLayout/globals.css";
|
||||
@import './scalar.css';
|
||||
@import './tryit.css';
|
||||
|
||||
/* Layout Components */
|
||||
.openapi-operation,
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
@reference "../../RootLayout/globals.css";
|
||||
|
||||
.openapi-tryit-activate {
|
||||
@apply flex items-center w-fit;
|
||||
}
|
||||
|
||||
.openapi-tryit-button {
|
||||
@apply flex gap-2 items-center cursor-pointer;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
|
||||
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
|
||||
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
|
||||
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
|
||||
@apply grow-0 shrink-0 truncate;
|
||||
@apply text-[13px] leading-6 px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
|
||||
}
|
||||
|
||||
.openapi-tryit-button svg {
|
||||
@apply size-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-button-spinner {
|
||||
@apply animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
/* Dialog */
|
||||
.openapi-tryit {
|
||||
@apply m-auto p-0 w-[min(72rem,calc(100vw-2rem))] h-[min(48rem,calc(100dvh-2rem))] max-w-none max-h-none;
|
||||
@apply bg-tint-base text-tint border border-tint-subtle shadow-2xl overflow-hidden;
|
||||
@apply rounded-xl straight-corners:rounded-none circular-corners:rounded-2xl;
|
||||
}
|
||||
|
||||
.openapi-tryit::backdrop {
|
||||
@apply bg-tint-12/40 backdrop-blur-xs;
|
||||
}
|
||||
|
||||
.openapi-tryit-layout {
|
||||
@apply flex flex-col h-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-header {
|
||||
@apply flex items-center gap-3 px-4 py-3 border-b border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-url {
|
||||
@apply flex-1 min-w-0 truncate font-mono text-sm text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-url-server {
|
||||
@apply text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-send {
|
||||
@apply shrink-0 cursor-pointer px-3 py-1 text-sm font-medium;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full transition-colors;
|
||||
}
|
||||
|
||||
.openapi-tryit-close {
|
||||
@apply shrink-0 cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-close svg {
|
||||
@apply size-4;
|
||||
}
|
||||
|
||||
.openapi-tryit-body {
|
||||
@apply flex-1 min-h-0 grid grid-cols-1 md:grid-cols-2 overflow-y-auto md:overflow-hidden;
|
||||
}
|
||||
|
||||
.openapi-tryit-request {
|
||||
@apply flex flex-col gap-5 p-4 md:overflow-y-auto border-b md:border-b-0 md:border-r border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-section {
|
||||
@apply flex flex-col gap-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-section-header {
|
||||
@apply flex items-center justify-between gap-3;
|
||||
}
|
||||
|
||||
.openapi-tryit-section-title {
|
||||
@apply text-xs font-semibold uppercase tracking-wide text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-field {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-label {
|
||||
@apply flex flex-wrap items-baseline gap-x-1.5 text-[0.813rem];
|
||||
}
|
||||
|
||||
.openapi-tryit-field-name {
|
||||
@apply font-mono text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-required {
|
||||
@apply text-danger;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-description {
|
||||
@apply text-xs text-tint line-clamp-2 basis-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-input {
|
||||
@apply w-full min-w-0 px-2.5 py-1.5 text-sm font-mono bg-tint-base text-tint-strong border border-tint-subtle placeholder:text-tint/60;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
@apply outline-none focus:border-primary focus:ring-2 focus:ring-primary/20;
|
||||
}
|
||||
|
||||
.openapi-tryit-input-small {
|
||||
@apply w-auto py-1 text-xs;
|
||||
}
|
||||
|
||||
.openapi-tryit-code {
|
||||
@apply resize-y leading-5 whitespace-pre;
|
||||
}
|
||||
|
||||
.openapi-tryit-invalid {
|
||||
@apply border-danger;
|
||||
}
|
||||
|
||||
.openapi-tryit-file {
|
||||
@apply text-sm text-tint file:mr-3 file:px-2.5 file:py-1 file:border file:border-tint-subtle file:bg-tint file:text-tint-strong file:rounded-md file:cursor-pointer;
|
||||
}
|
||||
|
||||
.openapi-tryit-auth {
|
||||
@apply grid grid-cols-1 sm:grid-cols-2 gap-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-hint {
|
||||
@apply text-xs text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-alert {
|
||||
@apply text-sm px-3 py-2 bg-danger text-danger border border-danger-subtle rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-table {
|
||||
@apply flex flex-col border border-tint-subtle divide-y divide-tint-subtle;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-table:empty {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
/* Checkbox · name · value · remove, as a row of a key/value table. */
|
||||
.openapi-tryit-row {
|
||||
@apply grid grid-cols-[auto_minmax(0,1fr)_minmax(0,1.3fr)_1.75rem] gap-x-2 items-center px-2 py-1.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-input {
|
||||
@apply py-1 text-[0.813rem];
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-field-label {
|
||||
@apply min-w-0;
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-field-name {
|
||||
@apply truncate;
|
||||
}
|
||||
|
||||
.openapi-tryit-check {
|
||||
@apply size-3.5 cursor-pointer disabled:cursor-default disabled:opacity-60;
|
||||
accent-color: rgb(var(--primary-9, 52 109 219));
|
||||
}
|
||||
|
||||
.openapi-tryit-row-remove {
|
||||
@apply cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-row-remove svg {
|
||||
@apply size-3.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-add {
|
||||
@apply self-start cursor-pointer px-2.5 py-1 text-xs text-tint-strong border border-dashed border-tint-subtle hover:bg-tint-hover;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
/* Response */
|
||||
.openapi-tryit-response {
|
||||
@apply flex flex-col gap-3 p-4 min-h-48 md:overflow-y-auto bg-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-empty {
|
||||
@apply items-center justify-center text-sm text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-spinner {
|
||||
@apply size-5 rounded-full border-2 border-tint-subtle border-t-primary animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-meta {
|
||||
@apply flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-tint font-mono;
|
||||
}
|
||||
|
||||
.openapi-tryit-tabs {
|
||||
@apply ml-auto flex gap-1;
|
||||
}
|
||||
|
||||
.openapi-tryit-tab {
|
||||
@apply cursor-pointer px-2 py-1 text-xs rounded-md straight-corners:rounded-none circular-corners:rounded-full text-tint hover:text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-tab[aria-selected='true'] {
|
||||
@apply bg-tint-active text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-body {
|
||||
@apply m-0 p-3 text-xs leading-5 font-mono whitespace-pre-wrap break-all text-tint-strong bg-tint-base border border-tint-subtle;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers {
|
||||
@apply m-0 flex flex-col text-xs font-mono;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers > div {
|
||||
@apply grid grid-cols-[minmax(8rem,auto)_1fr] gap-3 py-1.5 border-b border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers dt {
|
||||
@apply text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers dd {
|
||||
@apply m-0 text-tint break-all;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary {
|
||||
@apply flex flex-col gap-3 text-sm;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary img {
|
||||
@apply max-w-full max-h-96 self-start border border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary a {
|
||||
@apply text-primary underline;
|
||||
}
|
||||
@@ -75,7 +75,7 @@ export function Update(props: BlockProps<DocumentBlockUpdate>) {
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style="flex min-w-0 flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
style="flex flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
/>
|
||||
</FilteredUpdate>
|
||||
);
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { LinkContext } from '../primitives';
|
||||
import { useIsVisible } from '../VisibilityContext';
|
||||
@@ -39,10 +37,9 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
trackEvent(
|
||||
{ type: 'search_open' },
|
||||
{ pageId: null, displayContext: SiteInsightsDisplayContext.Embed }
|
||||
);
|
||||
trackEvent({
|
||||
type: 'search_open',
|
||||
});
|
||||
}, [trackEvent, isVisible]);
|
||||
|
||||
const tabsRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -59,7 +56,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -83,7 +79,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -15,7 +15,6 @@ import { Button } from '@/components/primitives/Button';
|
||||
import { DropdownMenuItem, useDropdownMenuClose } from '@/components/primitives/DropdownMenu';
|
||||
import { getURLForLLM } from '@/components/utils';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { getSiteMcpServerName } from '@/lib/mcp/naming';
|
||||
|
||||
type PageActionType = 'button' | 'dropdown-menu-item';
|
||||
|
||||
@@ -297,7 +296,7 @@ export function ActionOpenMCP(props: {
|
||||
const providerInfo = React.useMemo<{ label: string; icon: IconName; url: string }>(() => {
|
||||
switch (provider) {
|
||||
case 'vscode': {
|
||||
const vscodeConfig = { name: getSiteMcpServerName(siteTitle), url: mcpURL };
|
||||
const vscodeConfig = { name: siteTitle, url: mcpURL };
|
||||
return {
|
||||
label: 'VSCode',
|
||||
icon: 'vscode',
|
||||
@@ -333,7 +332,7 @@ export function ActionCopyMCPCommand(props: {
|
||||
const language = useLanguage();
|
||||
|
||||
const slug =
|
||||
getSiteMcpServerName(siteTitle)
|
||||
siteTitle
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '') || 'docs';
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
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 }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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,19 +1,24 @@
|
||||
import assertNever from 'assert-never';
|
||||
import urlJoin from 'url-join';
|
||||
|
||||
import type {
|
||||
RevisionPage,
|
||||
RevisionPageDocument,
|
||||
SiteSection,
|
||||
SiteSectionGroup,
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
type RevisionPage,
|
||||
type RevisionPageDocument,
|
||||
type SiteSection,
|
||||
type 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 { hasConfiguredPageActions } from '../PageActions/pageActionsData';
|
||||
import { PageActionsMenu } from '../PageActions/PageActionsMenu';
|
||||
import {
|
||||
PageActionsDropdown,
|
||||
type PageActionsDropdownURLs,
|
||||
} from '../PageActions/PageActionsDropdown';
|
||||
import { PageAsideToggleButton } from '../PageAside/PageAsideButton';
|
||||
import { PageIcon } from '../PageIcon';
|
||||
import { getPDFURLSearchParams } from '../PDF';
|
||||
import {
|
||||
findBestTargetURL,
|
||||
getTargetURLForSiteSpace,
|
||||
@@ -22,9 +27,11 @@ 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;
|
||||
@@ -139,8 +146,15 @@ 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 hasConfiguredPageActions = [
|
||||
CustomizationPageActionType.Assistant,
|
||||
CustomizationPageActionType.ExternalAi,
|
||||
CustomizationPageActionType.Markdown,
|
||||
CustomizationPageActionType.Mcp,
|
||||
CustomizationPageActionType.Pdf,
|
||||
CustomizationPageActionType.Git,
|
||||
].some((type) => isPageActionEnabled(context.customization, type));
|
||||
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions || withRSSFeed);
|
||||
|
||||
if (!page.layout.title && !page.layout.description && !hasPageActions) {
|
||||
return null;
|
||||
@@ -167,7 +181,19 @@ export async function PageHeader(props: {
|
||||
]
|
||||
)}
|
||||
>
|
||||
{hasPageActions ? <PageActionsMenu context={context} page={page} /> : null}
|
||||
{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}
|
||||
<PageAsideToggleButton />
|
||||
</div>
|
||||
);
|
||||
@@ -494,3 +520,67 @@ 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));
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ export function SearchContainer({
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -179,7 +178,6 @@ export function SearchContainer({
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -27,7 +27,6 @@ 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. */
|
||||
@@ -51,7 +50,6 @@ export function SearchFrame(props: {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
onResultSelect,
|
||||
onResultHover,
|
||||
@@ -80,7 +78,7 @@ export function SearchFrame(props: {
|
||||
fetching ? 'block animate-fade-in' : 'hidden animate-fade-out-slow'
|
||||
)}
|
||||
style={{
|
||||
animationDelay: fetching && results.length === 0 ? '2s' : undefined,
|
||||
animationDelay: fetching ? '2s' : undefined,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -120,7 +118,7 @@ export function SearchFrame(props: {
|
||||
) : (
|
||||
<SearchResults
|
||||
ref={resultsRef}
|
||||
query={resultsQuery}
|
||||
query={query}
|
||||
id={resultsId}
|
||||
fetching={fetching}
|
||||
results={results}
|
||||
|
||||
@@ -135,7 +135,7 @@ export const SearchInput = React.forwardRef<HTMLDivElement, SearchInputProps>(
|
||||
}
|
||||
}
|
||||
trailing={
|
||||
!showAsk && !fetching && value && resultsCount > 0 ? (
|
||||
!showAsk && 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, SearchResultSource } from './search-types';
|
||||
import type { ComputedPageResult } from './search-types';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -14,15 +14,13 @@ import { tcls } from '@/lib/tailwind';
|
||||
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
|
||||
props: {
|
||||
query: string;
|
||||
item: ComputedPageResult & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
item: ComputedPageResult;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const { query, item, active, style, ...rest } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const { preview: bestSection, description, href } = getPageResultPresentation(item);
|
||||
@@ -32,9 +30,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
|
||||
const insights = {
|
||||
type: 'search_open_result' as const,
|
||||
...item.search,
|
||||
position,
|
||||
resultsCount,
|
||||
query,
|
||||
result: {
|
||||
pageId: item.pageId,
|
||||
spaceId: item.spaceId,
|
||||
|
||||
@@ -4,36 +4,24 @@ import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { Favicon } from '../utils';
|
||||
import { HighlightQuery } from './HighlightQuery';
|
||||
import type { ComputedRecordResult, SearchResultSource } from './search-types';
|
||||
import type { ComputedRecordResult } 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 & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
item: ComputedRecordResult;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const { query, item, active, 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}
|
||||
@@ -48,7 +36,13 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
|
||||
fallback={<Icon icon="memo" className="size-4" />}
|
||||
/>
|
||||
}
|
||||
insights={insights}
|
||||
insights={{
|
||||
type: 'search_open_result',
|
||||
query,
|
||||
result: {
|
||||
recordId: item.id,
|
||||
},
|
||||
}}
|
||||
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;
|
||||
const shouldAnimateResults = !query || fetching;
|
||||
const previousCursor = React.useRef<number | null>(cursor);
|
||||
const seenResultKeys = React.useRef(new Set<string>());
|
||||
const lastQuery = React.useRef(query);
|
||||
@@ -228,8 +228,9 @@ 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,
|
||||
@@ -271,8 +272,6 @@ 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`,
|
||||
@@ -342,8 +341,6 @@ 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`,
|
||||
@@ -362,11 +359,15 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
{!fetching && results.length === 0 ? noResults : null}
|
||||
</>
|
||||
)}
|
||||
{fetching && results.length === 0 ? (
|
||||
{fetching ? (
|
||||
<div
|
||||
role="status"
|
||||
aria-busy="true"
|
||||
className="flex animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] flex-col gap-1 motion-reduce:animate-none"
|
||||
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'
|
||||
)}
|
||||
>
|
||||
<SearchResultsPlaceholder />
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
|
||||
import type { OrderedComputedResult } from './search-types';
|
||||
|
||||
describe('computeFilterSiteSpaceIds', () => {
|
||||
@@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDisplayedSearchResults', () => {
|
||||
describe('filterResultsBySiteSpaces', () => {
|
||||
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
|
||||
type: 'page',
|
||||
id,
|
||||
@@ -52,7 +52,7 @@ describe('getDisplayedSearchResults', () => {
|
||||
|
||||
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(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([
|
||||
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
|
||||
'a',
|
||||
'c',
|
||||
]);
|
||||
@@ -60,24 +60,6 @@ describe('getDisplayedSearchResults', () => {
|
||||
|
||||
it('returns every result when the scope is unrestricted', () => {
|
||||
const results = [page('b', 'other'), page('a', 'current')];
|
||||
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),
|
||||
]);
|
||||
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
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.
|
||||
*
|
||||
@@ -32,20 +29,20 @@ export function computeFilterSiteSpaceIds(
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the first results in server order within the selected site spaces. */
|
||||
export function getDisplayedSearchResults<Result extends OrderedComputedResult>(
|
||||
results: Result[],
|
||||
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
|
||||
export function filterResultsBySiteSpaces(
|
||||
results: OrderedComputedResult[],
|
||||
allowedSiteSpaceIds: string[] | undefined
|
||||
): 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;
|
||||
): OrderedComputedResult[] {
|
||||
if (!allowedSiteSpaceIds) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const allowed = new Set(allowedSiteSpaceIds);
|
||||
|
||||
return results.filter(
|
||||
(result) =>
|
||||
result.type === 'record' ||
|
||||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ export function computeRemoteSearchScope(
|
||||
}
|
||||
|
||||
switch (scope) {
|
||||
case 'all':
|
||||
return { mode: 'all' };
|
||||
case 'default':
|
||||
return { mode: 'current', siteSpaceId };
|
||||
case 'extended':
|
||||
|
||||
@@ -87,11 +87,6 @@ describe('createSearchPassStore', () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(authorizations).toEqual(sent);
|
||||
|
||||
const refresh = store.requestPass();
|
||||
expect(await search(store)).toEqual({ type: 'route', reason: undefined });
|
||||
await refresh;
|
||||
expect(authorizations).toEqual(sent);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -141,47 +136,4 @@ describe('createSearchPassStore', () => {
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(authorizations).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('falls back for an unknown space without latching later searches to the route', async () => {
|
||||
let searchCalls = 0;
|
||||
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (
|
||||
input: RequestInfo | URL
|
||||
) => {
|
||||
if (String(input) === '/~gitbook/search-pass') {
|
||||
return Response.json({ token: 'pass-1', expiresIn: 300_000 });
|
||||
}
|
||||
searchCalls += 1;
|
||||
if (searchCalls === 1) {
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
type: 'space',
|
||||
id: 'space_unknown',
|
||||
title: 'Unknown',
|
||||
score: 1,
|
||||
pages: [
|
||||
{
|
||||
id: 'page_1',
|
||||
title: 'Page 1',
|
||||
path: 'page-1',
|
||||
score: 1,
|
||||
rank: 1,
|
||||
ancestors: [],
|
||||
urls: { app: 'https://app.gitbook.com/o/org/s/space' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
return Response.json({ items: [] });
|
||||
}) as typeof fetch);
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
expect(await search(store)).toEqual({ type: 'route', reason: 'unknown_space' });
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(searchCalls).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,12 +124,11 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
|
||||
const search = async (input: {
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope: SearchSiteContentScope;
|
||||
signal: AbortSignal;
|
||||
asEmbeddable: boolean;
|
||||
}): Promise<DirectSearchOutcome> => {
|
||||
const { query, searchId, scope, signal, asEmbeddable } = input;
|
||||
const { query, scope, signal, asEmbeddable } = input;
|
||||
if (!directSearch) {
|
||||
return { type: 'route' };
|
||||
}
|
||||
@@ -140,7 +139,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
return waitForCooldown(state, signal);
|
||||
}
|
||||
if (state.status !== 'ready') {
|
||||
return { type: 'route', reason: state.reason === '401' ? undefined : state.reason };
|
||||
return { type: 'route', reason: state.reason };
|
||||
}
|
||||
if (query.length <= 1) {
|
||||
return { type: 'results', results: [] };
|
||||
@@ -164,7 +163,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope)),
|
||||
credentials: 'omit',
|
||||
signal: request.signal,
|
||||
});
|
||||
@@ -211,8 +210,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
// An unmapped space can come from a structure change after page load; fall back for this query only.
|
||||
return results ? { type: 'results', results } : { type: 'route', reason: 'unknown_space' };
|
||||
return results ? { type: 'results', results } : fallBack('unknown_space');
|
||||
};
|
||||
|
||||
return { requestPass, search };
|
||||
|
||||
@@ -2,10 +2,6 @@ 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;
|
||||
@@ -59,7 +55,6 @@ export type SearchSiteContentScope =
|
||||
|
||||
export interface SearchSiteContentRequest {
|
||||
asEmbeddable?: boolean;
|
||||
searchId?: string;
|
||||
query: string;
|
||||
scope: SearchSiteContentScope;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import { createElement } from 'react';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
|
||||
import { SearchContextProvider, shouldKeepSearchState, useSearchState } from './useSearch';
|
||||
|
||||
function SearchScopeValue() {
|
||||
return useSearchState()?.scope ?? null;
|
||||
}
|
||||
import { shouldKeepSearchState } from './useSearch';
|
||||
|
||||
describe('shouldKeepSearchState', () => {
|
||||
it('discards an empty default search state', () => {
|
||||
@@ -30,25 +23,3 @@ describe('shouldKeepSearchState', () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['scope=all', 'default'],
|
||||
['global=true', 'default'],
|
||||
['scope=current&global=true', 'current'],
|
||||
['scope=extended&global=true', 'extended'],
|
||||
])('resolves %s to %s for a linked search', (params, scope) => {
|
||||
const search = createElement(
|
||||
SearchContextProvider,
|
||||
{ prewarmURL: '/~gitbook/search' },
|
||||
createElement(SearchScopeValue)
|
||||
);
|
||||
|
||||
expect(
|
||||
renderToString(
|
||||
createElement(NuqsTestingAdapter, {
|
||||
searchParams: `q=setup&${params}`,
|
||||
children: search,
|
||||
})
|
||||
)
|
||||
).toBe(scope);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { type Values, parseAsString, parseAsStringLiteral, useQueryStates } from 'nuqs';
|
||||
import {
|
||||
type Values,
|
||||
parseAsBoolean,
|
||||
parseAsString,
|
||||
parseAsStringLiteral,
|
||||
useQueryStates,
|
||||
} from 'nuqs';
|
||||
import React from 'react';
|
||||
|
||||
import type { LinkProps } from '../primitives';
|
||||
@@ -10,6 +16,8 @@ import { useSearchPrewarm } from './useSearchPrewarm';
|
||||
import type { DirectSearchProps } from '@/lib/search-results';
|
||||
|
||||
export type SearchScope =
|
||||
/** Search all content on the site */
|
||||
| 'all'
|
||||
/** Search the current section's variant + matched/default variant for other sections */
|
||||
| 'default'
|
||||
/** Search all variants of the current section */
|
||||
@@ -33,8 +41,9 @@ export interface SearchState {
|
||||
const keyMap = {
|
||||
q: parseAsString,
|
||||
ask: parseAsString,
|
||||
scope: parseAsStringLiteral(['default', 'extended', 'current']).withDefault('default'),
|
||||
scope: parseAsStringLiteral(['all', 'default', 'extended', 'current']).withDefault('default'),
|
||||
section: parseAsString,
|
||||
global: parseAsBoolean, // Legacy support for global=true
|
||||
};
|
||||
|
||||
export type UpdateSearchState = (
|
||||
@@ -53,6 +62,11 @@ function normalizeRawState(values: Values<typeof keyMap>) {
|
||||
if (values.ask === 'true' && values.q) {
|
||||
return { ...values, q: null, ask: values.q };
|
||||
}
|
||||
// Handle legacy global=true
|
||||
if (values.global === true) {
|
||||
return { ...values, scope: 'all' as const, global: null };
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
|
||||
@@ -141,6 +141,7 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey: string;
|
||||
flush: () => void;
|
||||
resultsRef: React.RefObject<SearchResultsRef | null>;
|
||||
abort: () => void;
|
||||
askCount: number;
|
||||
onAskSelect: (index: number) => void;
|
||||
}) {
|
||||
@@ -153,6 +154,7 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect,
|
||||
} = props;
|
||||
@@ -188,6 +190,8 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
|
||||
if (resultsRef.current?.select()) {
|
||||
// Stop any in-flight search request only when activating a result.
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -203,6 +207,7 @@ function useSearchKeyboardNavigation(props: {
|
||||
results.length,
|
||||
onAskSelect,
|
||||
resultsRef,
|
||||
abort,
|
||||
query,
|
||||
fetching,
|
||||
requestKey,
|
||||
@@ -224,11 +229,13 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
pendingOpenRef.current = null;
|
||||
if (results.length > 0) {
|
||||
resultsRef.current?.selectFirst();
|
||||
if (resultsRef.current?.selectFirst()) {
|
||||
abort();
|
||||
}
|
||||
} else if (!error && askCount > 0) {
|
||||
onAskSelect(0);
|
||||
}
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, askCount, onAskSelect]);
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
|
||||
|
||||
return {
|
||||
cursor,
|
||||
@@ -372,10 +379,9 @@ export function useSearchController(
|
||||
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
|
||||
|
||||
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
|
||||
const { results, resultsQuery, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
asEmbeddable,
|
||||
disabled: options.requestsEnabled === false || showAsk || !(normalizedQuery || withAI),
|
||||
retainPreviousResults: Boolean(state?.open),
|
||||
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
|
||||
query: normalizedQuery,
|
||||
siteSpaceId: siteSpace.id,
|
||||
siteSpaceIds,
|
||||
@@ -436,6 +442,7 @@ export function useSearchController(
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect: askInAssistant,
|
||||
});
|
||||
@@ -456,7 +463,6 @@ export function useSearchController(
|
||||
query: normalizedQuery,
|
||||
results,
|
||||
resultsId: searchResultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
|
||||
@@ -8,36 +8,22 @@ import {
|
||||
createRecommendedQuestionResult,
|
||||
getEmptySearchResults,
|
||||
} from './empty-search-results';
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } 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,
|
||||
SearchResultSource,
|
||||
SearchSiteContentScope,
|
||||
} from './search-types';
|
||||
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
|
||||
import { streamRecommendedQuestions } from './server-actions';
|
||||
import { type SearchScope, useSearchPass } from './useSearch';
|
||||
import { useAI } from '@/components/AI';
|
||||
|
||||
export type ResultType = RemoteSearchResult | RecommendedQuestionResult;
|
||||
|
||||
const SEARCH_ID_BYTES = 16;
|
||||
|
||||
type RemoteSearchResult = OrderedComputedResult & SearchResultSource;
|
||||
|
||||
type SearchAnswer = {
|
||||
scopeKey: string;
|
||||
query: string;
|
||||
results: RemoteSearchResult[];
|
||||
};
|
||||
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
|
||||
|
||||
type RemoteSearchState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading'; requestKey: string; answer?: SearchAnswer }
|
||||
| { status: 'ready'; requestKey: string; answer: SearchAnswer }
|
||||
| { status: 'error'; requestKey: string };
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
|
||||
| { status: 'error' };
|
||||
|
||||
/**
|
||||
* We cache the recommended questions globally to avoid calling the API multiple times
|
||||
@@ -51,7 +37,6 @@ export function useSearchResults(props: {
|
||||
asEmbeddable?: boolean;
|
||||
disabled: boolean;
|
||||
query: string;
|
||||
retainPreviousResults: boolean;
|
||||
siteSpaceId: string;
|
||||
siteSpaceIds: string[];
|
||||
selectedSectionSiteSpaceIds?: string[];
|
||||
@@ -68,7 +53,6 @@ export function useSearchResults(props: {
|
||||
asEmbeddable,
|
||||
disabled,
|
||||
query,
|
||||
retainPreviousResults,
|
||||
siteSpaceId,
|
||||
siteSpaceIds,
|
||||
selectedSectionSiteSpaceIds,
|
||||
@@ -99,15 +83,8 @@ export function useSearchResults(props: {
|
||||
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
|
||||
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
|
||||
);
|
||||
const scopeKey = JSON.stringify([
|
||||
searchURL,
|
||||
asEmbeddable,
|
||||
siteSpaceId,
|
||||
scope,
|
||||
remoteScope,
|
||||
filterSiteSpaceIds,
|
||||
]);
|
||||
const requestKey = JSON.stringify([scopeKey, query]);
|
||||
// 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 [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
|
||||
|
||||
@@ -123,7 +100,6 @@ export function useSearchResults(props: {
|
||||
|
||||
React.useEffect(() => {
|
||||
if (disabled) {
|
||||
setRemoteState({ status: 'idle' });
|
||||
return;
|
||||
}
|
||||
if (!query) {
|
||||
@@ -150,7 +126,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>();
|
||||
let recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
const recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
|
||||
if (suggestions && suggestions.length > 0) {
|
||||
suggestions.forEach((question) => {
|
||||
@@ -177,10 +153,7 @@ export function useSearchResults(props: {
|
||||
}
|
||||
|
||||
questions.add(question);
|
||||
recommendedQuestions = [
|
||||
...recommendedQuestions,
|
||||
createRecommendedQuestionResult(question, question),
|
||||
];
|
||||
recommendedQuestions.push(createRecommendedQuestionResult(question, question));
|
||||
cachedRecommendedQuestions.set(siteSpaceId, recommendedQuestions);
|
||||
|
||||
if (!cancelled) {
|
||||
@@ -195,19 +168,14 @@ export function useSearchResults(props: {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}
|
||||
setRemoteState((state) => {
|
||||
const answer = 'answer' in state ? state.answer : undefined;
|
||||
return answer?.scopeKey === scopeKey
|
||||
? { status: 'loading', requestKey, answer }
|
||||
: { status: 'loading', requestKey };
|
||||
});
|
||||
setRemoteState({ status: 'loading' });
|
||||
let cancelled = false;
|
||||
const abortController = new AbortController();
|
||||
const send = async () => {
|
||||
flushRef.current = null;
|
||||
const fetchSearch = (
|
||||
scope: Parameters<typeof fetchSearchResults>[1]
|
||||
): Promise<RemoteSearchResult[]> =>
|
||||
): Promise<OrderedComputedResult[]> =>
|
||||
fetchSearchResults(
|
||||
searchURL,
|
||||
scope,
|
||||
@@ -220,29 +188,25 @@ export function useSearchResults(props: {
|
||||
try {
|
||||
const resultsPromise = fetchSearch(remoteScope);
|
||||
|
||||
const onResults = (results: RemoteSearchResult[]) => {
|
||||
const onResults = (results: OrderedComputedResult[]) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!results) {
|
||||
// Can happen when the route cannot be found and returns the page's html.
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
setRemoteState({ status: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoteState({
|
||||
status: 'ready',
|
||||
requestKey,
|
||||
answer: { scopeKey, query, results },
|
||||
});
|
||||
setRemoteState({ status: 'ready', requestKey, results });
|
||||
trackEvent({ type: 'search_type_query', query });
|
||||
};
|
||||
const onError = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
setRemoteState({ status: 'error' });
|
||||
};
|
||||
|
||||
await resultsPromise.then(onResults, onError);
|
||||
@@ -251,10 +215,10 @@ export function useSearchResults(props: {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
setRemoteState({ status: 'error' });
|
||||
}
|
||||
};
|
||||
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
|
||||
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 150);
|
||||
flushRef.current = () => {
|
||||
clearTimeout(timeout);
|
||||
void send();
|
||||
@@ -277,7 +241,6 @@ export function useSearchResults(props: {
|
||||
query,
|
||||
remoteScope,
|
||||
requestKey,
|
||||
scopeKey,
|
||||
trackEvent,
|
||||
withAI,
|
||||
siteSpaceId,
|
||||
@@ -289,16 +252,6 @@ 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?.();
|
||||
}, []);
|
||||
@@ -309,20 +262,10 @@ 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 =
|
||||
streamedQuestions ??
|
||||
cachedRecommendedQuestions.get(siteSpaceId) ??
|
||||
suggestions?.map((question, index) =>
|
||||
createRecommendedQuestionResult(`recommended-question-${index}`, question)
|
||||
) ??
|
||||
@@ -335,32 +278,27 @@ export function useSearchResults(props: {
|
||||
});
|
||||
}
|
||||
|
||||
return visibleAnswer
|
||||
? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds)
|
||||
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
|
||||
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
|
||||
: [];
|
||||
}, [
|
||||
visibleAnswer,
|
||||
remoteState,
|
||||
requestKey,
|
||||
query,
|
||||
filterSiteSpaceIds,
|
||||
withAI,
|
||||
streamedQuestions,
|
||||
siteSpaceId,
|
||||
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,
|
||||
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,
|
||||
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
|
||||
error: remoteState.status === 'error',
|
||||
requestKey,
|
||||
flush,
|
||||
abort,
|
||||
@@ -377,21 +315,17 @@ async function fetchSearchResults(
|
||||
signal: AbortSignal,
|
||||
asEmbeddable: boolean | undefined,
|
||||
searchPass: SearchPassStore | null
|
||||
): Promise<RemoteSearchResult[]> {
|
||||
const directSearchId = generateSearchId();
|
||||
): Promise<OrderedComputedResult[]> {
|
||||
const direct = await searchPass?.search({
|
||||
query,
|
||||
searchId: directSearchId,
|
||||
scope,
|
||||
signal,
|
||||
asEmbeddable: Boolean(asEmbeddable),
|
||||
});
|
||||
if (direct?.type === 'results') {
|
||||
const search = { query, searchId: directSearchId };
|
||||
return direct.results.map((result) => ({ ...result, search }));
|
||||
return direct.results;
|
||||
}
|
||||
|
||||
const searchId = direct ? generateSearchId() : directSearchId;
|
||||
const response = await fetch(searchURL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -401,7 +335,6 @@ async function fetchSearchResults(
|
||||
body: JSON.stringify({
|
||||
asEmbeddable,
|
||||
query,
|
||||
searchId,
|
||||
scope,
|
||||
}),
|
||||
signal,
|
||||
@@ -411,12 +344,5 @@ async function fetchSearchResults(
|
||||
throw new Error(`Search request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
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('');
|
||||
return response.json() as Promise<OrderedComputedResult[]>;
|
||||
}
|
||||
|
||||
@@ -17,11 +17,9 @@ export function useSearchResultsCursor(props: {
|
||||
}, [query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (fetching) {
|
||||
if (resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
}
|
||||
if (fetching && resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getAdvertisedMcpEndpoint, getLLMsTxtURL } from '@/lib/llms-directive';
|
||||
import { getLLMsTxtURL } from '@/lib/llms-directive';
|
||||
|
||||
/**
|
||||
* Agent-facing pointer to the site index, the Markdown versions of pages and the MCP server.
|
||||
* Agent-facing pointer to the site index and the Markdown versions of pages.
|
||||
*/
|
||||
export function LLMsTxtDirective(props: { context: GitBookSiteContext }) {
|
||||
const { context } = props;
|
||||
const mcpEndpoint = getAdvertisedMcpEndpoint(context);
|
||||
|
||||
return (
|
||||
<div className="sr-only">
|
||||
For the complete documentation index, see <a href={getLLMsTxtURL(context)}>llms.txt</a>.
|
||||
Markdown versions of documentation pages are available by appending <code>.md</code> to
|
||||
page URLs.
|
||||
{mcpEndpoint ? (
|
||||
<>
|
||||
{' '}
|
||||
Agents can also search and read this documentation through its{' '}
|
||||
<a href={mcpEndpoint}>MCP server</a>.
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -241,7 +241,6 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
|
||||
return {
|
||||
title: getPageFullTitle(context, page),
|
||||
description: page.description ?? '',
|
||||
keywords: page.keywords?.length ? page.keywords : undefined,
|
||||
alternates: {
|
||||
canonical,
|
||||
languages: alternates?.languages,
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const {
|
||||
fetchPageData,
|
||||
getLowercasePathnameRedirect,
|
||||
startSitePagePlan,
|
||||
resolveMissingPagePath,
|
||||
resolveSitePageFromURL,
|
||||
} = await import('./fetch');
|
||||
@@ -25,6 +25,81 @@ 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 };
|
||||
@@ -209,45 +284,3 @@ describe('getLowercasePathnameRedirect', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('startSitePagePlan', () => {
|
||||
function createContext(getRevisionPageDocument: (params: unknown) => Promise<unknown>) {
|
||||
return {
|
||||
space: { id: 'space-1' },
|
||||
revisionId: 'revision-1',
|
||||
revision: { pages: [page] },
|
||||
siteSpace: { id: 'site-space-1', pageId: null },
|
||||
dataFetcher: { getRevisionPageDocument: mock(getRevisionPageDocument) },
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
|
||||
it('requests the document of the page at the lowercased path', () => {
|
||||
const context = createContext(async () => ({ data: {} }));
|
||||
startSitePagePlan(context, { pathname: 'ReadMe' });
|
||||
expect(context.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing when the path does not resolve to a page', () => {
|
||||
const context = createContext(async () => ({ data: {} }));
|
||||
startSitePagePlan(context, { pathname: 'missing' });
|
||||
expect(context.dataFetcher.getRevisionPageDocument).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not leak a rejection when the request fails', async () => {
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown) => unhandled.push(reason);
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
try {
|
||||
const context = createContext(async () => ({ error: { code: 500, message: 'boom' } }));
|
||||
startSitePagePlan(context, { pathname: 'readme' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
expect(unhandled).toEqual([]);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
import { after } from 'next/server';
|
||||
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
type RevisionPageDocument,
|
||||
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { runSitePagePlan } from './plan';
|
||||
import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/context';
|
||||
import { getDataOrNull } from '@/lib/data';
|
||||
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
|
||||
import { withLeadingSlash } from '@/lib/paths';
|
||||
import { getRequestPlanStats, logPlanStats, markPlanStart, planScope } from '@/lib/plan-stats';
|
||||
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
|
||||
|
||||
const MAX_PAGE_URL_REDIRECTS = 5;
|
||||
@@ -32,7 +30,34 @@ export type PageParams = PagePathParams | PageIdParams;
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
|
||||
const pageTarget = await resolvePage(context, params);
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
context: {
|
||||
@@ -43,25 +68,6 @@ export async function fetchPageData(context: GitBookSiteContext, params: PagePar
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the site page plan from `generateViewport`, which Next runs before the page itself.
|
||||
*/
|
||||
export function startSitePagePlan(context: GitBookSiteContext, params: PagePathParams) {
|
||||
const pathname = getPathnameParam(params).toLowerCase();
|
||||
const resolved = resolveSiteSpacePagePath(context.siteSpace, context.revision.pages, pathname);
|
||||
if (resolved) {
|
||||
// TEMP: the scope marks the plan's calls, and the stats are logged once the response is sent.
|
||||
const stats = getRequestPlanStats();
|
||||
markPlanStart(stats);
|
||||
planScope.run(true, () => void runSitePagePlan(context, resolved.page));
|
||||
try {
|
||||
after(() => logPlanStats(stats));
|
||||
} catch {
|
||||
// Outside a request (tests, build), there is nothing to log.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a page from the params.
|
||||
* If the path can't be found, we try to resolve it from the API to handle redirects.
|
||||
|
||||
@@ -1,527 +0,0 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { runSitePagePlan } = await import('./plan');
|
||||
|
||||
const page = { id: 'page-1', type: 'document' } as RevisionPageDocument;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function setup(options: {
|
||||
customization?: Record<string, unknown>;
|
||||
embed?: unknown;
|
||||
document?: unknown;
|
||||
metaLinks?: unknown;
|
||||
documentPromise?: Promise<unknown>;
|
||||
resolveRefError?: boolean;
|
||||
}) {
|
||||
const dataFetcher = {
|
||||
getRevisionPageDocument: mock(
|
||||
() => options.documentPromise ?? Promise.resolve({ data: options.document ?? null })
|
||||
),
|
||||
listRevisionPageMetaLinks: mock(async () => ({ data: options.metaLinks ?? null })),
|
||||
getEmbedByUrl: mock(async () => ({ data: options.embed ?? {} })),
|
||||
getRevision: mock(async () => ({ data: {} })),
|
||||
};
|
||||
const imageResizer = { getImageSize: mock(async () => ({ width: 1, height: 1 })) };
|
||||
const context = {
|
||||
space: { id: 'space-1' },
|
||||
revisionId: 'revision-1',
|
||||
customization: {
|
||||
styling: { icons: 'regular' },
|
||||
header: {},
|
||||
footer: {},
|
||||
favicon: {},
|
||||
...options.customization,
|
||||
},
|
||||
structure: {
|
||||
type: 'siteSpaces',
|
||||
structure: [
|
||||
{ id: 'ss-1', space: { id: 'space-1', revision: 'revision-1' } },
|
||||
{ id: 'ss-2', space: { id: 'space-2', revision: 'revision-2' } },
|
||||
],
|
||||
},
|
||||
dataFetcher,
|
||||
imageResizer,
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
const resolveRef = mock(
|
||||
async (_doc: unknown, ref: { kind: string }, _ctx?: unknown, _opts?: unknown) => {
|
||||
if (options.resolveRefError) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
return ref.kind === 'file'
|
||||
? {
|
||||
href: 'https://files/image.png',
|
||||
file: {
|
||||
dimensions: undefined,
|
||||
contentType: 'image/png',
|
||||
downloadURL: 'https://files/download.png',
|
||||
},
|
||||
}
|
||||
: { href: '/x' };
|
||||
}
|
||||
);
|
||||
const loadIcons = mock(async () => ({}));
|
||||
const loadGitMetadata = mock(async () => undefined);
|
||||
return { context, dataFetcher, imageResizer, resolveRef, loadIcons, loadGitMetadata };
|
||||
}
|
||||
|
||||
const doc = (nodes: unknown[]) => ({ object: 'document', nodes }) as unknown as JSONDocument;
|
||||
|
||||
describe('runSitePagePlan', () => {
|
||||
it('requests the document and the meta links in parallel', async () => {
|
||||
const pending = deferred<unknown>();
|
||||
const s = setup({ documentPromise: pending.promise });
|
||||
const done = runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
expect(s.dataFetcher.listRevisionPageMetaLinks).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
pending.resolve({ data: null });
|
||||
await done;
|
||||
});
|
||||
|
||||
it('starts the Git metadata of the page for the Edit on Git action', async () => {
|
||||
const s = setup({});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.loadGitMetadata).toHaveBeenCalledWith(s.context, page);
|
||||
});
|
||||
|
||||
it('resolves cross-space links of the layout and the table of contents', async () => {
|
||||
const ref = (space: string, page: string) => ({ kind: 'page', space, page });
|
||||
const s = setup({
|
||||
customization: {
|
||||
header: {
|
||||
primaryLink: ref('space-2', 'primary'),
|
||||
links: [
|
||||
{
|
||||
title: 'Docs',
|
||||
to: ref('space-2', 'top'),
|
||||
links: [{ title: 'API', to: ref('space-2', 'nested') }],
|
||||
},
|
||||
{ title: 'Here', to: { kind: 'page', page: 'same-space' } },
|
||||
],
|
||||
},
|
||||
footer: { groups: [{ title: 'More', links: [{ to: ref('space-2', 'footer') }] }] },
|
||||
announcement: {
|
||||
enabled: true,
|
||||
message: 'Hi',
|
||||
link: { to: ref('space-2', 'announce') },
|
||||
},
|
||||
},
|
||||
});
|
||||
(s.context as unknown as { revision: unknown }).revision = {
|
||||
pages: [
|
||||
{
|
||||
type: 'group',
|
||||
pages: [{ type: 'link', target: ref('space-2', 'toc') }],
|
||||
},
|
||||
],
|
||||
};
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const resolved = s.resolveRef.mock.calls.map(([d, r]) => [
|
||||
d,
|
||||
(r as { page?: string }).page,
|
||||
]);
|
||||
for (const name of ['primary', 'top', 'nested', 'footer', 'announce', 'toc']) {
|
||||
expect(resolved).toContainEqual([null, name]);
|
||||
}
|
||||
expect(resolved).not.toContainEqual([null, 'same-space']);
|
||||
});
|
||||
|
||||
it('skips hidden table of contents links and a disabled announcement', async () => {
|
||||
const ref = (page: string) => ({ kind: 'page', space: 'space-2', page });
|
||||
const s = setup({
|
||||
customization: {
|
||||
announcement: { enabled: false, message: 'Hi', link: { to: ref('announce') } },
|
||||
},
|
||||
});
|
||||
(s.context as unknown as { revision: unknown }).revision = {
|
||||
pages: [
|
||||
{ type: 'link', hidden: true, target: ref('hidden-link') },
|
||||
{ type: 'group', hidden: true, pages: [{ type: 'link', target: ref('inside') }] },
|
||||
],
|
||||
};
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts embeds from the document with the page space', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{ object: 'block', type: 'embed', data: { url: 'https://a.example' }, nodes: [] },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
|
||||
url: 'https://a.example',
|
||||
spaceId: 'space-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves network refs of nested blocks and inlines, with anchor text for mentions', async () => {
|
||||
const link = { kind: 'page', space: 'space-2', page: 'p2' };
|
||||
const mention = { kind: 'anchor', page: 'p3', anchor: 'a' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{ object: 'inline', type: 'link', data: { ref: link }, nodes: [] },
|
||||
{ object: 'inline', type: 'mention', data: { ref: mention }, nodes: [] },
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
|
||||
expect(calls).toContainEqual([link, {}]);
|
||||
expect(calls).toContainEqual([mention, { resolveAnchorText: true }]);
|
||||
});
|
||||
|
||||
it('skips refs that resolve without a request', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'inline',
|
||||
type: 'link',
|
||||
data: { ref: { kind: 'page', page: 'p2' } },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('measures images without known dimensions like the image block does', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'images',
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'image',
|
||||
data: { ref: { kind: 'file', file: 'f1' } },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://files/image.png', {
|
||||
dpr: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('starts the revision of cross-space image files in the site', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'image',
|
||||
data: { ref: { kind: 'file', space: 'space-2', file: 'f1' } },
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
});
|
||||
|
||||
it('measures card covers and resolves cross-space card targets', async () => {
|
||||
const target = { kind: 'page', space: 'space-2', page: 'p2' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'table',
|
||||
data: {
|
||||
view: {
|
||||
type: 'cards',
|
||||
columns: [],
|
||||
coverDefinition: 'cover',
|
||||
coverDefinitionDark: 'coverDark',
|
||||
targetDefinition: 'target',
|
||||
},
|
||||
definition: {},
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
cover: { kind: 'file', file: 'f1' },
|
||||
coverDark: { kind: 'file', file: 'f2' },
|
||||
target,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const refs = s.resolveRef.mock.calls.map(([, ref]) => ref);
|
||||
expect(refs).toContainEqual({ kind: 'file', file: 'f1' });
|
||||
expect(refs).toContainEqual({ kind: 'file', file: 'f2' });
|
||||
expect(refs).toContainEqual(target);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(2);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
});
|
||||
|
||||
it('starts the requests of visible table columns only', async () => {
|
||||
const anchor = { kind: 'anchor', page: 'p3', anchor: 'a' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'table',
|
||||
data: {
|
||||
view: { type: 'grid', columns: ['people', 'link', 'picture'] },
|
||||
definition: {
|
||||
people: { type: 'users' },
|
||||
link: { type: 'content-ref' },
|
||||
picture: { type: 'image' },
|
||||
hidden: { type: 'users' },
|
||||
},
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
people: ['u1'],
|
||||
link: anchor,
|
||||
picture: { ref: { kind: 'file', file: 'f1' } },
|
||||
hidden: ['u2'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
|
||||
expect(calls).toContainEqual([{ kind: 'user', user: 'u1' }, {}]);
|
||||
expect(calls).toContainEqual([anchor, { resolveAnchorText: true }]);
|
||||
expect(calls).toContainEqual([{ kind: 'file', file: 'f1' }, {}]);
|
||||
expect(calls).not.toContainEqual([{ kind: 'user', user: 'u2' }, {}]);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps planning after a malformed table and skips values the render skips', async () => {
|
||||
const table = (data: unknown) => ({ object: 'block', type: 'table', data, nodes: [] });
|
||||
const s = setup({
|
||||
document: doc([
|
||||
table({ view: { type: 'grid', columns: ['a'] }, records: { r1: {} } }),
|
||||
table({
|
||||
view: {
|
||||
type: 'cards',
|
||||
columns: ['img', 'people'],
|
||||
coverDefinitionDark: 'dark',
|
||||
},
|
||||
definition: { img: { type: 'image' }, people: { type: 'users' } },
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
img: { ref: undefined },
|
||||
people: ['u1', 2],
|
||||
dark: { kind: 'file', file: 'f2' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ object: 'block', type: 'embed', data: { url: 'https://after' }, nodes: [] },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
|
||||
url: 'https://after',
|
||||
spaceId: 'space-1',
|
||||
});
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
expect(s.imageResizer.getImageSize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('measures the site logos, and the custom icon only without a header logo', async () => {
|
||||
const withLogo = setup({
|
||||
customization: {
|
||||
header: { logo: { light: 'https://l/h.png', dark: 'https://l/hd.png' } },
|
||||
footer: { logo: { light: 'https://l/f.png' } },
|
||||
favicon: { icon: { light: 'https://l/i.png', dark: 'https://l/id.png' } },
|
||||
},
|
||||
});
|
||||
await runSitePagePlan(withLogo.context, page, withLogo);
|
||||
const measured = withLogo.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(measured).toContainEqual(['https://l/h.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://l/hd.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://l/f.png', { dpr: 2 }]);
|
||||
expect(measured).not.toContainEqual(['https://l/i.png', { dpr: 2 }]);
|
||||
|
||||
const iconOnly = setup({
|
||||
customization: {
|
||||
favicon: { icon: { light: 'https://l/i.png', dark: 'https://l/id.png' } },
|
||||
},
|
||||
});
|
||||
await runSitePagePlan(iconOnly.context, page, iconOnly);
|
||||
const iconCalls = iconOnly.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(iconCalls).toContainEqual(['https://l/i.png', { dpr: 2 }]);
|
||||
expect(iconCalls).toContainEqual(['https://l/id.png', { dpr: 2 }]);
|
||||
});
|
||||
|
||||
it('measures the page cover like PageCover, only when the layout shows it', async () => {
|
||||
const cover = { ref: { kind: 'file', file: 'c1' }, refDark: { kind: 'file', file: 'c2' } };
|
||||
const s = setup({});
|
||||
await runSitePagePlan(
|
||||
s.context,
|
||||
{
|
||||
...page,
|
||||
cover,
|
||||
layout: { cover: true, coverSize: 'hero' },
|
||||
} as unknown as RevisionPageDocument,
|
||||
s
|
||||
);
|
||||
const refs = s.resolveRef.mock.calls.map(([d, ref]) => [d, ref]);
|
||||
expect(refs).toContainEqual([null, cover.ref]);
|
||||
expect(refs).toContainEqual([null, cover.refDark]);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://files/image.png', {});
|
||||
|
||||
const hidden = setup({});
|
||||
await runSitePagePlan(
|
||||
hidden.context,
|
||||
{
|
||||
...page,
|
||||
cover,
|
||||
layout: { cover: false, coverSize: 'hero' },
|
||||
} as unknown as RevisionPageDocument,
|
||||
hidden
|
||||
);
|
||||
expect(hidden.imageResizer.getImageSize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('measures inline images, drawings and image files like their blocks', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'inline',
|
||||
type: 'inline-image',
|
||||
data: { ref: { kind: 'file', file: 'i1' }, size: 'line' },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
object: 'block',
|
||||
type: 'drawing',
|
||||
data: { ref: { kind: 'file', file: 'd1' } },
|
||||
nodes: [],
|
||||
},
|
||||
{ object: 'block', type: 'file', data: { ref: { kind: 'file', file: 'f1' } } },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const measured = s.imageResizer.getImageSize.mock.calls as unknown[][];
|
||||
expect(measured).toContainEqual(['https://files/image.png', { dpr: 2 }]);
|
||||
expect(measured).toContainEqual(['https://files/image.png', { dpr: 3 }]);
|
||||
expect(measured).toContainEqual(['https://files/download.png', { dpr: 2 }]);
|
||||
});
|
||||
|
||||
it('measures the icon of link embeds once the embed arrives', async () => {
|
||||
const s = setup({
|
||||
embed: { type: 'link', icon: 'https://site/icon.png' },
|
||||
document: doc([{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] }]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://site/icon.png', {
|
||||
dpr: 2,
|
||||
});
|
||||
|
||||
const rich = setup({
|
||||
embed: { type: 'rich', icon: 'https://site/icon.png' },
|
||||
document: doc([{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] }]),
|
||||
});
|
||||
await runSitePagePlan(rich.context, page, rich);
|
||||
expect(rich.imageResizer.getImageSize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts the revision of meta-link alternates in the site alongside their space', async () => {
|
||||
const alternate = { kind: 'page', space: 'space-2', page: 'p9' };
|
||||
const s = setup({ metaLinks: { canonical: null, alternates: [alternate] } });
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
expect(s.resolveRef.mock.calls.map(([, ref]) => ref)).toContainEqual(alternate);
|
||||
});
|
||||
|
||||
it('settles without unhandled rejections when every branch fails', async () => {
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown) => unhandled.push(reason);
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
try {
|
||||
const s = setup({
|
||||
resolveRefError: true,
|
||||
metaLinks: { alternates: [{ kind: 'page', space: 'space-2', page: 'p' }] },
|
||||
document: doc([
|
||||
{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] },
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [{ object: 'inline', type: 'link', data: { ref: { kind: 'url' } } }],
|
||||
},
|
||||
]),
|
||||
});
|
||||
s.dataFetcher.getEmbedByUrl.mockImplementation(async () => {
|
||||
throw new Error('embed');
|
||||
});
|
||||
s.loadIcons.mockImplementation(async () => {
|
||||
throw new Error('icons');
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(unhandled).toEqual([]);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,393 +0,0 @@
|
||||
import type {
|
||||
ContentRef,
|
||||
DocumentBlockTable,
|
||||
JSONDocument,
|
||||
RevisionPageDocument,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import {
|
||||
getRecordCardCovers,
|
||||
isDocumentTableImageRecord,
|
||||
isStringArray,
|
||||
} from '@/components/DocumentView/Table/utils';
|
||||
import { getPageGitMetadata } from '@/components/PageActions/pageActionsData';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getDataOrNull, getPageDocument } from '@/lib/data';
|
||||
import { getSimplifiedContentType } from '@/lib/files';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
getCustomizationIconStyle,
|
||||
getInlineIconSources,
|
||||
} from '@/lib/icons/inline';
|
||||
import {
|
||||
type ResolveContentRefOptions,
|
||||
resolveContentRef,
|
||||
resolveContentRefInDocument,
|
||||
} from '@/lib/references';
|
||||
import { findSiteSpaceBy } from '@/lib/sites';
|
||||
|
||||
type Deps = {
|
||||
/** `document` is null for refs that don't come from the page document (meta links). */
|
||||
resolveRef: (
|
||||
document: JSONDocument | null,
|
||||
ref: ContentRef,
|
||||
context: GitBookSiteContext,
|
||||
options: ResolveContentRefOptions
|
||||
) => Promise<unknown>;
|
||||
loadIcons: (context: GitBookSiteContext, document: JSONDocument) => Promise<unknown>;
|
||||
loadGitMetadata: (context: GitBookSiteContext, page: RevisionPageDocument) => Promise<unknown>;
|
||||
};
|
||||
|
||||
const defaultDeps: Deps = {
|
||||
resolveRef: (document, ref, context, options) =>
|
||||
document
|
||||
? resolveContentRefInDocument(document, ref, context, options)
|
||||
: resolveContentRef(ref, context, options),
|
||||
loadIcons: (context, document) =>
|
||||
getInlineIconSources(
|
||||
getContentInlineIconSourceRequests({
|
||||
iconStyle: getCustomizationIconStyle(context.customization),
|
||||
document,
|
||||
})
|
||||
),
|
||||
loadGitMetadata: getPageGitMetadata,
|
||||
};
|
||||
|
||||
type Node = { object?: string; type?: string; data?: Record<string, unknown>; nodes?: unknown };
|
||||
|
||||
/** Node types the render resolves with `resolveAnchorText: true` (an extra page document). */
|
||||
const ANCHOR_TEXT_TYPES = new Set(['mention', 'content-ref']);
|
||||
|
||||
/**
|
||||
* Start every request a site page render will make, as soon as its input is known, instead of
|
||||
* when React reaches the component that needs it. Each call is the one the render makes, with
|
||||
* the same arguments, so the render reuses it through the per-request memo of the data fetcher
|
||||
* (and of the image size and icon helpers). Failures are left for the render to surface.
|
||||
*/
|
||||
export function runSitePagePlan(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument,
|
||||
deps: Deps = defaultDeps
|
||||
): Promise<void> {
|
||||
const pending: Promise<unknown>[] = [];
|
||||
const start = (fn: () => Promise<unknown>) => {
|
||||
let promise: Promise<unknown>;
|
||||
try {
|
||||
promise = fn();
|
||||
} catch (error) {
|
||||
promise = Promise.reject(error);
|
||||
}
|
||||
pending.push(promise.catch(() => {}));
|
||||
};
|
||||
|
||||
const measure = (src: string | undefined, options: { dpr?: number }) => {
|
||||
const resizer = context.imageResizer;
|
||||
if (src && resizer) {
|
||||
start(() => resizer.getImageSize(src, options));
|
||||
}
|
||||
};
|
||||
|
||||
const resolveFile = (document: JSONDocument | null, ref: ContentRef) =>
|
||||
deps.resolveRef(document, ref, context, {}) as Promise<{
|
||||
href: string;
|
||||
file?: { dimensions?: unknown; contentType?: string; downloadURL?: string };
|
||||
} | null>;
|
||||
|
||||
const resolveRef = (document: JSONDocument | null, ref: ContentRef, anchorText: boolean) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(() =>
|
||||
deps.resolveRef(document, ref, context, anchorText ? { resolveAnchorText: true } : {})
|
||||
);
|
||||
};
|
||||
|
||||
// Cross-space refs fetch the space, then its revision; the site structure already knows the
|
||||
// revision, so start both. A stale structure only costs one unused (usually cached) call.
|
||||
const startSpaceRevisionFor = (ref: ContentRef) => {
|
||||
const spaceId = 'space' in ref ? ref.space : undefined;
|
||||
if (!spaceId || spaceId === context.space.id) {
|
||||
return;
|
||||
}
|
||||
const found = findSiteSpaceBy(context.structure, (s) => s.space.id === spaceId);
|
||||
if (found) {
|
||||
start(() =>
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId,
|
||||
revisionId: found.siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const ids = { spaceId: context.space.id, revisionId: context.revisionId, pageId: page.id };
|
||||
|
||||
// The Edit on Git action reloads the page with its Git metadata, which the revision tree omits.
|
||||
start(() => deps.loadGitMetadata(context, page));
|
||||
|
||||
start(async () => {
|
||||
const links = await getDataOrNull(context.dataFetcher.listRevisionPageMetaLinks(ids));
|
||||
for (const ref of [links?.canonical, ...(links?.alternates ?? [])]) {
|
||||
if (ref) {
|
||||
resolveRef(null, ref, false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
start(async () => {
|
||||
const document = await getPageDocument(context, page);
|
||||
if (!document) {
|
||||
return;
|
||||
}
|
||||
start(() => deps.loadIcons(context, document));
|
||||
visit(document.nodes, (node) => {
|
||||
const data = node.data ?? {};
|
||||
if (node.type === 'embed' && typeof data.url === 'string') {
|
||||
start(async () => {
|
||||
const embed = await getDataOrNull(
|
||||
context.dataFetcher.getEmbedByUrl({
|
||||
url: data.url as string,
|
||||
spaceId: context.space.id,
|
||||
})
|
||||
);
|
||||
// Only link cards render the icon, without a size.
|
||||
if (embed && embed.type !== 'rich' && embed.type !== 'integration') {
|
||||
measure(embed.icon, { dpr: 2 });
|
||||
}
|
||||
});
|
||||
}
|
||||
if (node.type === 'image') {
|
||||
for (const ref of [data.ref, data.refDark]) {
|
||||
if (ref) {
|
||||
planImage(document, ref as ContentRef);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'inline-image') {
|
||||
// Line-sized inline images also measure the light image for their width.
|
||||
const lineSize = data.size === 'line' ? [{ dpr: 2 }, { dpr: 3 }] : [{ dpr: 2 }];
|
||||
if (data.ref) {
|
||||
planImage(document, data.ref as ContentRef, lineSize);
|
||||
}
|
||||
if (data.refDark) {
|
||||
planImage(document, data.refDark as ContentRef);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'drawing') {
|
||||
if (data.ref) {
|
||||
planImage(document, data.ref as ContentRef);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'file' && data.ref) {
|
||||
planFilePreview(document, data.ref as ContentRef);
|
||||
return;
|
||||
}
|
||||
if (node.type === 'table') {
|
||||
// Through `start` so a malformed table can't stop the rest of the walk.
|
||||
start(async () =>
|
||||
planTable(document, node.data as unknown as DocumentBlockTable['data'])
|
||||
);
|
||||
}
|
||||
const ref = data.ref as ContentRef | undefined;
|
||||
if (ref) {
|
||||
planRef(document, ref, ANCHOR_TEXT_TYPES.has(node.type ?? ''));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const planRef = (document: JSONDocument | null, ref: ContentRef, anchorText: boolean) => {
|
||||
if (needsRequest(ref, anchorText, context)) {
|
||||
resolveRef(document, ref, anchorText);
|
||||
}
|
||||
};
|
||||
|
||||
const planImage = (
|
||||
document: JSONDocument | null,
|
||||
ref: ContentRef,
|
||||
sizes: { dpr?: number }[] = [{ dpr: 2 }]
|
||||
) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(async () => {
|
||||
const resolved = await resolveFile(document, ref);
|
||||
// Like `Image`, a file with known dimensions is never measured.
|
||||
if (resolved && !resolved.file?.dimensions) {
|
||||
for (const options of sizes) {
|
||||
measure(resolved.href, options);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// The file block previews images from their download URL.
|
||||
const planFilePreview = (document: JSONDocument, ref: ContentRef) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(async () => {
|
||||
const file = (await resolveFile(document, ref))?.file;
|
||||
if (
|
||||
file &&
|
||||
!file.dimensions &&
|
||||
getSimplifiedContentType(file.contentType ?? '') === 'image'
|
||||
) {
|
||||
measure(file.downloadURL, { dpr: 2 });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Only what the table view renders: its columns, plus covers and target for cards.
|
||||
const planTable = (document: JSONDocument, table: DocumentBlockTable['data']) => {
|
||||
const { view, definition } = table;
|
||||
for (const record of Object.values(table.records ?? {})) {
|
||||
for (const column of view.columns ?? []) {
|
||||
const value = record.values[column];
|
||||
switch (definition[column]?.type) {
|
||||
case 'content-ref':
|
||||
if (value && typeof value === 'object' && 'kind' in value) {
|
||||
planRef(document, value as ContentRef, true);
|
||||
}
|
||||
break;
|
||||
case 'users':
|
||||
if (isStringArray(value)) {
|
||||
for (const user of value) {
|
||||
resolveRef(document, { kind: 'user', user }, false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'image':
|
||||
if (isDocumentTableImageRecord(value)) {
|
||||
planImage(document, 'ref' in value ? value.ref : value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (view.type === 'cards') {
|
||||
const { light, dark } = getRecordCardCovers(record, view);
|
||||
// The dark cover only renders alongside a light one.
|
||||
if (light.contentRef) {
|
||||
planImage(document, light.contentRef);
|
||||
if (dark.contentRef) {
|
||||
planImage(document, dark.contentRef);
|
||||
}
|
||||
}
|
||||
const target = view.targetDefinition
|
||||
? (record.values[view.targetDefinition] as ContentRef | undefined)
|
||||
: undefined;
|
||||
if (target) {
|
||||
planRef(document, target, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const planSite = () => {
|
||||
// Links the layout resolves: header, announcement, footer, and link pages of the table of contents.
|
||||
const { header: headerLinks, footer: footerLinks, announcement } = context.customization;
|
||||
const layoutRefs: (ContentRef | null | undefined)[] = [
|
||||
headerLinks.primaryLink,
|
||||
// Same condition as `Announcement`, which renders nothing otherwise.
|
||||
announcement?.enabled && announcement.message ? announcement.link?.to : undefined,
|
||||
...(headerLinks.links ?? []).flatMap((link) => [
|
||||
link.to,
|
||||
...(link.links ?? []).map((sub) => sub.to),
|
||||
]),
|
||||
...(footerLinks.groups ?? []).flatMap((group) =>
|
||||
(group.links ?? []).map((link) => link.to)
|
||||
),
|
||||
];
|
||||
visitPages(context.revision?.pages, (target) => layoutRefs.push(target));
|
||||
for (const ref of layoutRefs) {
|
||||
if (ref) {
|
||||
planRef(null, ref, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Logos and the custom icon carry no size, so the layout measures them on every page.
|
||||
const { header, footer, favicon } = context.customization;
|
||||
if (header.logo) {
|
||||
measure(header.logo.light, { dpr: 2 });
|
||||
measure(header.logo.dark, { dpr: 2 });
|
||||
} else if ('icon' in favicon && favicon.icon) {
|
||||
measure(favicon.icon.light, { dpr: 2 });
|
||||
measure(favicon.icon.dark, { dpr: 2 });
|
||||
}
|
||||
if (footer.logo) {
|
||||
measure(footer.logo.light, { dpr: 2 });
|
||||
measure(footer.logo.dark, { dpr: 2 });
|
||||
}
|
||||
|
||||
// Same conditions as SitePage (full/background) and PageBody (hero).
|
||||
const coverSize = page.layout?.coverSize;
|
||||
if (
|
||||
page.cover &&
|
||||
page.layout?.cover &&
|
||||
(coverSize === 'hero' || coverSize === 'full' || coverSize === 'background')
|
||||
) {
|
||||
for (const ref of [page.cover.ref, page.cover.refDark]) {
|
||||
if (ref) {
|
||||
planImage(null, ref, [{}]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// After every helper above is defined, and inside `start` so nothing throws out of the plan.
|
||||
start(async () => planSite());
|
||||
|
||||
return settle(pending);
|
||||
}
|
||||
|
||||
/** Whether resolving `ref` makes a request; same-space page and file refs resolve in memory. */
|
||||
function needsRequest(ref: ContentRef, anchorText: boolean, context: GitBookSiteContext) {
|
||||
if ('space' in ref && ref.space && ref.space !== context.space.id) {
|
||||
return true;
|
||||
}
|
||||
if (ref.kind === 'user' || ref.kind === 'openapi') {
|
||||
return true;
|
||||
}
|
||||
return ref.kind === 'anchor' && anchorText;
|
||||
}
|
||||
|
||||
/** Calls `fn` with the target of every link page, as the table of contents resolves them. */
|
||||
function visitPages(pages: unknown, fn: (target: ContentRef) => void) {
|
||||
if (!Array.isArray(pages)) {
|
||||
return;
|
||||
}
|
||||
for (const page of pages as {
|
||||
type?: string;
|
||||
hidden?: boolean;
|
||||
target?: ContentRef;
|
||||
pages?: unknown;
|
||||
}[]) {
|
||||
// The table of contents skips hidden pages and everything under them.
|
||||
if (!page || page.hidden) {
|
||||
continue;
|
||||
}
|
||||
if (page.type === 'link' && page.target) {
|
||||
fn(page.target);
|
||||
}
|
||||
visitPages(page.pages, fn);
|
||||
}
|
||||
}
|
||||
|
||||
function visit(nodes: unknown, fn: (node: Node) => void) {
|
||||
if (!Array.isArray(nodes)) {
|
||||
return;
|
||||
}
|
||||
for (const node of nodes as Node[]) {
|
||||
if (node && (node.object === 'block' || node.object === 'inline')) {
|
||||
fn(node);
|
||||
visit(node.nodes, fn);
|
||||
visit((node as { fragments?: unknown }).fragments, fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits for every started call, including ones started while waiting. */
|
||||
async function settle(pending: Promise<unknown>[]) {
|
||||
let settled = 0;
|
||||
while (settled < pending.length) {
|
||||
const batch = pending.slice(settled);
|
||||
settled = pending.length;
|
||||
await Promise.all(batch);
|
||||
}
|
||||
}
|
||||
@@ -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 && tag.emoji !== undefined) {
|
||||
if ('emoji' in tag) {
|
||||
return <Emoji code={tag.emoji} style="shrink-0" />;
|
||||
}
|
||||
|
||||
if ('icon' in tag && tag.icon) {
|
||||
if (tag.icon) {
|
||||
return <Icon icon={tag.icon as IconName} className={tcls('size-[1em]', 'shrink-0')} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,9 @@ import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { createLinker } from '@/lib/links';
|
||||
|
||||
/**
|
||||
* `urn:air:{publisher}:{name}[:{kind}]`, per the AI Catalog specification.
|
||||
* `urn:air:{publisher}:{namespace}:{name}`, per the AI Catalog specification.
|
||||
*/
|
||||
const AIR_URN_PATTERN = /^urn:air:[^:]+:[^:]+(:[^:]+)?$/;
|
||||
const AIR_URN_PATTERN = /^urn:air:[^:]+:[^:]+:[^:]+$/;
|
||||
|
||||
function makeContext(
|
||||
options: {
|
||||
@@ -49,7 +49,7 @@ describe('buildSiteAiCatalog', () => {
|
||||
specVersion: AI_CATALOG_SPEC_VERSION,
|
||||
entries: [
|
||||
{
|
||||
identifier: 'urn:air:docs.acme.org:site_123:mcp',
|
||||
identifier: 'urn:air:docs.acme.org:mcp:site_123',
|
||||
type: 'application/mcp-server-card+json',
|
||||
url: 'https://docs.acme.org/~gitbook/mcp/server-card',
|
||||
},
|
||||
@@ -75,19 +75,19 @@ describe('buildSiteAiCatalog', () => {
|
||||
{
|
||||
scenario: 'a custom domain',
|
||||
options: { host: 'docs.acme.org', siteBasePath: '/' },
|
||||
identifier: 'urn:air:docs.acme.org:site_123:mcp',
|
||||
identifier: 'urn:air:docs.acme.org:mcp:site_123',
|
||||
url: 'https://docs.acme.org/~gitbook/mcp/server-card',
|
||||
},
|
||||
{
|
||||
scenario: 'a gitbook.io subdomain',
|
||||
options: { host: 'acme.gitbook.io', siteBasePath: '/' },
|
||||
identifier: 'urn:air:acme.gitbook.io:site_123:mcp',
|
||||
identifier: 'urn:air:acme.gitbook.io:mcp:site_123',
|
||||
url: 'https://acme.gitbook.io/~gitbook/mcp/server-card',
|
||||
},
|
||||
{
|
||||
scenario: 'a subpath site',
|
||||
options: { host: 'gitbook.com', siteBasePath: '/docs/' },
|
||||
identifier: 'urn:air:gitbook.com:site_123:mcp',
|
||||
identifier: 'urn:air:gitbook.com:mcp:site_123',
|
||||
url: 'https://gitbook.com/docs/~gitbook/mcp/server-card',
|
||||
},
|
||||
])('anchors the entry to $scenario', ({ options, identifier, url }) => {
|
||||
@@ -106,7 +106,7 @@ describe('buildSiteAiCatalog', () => {
|
||||
});
|
||||
const entry = buildSiteAiCatalog({ ...context, linker })?.entries[0];
|
||||
|
||||
expect(entry?.identifier).toBe('urn:air:localhost:site_123:mcp');
|
||||
expect(entry?.identifier).toBe('urn:air:localhost:mcp:site_123');
|
||||
expect(entry?.identifier).toMatch(AIR_URN_PATTERN);
|
||||
});
|
||||
|
||||
|
||||
@@ -5,10 +5,7 @@ import { MCP_SERVER_CARD_PATH } from '@/lib/mcp/paths';
|
||||
import { SERVER_CARD_MEDIA_TYPE } from '@/lib/mcp/serverCard';
|
||||
|
||||
export const AI_CATALOG_MEDIA_TYPE = 'application/ai-catalog+json';
|
||||
/**
|
||||
* The v1.0 release candidate. The final v1.0 is not published yet.
|
||||
*/
|
||||
export const AI_CATALOG_SPEC_VERSION = '0.9';
|
||||
export const AI_CATALOG_SPEC_VERSION = '1.0';
|
||||
|
||||
/**
|
||||
* The AI Catalog a site publishes at `/.well-known/ai-catalog.json`, per the
|
||||
@@ -27,7 +24,7 @@ export interface AiCatalog {
|
||||
|
||||
export interface AiCatalogEntry {
|
||||
/**
|
||||
* Required. Domain-anchored `urn:air:{publisher}:{name}[:{kind}]`.
|
||||
* Required. Domain-anchored `urn:air:{publisher}:{namespace}:{name}`.
|
||||
*/
|
||||
identifier: string;
|
||||
/**
|
||||
@@ -50,7 +47,7 @@ export function buildSiteAiCatalog(context: GitBookSiteContext): AiCatalog | nul
|
||||
|
||||
if (isSiteMcpEnabled(context)) {
|
||||
entries.push({
|
||||
identifier: buildCatalogIdentifier(context, site.id, 'mcp'),
|
||||
identifier: buildCatalogIdentifier(context, 'mcp', site.id),
|
||||
type: SERVER_CARD_MEDIA_TYPE,
|
||||
url: linker.toAbsoluteURL(linker.toPathInSite(MCP_SERVER_CARD_PATH)),
|
||||
});
|
||||
@@ -81,9 +78,13 @@ export async function serveSiteAiCatalog(
|
||||
});
|
||||
}
|
||||
|
||||
function buildCatalogIdentifier(context: GitBookSiteContext, name: string, kind: string): string {
|
||||
function buildCatalogIdentifier(
|
||||
context: GitBookSiteContext,
|
||||
namespace: string,
|
||||
name: string
|
||||
): string {
|
||||
const publisher = new URL(context.linker.toAbsoluteURL(context.linker.toPathInSite('')))
|
||||
.hostname;
|
||||
|
||||
return `urn:air:${publisher}:${name}:${kind}`;
|
||||
return `urn:air:${publisher}:${namespace}:${name}`;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { assert } from 'ts-essentials';
|
||||
import type {
|
||||
ChangeRequest,
|
||||
CustomizationDefaultThemeMode,
|
||||
PublishedSiteContent,
|
||||
Revision,
|
||||
RevisionPageDocument,
|
||||
Site,
|
||||
@@ -31,13 +32,11 @@ import { isPublishedPreviewAllowed } from './preview';
|
||||
import type { AskVisitorAgent } from '@/lib/ask-visitor';
|
||||
import {
|
||||
type GitBookDataFetcher,
|
||||
type PublishedSiteContent,
|
||||
createDataFetcher,
|
||||
getDataOrNull,
|
||||
throwIfDataError,
|
||||
} from '@/lib/data';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { measureDataFetcher, measureImageResizer } from '@/lib/plan-stats';
|
||||
import type { DirectSearchProps } from '@/lib/search-results';
|
||||
import {
|
||||
findSiteSpaceBy,
|
||||
@@ -249,12 +248,9 @@ export function getBaseContext(input: {
|
||||
const { urlMode, siteURLData } = input;
|
||||
const siteURL = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL;
|
||||
|
||||
// TEMP: measured to log what the site page plan saves (lib/plan-stats.ts).
|
||||
const dataFetcher = measureDataFetcher(
|
||||
createDataFetcher({
|
||||
apiToken: siteURLData.apiToken ?? null,
|
||||
})
|
||||
);
|
||||
const dataFetcher = createDataFetcher({
|
||||
apiToken: siteURLData.apiToken ?? null,
|
||||
});
|
||||
|
||||
const linkerInput: SiteLinkerInput = {
|
||||
urlMode,
|
||||
@@ -265,14 +261,12 @@ export function getBaseContext(input: {
|
||||
};
|
||||
const linker = createSiteLinker(linkerInput);
|
||||
|
||||
const imageResizer = measureImageResizer(
|
||||
createImageResizer({
|
||||
imagesContextId: siteURLData.imagesContextId,
|
||||
// To ensure image resizing work for proxied sites,
|
||||
// we serve images from the root of the site.
|
||||
linker: linker,
|
||||
})
|
||||
);
|
||||
const imageResizer = createImageResizer({
|
||||
imagesContextId: siteURLData.imagesContextId,
|
||||
// To ensure image resizing work for proxied sites,
|
||||
// we serve images from the root of the site.
|
||||
linker: linker,
|
||||
});
|
||||
|
||||
const directSearch: GitBookBaseContext['directSearch'] =
|
||||
!siteURLData.revision && !siteURLData.changeRequest && !siteURLData.preview
|
||||
|
||||
@@ -33,7 +33,6 @@ describe('searchSiteContent', () => {
|
||||
organizationId: 'org-1',
|
||||
siteId: 'site-1',
|
||||
query: 'test',
|
||||
routeReason: 'fallback:403' as const,
|
||||
scope: { mode: 'all' as const },
|
||||
};
|
||||
|
||||
@@ -46,9 +45,6 @@ describe('searchSiteContent', () => {
|
||||
'https://api.example.com/cache/v1/orgs/org-1/sites/site-1/search'
|
||||
);
|
||||
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer site-token');
|
||||
expect(new Headers(init?.headers).get('x-gitbook-search-route-reason')).toBe(
|
||||
'fallback:403'
|
||||
);
|
||||
expect(cacheLife).not.toHaveBeenCalled();
|
||||
expect(cacheTag).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
GitBookAPI,
|
||||
type HttpResponse,
|
||||
type RenderIntegrationUI,
|
||||
type SiteSearchScope,
|
||||
} from '@gitbook/api';
|
||||
import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
|
||||
|
||||
@@ -13,7 +14,6 @@ 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,16 +793,28 @@ async function searchSiteContent(
|
||||
return trace(
|
||||
`searchSiteContent(${params.organizationId}, ${params.siteId}, ${params.query})`,
|
||||
async () => {
|
||||
const { organizationId, siteId, query, scope, searchId, routeReason } = params;
|
||||
const { organizationId, siteId, query, scope } = params;
|
||||
const api = apiClient(input);
|
||||
const res = await api.orgs.searchSiteContent(
|
||||
organizationId,
|
||||
siteId,
|
||||
toSearchSiteContentBody(query, scope, searchId),
|
||||
{
|
||||
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),
|
||||
},
|
||||
{},
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
headers: { 'x-gitbook-search-route-reason': routeReason },
|
||||
}
|
||||
);
|
||||
return res.data.items;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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';
|
||||
@@ -48,39 +50,64 @@ describe('preview auth redirects', () => {
|
||||
expect(redirect.origin + redirect.pathname).toBe(authURL.toString());
|
||||
expect(redirect.searchParams.get('redirect')).toBe(requestURL.toString());
|
||||
});
|
||||
});
|
||||
|
||||
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 } };
|
||||
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 };
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as ReturnType<typeof api.apiClient>);
|
||||
} as unknown as ReturnType<typeof api.apiClient>);
|
||||
|
||||
try {
|
||||
const result = await lookupPublishedContentByUrl({
|
||||
url: 'https://docs.example.com/section/~/changes/66/hello%20world?jwt_token=abc',
|
||||
url: requestURL,
|
||||
apiToken: null,
|
||||
redirectOnError: false,
|
||||
visitorPayload: {},
|
||||
});
|
||||
expect(result).toEqual({ data: { target: 'content', redirect } });
|
||||
} finally {
|
||||
apiClientSpy.mockRestore();
|
||||
|
||||
expect(result).toEqual({ data: { ...data, redirect: expectedRedirect } });
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
expect(urls).toEqual(['https://docs.example.com/section/~/changes/66/hello%20world']);
|
||||
});
|
||||
|
||||
describe('lookup URL', () => {
|
||||
it('resolves the full URL without search params in a single call', async () => {
|
||||
const urls: string[] = [];
|
||||
const apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import type * as API from '@gitbook/api';
|
||||
import type { GitBookAPI, PublishedSiteContentLookup, SiteVisitorPayload } from '@gitbook/api';
|
||||
|
||||
import { apiClient } from './api';
|
||||
import { getExposableError } from './errors';
|
||||
import type { DataFetcherResponse } from './types';
|
||||
import { getURLLookup, stripURLSearch } from './urls';
|
||||
import { getURLLookup, getURLLookupPathname, stripURLSearch } from './urls';
|
||||
import { tryCatch } from '@/lib/async';
|
||||
import { joinPath, joinPathWithBaseURL } from '@/lib/paths';
|
||||
import { isPreviewRequest } from '@/lib/preview';
|
||||
import { trace } from '@/lib/tracing';
|
||||
|
||||
type ResolveBody = Parameters<API.GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
|
||||
export type PublishedSiteContent = API.PublishedSiteContent &
|
||||
Partial<API.PublishedSiteContentAtRevision & API.PublishedSiteContentInChangeRequest>;
|
||||
type ResolveBody = Parameters<GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
|
||||
interface LookupPublishedContentByUrlInput {
|
||||
url: string;
|
||||
redirectOnError: boolean;
|
||||
apiToken: string | null;
|
||||
visitorPayload: API.SiteVisitorPayload;
|
||||
visitorPayload: SiteVisitorPayload;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +23,7 @@ interface LookupPublishedContentByUrlInput {
|
||||
*/
|
||||
export async function lookupPublishedContentByUrl(
|
||||
input: LookupPublishedContentByUrlInput
|
||||
): Promise<DataFetcherResponse<PublishedSiteContent | API.PublishedContentRedirect>> {
|
||||
): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
|
||||
const lookupURL = new URL(input.url);
|
||||
const lookup = getURLLookup(stripURLSearch(lookupURL));
|
||||
|
||||
@@ -42,12 +40,12 @@ export async function lookupPublishedContentByUrl(
|
||||
const callResult = await trace(
|
||||
{
|
||||
operation: 'resolvePublishedContentByUrl',
|
||||
name: lookup,
|
||||
name: lookup.url,
|
||||
},
|
||||
() =>
|
||||
tryCatch(
|
||||
api.urls.resolvePublishedContentByUrl({
|
||||
url: lookup,
|
||||
url: lookup.url,
|
||||
...(input.visitorPayload ? { visitor: input.visitorPayload } : {}),
|
||||
redirectOnError: input.redirectOnError,
|
||||
} as ResolveBody) //TODO: remove cast when we are sure that everything is good
|
||||
@@ -64,16 +62,47 @@ export async function lookupPublishedContentByUrl(
|
||||
data: { data },
|
||||
} = callResult;
|
||||
|
||||
if (!('redirect' in data)) {
|
||||
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 (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 };
|
||||
return {
|
||||
data: {
|
||||
...data,
|
||||
canonicalUrl: joinPathWithBaseURL(data.canonicalUrl, lookup.extraPath),
|
||||
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
|
||||
pathname: getURLLookupPathname(lookup, data),
|
||||
...(changeRequest ? { changeRequest } : {}),
|
||||
...(revision ? { revision } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,22 +1,5 @@
|
||||
import type * as api from '@gitbook/api';
|
||||
|
||||
export type SearchRouteReason =
|
||||
| 'preview'
|
||||
| 'revision'
|
||||
| 'change_request'
|
||||
| 'mcp'
|
||||
| 'no_pass'
|
||||
| 'fallback:401'
|
||||
| 'fallback:403'
|
||||
| 'fallback:429'
|
||||
| 'fallback:5xx'
|
||||
| 'fallback:http'
|
||||
| 'fallback:network'
|
||||
| 'fallback:timeout'
|
||||
| 'fallback:invalid'
|
||||
| 'fallback:unknown_space'
|
||||
| 'unknown';
|
||||
|
||||
export type DataFetcherErrorData = {
|
||||
code: number;
|
||||
message: string;
|
||||
@@ -197,8 +180,6 @@ export interface GitBookDataFetcher {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
query: string;
|
||||
routeReason: SearchRouteReason;
|
||||
searchId?: string;
|
||||
scope:
|
||||
| { mode: 'all' }
|
||||
| {
|
||||
|
||||
@@ -1,6 +1,88 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { getURLLookup, normalizeRequestURL, normalizeURL } from './urls';
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getURLLookup', () => {
|
||||
it.each([
|
||||
@@ -16,26 +98,68 @@ 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))).toBe(url);
|
||||
expect(getURLLookup(new URL(url))).toEqual({ url, extraPath: '' });
|
||||
});
|
||||
|
||||
it('looks up the normalized URL', () => {
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toBe(
|
||||
'https://docs.mycompany.com/hello'
|
||||
);
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toEqual({
|
||||
url: 'https://docs.mycompany.com/hello',
|
||||
extraPath: '',
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
);
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeRequestURL', () => {
|
||||
|
||||
@@ -1,13 +1,107 @@
|
||||
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): string | null {
|
||||
export function getURLLookup(input: URL): {
|
||||
url: string;
|
||||
extraPath: string;
|
||||
basePath?: string;
|
||||
changeRequest?: string;
|
||||
revision?: string;
|
||||
} | null {
|
||||
const url = normalizeURL(input);
|
||||
return isProxyRootRequest(url) ? null : url.toString();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,14 +9,12 @@ import type {
|
||||
CloudflareImageOptions,
|
||||
CloudflareResizeImageOptions,
|
||||
} from './types';
|
||||
import { cache } from '@/lib/cache';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
|
||||
/**
|
||||
* Get the size of an image.
|
||||
* Memoized per request so the site page plan's early call is reused by the render.
|
||||
*/
|
||||
export const getImageSize = cache(async function getImageSize(
|
||||
export async function getImageSize(
|
||||
input: string,
|
||||
defaultSize: Partial<CloudflareImageOptions> = {}
|
||||
): Promise<{ width: number; height: number } | null> {
|
||||
@@ -45,7 +43,7 @@ export const getImageSize = cache(async function getImageSize(
|
||||
logger.warn(`Error getting image size for ${input}:`, error);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a Cloudflare Image Resize operation on an image.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from './context';
|
||||
import { createLinker } from './links';
|
||||
@@ -17,7 +17,6 @@ describe('llms directive', () => {
|
||||
siteBasePath: '/docs',
|
||||
spaceBasePath: '/docs/v1',
|
||||
}),
|
||||
customization: { pageActions: { items: [] as CustomizationPageActionType[] } },
|
||||
} as GitBookSiteContext;
|
||||
|
||||
const page = {
|
||||
@@ -39,15 +38,4 @@ describe('llms directive', () => {
|
||||
'> For the complete documentation index, see [llms.txt](https://docs.company.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.company.com/docs/v1/guides/start.md).'
|
||||
);
|
||||
});
|
||||
|
||||
it('points to the MCP server when the site publishes one', () => {
|
||||
const mcpContext = {
|
||||
...context,
|
||||
customization: { pageActions: { items: [CustomizationPageActionType.Mcp] } },
|
||||
} as GitBookSiteContext;
|
||||
|
||||
expect(renderLLMsTxtMarkdownDirective(mcpContext, page)).toEndWith(
|
||||
' Agents can also search and read this documentation through its [MCP server](https://docs.company.com/docs/~gitbook/mcp).'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from './context';
|
||||
import { getSiteMcpEndpoint, isSiteMcpEnabled } from './mcp/endpoints';
|
||||
|
||||
/**
|
||||
* Return the URL for the site-level llms.txt file.
|
||||
@@ -20,24 +19,6 @@ export function getPageMarkdownURL(
|
||||
return `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the MCP endpoint to point agents to, or `undefined` when the site publishes none.
|
||||
*/
|
||||
export function getAdvertisedMcpEndpoint(context: GitBookSiteContext): string | undefined {
|
||||
return isSiteMcpEnabled(context) ? getSiteMcpEndpoint(context) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the sentence that points agents to the site's MCP server, or `undefined` when the site
|
||||
* publishes none.
|
||||
*/
|
||||
export function renderMcpMarkdownDirective(context: GitBookSiteContext): string | undefined {
|
||||
const mcpEndpoint = getAdvertisedMcpEndpoint(context);
|
||||
return mcpEndpoint
|
||||
? `Agents can also search and read this documentation through its [MCP server](${mcpEndpoint}).`
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the agent-facing directive that points agents to the site index.
|
||||
*/
|
||||
@@ -45,6 +26,5 @@ export function renderLLMsTxtMarkdownDirective(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument | RevisionPageGroup
|
||||
): string {
|
||||
const mcpDirective = renderMcpMarkdownDirective(context);
|
||||
return `> For the complete documentation index, see [llms.txt](${getLLMsTxtURL(context)}). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as [Markdown](${getPageMarkdownURL(context, page)}).${mcpDirective ? ` ${mcpDirective}` : ''}`;
|
||||
return `> For the complete documentation index, see [llms.txt](${getLLMsTxtURL(context)}). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as [Markdown](${getPageMarkdownURL(context, page)}).`;
|
||||
}
|
||||
|
||||
@@ -9,13 +9,6 @@ export function isSiteMcpEnabled(context: GitBookSiteContext): boolean {
|
||||
return context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute URL of the site's public MCP endpoint.
|
||||
*/
|
||||
export function getSiteMcpEndpoint(context: GitBookSiteContext): string {
|
||||
return context.linker.toAbsoluteURL(context.linker.toPathInSite('~gitbook/mcp'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `~gitbook/mcp` endpoint requires auth for the site (i.e VA site).
|
||||
*/
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
const DOCS_SUFFIX = ' Docs';
|
||||
const DOCS_WORD_PATTERN = /\bdoc(s|umentation)?\b/i;
|
||||
|
||||
/**
|
||||
* Characters {@link getSiteMcpServerName} can add to a title, for callers that cap its length.
|
||||
*/
|
||||
export const SITE_MCP_SERVER_NAME_MAX_ADDED_LENGTH = DOCS_SUFFIX.length;
|
||||
|
||||
/**
|
||||
* Get the name a client lists a site's MCP server under: the site title, marked as docs unless it
|
||||
* already says so.
|
||||
*/
|
||||
export function getSiteMcpServerName(siteTitle: string): string {
|
||||
const title = siteTitle.trim();
|
||||
if (!title) {
|
||||
return DOCS_SUFFIX.trim();
|
||||
}
|
||||
|
||||
// A customer often runs an MCP server for its own product, listed under the same name.
|
||||
return DOCS_WORD_PATTERN.test(title) ? title : `${title}${DOCS_SUFFIX}`;
|
||||
}
|
||||
@@ -93,7 +93,7 @@ describe('buildSiteMcpServerCard', () => {
|
||||
it('keeps the description and title within 100 characters', () => {
|
||||
const card = buildCard({ title: 'Acme' });
|
||||
|
||||
expect(card.title).toBe('Acme Docs MCP Server');
|
||||
expect(card.title).toBe('Acme MCP Server');
|
||||
expect(card.description).toBe('Search and read the Acme documentation over MCP.');
|
||||
expect(card.description.length).toBeLessThanOrEqual(MAX_TEXT_LENGTH);
|
||||
expect(card.title.length).toBeLessThanOrEqual(MAX_TEXT_LENGTH);
|
||||
@@ -102,7 +102,7 @@ describe('buildSiteMcpServerCard', () => {
|
||||
it('does not repeat an article a customer title already carries', () => {
|
||||
const card = buildCard({ title: 'The Acme Handbook' });
|
||||
|
||||
expect(card.title).toBe('The Acme Handbook Docs MCP Server');
|
||||
expect(card.title).toBe('The Acme Handbook MCP Server');
|
||||
expect(card.description).toBe(
|
||||
'Search and read The Acme Handbook documentation over MCP.'
|
||||
);
|
||||
@@ -112,7 +112,7 @@ describe('buildSiteMcpServerCard', () => {
|
||||
const card = buildCard({ title: 'A'.repeat(500) });
|
||||
|
||||
expect(card.title.length).toBe(MAX_TEXT_LENGTH);
|
||||
expect(card.title.endsWith('… Docs MCP Server')).toBe(true);
|
||||
expect(card.title.endsWith('… MCP Server')).toBe(true);
|
||||
expect(card.description.length).toBe(MAX_TEXT_LENGTH);
|
||||
expect(card.description.startsWith('Search and read the ')).toBe(true);
|
||||
expect(card.description.endsWith('… documentation over MCP.')).toBe(true);
|
||||
@@ -170,18 +170,8 @@ describe('buildSiteMcpServerCard', () => {
|
||||
|
||||
expect(acme.name).toBe('docs.acme.com/~gitbook/mcp');
|
||||
expect(other.name).toBe('gitbook.com/other/~gitbook/mcp');
|
||||
expect(acme.title).toBe('Acme Docs MCP Server');
|
||||
expect(other.title).toBe('Other Docs MCP Server');
|
||||
});
|
||||
|
||||
it('marks the server as docs only when the site title does not already say so', () => {
|
||||
for (const [title, expected] of [
|
||||
['Acme Docs', 'Acme Docs MCP Server'],
|
||||
['Acme Documentation', 'Acme Documentation MCP Server'],
|
||||
['Docker', 'Docker Docs MCP Server'],
|
||||
] as const) {
|
||||
expect(buildMcpServerInfo(makeContext({ title })).title).toBe(expected);
|
||||
}
|
||||
expect(acme.title).toBe('Acme MCP Server');
|
||||
expect(other.title).toBe('Other MCP Server');
|
||||
});
|
||||
|
||||
it('declares the capabilities the SDK reports at initialize', () => {
|
||||
|
||||
@@ -2,13 +2,7 @@ import type { Implementation, ServerCapabilities, Tool } from '@modelcontextprot
|
||||
import { SUPPORTED_PROTOCOL_VERSIONS } from '@modelcontextprotocol/sdk/types.js';
|
||||
|
||||
import packageJSON from '../../../package.json';
|
||||
import {
|
||||
getSiteMcpEndpoint,
|
||||
hasAdaptiveMcpEndpoint,
|
||||
isSiteMcpEnabled,
|
||||
mcpEndpointRequiresAuth,
|
||||
} from './endpoints';
|
||||
import { SITE_MCP_SERVER_NAME_MAX_ADDED_LENGTH, getSiteMcpServerName } from './naming';
|
||||
import { hasAdaptiveMcpEndpoint, isSiteMcpEnabled, mcpEndpointRequiresAuth } from './endpoints';
|
||||
import { type SiteMcpTool, createSiteMcpTools } from './tools';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { serveDiscoveryDocument } from '@/lib/discoveryDocument';
|
||||
@@ -162,6 +156,10 @@ export function buildMcpServerInfo(context: GitBookSiteContext): SiteMcpServerIn
|
||||
};
|
||||
}
|
||||
|
||||
export function getSiteMcpEndpoint(context: GitBookSiteContext): string {
|
||||
return context.linker.toAbsoluteURL(context.linker.toPathInSite('~gitbook/mcp'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a site's MCP server card.
|
||||
*
|
||||
@@ -225,8 +223,7 @@ function authorizationHeader(description: string): SiteMcpServerCardRemote['head
|
||||
* Name the server after the site it serves, within the 100 characters the schema allows a `title`.
|
||||
*/
|
||||
function buildTitle(siteTitle: string): string {
|
||||
const budget = MAX_TEXT_LENGTH - TITLE_SUFFIX.length - SITE_MCP_SERVER_NAME_MAX_ADDED_LENGTH;
|
||||
return `${getSiteMcpServerName(truncate(siteTitle, budget))}${TITLE_SUFFIX}`;
|
||||
return `${truncate(siteTitle, MAX_TEXT_LENGTH - TITLE_SUFFIX.length)}${TITLE_SUFFIX}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -93,7 +93,6 @@ export function createSiteMcpTools(
|
||||
organizationId: context.organizationId,
|
||||
siteId: site.id,
|
||||
query,
|
||||
routeReason: 'mcp',
|
||||
scope: getLanguageSearchScope(context.structure, searchLanguage),
|
||||
})
|
||||
);
|
||||
@@ -524,24 +523,8 @@ export function trackMcpEvent(args: Parameters<typeof trackServerInsightsEvents>
|
||||
* Register tools on the MCP server. Only used by the transport: the server card reads the same
|
||||
* definitions without registering anything.
|
||||
*/
|
||||
export function registerSiteMcpTools(
|
||||
server: McpServer,
|
||||
tools: SiteMcpTool[],
|
||||
options: {
|
||||
/**
|
||||
* Called when a tool runs, after the server has matched its name and validated its
|
||||
* arguments.
|
||||
*/
|
||||
onToolCall?: () => void;
|
||||
} = {}
|
||||
) {
|
||||
const { onToolCall } = options;
|
||||
|
||||
export function registerSiteMcpTools(server: McpServer, tools: SiteMcpTool[]) {
|
||||
for (const tool of tools) {
|
||||
const handler: SiteMcpTool['handler'] = (...args) => {
|
||||
onToolCall?.();
|
||||
return tool.handler(...args);
|
||||
};
|
||||
server.tool(tool.name, tool.description, tool.inputSchema, tool.annotations, handler);
|
||||
server.tool(tool.name, tool.description, tool.inputSchema, tool.annotations, tool.handler);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,3 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { createPlanStats, markPlanStart, recordCall, summarizePlanStats } from './plan-stats';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function clock() {
|
||||
let now = 0;
|
||||
return {
|
||||
now: () => now,
|
||||
set: (value: number) => {
|
||||
now = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
describe('plan stats', () => {
|
||||
it('counts the head start when the render asks before the plan call settles', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = deferred();
|
||||
recordCall(stats, 'getRevisionPageDocument', { pageId: 'p' }, call.promise, true);
|
||||
c.set(60);
|
||||
recordCall(stats, 'getRevisionPageDocument', { pageId: 'p' }, call.promise, false);
|
||||
c.set(100);
|
||||
call.resolve();
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.used).toBe(1);
|
||||
expect(summary.savedMsMax).toBe(60);
|
||||
expect(summary.savedMsTotal).toBe(60);
|
||||
});
|
||||
|
||||
it('counts the whole duration when the plan call settled before the render asked', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = deferred();
|
||||
recordCall(stats, 'getEmbedByUrl', { url: 'u' }, call.promise, true);
|
||||
c.set(50);
|
||||
call.resolve();
|
||||
await flush();
|
||||
c.set(200);
|
||||
recordCall(stats, 'getEmbedByUrl', { url: 'u' }, call.promise, false);
|
||||
|
||||
expect(summarizePlanStats(stats).savedMsMax).toBe(50);
|
||||
});
|
||||
|
||||
it('matches calls by method and argument shape', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
const call = Promise.resolve();
|
||||
recordCall(stats, 'getSpace', { spaceId: 's', shareKey: undefined }, call, true);
|
||||
recordCall(stats, 'getSpace', { shareKey: undefined, spaceId: 's' }, call, false);
|
||||
recordCall(stats, 'getRevision', { spaceId: 's' }, call, false);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.used).toBe(1);
|
||||
expect(summary.notPlanned).toEqual({
|
||||
getRevision: { count: 1, maxMs: 0, example: { spaceId: 's' } },
|
||||
});
|
||||
});
|
||||
|
||||
it('reports plan calls the render never made as wasted', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
recordCall(stats, 'getImageSize', ['https://x', { dpr: 2 }], Promise.resolve(), true);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.wasted).toEqual({ getImageSize: 1 });
|
||||
expect(summary.used).toBe(0);
|
||||
});
|
||||
|
||||
it('measures rejected calls too', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
const call = Promise.reject(new Error('boom'));
|
||||
recordCall(stats, 'getRevision', { spaceId: 's' }, call, false);
|
||||
call.catch(() => {});
|
||||
c.set(30);
|
||||
await flush();
|
||||
|
||||
expect(summarizePlanStats(stats).notPlanned).toEqual({
|
||||
getRevision: { count: 1, maxMs: 30, example: { spaceId: 's' } },
|
||||
});
|
||||
});
|
||||
|
||||
it('only reports render calls made after the plan began as not planned', async () => {
|
||||
const c = clock();
|
||||
const stats = createPlanStats(c.now);
|
||||
recordCall(stats, 'getPublishedContentSite', { siteId: 's' }, Promise.resolve(), false);
|
||||
c.set(10);
|
||||
markPlanStart(stats);
|
||||
c.set(20);
|
||||
recordCall(stats, 'getRevisionPageByPath', { path: 'p' }, Promise.resolve(), false);
|
||||
await flush();
|
||||
|
||||
const summary = summarizePlanStats(stats);
|
||||
expect(summary.beforePlan).toBe(1);
|
||||
expect(Object.keys(summary.notPlanned)).toEqual(['getRevisionPageByPath']);
|
||||
});
|
||||
|
||||
it('keeps only ids in the example of a not planned call', async () => {
|
||||
const stats = createPlanStats(() => 0);
|
||||
recordCall(
|
||||
stats,
|
||||
'getSpace',
|
||||
{ spaceId: 's', shareKey: 'secret', extra: { deep: true } },
|
||||
Promise.resolve(),
|
||||
false
|
||||
);
|
||||
await flush();
|
||||
|
||||
expect(summarizePlanStats(stats).notPlanned.getSpace?.example).toEqual({ spaceId: 's' });
|
||||
});
|
||||
});
|
||||
@@ -1,195 +0,0 @@
|
||||
// TEMP: measures what the site page plan saves; remove once the plan is validated in production.
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { identify } from 'object-identity';
|
||||
import * as React from 'react';
|
||||
|
||||
import type { GitBookDataFetcher } from '@/lib/data';
|
||||
import type { ImageResizer } from '@/lib/images';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
|
||||
/** Set while the plan runs, so its calls can be told apart from the render's. */
|
||||
export const planScope = new AsyncLocalStorage<true>();
|
||||
|
||||
type Entry = {
|
||||
label: string;
|
||||
example?: Record<string, string>;
|
||||
planStart?: number;
|
||||
planEnd?: number;
|
||||
renderAsk?: number;
|
||||
renderEnd?: number;
|
||||
};
|
||||
|
||||
export type PlanStats = {
|
||||
now: () => number;
|
||||
t0: number;
|
||||
planStart?: number;
|
||||
entries: Map<string, Entry>;
|
||||
};
|
||||
|
||||
export function createPlanStats(now: () => number = Date.now): PlanStats {
|
||||
return { now, t0: now(), entries: new Map() };
|
||||
}
|
||||
|
||||
/** Render calls made before this are the site context fetch, not gaps in the plan. */
|
||||
export function markPlanStart(stats: PlanStats) {
|
||||
stats.planStart ??= stats.now();
|
||||
}
|
||||
|
||||
/** One per request; outside a render scope this just returns a fresh, unused object. */
|
||||
export const getRequestPlanStats = React.cache(() => createPlanStats());
|
||||
|
||||
/** Record the first plan call and the first render call of a request, keyed by method and args. */
|
||||
export function recordCall(
|
||||
stats: PlanStats,
|
||||
label: string,
|
||||
args: unknown,
|
||||
promise: Promise<unknown>,
|
||||
inPlan: boolean
|
||||
) {
|
||||
const key = `${label}:${identify(args)}`;
|
||||
let entry = stats.entries.get(key);
|
||||
if (!entry) {
|
||||
entry = { label };
|
||||
stats.entries.set(key, entry);
|
||||
}
|
||||
const current = entry;
|
||||
const settled = () => stats.now();
|
||||
if (inPlan && current.planStart === undefined) {
|
||||
current.planStart = stats.now();
|
||||
promise.then(
|
||||
() => {
|
||||
current.planEnd = settled();
|
||||
},
|
||||
() => {
|
||||
current.planEnd = settled();
|
||||
}
|
||||
);
|
||||
} else if (!inPlan && current.renderAsk === undefined) {
|
||||
current.renderAsk = stats.now();
|
||||
current.example = pickIds(args);
|
||||
promise.then(
|
||||
() => {
|
||||
current.renderEnd = settled();
|
||||
},
|
||||
() => {
|
||||
current.renderEnd = settled();
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only id-like string fields, so logs never carry share keys, tokens or content. */
|
||||
function pickIds(args: unknown): Record<string, string> | undefined {
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
||||
return undefined;
|
||||
}
|
||||
const ids: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(args)) {
|
||||
if (key.endsWith('Id') && typeof value === 'string') {
|
||||
ids[key] = value;
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function summarizePlanStats(stats: PlanStats) {
|
||||
let used = 0;
|
||||
let beforePlan = 0;
|
||||
let savedMsTotal = 0;
|
||||
let savedMsMax = 0;
|
||||
const wasted: Record<string, number> = {};
|
||||
const notPlanned: Record<
|
||||
string,
|
||||
{ count: number; maxMs: number; example?: Record<string, string> }
|
||||
> = {};
|
||||
const saved: { label: string; ms: number }[] = [];
|
||||
|
||||
for (const entry of stats.entries.values()) {
|
||||
const { planStart, planEnd, renderAsk, renderEnd } = entry;
|
||||
if (planStart !== undefined && renderAsk !== undefined) {
|
||||
used++;
|
||||
if (planEnd !== undefined) {
|
||||
// Without the plan the render would have started this call itself when it asked.
|
||||
const withoutPlan = renderAsk + (planEnd - planStart);
|
||||
const withPlan = Math.max(renderAsk, planEnd);
|
||||
const ms = Math.max(0, withoutPlan - withPlan);
|
||||
savedMsTotal += ms;
|
||||
savedMsMax = Math.max(savedMsMax, ms);
|
||||
saved.push({ label: entry.label, ms });
|
||||
}
|
||||
} else if (planStart !== undefined) {
|
||||
wasted[entry.label] = (wasted[entry.label] ?? 0) + 1;
|
||||
} else if (
|
||||
renderAsk !== undefined &&
|
||||
stats.planStart !== undefined &&
|
||||
renderAsk < stats.planStart
|
||||
) {
|
||||
beforePlan++;
|
||||
} else if (renderAsk !== undefined) {
|
||||
const item = (notPlanned[entry.label] ??= {
|
||||
count: 0,
|
||||
maxMs: 0,
|
||||
example: entry.example,
|
||||
});
|
||||
item.count++;
|
||||
if (renderEnd !== undefined) {
|
||||
item.maxMs = Math.max(item.maxMs, renderEnd - renderAsk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
used,
|
||||
savedMsTotal,
|
||||
savedMsMax,
|
||||
topSaved: saved.sort((a, b) => b.ms - a.ms).slice(0, 5),
|
||||
wasted,
|
||||
beforePlan,
|
||||
notPlanned,
|
||||
};
|
||||
}
|
||||
|
||||
export function logPlanStats(stats: PlanStats) {
|
||||
const summary = summarizePlanStats(stats);
|
||||
// One JSON string so log tooling keeps nested fields (console truncates objects at depth 2).
|
||||
getLogger()
|
||||
.subLogger('data-plan')
|
||||
.info(
|
||||
'site-page-plan.stats',
|
||||
JSON.stringify({ elapsedMs: stats.now() - stats.t0, ...summary })
|
||||
);
|
||||
}
|
||||
|
||||
function record<T>(label: string, args: unknown, promise: Promise<T>): Promise<T> {
|
||||
try {
|
||||
recordCall(getRequestPlanStats(), label, args, promise, planScope.getStore() === true);
|
||||
} catch {
|
||||
// Measuring must never break a fetch.
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** Wrap a request's data fetcher so each call is timed; `withToken` fetchers aren't measured. */
|
||||
export function measureDataFetcher(fetcher: GitBookDataFetcher): GitBookDataFetcher {
|
||||
return new Proxy(fetcher, {
|
||||
get(target, prop, receiver) {
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
if (typeof prop !== 'string' || prop === 'api' || prop === 'withToken') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value !== 'function') {
|
||||
return value;
|
||||
}
|
||||
return (...args: unknown[]) =>
|
||||
record(prop, args[0], (value as (...a: unknown[]) => Promise<unknown>)(...args));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function measureImageResizer(resizer: ImageResizer): ImageResizer {
|
||||
return {
|
||||
...resizer,
|
||||
getImageSize: (input, options) =>
|
||||
record('getImageSize', [input, options], resizer.getImageSize(input, options)),
|
||||
};
|
||||
}
|
||||
@@ -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', permissions: { view: true } },
|
||||
space: { id: `space_${id}`, title, language: 'en' },
|
||||
urls: { published },
|
||||
...extra,
|
||||
} as SiteSpace;
|
||||
@@ -102,7 +102,6 @@ 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',
|
||||
@@ -165,45 +164,14 @@ describe('computePublishedSearchResults', () => {
|
||||
'space_v2/auth',
|
||||
'space_guides/status',
|
||||
'space_v1/legacy',
|
||||
'space_v0/reference',
|
||||
'record_1',
|
||||
]);
|
||||
});
|
||||
|
||||
it('includes readable published hidden spaces and excludes draft, denied, or unpublished placements', () => {
|
||||
const hidden = siteSpace('hidden', 'Older docs', 'https://docs.example.com/old/', {
|
||||
hidden: true,
|
||||
});
|
||||
const denied = siteSpace('denied', 'Denied', 'https://docs.example.com/denied/');
|
||||
denied.space.permissions.view = false;
|
||||
const draft = siteSpace('draft', 'Draft', 'https://docs.example.com/draft/', {
|
||||
draft: true,
|
||||
});
|
||||
const unpublished = siteSpace('unpublished', 'Unpublished', '', {
|
||||
urls: {},
|
||||
});
|
||||
|
||||
const spaces = getSearchSpaceLookup({
|
||||
type: 'siteSpaces',
|
||||
structure: [hidden, denied, draft, unpublished],
|
||||
});
|
||||
expect(spaces).toEqual({
|
||||
space_hidden: {
|
||||
siteSpaceId: 'ss_hidden',
|
||||
spaceURL: 'https://docs.example.com/old/',
|
||||
breadcrumbs: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back when a result belongs to an unknown space', () => {
|
||||
it('leaves hidden variants out of the lookup, so their results go to the route', () => {
|
||||
const spaces = getSearchSpaceLookup(structure);
|
||||
expect(Object.keys(spaces).sort()).toEqual([
|
||||
'space_guides',
|
||||
'space_v0',
|
||||
'space_v1',
|
||||
'space_v2',
|
||||
]);
|
||||
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',
|
||||
@@ -212,7 +180,7 @@ describe('computePublishedSearchResults', () => {
|
||||
spaceBasePath: '/api/',
|
||||
gitbookURL: undefined,
|
||||
});
|
||||
const searchResults = [space('unknown', 1, [{ id: 'page', path: 'page', rank: 1 }])];
|
||||
const searchResults = [...items, space('v0', 1, [{ id: 'draft', path: 'draft', rank: 5 }])];
|
||||
expect(
|
||||
computePublishedSearchResults({ asEmbeddable: false, linker, searchResults, spaces })
|
||||
).toBeNull();
|
||||
|
||||
@@ -52,12 +52,10 @@ export type DirectSearchProps = {
|
||||
*/
|
||||
export function toSearchSiteContentBody(
|
||||
query: string,
|
||||
scope: SearchSiteContentScope,
|
||||
searchId?: string
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] & { searchId?: string } {
|
||||
scope: SearchSiteContentScope
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] {
|
||||
return {
|
||||
query,
|
||||
searchId,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
@@ -121,7 +119,7 @@ export function computePublishedSearchResults(input: {
|
||||
const { asEmbeddable, linker, searchResults, spaces } = input;
|
||||
|
||||
const hasUnknownSpace = searchResults.some(
|
||||
(item) => item.type === 'space' && item.pages.length > 0 && !Object.hasOwn(spaces, item.id)
|
||||
(item) => item.type === 'space' && item.pages.length > 0 && !spaces[item.id]
|
||||
);
|
||||
if (hasUnknownSpace) {
|
||||
return null;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user