mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-26 10:13:46 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d300985bc | |||
| 9f2701c616 | |||
| 0173636ced | |||
| a3d37f341a | |||
| 68e3dace27 | |||
| 7af524a834 | |||
| 3ec61a78cf | |||
| 7f08fb14d1 | |||
| 867da7b94c |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Bump @opennextjs/aws to 4.2.1 and @opennextjs/cloudflare to 1.20.19.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Retry direct site search on the site's own domain after a network error or timeout.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Show site revision previews as their site revision pins them, including OpenAPI specs.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Paginate published Updates pages with more than 50 entries into 20-entry pages.
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -128,8 +128,8 @@
|
||||
"@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",
|
||||
"@opennextjs/aws": "4.2.1",
|
||||
"@opennextjs/cloudflare": "1.20.19",
|
||||
"@panzoom/panzoom": "^4.6.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
@@ -845,6 +845,8 @@
|
||||
|
||||
"@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="],
|
||||
|
||||
"@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="],
|
||||
|
||||
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
|
||||
|
||||
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
|
||||
@@ -937,9 +939,9 @@
|
||||
|
||||
"@octokit/types": ["@octokit/types@14.1.0", "", { "dependencies": { "@octokit/openapi-types": "^25.1.0" } }, "sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g=="],
|
||||
|
||||
"@opennextjs/aws": ["@opennextjs/aws@4.2.0", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-uWWER/P66CphCM+L0WlN9DSj3LauN/HjfK64V0+Hs+hjzKuQLGII/Q7FhkU1j/BEG4zbjIvkuJorzIyFwVWZiQ=="],
|
||||
"@opennextjs/aws": ["@opennextjs/aws@4.2.1", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-LQAwFWN4/tCxqnosOSIGHQ3SKh43d+sIBy5rwWEw0m6I+Qku7P4FDmfupfZ+MTcdZcs7nG8Rbu0+U6Z6S6ts8g=="],
|
||||
|
||||
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.18", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.2.0", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "esbuild": "0.28.2", "glob": "^13.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-6hy3RJHP7+OMxUxYLRCgzQipuJJ1n7JowszTHn/i2KGxPXccQuvs42YI5ZchV7Fd0JGrtIDj0lhgvw+dp7yMrg=="],
|
||||
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.19", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.2.1", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "esbuild": "0.28.2", "glob": "^14.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-OnKUZ+Ljaj9E9L/pk5Ove2kCmIUEk4hPmgc+YLE1gIZyg/isir+PKUlRIviV88N550/GA4yugcPN7KEv0es72A=="],
|
||||
|
||||
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
|
||||
|
||||
@@ -2167,7 +2169,7 @@
|
||||
|
||||
"github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="],
|
||||
|
||||
"glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="],
|
||||
"glob": ["glob@14.0.6", "", { "dependencies": { "minimatch": "^11.0.5", "minipass": "^7.1.3", "path-scurry": "^3.0.0" } }, "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw=="],
|
||||
|
||||
"glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
@@ -2595,7 +2597,7 @@
|
||||
|
||||
"miniflare": ["miniflare@4.20260401.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.24.4", "workerd": "1.20260401.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-lngHPzZFN9sxYG/mhzvnWiBMNVAN5MsO/7g32ttJ07rymtiK/ZBalODTKb8Od+BQdlU5DOR4CjVt9NydjnUyYg=="],
|
||||
|
||||
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||
"minimatch": ["minimatch@11.0.9", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q=="],
|
||||
|
||||
"minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],
|
||||
|
||||
@@ -2737,7 +2739,7 @@
|
||||
|
||||
"path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],
|
||||
|
||||
"path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="],
|
||||
"path-scurry": ["path-scurry@3.0.0", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg=="],
|
||||
|
||||
"path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
|
||||
|
||||
|
||||
@@ -781,7 +781,7 @@ const searchPassTestCases: Test[] = [
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Dropped API request: the search falls back to the route after its time limit',
|
||||
name: 'Dropped API request: search uses the site proxy before falling back to the route',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
@@ -791,6 +791,18 @@ const searchPassTestCases: Test[] = [
|
||||
await page.route(SEARCH_API_URL, (route) => {
|
||||
apiCalls.push(route.request());
|
||||
});
|
||||
const proxyCalls: Request[] = [];
|
||||
await page.route(
|
||||
/\/~gitbook\/search-direct\/orgs\/[^/]+\/sites\/[^/]+$/,
|
||||
async (route) => {
|
||||
proxyCalls.push(route.request());
|
||||
if (proxyCalls.length === 1) {
|
||||
await route.fulfill({ json: { items: [SEARCH_PASS_RECORD] } });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ status: 502 });
|
||||
}
|
||||
);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
@@ -798,12 +810,24 @@ const searchPassTestCases: Test[] = [
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
await page.clock.fastForward(5_000);
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('timeout');
|
||||
expect((await routeSearches[0]?.response())?.status()).toBe(200);
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
expect(routeSearches).toHaveLength(0);
|
||||
expect((await proxyCalls[0]?.allHeaders())?.['x-gitbook-search-pass']).toBe(
|
||||
'test-search-pass-1'
|
||||
);
|
||||
|
||||
await typeSearch(page, ' editor');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('502');
|
||||
expect((await routeSearches[0]?.response())?.status()).toBe(200);
|
||||
|
||||
await typeSearch(page, ' blocks');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
|
||||
expect(proxyCalls).toHaveLength(2);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
"@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",
|
||||
"@opennextjs/aws": "4.2.1",
|
||||
"@opennextjs/cloudflare": "1.20.19",
|
||||
"@panzoom/panzoom": "^4.6.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@/app/utils';
|
||||
import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
} from '@/components/SitePage';
|
||||
import { parseUpdatesPageParam } from '@/lib/updates-url';
|
||||
|
||||
type PageProps = {
|
||||
params: Promise<RouteParams & { page: string }>;
|
||||
};
|
||||
|
||||
export default async function Page(props: PageProps) {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getDynamicSiteContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return (
|
||||
<SitePage
|
||||
context={context}
|
||||
pageParams={{ pathname }}
|
||||
staticRoute={false}
|
||||
updatesPage={updatesPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const { context } = await getDynamicSiteContext(await props.params);
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getDynamicSiteContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return generateSitePageMetadata({
|
||||
context,
|
||||
pageParams: { pathname },
|
||||
updatesPage,
|
||||
});
|
||||
}
|
||||
+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);
|
||||
}
|
||||
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
|
||||
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
|
||||
import { getEmbeddableDynamicContext } from '@/lib/embeddable';
|
||||
import { parseUpdatesPageParam } from '@/lib/updates-url';
|
||||
|
||||
type PageProps = {
|
||||
params: Promise<RouteParams & { page: string }>;
|
||||
};
|
||||
|
||||
export default async function Page(props: PageProps) {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getEmbeddableDynamicContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return (
|
||||
<EmbeddableDocsPage
|
||||
context={context}
|
||||
pageParams={{ pathname }}
|
||||
staticRoute={false}
|
||||
updatesPage={updatesPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getEmbeddableDynamicContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils';
|
||||
import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
} from '@/components/SitePage';
|
||||
import { parseUpdatesPageParam } from '@/lib/updates-url';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
type PageProps = {
|
||||
params: Promise<RouteParams & { page: string }>;
|
||||
};
|
||||
|
||||
export default async function Page(props: PageProps) {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getStaticSiteContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return (
|
||||
<SitePage
|
||||
context={context}
|
||||
pageParams={{ pathname }}
|
||||
staticRoute
|
||||
updatesPage={updatesPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const { context } = await getStaticSiteContext(await props.params);
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getStaticSiteContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return generateSitePageMetadata({
|
||||
context,
|
||||
pageParams: { pathname },
|
||||
updatesPage,
|
||||
});
|
||||
}
|
||||
+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);
|
||||
}
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
|
||||
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
|
||||
import { getEmbeddableStaticContext } from '@/lib/embeddable';
|
||||
import { parseUpdatesPageParam } from '@/lib/updates-url';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
type PageProps = {
|
||||
params: Promise<RouteParams & { page: string }>;
|
||||
};
|
||||
|
||||
export default async function Page(props: PageProps) {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getEmbeddableStaticContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return (
|
||||
<EmbeddableDocsPage
|
||||
context={context}
|
||||
pageParams={{ pathname }}
|
||||
staticRoute
|
||||
updatesPage={updatesPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
const updatesPage = parseUpdatesPageParam(params.page);
|
||||
if (updatesPage === null) {
|
||||
notFound();
|
||||
}
|
||||
const { context } = await getEmbeddableStaticContext(params);
|
||||
const pathname = getPagePathFromParams(params);
|
||||
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
|
||||
}
|
||||
@@ -14,6 +14,11 @@ export async function hasContentBeenUpdated(props: { revisionId: string }) {
|
||||
const context = await getServerActionBaseContext();
|
||||
const siteURLData = await getSiteURLDataFromMiddleware();
|
||||
|
||||
// A site revision never changes what it shows.
|
||||
if (siteURLData.siteRevision) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (siteURLData.changeRequest) {
|
||||
const changeRequest = await getDataOrNull(
|
||||
context.dataFetcher.getChangeRequest({
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import { useHash, scrollToHash } from '../hooks';
|
||||
import { CONTENT_STYLE_REDUCED, MAIN_CONTENT_ID } from '../layout';
|
||||
import { Button, SkeletonUpdate, SuspenseLoadedHint } from '../primitives';
|
||||
import { UpdatesFilterContext, applyTagFilterAttribute, areTagsEqual } from './UpdatesFilter';
|
||||
import { UpdatesFilterScript } from './UpdatesFilterScript';
|
||||
import {
|
||||
type FilteredUpdatesPageResult,
|
||||
getFilteredUpdatesPage,
|
||||
resolveUpdatesAnchor,
|
||||
} from './UpdatesServerActions';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import {
|
||||
UPDATES_FILTER_KEY_ATTR,
|
||||
UPDATES_FILTER_SEARCH_PARAM,
|
||||
type UpdatesPageRange,
|
||||
getUpdatesPageRange,
|
||||
normalizeUpdatesFilterTags,
|
||||
updatesFilterStyleKey,
|
||||
} from '@/lib/updates';
|
||||
import {
|
||||
UPDATES_PAGE_SEARCH_PARAM,
|
||||
parseUpdatesPageParam,
|
||||
setUpdatesPageParam,
|
||||
} from '@/lib/updates-url';
|
||||
|
||||
const PENDING_FILTER_ATTR = 'data-updates-pending-filter';
|
||||
export const HIDE_PENDING_UPDATES = '[html[data-updates-pending-filter]_&]:hidden';
|
||||
|
||||
type FilteredPage = Extract<FilteredUpdatesPageResult, { status: 'ok' }>;
|
||||
type UpdatesView =
|
||||
| { status: 'unfiltered'; pagination: UpdatesPageRange }
|
||||
| { status: 'loading'; pagination: UpdatesPageRange | null }
|
||||
| { status: 'error'; pagination: null }
|
||||
| ({ status: 'filtered' } & Omit<FilteredPage, 'status'>);
|
||||
|
||||
type UpdatesSelection = { tags: string[]; page: number };
|
||||
|
||||
const PaginatedUpdatesContext = React.createContext<{
|
||||
view: UpdatesView;
|
||||
goToPage: (page: number) => void;
|
||||
retry: () => void;
|
||||
} | null>(null);
|
||||
|
||||
export function PaginatedUpdatesProvider(props: {
|
||||
pageId: string;
|
||||
revisionId: string;
|
||||
isEmbeddable: boolean;
|
||||
tagSlugs: string[];
|
||||
initialPagination: UpdatesPageRange;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { pageId, revisionId, isEmbeddable, tagSlugs, initialPagination, children } = props;
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const hash = useHash();
|
||||
const availableTags = React.useMemo(() => new Set(tagSlugs), [tagSlugs]);
|
||||
const styleKey = updatesFilterStyleKey(tagSlugs);
|
||||
const [selectedTags, setSelectedTags] = React.useState<string[]>([]);
|
||||
const [view, setView] = React.useState<UpdatesView>({
|
||||
status: 'unfiltered',
|
||||
pagination: initialPagination,
|
||||
});
|
||||
const selection = React.useRef<UpdatesSelection>({ tags: [], page: initialPagination.page });
|
||||
const hasNewerRevision = React.useRef(false);
|
||||
const requestId = React.useRef(0);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
document.documentElement.setAttribute(UPDATES_FILTER_KEY_ATTR, styleKey);
|
||||
return () => {
|
||||
requestId.current++;
|
||||
document.documentElement.removeAttribute(UPDATES_FILTER_KEY_ATTR);
|
||||
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
|
||||
applyTagFilterAttribute([]);
|
||||
};
|
||||
}, [styleKey]);
|
||||
|
||||
const syncLocation = React.useCallback(
|
||||
(force = false) => {
|
||||
const url = new URL(window.location.href);
|
||||
const { tags, page } = getUpdatesSelection(url, availableTags);
|
||||
const previous = selection.current;
|
||||
const sameTags = areTagsEqual(tags, previous.tags);
|
||||
if (!force && sameTags && page === previous.page) {
|
||||
return;
|
||||
}
|
||||
|
||||
const id = ++requestId.current;
|
||||
selection.current = { tags, page };
|
||||
setSelectedTags(tags);
|
||||
applyTagFilterAttribute(tags);
|
||||
|
||||
if (!tags.length) {
|
||||
if (page !== initialPagination.page) {
|
||||
setView({ status: 'loading', pagination: null });
|
||||
router.replace(relativeURL(url));
|
||||
return;
|
||||
}
|
||||
if (hasNewerRevision.current) {
|
||||
setView({ status: 'loading', pagination: null });
|
||||
window.location.replace(relativeURL(url));
|
||||
return;
|
||||
}
|
||||
setView({ status: 'unfiltered', pagination: initialPagination });
|
||||
return;
|
||||
}
|
||||
|
||||
setView((current) => {
|
||||
let pagination = null;
|
||||
if (sameTags && current.pagination) {
|
||||
pagination = getUpdatesPageRange(page, current.pagination.totalItems);
|
||||
}
|
||||
return { status: 'loading', pagination };
|
||||
});
|
||||
|
||||
async function load() {
|
||||
let result: FilteredUpdatesPageResult = { status: 'error' };
|
||||
try {
|
||||
result = await getFilteredUpdatesPage({ pageId, tags, page, isEmbeddable });
|
||||
} catch {
|
||||
// Network or aborted action leaves the filter selected so the reader can retry.
|
||||
}
|
||||
const currentURL = new URL(window.location.href);
|
||||
const selected = getUpdatesSelection(currentURL, availableTags);
|
||||
if (
|
||||
id !== requestId.current ||
|
||||
currentURL.pathname !== url.pathname ||
|
||||
selected.page !== page ||
|
||||
!areTagsEqual(selected.tags, tags)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
setView({ status: 'error', pagination: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.revisionId !== revisionId) {
|
||||
hasNewerRevision.current = true;
|
||||
}
|
||||
|
||||
if (result.status === 'unfiltered') {
|
||||
const fallback = currentURL;
|
||||
fallback.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
|
||||
setUpdatesPageParam(fallback.searchParams, initialPagination.page);
|
||||
window.history.replaceState(null, '', relativeURL(fallback));
|
||||
selection.current = { tags: [], page: initialPagination.page };
|
||||
setSelectedTags([]);
|
||||
applyTagFilterAttribute([]);
|
||||
if (hasNewerRevision.current) {
|
||||
setView({ status: 'loading', pagination: null });
|
||||
window.location.replace(relativeURL(fallback));
|
||||
return;
|
||||
}
|
||||
setView({ status: 'unfiltered', pagination: initialPagination });
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.pagination.isClamped) {
|
||||
const clamped = currentURL;
|
||||
setUpdatesPageParam(clamped.searchParams, result.pagination.page);
|
||||
window.history.replaceState(null, '', relativeURL(clamped));
|
||||
selection.current = { tags, page: result.pagination.page };
|
||||
}
|
||||
setView({
|
||||
status: 'filtered',
|
||||
revisionId: result.revisionId,
|
||||
content: result.content,
|
||||
sections: result.sections,
|
||||
pagination: result.pagination,
|
||||
});
|
||||
}
|
||||
|
||||
void load();
|
||||
},
|
||||
[availableTags, pageId, revisionId, initialPagination, isEmbeddable, router]
|
||||
);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
syncLocation();
|
||||
}, [searchParams, syncLocation]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const onPopState = () => syncLocation();
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return () => {
|
||||
window.removeEventListener('popstate', onPopState);
|
||||
};
|
||||
}, [syncLocation]);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
if (view.status !== 'loading') {
|
||||
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
|
||||
}
|
||||
}, [view]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
view.status === 'loading' ||
|
||||
view.status === 'error' ||
|
||||
(view.status === 'unfiltered' && selection.current.tags.length > 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
async function resolveHash() {
|
||||
const url = new URL(window.location.href);
|
||||
const anchorHash = url.hash;
|
||||
if (!anchorHash || scrollToHash(anchorHash.slice(1))) {
|
||||
return;
|
||||
}
|
||||
|
||||
let anchor: string;
|
||||
try {
|
||||
anchor = decodeURIComponent(anchorHash.slice(1));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const id = requestId.current;
|
||||
const { tags } = selection.current;
|
||||
try {
|
||||
const result = await resolveUpdatesAnchor({ pageId, anchor, tags, isEmbeddable });
|
||||
if (
|
||||
!active ||
|
||||
!result.found ||
|
||||
id !== requestId.current ||
|
||||
url.href !== window.location.href
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdatesPageParam(url.searchParams, result.page);
|
||||
if (result.clearTags) {
|
||||
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
|
||||
}
|
||||
if (url.href !== window.location.href) {
|
||||
router.replace(relativeURL(url));
|
||||
}
|
||||
} catch {
|
||||
// An unresolved hash should leave the visitor on the current page.
|
||||
}
|
||||
}
|
||||
|
||||
void resolveHash();
|
||||
window.addEventListener('hashchange', resolveHash);
|
||||
return () => {
|
||||
active = false;
|
||||
window.removeEventListener('hashchange', resolveHash);
|
||||
};
|
||||
}, [hash, isEmbeddable, pageId, router, view]);
|
||||
|
||||
function navigate(tags: string[], page: number, history: 'push' | 'replace') {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
|
||||
for (const tag of tags) {
|
||||
url.searchParams.append(UPDATES_FILTER_SEARCH_PARAM, tag);
|
||||
}
|
||||
setUpdatesPageParam(url.searchParams, page);
|
||||
url.hash = '';
|
||||
if (tags.length === 0 && (page !== initialPagination.page || hasNewerRevision.current)) {
|
||||
requestId.current++;
|
||||
selection.current = { tags, page };
|
||||
setSelectedTags(tags);
|
||||
applyTagFilterAttribute(tags);
|
||||
setView({ status: 'loading', pagination: null });
|
||||
if (hasNewerRevision.current) {
|
||||
window.location.replace(relativeURL(url));
|
||||
} else {
|
||||
router.replace(relativeURL(url));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (history === 'push') {
|
||||
window.history.pushState(null, '', relativeURL(url));
|
||||
} else {
|
||||
window.history.replaceState(null, '', relativeURL(url));
|
||||
}
|
||||
syncLocation();
|
||||
const main = document.getElementById(MAIN_CONTENT_ID);
|
||||
if (main) {
|
||||
main.scrollIntoView({ block: 'start', behavior: 'instant' });
|
||||
main.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTag(tag: string) {
|
||||
const { tags } = selection.current;
|
||||
if (tags.includes(tag)) {
|
||||
navigate(
|
||||
tags.filter((selected) => selected !== tag),
|
||||
1,
|
||||
'replace'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
navigate(normalizeUpdatesFilterTags([...tags, tag], availableTags), 1, 'replace');
|
||||
}
|
||||
|
||||
return (
|
||||
<UpdatesFilterContext.Provider
|
||||
value={{
|
||||
selectedTags,
|
||||
selectedTagSet: new Set(selectedTags),
|
||||
toggleTag,
|
||||
clearTags: () => navigate([], 1, 'replace'),
|
||||
}}
|
||||
>
|
||||
<PaginatedUpdatesContext.Provider
|
||||
value={{
|
||||
view,
|
||||
goToPage: (page) => navigate(selection.current.tags, page, 'push'),
|
||||
retry: () => syncLocation(true),
|
||||
}}
|
||||
>
|
||||
{tagSlugs.length > 0 && (
|
||||
<UpdatesFilterScript
|
||||
tagSlugs={tagSlugs}
|
||||
filterAttribute={PENDING_FILTER_ATTR}
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</PaginatedUpdatesContext.Provider>
|
||||
</UpdatesFilterContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePaginatedUpdates() {
|
||||
return React.useContext(PaginatedUpdatesContext);
|
||||
}
|
||||
|
||||
export function PaginatedUpdatesBody(props: { children: React.ReactNode }) {
|
||||
const updates = usePaginatedUpdates();
|
||||
const language = useLanguage();
|
||||
if (updates?.view.status === 'loading') {
|
||||
return <SkeletonUpdate className={CONTENT_STYLE_REDUCED} />;
|
||||
}
|
||||
if (updates?.view.status === 'error') {
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className={`${CONTENT_STYLE_REDUCED} flex items-center justify-between gap-4 rounded-lg border border-tint-subtle p-4 text-sm text-tint`}
|
||||
>
|
||||
<span>{tString(language, 'unexpected_error')}</span>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
label={tString(language, 'unexpected_error_retry')}
|
||||
onClick={updates.retry}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (updates?.view.status === 'filtered') {
|
||||
return (
|
||||
<div className="contents" data-content-ref-root="">
|
||||
<SuspenseLoadedHint />
|
||||
{updates.view.content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <div className={`contents ${HIDE_PENDING_UPDATES}`}>{props.children}</div>;
|
||||
}
|
||||
|
||||
function getUpdatesSelection(url: URL, availableTags: ReadonlySet<string>): UpdatesSelection {
|
||||
return {
|
||||
tags: normalizeUpdatesFilterTags(
|
||||
url.searchParams.getAll(UPDATES_FILTER_SEARCH_PARAM),
|
||||
availableTags
|
||||
),
|
||||
page: parseUpdatesPageParam(url.searchParams.get(UPDATES_PAGE_SEARCH_PARAM)) ?? 1,
|
||||
};
|
||||
}
|
||||
|
||||
function relativeURL(url: URL): string {
|
||||
return `${url.pathname}${url.search}${url.hash}`;
|
||||
}
|
||||
@@ -36,7 +36,7 @@ const emptyUpdatesFilterContext: UpdatesFilterContextValue = {
|
||||
clearTags: () => {},
|
||||
};
|
||||
|
||||
const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
|
||||
export const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
|
||||
|
||||
export function UpdatesFilterProvider(props: { tagSlugs: string[]; children: React.ReactNode }) {
|
||||
const { tagSlugs, children } = props;
|
||||
@@ -249,12 +249,12 @@ function TagChip(props: { tag: RevisionTag; onToggle: (tag: string) => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
function areTagsEqual(left: string[], right: string[]): boolean {
|
||||
export function areTagsEqual(left: string[], right: string[]): boolean {
|
||||
return left.length === right.length && left.every((tag, index) => tag === right[index]);
|
||||
}
|
||||
|
||||
/** Mirrors the active filter onto `<html>`, matching what the pre-paint script does on first load. */
|
||||
function applyTagFilterAttribute(tags: string[]) {
|
||||
export function applyTagFilterAttribute(tags: string[]) {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -58,12 +58,12 @@ export function applyUpdatesFilterScript(
|
||||
* Inline script that applies the URL's `?tag=` filter to `<html>` before first paint. Rendered only
|
||||
* on pages with filterable updates (see SitePage), not globally.
|
||||
*/
|
||||
export function UpdatesFilterScript(props: { tagSlugs: string[] }) {
|
||||
const { tagSlugs } = props;
|
||||
export function UpdatesFilterScript(props: { tagSlugs: string[]; filterAttribute?: string }) {
|
||||
const { tagSlugs, filterAttribute = UPDATES_TAG_FILTER_ATTR } = props;
|
||||
const inserted = useRef(false);
|
||||
const scriptArgs = serializeUpdatesFilterScriptArgs([
|
||||
UPDATES_FILTER_SEARCH_PARAM,
|
||||
UPDATES_TAG_FILTER_ATTR,
|
||||
filterAttribute,
|
||||
UPDATES_TAG_FILTER_CAP,
|
||||
tagSlugs,
|
||||
UPDATES_FILTER_KEY_ATTR,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { CONTENT_STYLE_REDUCED } from '../layout';
|
||||
import { Button } from '../primitives';
|
||||
import { HIDE_PENDING_UPDATES, usePaginatedUpdates } from './PaginatedUpdates';
|
||||
import { tString } from '@/intl/translate';
|
||||
import type { TranslationLanguage } from '@/intl/translations';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import {
|
||||
UPDATES_FILTER_SEARCH_PARAM,
|
||||
UPDATES_MAX_PAGE,
|
||||
setUpdatesPageParam,
|
||||
} from '@/lib/updates-url';
|
||||
|
||||
export function UpdatesPagination(props: { language: TranslationLanguage; baseHref: string }) {
|
||||
const { language, baseHref } = props;
|
||||
const updates = usePaginatedUpdates();
|
||||
const searchParams = useSearchParams();
|
||||
if (!updates?.view.pagination || updates.view.pagination.totalPages <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { view, goToPage } = updates;
|
||||
const { page, totalPages, totalItems, start, end } = updates.view.pagination;
|
||||
const number = new Intl.NumberFormat(language.locale);
|
||||
const previousLabel = tString(language, 'previous_page');
|
||||
const nextLabel = tString(language, 'next_page');
|
||||
|
||||
function buttonProps(targetPage: number, rel: 'prev' | 'next') {
|
||||
if (view.status !== 'unfiltered') {
|
||||
return { onClick: () => goToPage(targetPage) };
|
||||
}
|
||||
const params = new URLSearchParams(searchParams?.toString());
|
||||
params.delete(UPDATES_FILTER_SEARCH_PARAM);
|
||||
setUpdatesPageParam(params, targetPage);
|
||||
const query = params.toString();
|
||||
let href = baseHref;
|
||||
if (query) {
|
||||
href += `?${query}`;
|
||||
}
|
||||
return { href, rel };
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
CONTENT_STYLE_REDUCED,
|
||||
'mt-8 flex items-center justify-between gap-2 border-t border-tint-subtle pt-4',
|
||||
view.status === 'unfiltered' && HIDE_PENDING_UPDATES
|
||||
)}
|
||||
>
|
||||
<div aria-live="polite" className="text-sm text-tint">
|
||||
{tString(
|
||||
language,
|
||||
'updates_pagination_range',
|
||||
number.format(start),
|
||||
number.format(end),
|
||||
number.format(totalItems)
|
||||
)}
|
||||
</div>
|
||||
<nav
|
||||
aria-label={tString(language, 'updates_pagination_navigation')}
|
||||
className="flex justify-end gap-2"
|
||||
>
|
||||
{page > 1 && (
|
||||
<Button
|
||||
variant="blank"
|
||||
size="small"
|
||||
icon="chevron-left"
|
||||
label={previousLabel}
|
||||
{...buttonProps(page - 1, 'prev')}
|
||||
/>
|
||||
)}
|
||||
{page < totalPages && page < UPDATES_MAX_PAGE && (
|
||||
<Button
|
||||
variant="blank"
|
||||
size="small"
|
||||
trailing={<Icon icon="chevron-right" className="size-3" />}
|
||||
label={nextLabel}
|
||||
{...buttonProps(page + 1, 'next')}
|
||||
/>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
'use server';
|
||||
|
||||
import type * as React from 'react';
|
||||
|
||||
import { IconsProvider } from '@gitbook/icons';
|
||||
|
||||
import { PageBodyDocument } from '../PageBody/PageBodyDocument';
|
||||
import { getPageDocument } from '@/lib/data';
|
||||
import { getDocumentSections } from '@/lib/document-sections';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
getCustomizationIconStyle,
|
||||
getInlineIconSources,
|
||||
} from '@/lib/icons/inline';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { resolvePageId } from '@/lib/pages';
|
||||
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import {
|
||||
findUpdateAnchorPage,
|
||||
getDocumentFilterableTags,
|
||||
normalizeUpdatesFilterTags,
|
||||
paginateUpdatesDocument,
|
||||
} from '@/lib/updates';
|
||||
import { UPDATES_MAX_PAGE } from '@/lib/updates-url';
|
||||
|
||||
type UpdatesPageAction = {
|
||||
pageId: string;
|
||||
tags: string[];
|
||||
isEmbeddable: boolean;
|
||||
};
|
||||
|
||||
export type FilteredUpdatesPageResult =
|
||||
| {
|
||||
status: 'ok';
|
||||
revisionId: string;
|
||||
content: React.ReactNode;
|
||||
sections: Awaited<ReturnType<typeof getDocumentSections>>;
|
||||
pagination: NonNullable<ReturnType<typeof paginateUpdatesDocument>['pagination']>;
|
||||
}
|
||||
| {
|
||||
status: 'unfiltered';
|
||||
revisionId: string;
|
||||
}
|
||||
| {
|
||||
status: 'error';
|
||||
};
|
||||
|
||||
export async function getFilteredUpdatesPage(
|
||||
options: UpdatesPageAction & { page: number }
|
||||
): Promise<FilteredUpdatesPageResult> {
|
||||
const logger = getLogger().subLogger('updatesPagination');
|
||||
if (!Number.isInteger(options.page) || options.page < 1 || options.page > UPDATES_MAX_PAGE) {
|
||||
logger.warn('Invalid filtered updates page number');
|
||||
return { status: 'error' };
|
||||
}
|
||||
try {
|
||||
const { context, page, document } = await getUpdatesPageDocument(options);
|
||||
const availableTags = new Set(
|
||||
getDocumentFilterableTags(document, context.revision).map((tag) => tag.slug)
|
||||
);
|
||||
const tags = normalizeUpdatesFilterTags(options.tags, availableTags);
|
||||
if (!tags.length) {
|
||||
logger.info('No selected tags on the current revision', { pageId: page.id });
|
||||
return { status: 'unfiltered', revisionId: context.revisionId };
|
||||
}
|
||||
|
||||
const result = paginateUpdatesDocument(document, context.revision, {
|
||||
page: options.page,
|
||||
tags,
|
||||
});
|
||||
if (!result.pagination) {
|
||||
logger.info('Current revision no longer needs updates pagination', { pageId: page.id });
|
||||
return { status: 'unfiltered', revisionId: context.revisionId };
|
||||
}
|
||||
|
||||
const [sections, iconSources] = await Promise.all([
|
||||
getDocumentSections(context, result.document),
|
||||
getInlineIconSources(
|
||||
getContentInlineIconSourceRequests({
|
||||
iconStyle: getCustomizationIconStyle(context.customization),
|
||||
document: result.document,
|
||||
})
|
||||
),
|
||||
]);
|
||||
logger.info('Rendered filtered updates page', {
|
||||
siteId: context.site.id,
|
||||
pageId: page.id,
|
||||
page: result.pagination.page,
|
||||
totalItems: result.pagination.totalItems,
|
||||
totalPages: result.pagination.totalPages,
|
||||
});
|
||||
return {
|
||||
status: 'ok',
|
||||
revisionId: context.revisionId,
|
||||
content: (
|
||||
<IconsProvider iconSources={iconSources}>
|
||||
<PageBodyDocument context={context} page={page} document={result.document} />
|
||||
</IconsProvider>
|
||||
),
|
||||
sections,
|
||||
pagination: result.pagination,
|
||||
};
|
||||
} catch {
|
||||
logger.warn('Could not render filtered updates page');
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveUpdatesAnchor(options: UpdatesPageAction & { anchor: string }) {
|
||||
const logger = getLogger().subLogger('updatesPagination');
|
||||
try {
|
||||
const { context, page, document } = await getUpdatesPageDocument(options);
|
||||
const result = findUpdateAnchorPage(document, context.revision, options);
|
||||
logger.info('Resolved updates anchor', {
|
||||
siteId: context.site.id,
|
||||
pageId: page.id,
|
||||
found: result.found,
|
||||
page: result.found && result.page,
|
||||
});
|
||||
if (result.found && result.page <= UPDATES_MAX_PAGE) {
|
||||
return result;
|
||||
}
|
||||
} catch {
|
||||
logger.warn('Could not resolve updates anchor');
|
||||
}
|
||||
return { found: false as const };
|
||||
}
|
||||
|
||||
async function getUpdatesPageDocument({ pageId, isEmbeddable }: UpdatesPageAction) {
|
||||
const context = await fetchServerActionSiteContext(
|
||||
await getServerActionBaseContext({ isEmbeddable })
|
||||
);
|
||||
const target = resolvePageId(context.revision.pages, pageId);
|
||||
if (!target) {
|
||||
throw new Error('Updates page not found');
|
||||
}
|
||||
|
||||
const { page } = target;
|
||||
const document = await getPageDocument(context, page);
|
||||
if (!document) {
|
||||
throw new Error('Updates document not found');
|
||||
}
|
||||
return { context: { ...context, page }, page, document };
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
import { SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
import { IconsProvider } from '@gitbook/icons';
|
||||
|
||||
import { PaginatedUpdatesProvider } from '../DocumentView/PaginatedUpdates';
|
||||
import { HeaderMobileMenu } from '../Header/HeaderMobileMenu';
|
||||
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
|
||||
import { PageBody } from '../PageBody';
|
||||
@@ -33,6 +35,7 @@ export const dynamic = 'force-static';
|
||||
type EmbeddableDocsPageProps = {
|
||||
context: GitBookSiteContext;
|
||||
pageParams: PagePathParams;
|
||||
updatesPage?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -41,11 +44,51 @@ type EmbeddableDocsPageProps = {
|
||||
export async function EmbeddableDocsPage(
|
||||
props: EmbeddableDocsPageProps & { staticRoute: boolean }
|
||||
) {
|
||||
const { context, pageParams } = props;
|
||||
const { page, document, ancestors, withPageFeedback } = await getSitePageData({
|
||||
context,
|
||||
pageParams,
|
||||
});
|
||||
const { context } = props;
|
||||
const {
|
||||
page,
|
||||
document,
|
||||
ancestors,
|
||||
withPageFeedback,
|
||||
contentHasUpdates,
|
||||
pagination,
|
||||
pageHref,
|
||||
filterableTags,
|
||||
iconSources,
|
||||
} = await getSitePageData(props);
|
||||
let updatesBaseHref: string | undefined;
|
||||
if (pagination) {
|
||||
updatesBaseHref = pageHref;
|
||||
}
|
||||
let pageBody = (
|
||||
<PageBody
|
||||
context={context}
|
||||
page={page}
|
||||
ancestors={ancestors}
|
||||
document={document}
|
||||
withPageFeedback={withPageFeedback}
|
||||
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
|
||||
staticRoute={props.staticRoute}
|
||||
contentHasUpdates={contentHasUpdates}
|
||||
updatesBaseHref={updatesBaseHref}
|
||||
/>
|
||||
);
|
||||
if (pagination) {
|
||||
pageBody = (
|
||||
<IconsProvider iconSources={iconSources}>
|
||||
<PaginatedUpdatesProvider
|
||||
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
|
||||
pageId={page.id}
|
||||
revisionId={context.revisionId}
|
||||
isEmbeddable
|
||||
tagSlugs={filterableTags.map((tag) => tag.slug)}
|
||||
initialPagination={pagination}
|
||||
>
|
||||
{pageBody}
|
||||
</PaginatedUpdatesProvider>
|
||||
</IconsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const variants = categorizeVariants(context);
|
||||
|
||||
@@ -147,15 +190,7 @@ export async function EmbeddableDocsPage(
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<PageBody
|
||||
context={context}
|
||||
page={page}
|
||||
ancestors={ancestors}
|
||||
document={document}
|
||||
withPageFeedback={withPageFeedback}
|
||||
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
|
||||
staticRoute={props.staticRoute}
|
||||
/>
|
||||
{pageBody}
|
||||
</ScrollContainer>
|
||||
</EmbeddableFrameBody>
|
||||
</EmbeddableFrameMain>
|
||||
|
||||
@@ -15,7 +15,7 @@ import { PageFeedbackForm } from '../PageFeedback';
|
||||
import { SideSheet } from '../primitives/SideSheet';
|
||||
import { ThemeToggler } from '../ThemeToggler';
|
||||
import { PageAsideCloseButton } from './PageAsideButton';
|
||||
import { ScrollSectionsList } from './ScrollSectionsList';
|
||||
import { PaginatedScrollSectionsList, ScrollSectionsList } from './ScrollSectionsList';
|
||||
import { ScrollToTopButton } from './ScrollToTopButton';
|
||||
import { getSpaceLanguage, t, tString } from '@/intl/server';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
@@ -29,6 +29,7 @@ export async function PageAside(props: {
|
||||
page: RevisionPageDocument;
|
||||
document: JSONDocument | null;
|
||||
filterableTags: RevisionTag[];
|
||||
withUpdatesPagination: boolean;
|
||||
context: GitBookSiteContext;
|
||||
withHeaderOffset: { sectionsHeader: boolean; topHeader: boolean };
|
||||
withFullPageCover: boolean;
|
||||
@@ -142,7 +143,11 @@ export async function PageAside(props: {
|
||||
<div className="flex shrink flex-col overflow-hidden">
|
||||
{document ? (
|
||||
<React.Suspense fallback={null}>
|
||||
<PageAsideSections document={document} context={context} />
|
||||
<PageAsideSections
|
||||
document={document}
|
||||
context={context}
|
||||
withUpdatesPagination={props.withUpdatesPagination}
|
||||
/>
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
<PageAsideActions page={page} withPageFeedback={withPageFeedback} />
|
||||
@@ -157,11 +162,19 @@ export async function PageAside(props: {
|
||||
);
|
||||
}
|
||||
|
||||
async function PageAsideSections(props: { document: JSONDocument; context: GitBookSiteContext }) {
|
||||
async function PageAsideSections(props: {
|
||||
document: JSONDocument;
|
||||
context: GitBookSiteContext;
|
||||
withUpdatesPagination: boolean;
|
||||
}) {
|
||||
const { document, context } = props;
|
||||
|
||||
const sections = await getDocumentSections(context, document);
|
||||
|
||||
if (props.withUpdatesPagination) {
|
||||
return <PaginatedScrollSectionsList sections={sections} />;
|
||||
}
|
||||
|
||||
return sections.length > 1 ? (
|
||||
<div data-gb-page-outline className="overflow-y-auto">
|
||||
<ScrollSectionsList sections={sections} />
|
||||
|
||||
@@ -4,6 +4,10 @@ import React from 'react';
|
||||
import { OpenAPIMethodBadge } from '@gitbook/react-openapi';
|
||||
|
||||
import { HEADER_HEIGHT_DESKTOP } from '../layout';
|
||||
import {
|
||||
HIDE_PENDING_UPDATES,
|
||||
usePaginatedUpdates,
|
||||
} from '@/components/DocumentView/PaginatedUpdates';
|
||||
import { useUpdatesFilter } from '@/components/DocumentView/UpdatesFilter';
|
||||
import { useScrollActiveId } from '@/components/hooks';
|
||||
import { useBodyLoaded } from '@/components/primitives';
|
||||
@@ -21,6 +25,34 @@ const SECTION_INTERSECTING_THRESHOLD = 0.9;
|
||||
*/
|
||||
const ACTIVE_ITEM_OFFSET = 100;
|
||||
|
||||
export function PaginatedScrollSectionsList(props: { sections: DocumentSection[] }) {
|
||||
const updates = usePaginatedUpdates();
|
||||
const view = updates?.view;
|
||||
if (view?.status === 'loading' || view?.status === 'error') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let sections = props.sections;
|
||||
if (view?.status === 'filtered') {
|
||||
sections = view.sections;
|
||||
}
|
||||
if (sections.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-gb-page-outline
|
||||
className={tcls(
|
||||
'overflow-y-auto',
|
||||
view?.status === 'unfiltered' && HIDE_PENDING_UPDATES
|
||||
)}
|
||||
>
|
||||
<ScrollSectionsList sections={sections} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }) {
|
||||
const { selectedTagSet } = useUpdatesFilter();
|
||||
const ids = React.useMemo(
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
SiteInsightsDisplayContext,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
|
||||
import { DocumentViewSkeleton } from '../DocumentView';
|
||||
import { PaginatedUpdatesBody } from '../DocumentView/PaginatedUpdates';
|
||||
import { UpdatesPagination } from '../DocumentView/UpdatesPagination';
|
||||
import { CurrentPageProvider } from '../hooks/useCurrentPage';
|
||||
import { TrackPageViewEvent } from '../Insights';
|
||||
import { CONTENT_STYLE } from '../layout';
|
||||
@@ -12,6 +14,7 @@ import { PageFeedbackForm } from '../PageFeedback';
|
||||
import { DateRelative, SuspenseLoadedHint } from '../primitives';
|
||||
import OptionalSuspense from './OptionalSuspense';
|
||||
import { PageBodyBlankslate } from './PageBodyBlankslate';
|
||||
import { PageBodyDocument } from './PageBodyDocument';
|
||||
import { PageCover } from './PageCover';
|
||||
import { PageFooterNavigation } from './PageFooterNavigation';
|
||||
import { PageHeader } from './PageHeader';
|
||||
@@ -20,19 +23,11 @@ import { MAIN_CONTENT_ID } from '@/components/layout';
|
||||
import { getSpaceLanguage } from '@/intl/server';
|
||||
import { t } from '@/intl/translate';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import {
|
||||
hasAPIBlock,
|
||||
hasFullWidthBlock,
|
||||
hasMoreThan,
|
||||
hasTopLevelBlock,
|
||||
isNodeEmpty,
|
||||
} from '@/lib/document';
|
||||
import { hasAPIBlock, hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
|
||||
import type { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getPageRSSURL } from '@/routes/rss';
|
||||
|
||||
const LINK_PREVIEW_MAX_COUNT = 500;
|
||||
|
||||
export async function PageBody(props: {
|
||||
context: GitBookSiteContext;
|
||||
page: RevisionPageDocument;
|
||||
@@ -41,6 +36,8 @@ export async function PageBody(props: {
|
||||
withPageFeedback: boolean;
|
||||
insightsDisplayContext: SiteInsightsDisplayContext;
|
||||
staticRoute: boolean;
|
||||
contentHasUpdates: boolean;
|
||||
updatesBaseHref?: string | undefined;
|
||||
}) {
|
||||
const {
|
||||
page,
|
||||
@@ -50,26 +47,14 @@ export async function PageBody(props: {
|
||||
withPageFeedback,
|
||||
insightsDisplayContext,
|
||||
staticRoute,
|
||||
contentHasUpdates,
|
||||
updatesBaseHref,
|
||||
} = props;
|
||||
const { customization } = context;
|
||||
|
||||
// Update blocks can only be at the top level of the document, so we optimize the check.
|
||||
const contentHasUpdates = document
|
||||
? hasTopLevelBlock(document, (block) => block.type === 'updates')
|
||||
: false;
|
||||
|
||||
// Comments can only be made on change request previews, so public pages skip their markers.
|
||||
const withCommentAnchors = Boolean(context.changeRequest);
|
||||
|
||||
// Render link previews only if there are less than LINK_PREVIEW_MAX_COUNT links in the document.
|
||||
const withLinkPreviews = document
|
||||
? !hasMoreThan(
|
||||
document,
|
||||
(inline) => inline.object === 'inline' && inline.type === 'link',
|
||||
LINK_PREVIEW_MAX_COUNT
|
||||
)
|
||||
: false;
|
||||
|
||||
// Determine if content should use wide layout (2-column or 1-column instead of 3-column)
|
||||
// This happens when: (1) document has full-width blocks, OR (2) page layout is explicitly set to 'wide'
|
||||
const wideContent = document ? hasFullWidthBlock(document) : false;
|
||||
@@ -92,6 +77,29 @@ export async function PageBody(props: {
|
||||
|
||||
const pageHasToc = page.layout.tableOfContents && hasVisibleTOCItems;
|
||||
|
||||
let content = <PageBodyBlankslate page={page} context={context} />;
|
||||
if (document && !isNodeEmpty(document)) {
|
||||
content = (
|
||||
<OptionalSuspense
|
||||
staticRoute={staticRoute}
|
||||
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
|
||||
>
|
||||
<SuspenseLoadedHint />
|
||||
<div className="contents" data-content-ref-root="">
|
||||
<PageBodyDocument document={document} context={context} page={page} />
|
||||
</div>
|
||||
</OptionalSuspense>
|
||||
);
|
||||
}
|
||||
if (updatesBaseHref) {
|
||||
content = (
|
||||
<>
|
||||
<PaginatedUpdatesBody>{content}</PaginatedUpdatesBody>
|
||||
<UpdatesPagination language={language} baseHref={updatesBaseHref} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CurrentPageProvider page={{ spaceId: context.space.id, pageId: page.id }}>
|
||||
{contentHasUpdates ? (
|
||||
@@ -104,10 +112,11 @@ export async function PageBody(props: {
|
||||
) : null}
|
||||
<main
|
||||
id={MAIN_CONTENT_ID}
|
||||
tabIndex={-1}
|
||||
// Comments on the whole page target anywhere in it that isn't a block.
|
||||
{...(withCommentAnchors ? { 'data-comment-page': '' } : {})}
|
||||
className={tcls(
|
||||
'relative min-w-0 flex-1',
|
||||
'relative min-w-0 flex-1 outline-none',
|
||||
'break-anywhere', // Allow words to break if they are too long.
|
||||
'py-8',
|
||||
'layout-wide:no-sidebar:lg:max-xl:pb-20', // Add padding to prevent overlap of minimised trademark
|
||||
@@ -138,32 +147,7 @@ export async function PageBody(props: {
|
||||
hasAPIBlocks={hasAPIBlocks}
|
||||
asEmbeddable={insightsDisplayContext === SiteInsightsDisplayContext.Embed}
|
||||
/>
|
||||
{document && !isNodeEmpty(document) ? (
|
||||
<OptionalSuspense
|
||||
staticRoute={staticRoute}
|
||||
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
|
||||
>
|
||||
<SuspenseLoadedHint />
|
||||
<div className="contents" data-content-ref-root="">
|
||||
<DocumentView
|
||||
document={document}
|
||||
style="flex flex-col [&>*+*]:mt-5"
|
||||
context={{
|
||||
mode: 'default',
|
||||
contentContext: {
|
||||
...context,
|
||||
page,
|
||||
},
|
||||
withLinkPreviews,
|
||||
withCommentAnchors,
|
||||
isPageBody: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</OptionalSuspense>
|
||||
) : (
|
||||
<PageBodyBlankslate page={page} context={context} />
|
||||
)}
|
||||
{content}
|
||||
</div>
|
||||
|
||||
{page.layout.pagination && customization.pagination.enabled ? (
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import { DocumentView } from '../DocumentView';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { hasMoreThan } from '@/lib/document';
|
||||
|
||||
const LINK_PREVIEW_MAX_COUNT = 500;
|
||||
|
||||
export function PageBodyDocument(props: {
|
||||
context: GitBookSiteContext;
|
||||
page: RevisionPageDocument;
|
||||
document: JSONDocument;
|
||||
}) {
|
||||
const { context, page, document } = props;
|
||||
const withLinkPreviews = !hasMoreThan(
|
||||
document,
|
||||
(inline) => inline.object === 'inline' && inline.type === 'link',
|
||||
LINK_PREVIEW_MAX_COUNT
|
||||
);
|
||||
|
||||
return (
|
||||
<DocumentView
|
||||
document={document}
|
||||
style="flex flex-col [&>*+*]:mt-5"
|
||||
context={{
|
||||
mode: 'default',
|
||||
contentContext: { ...context, page },
|
||||
withLinkPreviews,
|
||||
withCommentAnchors: Boolean(context.changeRequest),
|
||||
isPageBody: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
|
||||
|
||||
import { createSearchPassStore } from './search-pass-store';
|
||||
import { SEARCH_FALLBACK_HEADER, createSearchPassStore } from './search-pass-store';
|
||||
import type { DirectSearchProps } from '@/lib/search-results';
|
||||
|
||||
const endpoint = 'https://api.gitbook.com/v1/orgs/org_1/sites/site_1/search';
|
||||
const proxyURL = '/~gitbook/search-direct/orgs/org_1/sites/site_1';
|
||||
const directSearch: DirectSearchProps = {
|
||||
apiURL: 'https://api.gitbook.com',
|
||||
organizationId: 'org_1',
|
||||
siteId: 'site_1',
|
||||
proxyURL,
|
||||
linker: {
|
||||
urlMode: 'url-host',
|
||||
siteHost: 'docs.example.com',
|
||||
@@ -60,6 +62,150 @@ describe('createSearchPassStore', () => {
|
||||
let restore: (() => void) | undefined;
|
||||
afterEach(() => restore?.());
|
||||
|
||||
it('switches to the site proxy after an API network failure', async () => {
|
||||
const fetchSpy = spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockImplementation(async () => Response.json({ items: [] }));
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
|
||||
directSearch.passURL,
|
||||
endpoint,
|
||||
proxyURL,
|
||||
proxyURL,
|
||||
]);
|
||||
const init = fetchSpy.mock.calls[2]?.[1];
|
||||
expect(init).toMatchObject({ mode: 'same-origin', credentials: 'same-origin' });
|
||||
expect(init?.body).toBe(JSON.stringify({ query: 'tokens', mode: 'all' }));
|
||||
const headers = new Headers(init?.headers);
|
||||
expect(headers.get('x-gitbook-search-pass')).toBe('pass-1');
|
||||
expect(headers.get(SEARCH_FALLBACK_HEADER)).toBe('network');
|
||||
expect(headers.has('authorization')).toBe(false);
|
||||
expect(new Headers(fetchSpy.mock.calls[3]?.[1]?.headers).has(SEARCH_FALLBACK_HEADER)).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('switches to the site proxy after an API timeout', async () => {
|
||||
const originalSetTimeout = globalThis.setTimeout;
|
||||
const timeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation(((
|
||||
fn: (...args: unknown[]) => void,
|
||||
ms?: number,
|
||||
...args: unknown[]
|
||||
) => {
|
||||
let delay = ms;
|
||||
if (ms === 5_000) {
|
||||
delay = 0;
|
||||
}
|
||||
return originalSetTimeout(fn, delay, ...args);
|
||||
}) as typeof setTimeout);
|
||||
const fetchSpy = spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
|
||||
.mockImplementationOnce(
|
||||
(_url, init) =>
|
||||
new Promise((_, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
'abort',
|
||||
() => reject(new DOMException('Aborted', 'AbortError')),
|
||||
{ once: true }
|
||||
);
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(Response.json({ items: [] }));
|
||||
restore = () => {
|
||||
timeoutSpy.mockRestore();
|
||||
fetchSpy.mockRestore();
|
||||
};
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
|
||||
directSearch.passURL,
|
||||
endpoint,
|
||||
proxyURL,
|
||||
]);
|
||||
expect(new Headers(fetchSpy.mock.calls[2]?.[1]?.headers).get(SEARCH_FALLBACK_HEADER)).toBe(
|
||||
'timeout'
|
||||
);
|
||||
});
|
||||
|
||||
it('refreshes the pass on a 401 from the site proxy', async () => {
|
||||
const fetchSpy = spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 401 }))
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-2', expiresIn: 300_000 }))
|
||||
.mockResolvedValueOnce(Response.json({ items: [] }));
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
expect(await search(store)).toEqual({ type: 'route', reason: '401' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(await search(store)).toEqual({ type: 'results', results: [] });
|
||||
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
|
||||
directSearch.passURL,
|
||||
endpoint,
|
||||
proxyURL,
|
||||
directSearch.passURL,
|
||||
proxyURL,
|
||||
]);
|
||||
expect(new Headers(fetchSpy.mock.calls[4]?.[1]?.headers).get('x-gitbook-search-pass')).toBe(
|
||||
'pass-2'
|
||||
);
|
||||
});
|
||||
|
||||
it('honors rate-limit headers on a 429 from the site proxy', async () => {
|
||||
const resetAtSeconds = Math.ceil((Date.now() + 30_000) / 1000);
|
||||
const fetchSpy = spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 429,
|
||||
headers: {
|
||||
'x-ratelimit-scope': 'site',
|
||||
'x-ratelimit-reset': String(resetAtSeconds),
|
||||
},
|
||||
})
|
||||
);
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
await expect(search(store)).rejects.toThrow('Search is rate limited');
|
||||
await expect(search(store)).rejects.toThrow('Search is rate limited');
|
||||
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
|
||||
directSearch.passURL,
|
||||
endpoint,
|
||||
proxyURL,
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses the server route after the site proxy also fails', async () => {
|
||||
const fetchSpy = spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 502 }));
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
const store = createSearchPassStore(directSearch);
|
||||
await store.requestPass();
|
||||
|
||||
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
|
||||
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
|
||||
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
|
||||
directSearch.passURL,
|
||||
endpoint,
|
||||
proxyURL,
|
||||
]);
|
||||
});
|
||||
|
||||
it('stays on the route for the rest of the page after a 403', async () => {
|
||||
const { authorizations, fetchSpy } = mockFetch([403]);
|
||||
restore = () => fetchSpy.mockRestore();
|
||||
|
||||
@@ -32,6 +32,11 @@ type DirectSearchOutcome =
|
||||
| { type: 'results'; results: OrderedComputedResult[] }
|
||||
| { type: 'route'; reason?: string };
|
||||
|
||||
type SearchAttempt =
|
||||
| { type: 'success'; body: string }
|
||||
| { type: 'http'; response: Response }
|
||||
| { type: 'failure'; reason: 'network' | 'timeout' };
|
||||
|
||||
export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
|
||||
|
||||
/**
|
||||
@@ -39,6 +44,7 @@ export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
|
||||
*/
|
||||
export function createSearchPassStore(directSearch: DirectSearchProps | undefined) {
|
||||
let state: SearchPassState = { status: 'none' };
|
||||
let useProxy = false;
|
||||
let pendingRequest: Promise<void> | null = null;
|
||||
|
||||
const sendPassRequest = async () => {
|
||||
@@ -77,7 +83,9 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
(current.status === 'none' && current.reason === '401') ||
|
||||
(current.status === 'ready' && current.replacesRejectedPass),
|
||||
};
|
||||
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
|
||||
if (!useProxy) {
|
||||
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
|
||||
}
|
||||
} else if (current.status === 'ready') {
|
||||
state = { status: 'none' };
|
||||
}
|
||||
@@ -146,78 +154,144 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
return { type: 'results', results: [] };
|
||||
}
|
||||
|
||||
const { token, replacesRejectedPass } = state;
|
||||
const { apiURL, organizationId, siteId } = directSearch;
|
||||
// A request dropped on the way to the API never settles, so it gets its own time limit.
|
||||
// The browser targets predate `AbortSignal.any`.
|
||||
const request = new AbortController();
|
||||
if (signal.aborted) {
|
||||
request.abort();
|
||||
let pass = state;
|
||||
const { apiURL, organizationId, siteId, proxyURL } = directSearch;
|
||||
const usingProxy = useProxy;
|
||||
let url = `${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`;
|
||||
if (usingProxy) {
|
||||
url = proxyURL;
|
||||
}
|
||||
signal.addEventListener('abort', () => request.abort(), { once: true });
|
||||
const timeout = setTimeout(() => request.abort(), DIRECT_SEARCH_TIMEOUT_MS);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
|
||||
credentials: 'omit',
|
||||
signal: request.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (signal.aborted) {
|
||||
throw error;
|
||||
const body = JSON.stringify(toSearchSiteContentBody(query, scope, searchId));
|
||||
let attempt = await sendSearch(url, usingProxy, pass.token, body, signal);
|
||||
|
||||
if (attempt.type === 'failure' && !usingProxy) {
|
||||
const current = state as SearchPassState;
|
||||
// TODO: timeout can mean a slow API rather than a blocked host, so consider not sticking to the proxy for the session.
|
||||
if (current.status === 'ready') {
|
||||
useProxy = true;
|
||||
pass = current;
|
||||
attempt = await sendSearch(
|
||||
proxyURL,
|
||||
true,
|
||||
pass.token,
|
||||
body,
|
||||
signal,
|
||||
attempt.reason
|
||||
);
|
||||
} else if (current.status === 'none') {
|
||||
useProxy = true;
|
||||
return { type: 'route', reason: attempt.reason };
|
||||
}
|
||||
return fallBack(request.signal.aborted ? 'timeout' : 'network');
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
return replacesRejectedPass ? fallBack('401') : dropPass(token, '401');
|
||||
if (attempt.type === 'failure') {
|
||||
const current = state as SearchPassState;
|
||||
if (current.status === 'route') {
|
||||
return waitForCooldown(current, signal);
|
||||
}
|
||||
return fallBack(attempt.reason);
|
||||
}
|
||||
if (response.status === 429) {
|
||||
state = {
|
||||
status: 'route',
|
||||
reason: '429',
|
||||
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
|
||||
};
|
||||
return waitForCooldown(state, signal);
|
||||
}
|
||||
if (!response.ok) {
|
||||
if (attempt.type === 'http') {
|
||||
const { response } = attempt;
|
||||
if (response.status === 401) {
|
||||
if (pass.replacesRejectedPass) {
|
||||
return fallBack('401');
|
||||
}
|
||||
return dropPass(pass.token, '401');
|
||||
}
|
||||
if (response.status === 429) {
|
||||
state = {
|
||||
status: 'route',
|
||||
reason: '429',
|
||||
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
|
||||
};
|
||||
return waitForCooldown(state, signal);
|
||||
}
|
||||
return fallBack(String(response.status));
|
||||
}
|
||||
|
||||
let results: OrderedComputedResult[] | null;
|
||||
try {
|
||||
const { items } = (await response.json()) as {
|
||||
const { items } = JSON.parse(attempt.body) as {
|
||||
items: (SearchSpaceResult | SearchRecordResult)[];
|
||||
};
|
||||
const linker = createSiteLinker(directSearch.linker);
|
||||
results = computePublishedSearchResults({
|
||||
let linker = createSiteLinker(directSearch.linker);
|
||||
if (asEmbeddable) {
|
||||
linker = getEmbeddableLinker(linker);
|
||||
}
|
||||
const results = computePublishedSearchResults({
|
||||
asEmbeddable,
|
||||
linker: asEmbeddable ? getEmbeddableLinker(linker) : linker,
|
||||
linker,
|
||||
searchResults: items,
|
||||
spaces: directSearch.spaces,
|
||||
});
|
||||
} catch (error) {
|
||||
if (signal.aborted) {
|
||||
throw error;
|
||||
if (!results) {
|
||||
return { type: 'route', reason: 'unknown_space' };
|
||||
}
|
||||
return fallBack(request.signal.aborted ? 'timeout' : 'invalid');
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
return { type: 'results', results };
|
||||
} catch {
|
||||
return fallBack('invalid');
|
||||
}
|
||||
|
||||
// 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 { requestPass, search };
|
||||
}
|
||||
|
||||
async function sendSearch(
|
||||
url: string,
|
||||
useProxy: boolean,
|
||||
token: string,
|
||||
body: string,
|
||||
signal: AbortSignal,
|
||||
fallbackReason?: 'network' | 'timeout'
|
||||
): Promise<SearchAttempt> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
let mode: RequestMode | undefined;
|
||||
let credentials: RequestCredentials = 'omit';
|
||||
if (useProxy) {
|
||||
mode = 'same-origin';
|
||||
credentials = 'same-origin';
|
||||
headers['x-gitbook-search-pass'] = token;
|
||||
if (fallbackReason) {
|
||||
headers[SEARCH_FALLBACK_HEADER] = fallbackReason;
|
||||
}
|
||||
} else {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const request = new AbortController();
|
||||
const abort = () => request.abort();
|
||||
if (signal.aborted) {
|
||||
abort();
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
const timeout = setTimeout(abort, DIRECT_SEARCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body,
|
||||
credentials,
|
||||
mode,
|
||||
signal: request.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
return { type: 'http', response };
|
||||
}
|
||||
return { type: 'success', body: await response.text() };
|
||||
} catch (error) {
|
||||
if (signal.aborted) {
|
||||
throw error;
|
||||
}
|
||||
if (request.signal.aborted) {
|
||||
return { type: 'failure', reason: 'timeout' };
|
||||
}
|
||||
return { type: 'failure', reason: 'network' };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold a search until a short rate limit cooldown ends, then send it to the route.
|
||||
* During a longer cooldown the search fails at once, as the route would.
|
||||
|
||||
@@ -132,9 +132,13 @@ export function getDirectSearchProps(context: GitBookSiteContext): DirectSearchP
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { organizationId, siteId } = context.directSearch;
|
||||
return {
|
||||
...context.directSearch,
|
||||
spaces: getSearchSpaceLookup(context.structure),
|
||||
passURL: context.linker.toPathInSite('~gitbook/search-pass'),
|
||||
proxyURL: context.linker.toPathInSite(
|
||||
`~gitbook/search-direct/orgs/${organizationId}/sites/${siteId}`
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CustomizationHeaderPreset,
|
||||
SiteInsightsDisplayContext,
|
||||
type TranslationLanguage,
|
||||
type RevisionTag,
|
||||
} from '@gitbook/api';
|
||||
import { IconsProvider } from '@gitbook/icons';
|
||||
|
||||
@@ -18,34 +19,43 @@ import {
|
||||
} from './fetch';
|
||||
import { PageClientLayout } from './PageClientLayout';
|
||||
import { getPageFullTitle } from './title';
|
||||
import { PaginatedUpdatesProvider } from '@/components/DocumentView/PaginatedUpdates';
|
||||
import { UpdatesFilterProvider } from '@/components/DocumentView/UpdatesFilter';
|
||||
import { UpdatesFilterScript } from '@/components/DocumentView/UpdatesFilterScript';
|
||||
import { PageAside } from '@/components/PageAside';
|
||||
import { PageBody, PageCover } from '@/components/PageBody';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getDataOrNull, getPageDocument } from '@/lib/data';
|
||||
import { hasTopLevelBlock } from '@/lib/document';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
getCustomizationIconStyle,
|
||||
getInlineIconSources,
|
||||
} from '@/lib/icons/inline';
|
||||
import { getResizedImageURL } from '@/lib/images';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { getPagePath } from '@/lib/pages';
|
||||
import { resolveContentRef } from '@/lib/references';
|
||||
import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
|
||||
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import {
|
||||
countDocumentUpdates,
|
||||
generateUpdatesFilterCSS,
|
||||
getUpdatesPageRange,
|
||||
paginateUpdatesDocument,
|
||||
UPDATES_PAGINATION_THRESHOLD,
|
||||
getDocumentFilterableTags,
|
||||
updatesFilterStyleHref,
|
||||
} from '@/lib/updates';
|
||||
import { UPDATES_PAGE_SEARCH_PARAM } from '@/lib/updates-url';
|
||||
|
||||
export { getPageFullTitle } from './title';
|
||||
|
||||
export type SitePageProps = {
|
||||
context: GitBookSiteContext;
|
||||
pageParams: PagePathParams;
|
||||
updatesPage?: number;
|
||||
};
|
||||
|
||||
type AlternateLinkSpace = {
|
||||
@@ -85,11 +95,18 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
|
||||
withTopHeader,
|
||||
pageMetaLinks,
|
||||
iconSources,
|
||||
filterableTags,
|
||||
contentHasUpdates,
|
||||
pagination,
|
||||
pageHref,
|
||||
} = await getSitePageData(props);
|
||||
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
|
||||
const filterableTags = document ? getDocumentFilterableTags(document, context.revision) : [];
|
||||
const filterableTagSlugs = filterableTags.map((tag) => tag.slug);
|
||||
const content = (
|
||||
let updatesBaseHref: string | undefined;
|
||||
if (pagination) {
|
||||
updatesBaseHref = pageHref;
|
||||
}
|
||||
let content = (
|
||||
<>
|
||||
{/* Using `contents` makes the children of this div according to its parent — which keeps them in a single flex row with the TOC by default.
|
||||
If there's a page cover, we use `flex flex-col` to lay out the PageCover above the PageBody + PageAside instead. */}
|
||||
@@ -119,6 +136,7 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
|
||||
page={page}
|
||||
document={document}
|
||||
filterableTags={filterableTags}
|
||||
withUpdatesPagination={Boolean(pagination)}
|
||||
withHeaderOffset={headerOffset}
|
||||
withFullPageCover={withFullPageCover}
|
||||
withPageFeedback={withPageFeedback}
|
||||
@@ -132,6 +150,8 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
|
||||
withPageFeedback={withPageFeedback}
|
||||
insightsDisplayContext={SiteInsightsDisplayContext.Site}
|
||||
staticRoute={props.staticRoute}
|
||||
contentHasUpdates={contentHasUpdates}
|
||||
updatesBaseHref={updatesBaseHref}
|
||||
/>
|
||||
</div>
|
||||
<PageClientLayout pageMetaLinks={pageMetaLinks} />
|
||||
@@ -139,18 +159,34 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
|
||||
</>
|
||||
);
|
||||
|
||||
if (pagination) {
|
||||
content = (
|
||||
<PaginatedUpdatesProvider
|
||||
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
|
||||
pageId={page.id}
|
||||
revisionId={context.revisionId}
|
||||
isEmbeddable={false}
|
||||
tagSlugs={filterableTagSlugs}
|
||||
initialPagination={pagination}
|
||||
>
|
||||
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
|
||||
{content}
|
||||
</PaginatedUpdatesProvider>
|
||||
);
|
||||
} else if (filterableTagSlugs.length > 0) {
|
||||
content = (
|
||||
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
|
||||
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
|
||||
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
|
||||
{content}
|
||||
</UpdatesFilterProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IconsProvider iconSources={iconSources}>
|
||||
<PageContextProvider pageId={page.id} spaceId={context.space.id} title={page.title}>
|
||||
{filterableTagSlugs.length > 0 ? (
|
||||
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
|
||||
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
|
||||
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
|
||||
{content}
|
||||
</UpdatesFilterProvider>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
{content}
|
||||
</PageContextProvider>
|
||||
</IconsProvider>
|
||||
);
|
||||
@@ -204,7 +240,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
|
||||
const { page, ancestors } = pageTarget;
|
||||
const { customization, revision, linker, imageResizer } = context;
|
||||
|
||||
const canonical = (
|
||||
let canonical = (
|
||||
pageMetaLinks?.canonical
|
||||
? new URL(
|
||||
// If the canonical link is an absolute URL, use it as is.
|
||||
@@ -216,6 +252,23 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
|
||||
linker.toAbsoluteURL(linker.toPathForPage({ pages: revision.pages, page }))
|
||||
).replace(/\/+$/, ''); // Trim trailing slashes in canonical URL to match the redirect behavior
|
||||
|
||||
let title = getPageFullTitle(context, page);
|
||||
if (props.updatesPage) {
|
||||
const document = await getPageDocument(context, page);
|
||||
if (document) {
|
||||
const count = countDocumentUpdates(document);
|
||||
if (count > UPDATES_PAGINATION_THRESHOLD) {
|
||||
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
|
||||
title = `${title} (Page ${pageNumber})`;
|
||||
if (!pageMetaLinks?.canonical) {
|
||||
const url = new URL(canonical);
|
||||
url.searchParams.set(UPDATES_PAGE_SEARCH_PARAM, String(pageNumber));
|
||||
canonical = url.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const alternates = pageMetaLinks?.alternates.reduce<{
|
||||
languages: Record<string, string>;
|
||||
generic: {
|
||||
@@ -239,7 +292,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
|
||||
);
|
||||
|
||||
return {
|
||||
title: getPageFullTitle(context, page),
|
||||
title,
|
||||
description: page.description ?? '',
|
||||
keywords: page.keywords?.length ? page.keywords : undefined,
|
||||
alternates: {
|
||||
@@ -327,7 +380,44 @@ export async function getSitePageData(props: SitePageProps) {
|
||||
|
||||
const withSections = Boolean(visibleSections && visibleSections.list.length > 0);
|
||||
|
||||
const document = await getPageDocument(context, page);
|
||||
const fullDocument = await getPageDocument(context, page);
|
||||
const pageHref = context.linker.toPathForPagePath({ path: rawPathname });
|
||||
let contentHasUpdates = false;
|
||||
let filterableTags: RevisionTag[] = [];
|
||||
let document = fullDocument;
|
||||
let pagination = null;
|
||||
if (fullDocument) {
|
||||
contentHasUpdates = hasTopLevelBlock(fullDocument, (block) => block.type === 'updates');
|
||||
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
|
||||
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
|
||||
page: props.updatesPage ?? 1,
|
||||
}));
|
||||
}
|
||||
|
||||
if (pagination || props.updatesPage) {
|
||||
const logger = getLogger().subLogger('updatesPagination', {
|
||||
labels: { siteId: context.site.id, pageId: page.id },
|
||||
});
|
||||
if (props.updatesPage && (!pagination || pagination.isClamped)) {
|
||||
const targetPage = pagination?.page ?? 1;
|
||||
logger.info('Redirected out-of-range updates page', {
|
||||
requestedPage: props.updatesPage,
|
||||
targetPage,
|
||||
});
|
||||
if (targetPage > 1) {
|
||||
redirect(`${pageHref}?${UPDATES_PAGE_SEARCH_PARAM}=${targetPage}`);
|
||||
}
|
||||
redirect(pageHref);
|
||||
}
|
||||
if (pagination) {
|
||||
logger.info('Rendered updates page', {
|
||||
page: pagination.page,
|
||||
totalItems: pagination.totalItems,
|
||||
totalPages: pagination.totalPages,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const iconStyle = getCustomizationIconStyle(customization);
|
||||
const iconSources = await getInlineIconSources(
|
||||
getContentInlineIconSourceRequests({
|
||||
@@ -347,6 +437,10 @@ export async function getSitePageData(props: SitePageProps) {
|
||||
withTopHeader,
|
||||
pageMetaLinks,
|
||||
iconSources,
|
||||
contentHasUpdates,
|
||||
filterableTags,
|
||||
pagination,
|
||||
pageHref,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import type { RevisionPageDocument, SiteRedirectDestination } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const {
|
||||
getLowercasePathnameRedirect,
|
||||
startSitePagePlan,
|
||||
resolveMissingPagePath,
|
||||
resolveSitePageFromURL,
|
||||
} = await import('./fetch');
|
||||
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
|
||||
await import('./fetch');
|
||||
const { normalizeURL } = await import('@/lib/data/urls');
|
||||
const { createLinker } = await import('@/lib/links');
|
||||
|
||||
@@ -27,15 +23,28 @@ const page = {
|
||||
|
||||
describe('resolveMissingPagePath', () => {
|
||||
function createRedirectContext(options: {
|
||||
siteRedirect?: { source?: string; target: string; permanent?: boolean };
|
||||
siteRedirect?: {
|
||||
source?: string;
|
||||
target: string;
|
||||
permanent?: boolean;
|
||||
destination?: SiteRedirectDestination;
|
||||
};
|
||||
spaceRedirectPageId?: string;
|
||||
contextId?: string;
|
||||
structure?: GitBookSiteContext['structure'];
|
||||
revisionsBySpace?: Record<string, RevisionPageDocument[]>;
|
||||
}) {
|
||||
const getSiteRedirectBySource = mock(async ({ source }: { source: string }) =>
|
||||
options.siteRedirect && source === (options.siteRedirect.source ?? '/old')
|
||||
? {
|
||||
data: {
|
||||
target: options.siteRedirect.target,
|
||||
redirect: { permanent: options.siteRedirect.permanent ?? false },
|
||||
redirect: {
|
||||
permanent: options.siteRedirect.permanent ?? false,
|
||||
...(options.siteRedirect.destination
|
||||
? { destination: options.siteRedirect.destination }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
@@ -45,19 +54,35 @@ describe('resolveMissingPagePath', () => {
|
||||
? { data: { id: options.spaceRedirectPageId } }
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
);
|
||||
const getRevision = mock(async ({ spaceId }: { spaceId: string }) =>
|
||||
options.revisionsBySpace?.[spaceId]
|
||||
? { data: { pages: options.revisionsBySpace[spaceId] } }
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
);
|
||||
|
||||
const defaultSiteSpace = {
|
||||
id: 'site-space-1',
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
};
|
||||
|
||||
return {
|
||||
organizationId: 'org-1',
|
||||
site: { id: 'site-1' },
|
||||
siteSpace: defaultSiteSpace,
|
||||
structure: options.structure ?? {
|
||||
type: 'siteSpaces',
|
||||
structure: [defaultSiteSpace],
|
||||
},
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
revisionId: 'revision-1',
|
||||
revision: { pages: [page] },
|
||||
contextId: options.contextId,
|
||||
linker: {
|
||||
toPathInSpace: (path: string) => path,
|
||||
toRelativePathInSite: (path: string) => path,
|
||||
toLinkForContent: (url: string) => new URL(url).pathname,
|
||||
},
|
||||
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath },
|
||||
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath, getRevision },
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
|
||||
@@ -91,6 +116,224 @@ describe('resolveMissingPagePath', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a site redirect that targets the current path', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted',
|
||||
target: 'https://docs.example.com/release-notes/restricted',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect that targets the current path with trailing slash, case, or query differences', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted',
|
||||
target: 'https://docs.example.com/Release-Notes/Restricted/?tab=1#top',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a space-relative redirect that resolves back to the current section path', async () => {
|
||||
const context = {
|
||||
...createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/v3/getting-started',
|
||||
target: 'https://docs.example.com/docs/v3/getting-started',
|
||||
},
|
||||
}),
|
||||
linker: createLinker({
|
||||
host: 'docs.example.com',
|
||||
siteBasePath: '/',
|
||||
spaceBasePath: '/docs/',
|
||||
}),
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'v3/getting-started')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden site space on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/getting-started',
|
||||
target: 'https://docs.example.com/docs/v3/getting-started',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-hidden',
|
||||
pageId: 'page-v3',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'getting-started')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden section on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure: {
|
||||
type: 'sections',
|
||||
structure: [
|
||||
{
|
||||
object: 'site-section',
|
||||
id: 'section-visible',
|
||||
siteSpaces: [
|
||||
{
|
||||
id: 'site-space-1',
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'],
|
||||
siteRedirect: {
|
||||
source: '/old-section',
|
||||
target: 'https://docs.example.com/hidden-section',
|
||||
destination: {
|
||||
kind: 'site-section',
|
||||
siteSectionId: 'section-hidden',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'old-section')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden page in the current space on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted.html',
|
||||
target: 'https://docs.example.com/release-notes/restricted',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-1',
|
||||
pageId: 'hidden-page',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await resolveMissingPagePath(context, 'release-notes/restricted.html')
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('checks target page visibility in another accessible space on an adaptive site', async () => {
|
||||
const otherSpace = {
|
||||
id: 'site-space-2',
|
||||
space: { id: 'space-2', revision: 'revision-2' },
|
||||
};
|
||||
const structure = {
|
||||
type: 'siteSpaces',
|
||||
structure: [
|
||||
{ id: 'site-space-1', space: { id: 'space-1', revision: 'revision-1' } },
|
||||
otherSpace,
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'];
|
||||
|
||||
const hiddenContext = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure,
|
||||
revisionsBySpace: { 'space-2': [] },
|
||||
siteRedirect: {
|
||||
source: '/old',
|
||||
target: 'https://docs.example.com/other/secret',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-2',
|
||||
pageId: 'page-secret',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await resolveMissingPagePath(hiddenContext, 'old')).toBeUndefined();
|
||||
|
||||
const visibleContext = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure,
|
||||
revisionsBySpace: { 'space-2': [{ ...page, id: 'page-secret', path: 'secret' }] },
|
||||
siteRedirect: {
|
||||
source: '/old',
|
||||
target: 'https://docs.example.com/other/secret',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-2',
|
||||
pageId: 'page-secret',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await resolveMissingPagePath(visibleContext, 'old')).toEqual({
|
||||
type: 'redirect',
|
||||
destination: '/other/secret',
|
||||
permanent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting the reassigned default variant path of the current space', async () => {
|
||||
const context = {
|
||||
...createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/guide/missing',
|
||||
target: 'https://docs.example.com/guide/v3/missing',
|
||||
destination: {
|
||||
kind: 'site-space',
|
||||
siteSpaceId: 'site-space-v3',
|
||||
},
|
||||
},
|
||||
structure: {
|
||||
type: 'sections',
|
||||
structure: [
|
||||
{
|
||||
object: 'site-section',
|
||||
id: 'section-guide',
|
||||
siteSpaces: [
|
||||
{
|
||||
id: 'site-space-v3',
|
||||
path: 'v3',
|
||||
default: true,
|
||||
space: { id: 'space-v3', revision: 'revision-1' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'],
|
||||
}),
|
||||
siteSpace: {
|
||||
id: 'site-space-v3',
|
||||
path: 'v3',
|
||||
default: true,
|
||||
space: { id: 'space-v3', revision: 'revision-1' },
|
||||
},
|
||||
linker: createLinker({
|
||||
host: 'docs.example.com',
|
||||
siteBasePath: '/',
|
||||
spaceBasePath: '/guide/',
|
||||
}),
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'missing')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps a redirect whose current path contains a literal question mark', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/foo/bar%3Fbaz',
|
||||
target: 'https://docs.example.com/foo/bar',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'foo/bar?baz')).toEqual({
|
||||
type: 'redirect',
|
||||
destination: '/foo/bar',
|
||||
permanent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves a space redirect to a page', async () => {
|
||||
const context = createRedirectContext({ spaceRedirectPageId: page.id });
|
||||
|
||||
@@ -209,45 +452,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,19 +1,22 @@
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
import { after } from 'next/server';
|
||||
|
||||
import {
|
||||
type RevisionPageDocument,
|
||||
type SiteRedirect,
|
||||
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';
|
||||
import {
|
||||
findSiteSpaceBy,
|
||||
findSiteSpaceByUrl,
|
||||
getSiteStructureSections,
|
||||
resolveSiteSpacePagePath,
|
||||
} from '@/lib/sites';
|
||||
|
||||
const MAX_PAGE_URL_REDIRECTS = 5;
|
||||
|
||||
@@ -43,25 +46,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.
|
||||
@@ -135,6 +119,14 @@ export async function resolveMissingPagePath(
|
||||
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
|
||||
);
|
||||
|
||||
const currentPath = linker.toPathInSpace(redirectPathname);
|
||||
let currentPathWithDefaultVariant: string | null = null;
|
||||
if (context.siteSpace.default && context.siteSpace.path) {
|
||||
currentPathWithDefaultVariant = linker.toPathInSpace(
|
||||
`/${context.siteSpace.path}${redirectPathname}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const source of redirectSources) {
|
||||
// We try to resolve the site redirect
|
||||
const resolvedSiteRedirect =
|
||||
@@ -148,6 +140,18 @@ export async function resolveMissingPagePath(
|
||||
})
|
||||
));
|
||||
if (resolvedSiteRedirect) {
|
||||
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
|
||||
// Skip self-redirects (including default-variant canonical aliases) and hidden adaptive targets.
|
||||
const targetsCurrentPath =
|
||||
isSameRedirectPath(currentPath, destination) ||
|
||||
(currentPathWithDefaultVariant !== null &&
|
||||
isSameRedirectPath(currentPathWithDefaultVariant, destination));
|
||||
if (
|
||||
targetsCurrentPath ||
|
||||
!(await isRedirectDestinationAccessible(context, resolvedSiteRedirect.redirect))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
const isPublicLiveContext =
|
||||
!shareKey &&
|
||||
!context.changeRequest &&
|
||||
@@ -156,7 +160,7 @@ export async function resolveMissingPagePath(
|
||||
!context.isLoggedInVisitor;
|
||||
return {
|
||||
type: 'redirect',
|
||||
destination: linker.toLinkForContent(resolvedSiteRedirect.target),
|
||||
destination,
|
||||
permanent: Boolean(
|
||||
resolvedSiteRedirect.redirect?.permanent &&
|
||||
!resolvedSiteRedirect.redirect.draft &&
|
||||
@@ -224,6 +228,17 @@ export async function resolveSitePageFromURL(
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
|
||||
if (!destination.startsWith('/') || destination.startsWith('//')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
|
||||
return (
|
||||
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a pathname into a candidate source for site redirect matching.
|
||||
* The pathname is already percent-encoded, so each segment is decoded before being encoded
|
||||
@@ -248,6 +263,60 @@ function safeDecodeURIComponent(segment: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
async function isRedirectDestinationAccessible(
|
||||
context: GitBookSiteContext,
|
||||
siteRedirect: SiteRedirect | null
|
||||
): Promise<boolean> {
|
||||
if (!context.contextId || !siteRedirect?.destination) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { destination } = siteRedirect;
|
||||
switch (destination.kind) {
|
||||
case 'external':
|
||||
return true;
|
||||
case 'site-section':
|
||||
return getSiteStructureSections(context.structure, { ignoreGroups: true }).some(
|
||||
(section) => section.id === destination.siteSectionId
|
||||
);
|
||||
case 'site-space':
|
||||
return Boolean(
|
||||
findSiteSpaceBy(context.structure, (entry) => entry.id === destination.siteSpaceId)
|
||||
);
|
||||
case 'site-page': {
|
||||
const target = findSiteSpaceBy(
|
||||
context.structure,
|
||||
(entry) => entry.id === destination.siteSpaceId
|
||||
);
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
if (destination.siteSpaceId === context.siteSpace.id) {
|
||||
return Boolean(resolvePageId(context.revision.pages, destination.pageId));
|
||||
}
|
||||
const targetRevision = await getDataOrNull(
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId: target.siteSpace.space.id,
|
||||
revisionId: target.siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
if (!targetRevision) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(resolvePageId(targetRevision.pages, destination.pageId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRedirectPathname(pathname: string): string {
|
||||
const normalized = pathname
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
|
||||
.join('/');
|
||||
return `/${normalized}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the page path from the params.
|
||||
*/
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,10 @@ export const activeClasses = {
|
||||
export const Button = React.forwardRef<
|
||||
HTMLButtonElement | HTMLAnchorElement,
|
||||
ButtonProps &
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement> & { target?: React.HTMLAttributeAnchorTarget }
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
target?: React.HTMLAttributeAnchorTarget;
|
||||
rel?: string;
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
@@ -164,6 +167,11 @@ export const Button = React.forwardRef<
|
||||
}
|
||||
}
|
||||
|
||||
let trailingElement = null;
|
||||
if (trailing) {
|
||||
trailingElement = <span className="button-trailing-icon ms-auto">{trailing}</span>;
|
||||
}
|
||||
|
||||
const content = (
|
||||
<>
|
||||
{iconElement}
|
||||
@@ -177,6 +185,7 @@ export const Button = React.forwardRef<
|
||||
{children ?? label}
|
||||
</span>
|
||||
)}
|
||||
{trailingElement}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -207,7 +216,6 @@ export const Button = React.forwardRef<
|
||||
{...rest}
|
||||
>
|
||||
{content}
|
||||
{trailing ? <span className="button-trailing-icon ms-auto">{trailing}</span> : null}
|
||||
</button>
|
||||
);
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ export const ar: TranslationLanguage = {
|
||||
on_this_page: 'في هذه الصفحة',
|
||||
next_page: 'التالي',
|
||||
previous_page: 'السابق',
|
||||
updates_pagination_navigation: 'التنقل بين الصفحات',
|
||||
updates_pagination_range: '${1} - ${2} من أصل ${3} تحديثات',
|
||||
toc_back_to_space: 'العودة إلى ${1}',
|
||||
page_last_modified: 'آخر تحديث ${1}',
|
||||
was_this_helpful: 'هل كان هذا مفيدا؟',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const bg: TranslationLanguage = {
|
||||
on_this_page: 'На тази страница',
|
||||
next_page: 'Следваща',
|
||||
previous_page: 'Предишна',
|
||||
updates_pagination_navigation: 'Навигация между страниците',
|
||||
updates_pagination_range: '${1} - ${2} от ${3} актуализации',
|
||||
toc_back_to_space: 'Обратно към ${1}',
|
||||
page_last_modified: 'Последна актуализация ${1}',
|
||||
was_this_helpful: 'Беше ли полезно?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const cs: TranslationLanguage = {
|
||||
on_this_page: 'Na této stránce',
|
||||
next_page: 'Další',
|
||||
previous_page: 'Předchozí',
|
||||
updates_pagination_navigation: 'Navigace mezi stránkami',
|
||||
updates_pagination_range: '${1} - ${2} z ${3} aktualizací',
|
||||
toc_back_to_space: 'Zpět na ${1}',
|
||||
page_last_modified: 'Poslední aktualizace ${1}',
|
||||
was_this_helpful: 'Bylo to užitečné?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const da: TranslationLanguage = {
|
||||
on_this_page: 'På denne side',
|
||||
next_page: 'Næste',
|
||||
previous_page: 'Forrige',
|
||||
updates_pagination_navigation: 'Sidenavigation',
|
||||
updates_pagination_range: '${1} - ${2} af ${3} opdateringer',
|
||||
toc_back_to_space: 'Tilbage til ${1}',
|
||||
page_last_modified: 'Sidst opdateret ${1}',
|
||||
was_this_helpful: 'Var dette nyttigt?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const de: TranslationLanguage = {
|
||||
on_this_page: 'Auf dieser Seite',
|
||||
next_page: 'Nächste',
|
||||
previous_page: 'Vorherige',
|
||||
updates_pagination_navigation: 'Seitennavigation',
|
||||
updates_pagination_range: '${1} - ${2} von ${3} Updates',
|
||||
toc_back_to_space: 'Zurück zu ${1}',
|
||||
page_last_modified: 'Zuletzt aktualisiert ${1}',
|
||||
was_this_helpful: 'War das hilfreich?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const el: TranslationLanguage = {
|
||||
on_this_page: 'Σε αυτήν τη σελίδα',
|
||||
next_page: 'Επόμενη',
|
||||
previous_page: 'Προηγούμενη',
|
||||
updates_pagination_navigation: 'Πλοήγηση σελίδων',
|
||||
updates_pagination_range: '${1} - ${2} από ${3} ενημερώσεις',
|
||||
toc_back_to_space: 'Επιστροφή σε ${1}',
|
||||
page_last_modified: 'Τελευταία ενημέρωση ${1}',
|
||||
was_this_helpful: 'Ήταν χρήσιμο αυτό;',
|
||||
|
||||
@@ -44,6 +44,8 @@ export const en = {
|
||||
on_this_page: 'On this page',
|
||||
next_page: 'Next',
|
||||
previous_page: 'Previous',
|
||||
updates_pagination_navigation: 'Pagination Navigation',
|
||||
updates_pagination_range: '${1} - ${2} of ${3} updates',
|
||||
toc_back_to_space: 'Back to ${1}',
|
||||
page_last_modified: 'Last updated ${1}',
|
||||
was_this_helpful: 'Was this helpful?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const es: TranslationLanguage = {
|
||||
on_this_page: 'En esta página',
|
||||
next_page: 'Siguiente',
|
||||
previous_page: 'Anterior',
|
||||
updates_pagination_navigation: 'Navegación entre páginas',
|
||||
updates_pagination_range: '${1} - ${2} de ${3} actualizaciones',
|
||||
toc_back_to_space: 'Volver a ${1}',
|
||||
page_last_modified: 'Última actualización ${1}',
|
||||
was_this_helpful: '¿Te fue útil?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const et: TranslationLanguage = {
|
||||
on_this_page: 'Sellel lehel',
|
||||
next_page: 'Järgmine',
|
||||
previous_page: 'Eelmine',
|
||||
updates_pagination_navigation: 'Lehekülgede vahel liikumine',
|
||||
updates_pagination_range: '${1} - ${2} / ${3} uuendust',
|
||||
toc_back_to_space: 'Tagasi: ${1}',
|
||||
page_last_modified: 'Viimati uuendatud ${1}',
|
||||
was_this_helpful: 'Kas sellest oli abi?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const fi: TranslationLanguage = {
|
||||
on_this_page: 'Tällä sivulla',
|
||||
next_page: 'Seuraava',
|
||||
previous_page: 'Edellinen',
|
||||
updates_pagination_navigation: 'Sivujen selaus',
|
||||
updates_pagination_range: '${1} - ${2} / ${3} päivitystä',
|
||||
toc_back_to_space: 'Takaisin: ${1}',
|
||||
page_last_modified: 'Päivitetty viimeksi ${1}',
|
||||
was_this_helpful: 'Oliko tästä apua?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const fr: TranslationLanguage = {
|
||||
on_this_page: 'Sur cette page',
|
||||
next_page: 'Suivant',
|
||||
previous_page: 'Précédent',
|
||||
updates_pagination_navigation: 'Navigation entre les pages',
|
||||
updates_pagination_range: '${1} - ${2} sur ${3} mises à jour',
|
||||
toc_back_to_space: 'Retour à ${1}',
|
||||
page_last_modified: 'Mis à jour ${1}',
|
||||
was_this_helpful: 'Ce contenu vous a-t-il été utile ?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const he: TranslationLanguage = {
|
||||
on_this_page: 'בדף הזה',
|
||||
next_page: 'הבא',
|
||||
previous_page: 'הקודם',
|
||||
updates_pagination_navigation: 'ניווט בין עמודים',
|
||||
updates_pagination_range: '${1} - ${2} מתוך ${3} עדכונים',
|
||||
toc_back_to_space: 'חזרה אל ${1}',
|
||||
page_last_modified: 'עודכן לאחרונה ${1}',
|
||||
was_this_helpful: 'האם זה היה מועיל?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const hi: TranslationLanguage = {
|
||||
on_this_page: 'इस पृष्ठ पर',
|
||||
next_page: 'अगला',
|
||||
previous_page: 'पिछला',
|
||||
updates_pagination_navigation: 'पेज नेविगेशन',
|
||||
updates_pagination_range: '${3} अपडेट में से ${1} - ${2}',
|
||||
toc_back_to_space: '${1} पर वापस जाएँ',
|
||||
page_last_modified: 'अंतिम अपडेट ${1}',
|
||||
was_this_helpful: 'क्या यह उपयोगी था?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const hr: TranslationLanguage = {
|
||||
on_this_page: 'Na ovoj stranici',
|
||||
next_page: 'Sljedeća',
|
||||
previous_page: 'Prethodna',
|
||||
updates_pagination_navigation: 'Navigacija stranicama',
|
||||
updates_pagination_range: '${1} - ${2} od ${3} ažuriranja',
|
||||
toc_back_to_space: 'Natrag na ${1}',
|
||||
page_last_modified: 'Zadnje ažurirano ${1}',
|
||||
was_this_helpful: 'Je li ovo bilo korisno?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const hu: TranslationLanguage = {
|
||||
on_this_page: 'Ezen az oldalon',
|
||||
next_page: 'Következő',
|
||||
previous_page: 'Előző',
|
||||
updates_pagination_navigation: 'Lapozás',
|
||||
updates_pagination_range: '${1} - ${2} / ${3} frissítés',
|
||||
toc_back_to_space: 'Vissza ide: ${1}',
|
||||
page_last_modified: 'Utoljára frissítve: ${1}',
|
||||
was_this_helpful: 'Hasznos volt ez?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const id: TranslationLanguage = {
|
||||
on_this_page: 'Di halaman ini',
|
||||
next_page: 'Berikutnya',
|
||||
previous_page: 'Sebelumnya',
|
||||
updates_pagination_navigation: 'Navigasi halaman',
|
||||
updates_pagination_range: '${1} - ${2} dari ${3} pembaruan',
|
||||
toc_back_to_space: 'Kembali ke ${1}',
|
||||
page_last_modified: 'Terakhir diperbarui ${1}',
|
||||
was_this_helpful: 'Apakah ini membantu?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const it: TranslationLanguage = {
|
||||
on_this_page: 'In questa pagina',
|
||||
next_page: 'Successivo',
|
||||
previous_page: 'Precedente',
|
||||
updates_pagination_navigation: 'Navigazione tra le pagine',
|
||||
updates_pagination_range: '${1} - ${2} di ${3} aggiornamenti',
|
||||
toc_back_to_space: 'Torna a ${1}',
|
||||
page_last_modified: 'Ultimo aggiornamento ${1}',
|
||||
was_this_helpful: 'È stato utile?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const ja: TranslationLanguage = {
|
||||
on_this_page: 'このページ内',
|
||||
next_page: '次へ',
|
||||
previous_page: '前へ',
|
||||
updates_pagination_navigation: 'ページナビゲーション',
|
||||
updates_pagination_range: '全${3}件の更新のうち${1}〜${2}件',
|
||||
toc_back_to_space: '${1}に戻る',
|
||||
page_last_modified: '最終更新 ${1}',
|
||||
was_this_helpful: '役に立ちましたか?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const ko: TranslationLanguage = {
|
||||
on_this_page: '이 페이지에서',
|
||||
next_page: '다음',
|
||||
previous_page: '이전',
|
||||
updates_pagination_navigation: '페이지 탐색',
|
||||
updates_pagination_range: '업데이트 ${3}개 중 ${1} - ${2}개',
|
||||
toc_back_to_space: '${1}(으)로 돌아가기',
|
||||
page_last_modified: '마지막 업데이트 ${1}',
|
||||
was_this_helpful: '도움이 되었나요?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const lt: TranslationLanguage = {
|
||||
on_this_page: 'Šiame puslapyje',
|
||||
next_page: 'Kitas',
|
||||
previous_page: 'Ankstesnis',
|
||||
updates_pagination_navigation: 'Puslapių navigacija',
|
||||
updates_pagination_range: '${1} - ${2} iš ${3} naujinimų',
|
||||
toc_back_to_space: 'Atgal į ${1}',
|
||||
page_last_modified: 'Paskutinį kartą atnaujinta ${1}',
|
||||
was_this_helpful: 'Ar tai buvo naudinga?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const lv: TranslationLanguage = {
|
||||
on_this_page: 'Šajā lapā',
|
||||
next_page: 'Nākamā',
|
||||
previous_page: 'Iepriekšējā',
|
||||
updates_pagination_navigation: 'Lapu navigācija',
|
||||
updates_pagination_range: '${1} - ${2} no ${3} atjauninājumiem',
|
||||
toc_back_to_space: 'Atpakaļ uz ${1}',
|
||||
page_last_modified: 'Pēdoreiz atjaunināts ${1}',
|
||||
was_this_helpful: 'Vai tas bija noderīgi?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const ms: TranslationLanguage = {
|
||||
on_this_page: 'Pada halaman ini',
|
||||
next_page: 'Seterusnya',
|
||||
previous_page: 'Sebelumnya',
|
||||
updates_pagination_navigation: 'Navigasi halaman',
|
||||
updates_pagination_range: '${1} - ${2} daripada ${3} kemas kini',
|
||||
toc_back_to_space: 'Kembali ke ${1}',
|
||||
page_last_modified: 'Terakhir dikemas kini ${1}',
|
||||
was_this_helpful: 'Adakah ini membantu?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const nl: TranslationLanguage = {
|
||||
on_this_page: 'Op deze pagina',
|
||||
next_page: 'Volgende',
|
||||
previous_page: 'Vorige',
|
||||
updates_pagination_navigation: 'Paginanavigatie',
|
||||
updates_pagination_range: '${1} - ${2} van ${3} updates',
|
||||
toc_back_to_space: 'Terug naar ${1}',
|
||||
page_last_modified: 'Laatst bijgewerkt ${1}',
|
||||
was_this_helpful: 'Was dit nuttig?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const no: TranslationLanguage = {
|
||||
on_this_page: 'På denne siden',
|
||||
next_page: 'Neste',
|
||||
previous_page: 'Forrige',
|
||||
updates_pagination_navigation: 'Sidenavigasjon',
|
||||
updates_pagination_range: '${1} - ${2} av ${3} oppdateringer',
|
||||
toc_back_to_space: 'Tilbake til ${1}',
|
||||
page_last_modified: 'Sist oppdatert ${1}',
|
||||
was_this_helpful: 'Var dette nyttig?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const pl: TranslationLanguage = {
|
||||
on_this_page: 'Na tej stronie',
|
||||
next_page: 'Dalej',
|
||||
previous_page: 'Wstecz',
|
||||
updates_pagination_navigation: 'Nawigacja między stronami',
|
||||
updates_pagination_range: '${1} - ${2} z ${3} aktualizacji',
|
||||
toc_back_to_space: 'Powrót do ${1}',
|
||||
page_last_modified: 'Ostatnia aktualizacja ${1}',
|
||||
was_this_helpful: 'Czy to było pomocne?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const pt_br: TranslationLanguage = {
|
||||
on_this_page: 'Nesta página',
|
||||
next_page: 'Próximo',
|
||||
previous_page: 'Anterior',
|
||||
updates_pagination_navigation: 'Navegação entre páginas',
|
||||
updates_pagination_range: '${1} - ${2} de ${3} atualizações',
|
||||
toc_back_to_space: 'Voltar para ${1}',
|
||||
page_last_modified: 'Atualizado ${1}',
|
||||
was_this_helpful: 'Isto foi útil?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const pt: TranslationLanguage = {
|
||||
on_this_page: 'Nesta página',
|
||||
next_page: 'Seguinte',
|
||||
previous_page: 'Anterior',
|
||||
updates_pagination_navigation: 'Navegação entre páginas',
|
||||
updates_pagination_range: '${1} - ${2} de ${3} atualizações',
|
||||
toc_back_to_space: 'Voltar para ${1}',
|
||||
page_last_modified: 'Última atualização ${1}',
|
||||
was_this_helpful: 'Isto foi útil?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const ro: TranslationLanguage = {
|
||||
on_this_page: 'Pe această pagină',
|
||||
next_page: 'Următoarea',
|
||||
previous_page: 'Anterioara',
|
||||
updates_pagination_navigation: 'Navigare între pagini',
|
||||
updates_pagination_range: '${1} - ${2} din ${3} actualizări',
|
||||
toc_back_to_space: 'Înapoi la ${1}',
|
||||
page_last_modified: 'Ultima actualizare ${1}',
|
||||
was_this_helpful: 'A fost util?',
|
||||
|
||||
@@ -47,6 +47,8 @@ export const ru: TranslationLanguage = {
|
||||
on_this_page: 'На этой странице',
|
||||
next_page: 'Следующая',
|
||||
previous_page: 'Предыдущая',
|
||||
updates_pagination_navigation: 'Навигация по страницам',
|
||||
updates_pagination_range: '${1} - ${2} из ${3} обновлений',
|
||||
toc_back_to_space: 'Назад к ${1}',
|
||||
page_last_modified: 'Последнее обновление ${1}',
|
||||
was_this_helpful: 'Это было полезно?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const sk: TranslationLanguage = {
|
||||
on_this_page: 'Na tejto stránke',
|
||||
next_page: 'Ďalej',
|
||||
previous_page: 'Predchádzajúca',
|
||||
updates_pagination_navigation: 'Navigácia medzi stránkami',
|
||||
updates_pagination_range: '${1} - ${2} z ${3} aktualizácií',
|
||||
toc_back_to_space: 'Späť na ${1}',
|
||||
page_last_modified: 'Naposledy aktualizované ${1}',
|
||||
was_this_helpful: 'Bolo to užitočné?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const sl: TranslationLanguage = {
|
||||
on_this_page: 'Na tej strani',
|
||||
next_page: 'Naslednja',
|
||||
previous_page: 'Prejšnja',
|
||||
updates_pagination_navigation: 'Krmarjenje med stranmi',
|
||||
updates_pagination_range: '${1} - ${2} od ${3} posodobitev',
|
||||
toc_back_to_space: 'Nazaj na ${1}',
|
||||
page_last_modified: 'Nazadnje posodobljeno ${1}',
|
||||
was_this_helpful: 'Je bilo to koristno?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const sv: TranslationLanguage = {
|
||||
on_this_page: 'På den här sidan',
|
||||
next_page: 'Nästa',
|
||||
previous_page: 'Föregående',
|
||||
updates_pagination_navigation: 'Sidnavigering',
|
||||
updates_pagination_range: '${1} - ${2} av ${3} uppdateringar',
|
||||
toc_back_to_space: 'Tillbaka till ${1}',
|
||||
page_last_modified: 'Senast uppdaterad ${1}',
|
||||
was_this_helpful: 'Var detta till hjälp?',
|
||||
|
||||
@@ -45,6 +45,8 @@ export const th: TranslationLanguage = {
|
||||
on_this_page: 'ในหน้านี้',
|
||||
next_page: 'ถัดไป',
|
||||
previous_page: 'ก่อนหน้า',
|
||||
updates_pagination_navigation: 'การนำทางระหว่างหน้า',
|
||||
updates_pagination_range: '${1} - ${2} จากการอัปเดต ${3} รายการ',
|
||||
toc_back_to_space: 'กลับไปที่ ${1}',
|
||||
page_last_modified: 'อัปเดตล่าสุด ${1}',
|
||||
was_this_helpful: 'สิ่งนี้มีประโยชน์หรือไม่?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const tr: TranslationLanguage = {
|
||||
on_this_page: 'Bu sayfada',
|
||||
next_page: 'Sonraki',
|
||||
previous_page: 'Önceki',
|
||||
updates_pagination_navigation: 'Sayfa gezinme',
|
||||
updates_pagination_range: '${3} güncellemeden ${1} - ${2}',
|
||||
toc_back_to_space: 'Şuraya dön: ${1}',
|
||||
page_last_modified: 'Son güncelleme ${1}',
|
||||
was_this_helpful: 'Bu yararlı oldu mu?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const uk: TranslationLanguage = {
|
||||
on_this_page: 'На цій сторінці',
|
||||
next_page: 'Наступна',
|
||||
previous_page: 'Попередня',
|
||||
updates_pagination_navigation: 'Навігація сторінками',
|
||||
updates_pagination_range: '${1} - ${2} з ${3} оновлень',
|
||||
toc_back_to_space: 'Назад до ${1}',
|
||||
page_last_modified: 'Останнє оновлення ${1}',
|
||||
was_this_helpful: 'Це було корисно?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const vi: TranslationLanguage = {
|
||||
on_this_page: 'Trên trang này',
|
||||
next_page: 'Tiếp theo',
|
||||
previous_page: 'Trước',
|
||||
updates_pagination_navigation: 'Điều hướng trang',
|
||||
updates_pagination_range: '${1} - ${2} trong số ${3} bản cập nhật',
|
||||
toc_back_to_space: 'Quay lại ${1}',
|
||||
page_last_modified: 'Cập nhật lần cuối ${1}',
|
||||
was_this_helpful: 'Nội dung này có hữu ích không?',
|
||||
|
||||
@@ -45,6 +45,8 @@ export const yue: TranslationLanguage = {
|
||||
on_this_page: '本頁內容',
|
||||
next_page: '下一頁',
|
||||
previous_page: '上一頁',
|
||||
updates_pagination_navigation: '分頁導覽',
|
||||
updates_pagination_range: '第 ${1} 至 ${2} 項更新,共 ${3} 項',
|
||||
toc_back_to_space: '返去${1}',
|
||||
page_last_modified: '最後更新 ${1}',
|
||||
was_this_helpful: '呢個有冇幫助?',
|
||||
|
||||
@@ -45,6 +45,8 @@ export const zh_tw: TranslationLanguage = {
|
||||
on_this_page: '本頁內容',
|
||||
next_page: '下一頁',
|
||||
previous_page: '上一頁',
|
||||
updates_pagination_navigation: '分頁導覽',
|
||||
updates_pagination_range: '第 ${1} 至 ${2} 項更新,共 ${3} 項',
|
||||
toc_back_to_space: '返回${1}',
|
||||
page_last_modified: '最後更新於 ${1}',
|
||||
was_this_helpful: '這有幫助嗎?',
|
||||
|
||||
@@ -46,6 +46,8 @@ export const zh: TranslationLanguage = {
|
||||
on_this_page: '在本页',
|
||||
next_page: '下一页',
|
||||
previous_page: '上一页',
|
||||
updates_pagination_navigation: '分页导航',
|
||||
updates_pagination_range: '第 ${1} 至 ${2} 条更新,共 ${3} 条',
|
||||
toc_back_to_space: '返回${1}',
|
||||
page_last_modified: '最后更新于 ${1}',
|
||||
was_this_helpful: '这有帮助吗?',
|
||||
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
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,
|
||||
@@ -45,6 +44,7 @@ import {
|
||||
getLinkerForSiteSpace,
|
||||
getLocalizedTitle,
|
||||
getSiteStructureSections,
|
||||
listAllSiteSpaces,
|
||||
} from '@/lib/sites';
|
||||
|
||||
/**
|
||||
@@ -58,8 +58,6 @@ export type SiteURLData = Pick<
|
||||
| 'site'
|
||||
| 'siteSpace'
|
||||
| 'space'
|
||||
| 'revision'
|
||||
| 'changeRequest'
|
||||
| 'shareKey'
|
||||
| 'siteSection'
|
||||
| 'siteBasePath'
|
||||
@@ -72,6 +70,14 @@ export type SiteURLData = Pick<
|
||||
*/
|
||||
imagesContextId: string;
|
||||
|
||||
/**
|
||||
* Space revision, change request or site revision the URL previews: at most one is set. The
|
||||
* middleware reads them from the resolved content, which types them as exclusive.
|
||||
*/
|
||||
revision?: string;
|
||||
changeRequest?: string;
|
||||
siteRevision?: string;
|
||||
|
||||
/**
|
||||
* Whether this request is a fallback rendering.
|
||||
* We use this when switching variant as we don't know if the page exists in the other variant.
|
||||
@@ -145,7 +151,7 @@ export type GitBookBaseContext = {
|
||||
/**
|
||||
* Target for the browser to query the site search API directly with a search pass.
|
||||
*/
|
||||
directSearch?: Omit<DirectSearchProps, 'spaces' | 'passURL'>;
|
||||
directSearch?: Omit<DirectSearchProps, 'spaces' | 'passURL' | 'proxyURL'>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -218,6 +224,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
|
||||
/** Whether search indexation is blocked for this deployment. */
|
||||
noIndexSearch: boolean;
|
||||
|
||||
/** Site revision the URL previews. Content is read as it pins it. */
|
||||
siteRevision?: string;
|
||||
|
||||
/** Whether the request included a visitor token. */
|
||||
isLoggedInVisitor: boolean;
|
||||
|
||||
@@ -249,12 +258,16 @@ 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,
|
||||
siteRevision: siteURLData.siteRevision
|
||||
? {
|
||||
organizationId: siteURLData.organization,
|
||||
siteId: siteURLData.site,
|
||||
siteRevisionId: siteURLData.siteRevision,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const linkerInput: SiteLinkerInput = {
|
||||
urlMode,
|
||||
@@ -265,14 +278,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
|
||||
@@ -311,6 +322,7 @@ export async function fetchSiteContextByURLLookup(
|
||||
contextId: data.contextId,
|
||||
isFallback: data.isFallback ?? false,
|
||||
noIndexSearch: data.noIndexSearch ?? false,
|
||||
siteRevision: data.siteRevision,
|
||||
isLoggedInVisitor: data.isLoggedInVisitor ?? false,
|
||||
preview: data.preview ?? false,
|
||||
displayAgentInstructions: data.displayAgentInstructions,
|
||||
@@ -335,6 +347,7 @@ export async function fetchSiteContextByIds(
|
||||
contextId?: string;
|
||||
isFallback: boolean;
|
||||
noIndexSearch: boolean;
|
||||
siteRevision?: string;
|
||||
isLoggedInVisitor: boolean;
|
||||
preview: boolean;
|
||||
displayAgentInstructions?: boolean;
|
||||
@@ -468,6 +481,12 @@ export async function fetchSiteContextByIds(
|
||||
|
||||
return {
|
||||
...spaceContext,
|
||||
// Only the site's own spaces are read at the site revision it previews.
|
||||
dataFetcher: ids.siteRevision
|
||||
? spaceContext.dataFetcher.withSiteRevisionSpaces(
|
||||
listAllSiteSpaces(siteStructure).map((entry) => entry.space.id)
|
||||
)
|
||||
: spaceContext.dataFetcher,
|
||||
locale: siteSpace.space.language ?? spaceContext.locale,
|
||||
linker: getLinkerForSiteSpace(siteLinker, siteSpace, spaceContext.revision.pages),
|
||||
organizationId: ids.organization,
|
||||
@@ -483,6 +502,7 @@ export async function fetchSiteContextByIds(
|
||||
contextId: ids.contextId,
|
||||
isFallback: ids.isFallback,
|
||||
noIndexSearch: ids.noIndexSearch,
|
||||
siteRevision: ids.siteRevision,
|
||||
isLoggedInVisitor: ids.isLoggedInVisitor,
|
||||
preview: ids.preview,
|
||||
displayAgentInstructions: ids.displayAgentInstructions,
|
||||
|
||||
@@ -11,7 +11,7 @@ import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-t
|
||||
|
||||
import { cache } from '../cache';
|
||||
import { DataFetcherError, wrapDataFetcherError } from './errors';
|
||||
import type { GitBookDataFetcher } from './types';
|
||||
import type { DataFetcherResponse, GitBookDataFetcher } from './types';
|
||||
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
|
||||
import { toSearchSiteContentBody } from '@/lib/search-results';
|
||||
import { trace } from '@/lib/tracing';
|
||||
@@ -21,6 +21,25 @@ interface DataFetcherInput {
|
||||
* API token.
|
||||
*/
|
||||
apiToken: string | null;
|
||||
|
||||
/**
|
||||
* Site revision being previewed. The site's spaces and OpenAPI specs are read at it.
|
||||
*/
|
||||
siteRevision?: DataFetcherSiteRevision;
|
||||
}
|
||||
|
||||
/**
|
||||
* A site revision, as a preview URL resolves it.
|
||||
*/
|
||||
export interface DataFetcherSiteRevision {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
siteRevisionId: string;
|
||||
/**
|
||||
* Spaces of the site, read at the site revision. Other spaces are read live. Until the site
|
||||
* structure is known, every space is read at the site revision.
|
||||
*/
|
||||
spaceIds?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,10 +65,18 @@ export function createDataFetcher(
|
||||
|
||||
withToken({ apiToken }) {
|
||||
return createDataFetcher({
|
||||
...input,
|
||||
apiToken,
|
||||
});
|
||||
},
|
||||
|
||||
withSiteRevisionSpaces(spaceIds) {
|
||||
return createDataFetcher({
|
||||
...input,
|
||||
siteRevision: input.siteRevision ? { ...input.siteRevision, spaceIds } : undefined,
|
||||
});
|
||||
},
|
||||
|
||||
//
|
||||
// API that are tied to the token
|
||||
//
|
||||
@@ -77,61 +104,120 @@ export function createDataFetcher(
|
||||
});
|
||||
},
|
||||
getRevision(params) {
|
||||
return getRevision(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
metadata: params.metadata ?? false,
|
||||
});
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
getRevisionAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
metadata: params.metadata ?? false,
|
||||
}),
|
||||
() =>
|
||||
getRevision(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
metadata: params.metadata ?? false,
|
||||
})
|
||||
);
|
||||
},
|
||||
getRevisionPageByPath(params) {
|
||||
return getRevisionPageByPath(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
path: params.path,
|
||||
metadata: params.metadata,
|
||||
cachedMetadata: params.cachedMetadata,
|
||||
});
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
getPageByPathAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
path: params.path,
|
||||
metadata: params.metadata ?? false,
|
||||
cachedMetadata: params.cachedMetadata ?? false,
|
||||
}),
|
||||
() =>
|
||||
getRevisionPageByPath(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
path: params.path,
|
||||
metadata: params.metadata,
|
||||
cachedMetadata: params.cachedMetadata,
|
||||
})
|
||||
);
|
||||
},
|
||||
getRevisionPageMarkdown(params) {
|
||||
return getRevisionPageMarkdown(
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
{
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
},
|
||||
// We pass the name of the function to distinguish between cache entries
|
||||
// By default Next only uses the arguments, the filename and the position of the function inside the file
|
||||
// By adding a dummy argument with the function name, we can change the order without breaking anything
|
||||
'getRevisionPageMarkdown'
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
getPageMarkdownAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
pageId: params.pageId,
|
||||
}),
|
||||
() =>
|
||||
getRevisionPageMarkdown(
|
||||
input,
|
||||
{
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
},
|
||||
// We pass the name of the function to distinguish between cache entries
|
||||
// By default Next only uses the arguments, the filename and the position of the function inside the file
|
||||
// By adding a dummy argument with the function name, we can change the order without breaking anything
|
||||
'getRevisionPageMarkdown'
|
||||
)
|
||||
);
|
||||
},
|
||||
getRevisionPageDocument(params) {
|
||||
return getRevisionPageDocument(
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
{
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
},
|
||||
// We pass the name of the function to distinguish between cache entries
|
||||
// By default Next only uses the arguments, the filename and the position of the function inside the file
|
||||
// By adding a dummy argument with the function name, we can change the order without breaking anything
|
||||
'getRevisionPageDocument'
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
getPageDocumentAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
pageId: params.pageId,
|
||||
}),
|
||||
() =>
|
||||
getRevisionPageDocument(
|
||||
input,
|
||||
{
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
},
|
||||
// We pass the name of the function to distinguish between cache entries
|
||||
// By default Next only uses the arguments, the filename and the position of the function inside the file
|
||||
// By adding a dummy argument with the function name, we can change the order without breaking anything
|
||||
'getRevisionPageDocument'
|
||||
)
|
||||
);
|
||||
},
|
||||
getRevisionReusableContentDocument(params) {
|
||||
return getRevisionReusableContentDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
reusableContentId: params.reusableContentId,
|
||||
});
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
getReusableContentDocumentAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
reusableContentId: params.reusableContentId,
|
||||
}),
|
||||
() =>
|
||||
getRevisionReusableContentDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
reusableContentId: params.reusableContentId,
|
||||
})
|
||||
);
|
||||
},
|
||||
getLatestOpenAPISpecVersionContent(params) {
|
||||
return getLatestOpenAPISpecVersionContent(input, {
|
||||
organizationId: params.organizationId,
|
||||
slug: params.slug,
|
||||
});
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
null,
|
||||
(siteRevisionInput) =>
|
||||
getOpenAPISpecContentAtSiteRevision(siteRevisionInput, { slug: params.slug }),
|
||||
() =>
|
||||
getLatestOpenAPISpecVersionContent(input, {
|
||||
organizationId: params.organizationId,
|
||||
slug: params.slug,
|
||||
})
|
||||
);
|
||||
},
|
||||
getSpace(params) {
|
||||
return getSpace(input, {
|
||||
@@ -195,15 +281,233 @@ export function createDataFetcher(
|
||||
},
|
||||
|
||||
listRevisionPageMetaLinks(params) {
|
||||
return listRevisionPageMetaLinks(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
});
|
||||
return readAtSiteRevision(
|
||||
input,
|
||||
params.spaceId,
|
||||
(siteRevisionInput) =>
|
||||
listPageMetaLinksAtSiteRevision(siteRevisionInput, {
|
||||
spaceId: params.spaceId,
|
||||
pageId: params.pageId,
|
||||
}),
|
||||
() =>
|
||||
listRevisionPageMetaLinks(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
})
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Data fetcher input to read at a site revision. It leaves out the site's space IDs, which only
|
||||
* choose what to read at the site revision, so they stay out of cache keys.
|
||||
*/
|
||||
type SiteRevisionDataFetcherInput = DataFetcherInput & {
|
||||
siteRevision: Omit<DataFetcherSiteRevision, 'spaceIds'>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Read content at the site revision of the input, or `live` when there is no site revision or
|
||||
* for a space outside the site. An OpenAPI spec (no space) is always read at the site revision.
|
||||
*/
|
||||
async function readAtSiteRevision<T>(
|
||||
input: DataFetcherInput,
|
||||
spaceId: string | null,
|
||||
atSiteRevision: (input: SiteRevisionDataFetcherInput) => Promise<DataFetcherResponse<T>>,
|
||||
live: () => Promise<DataFetcherResponse<T>>
|
||||
): Promise<DataFetcherResponse<T>> {
|
||||
const { siteRevision } = input;
|
||||
if (!siteRevision || (spaceId && siteRevision.spaceIds?.includes(spaceId) === false)) {
|
||||
return live();
|
||||
}
|
||||
|
||||
const { spaceIds: _spaceIds, ...cacheableSiteRevision } = siteRevision;
|
||||
return atSiteRevision({ ...input, siteRevision: cacheableSiteRevision });
|
||||
}
|
||||
|
||||
// Each read at a site revision sends the same query as its live counterpart.
|
||||
|
||||
const getRevisionAtSiteRevision = cache(
|
||||
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; metadata: boolean }) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`getRevisionAtSiteRevision(${params.spaceId})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.getRevisionInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
{ metadata: params.metadata },
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const getPageByPathAtSiteRevision = cache(
|
||||
async (
|
||||
input: SiteRevisionDataFetcherInput,
|
||||
params: { spaceId: string; path: string; metadata: boolean; cachedMetadata: boolean }
|
||||
) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`getPageByPathAtSiteRevision(${params.spaceId}, ${params.path})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.getPageByPathInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
encodeURIComponent(params.path),
|
||||
{ metadata: params.metadata, cachedMetadata: params.cachedMetadata },
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const getPageMarkdownAtSiteRevision = cache(
|
||||
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
|
||||
'use cache';
|
||||
return wrapDataFetcherError(async () => {
|
||||
return trace(
|
||||
`getPageMarkdownAtSiteRevision(${params.spaceId}, ${params.pageId})`,
|
||||
async () => {
|
||||
const { organizationId, siteId, siteRevisionId } = input.siteRevision;
|
||||
const res = await apiClient(input).orgs.getPageInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
params.pageId,
|
||||
{
|
||||
format: 'markdown',
|
||||
'format.markdown.refs': 'stable',
|
||||
evaluated: 'deterministic-only',
|
||||
metadata: false,
|
||||
},
|
||||
{ ...noCacheFetchOptions }
|
||||
);
|
||||
cacheTag(...getCacheTagsFromResponse(res));
|
||||
cacheLife('max');
|
||||
|
||||
if (!('markdown' in res.data)) {
|
||||
throw new DataFetcherError('Page is not a document', 404);
|
||||
}
|
||||
return res.data.markdown;
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const getPageDocumentAtSiteRevision = cache(
|
||||
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`getPageDocumentAtSiteRevision(${params.spaceId}, ${params.pageId})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.getPageDocumentInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
params.pageId,
|
||||
{ evaluated: 'deterministic-only', dereferenced: 'reusable-contents' },
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const getReusableContentDocumentAtSiteRevision = cache(
|
||||
async (
|
||||
input: SiteRevisionDataFetcherInput,
|
||||
params: { spaceId: string; reusableContentId: string }
|
||||
) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`getReusableContentDocumentAtSiteRevision(${params.spaceId}, ${params.reusableContentId})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.getReusableContentDocumentInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
params.reusableContentId,
|
||||
{ evaluated: 'deterministic-only' },
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const listPageMetaLinksAtSiteRevision = cache(
|
||||
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`listPageMetaLinksAtSiteRevision(${params.spaceId}, ${params.pageId})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.listPageMetaLinksInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.spaceId,
|
||||
params.pageId,
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const getOpenAPISpecContentAtSiteRevision = cache(
|
||||
async (input: SiteRevisionDataFetcherInput, params: { slug: string }) => {
|
||||
'use cache';
|
||||
return fetchAtSiteRevision(
|
||||
input,
|
||||
`getOpenAPISpecContentAtSiteRevision(${params.slug})`,
|
||||
(api, { organizationId, siteId, siteRevisionId }) =>
|
||||
api.orgs.getOpenApiSpecContentInSiteRevision(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteRevisionId,
|
||||
params.slug,
|
||||
{ ...noCacheFetchOptions }
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Fetch from an endpoint at a site revision. What a site revision pins never changes, so the
|
||||
* response is cached forever.
|
||||
*/
|
||||
function fetchAtSiteRevision<T>(
|
||||
input: SiteRevisionDataFetcherInput,
|
||||
name: string,
|
||||
request: (
|
||||
api: ReturnType<typeof apiClient>,
|
||||
siteRevision: SiteRevisionDataFetcherInput['siteRevision']
|
||||
) => Promise<HttpResponse<T, unknown>>
|
||||
): Promise<DataFetcherResponse<T>> {
|
||||
return wrapDataFetcherError(async () => {
|
||||
return trace(name, async () => {
|
||||
const res = await request(apiClient(input), input.siteRevision);
|
||||
cacheTag(...getCacheTagsFromResponse(res));
|
||||
cacheLife('max');
|
||||
return res.data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer the cache life from the api response headers.
|
||||
* @param response The response from the API call.
|
||||
|
||||
@@ -51,6 +51,12 @@ export interface GitBookDataFetcher {
|
||||
*/
|
||||
withToken(input: { apiToken: string }): GitBookDataFetcher;
|
||||
|
||||
/**
|
||||
* Create a data fetcher that reads only these spaces at the site revision it previews, and
|
||||
* other spaces live.
|
||||
*/
|
||||
withSiteRevisionSpaces(spaceIds: string[]): GitBookDataFetcher;
|
||||
|
||||
/**
|
||||
* Get a user by its ID.
|
||||
*/
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -35,4 +35,61 @@ describe('#enrichFilesystem', () => {
|
||||
expect(paths['/a'].get['x-gitbook-description-html']).toBe('<p>constructor</p>');
|
||||
expect(paths['/b'].get['x-gitbook-description-html']).toBe('<p>constructor</p>');
|
||||
});
|
||||
|
||||
async function enrichSchemas(schemas: Record<string, unknown>) {
|
||||
const { filesystem } = await parseOpenAPI({
|
||||
value: JSON.stringify({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 'Test', version: '1.0.0' },
|
||||
paths: {},
|
||||
components: { schemas },
|
||||
}),
|
||||
rootURL: null,
|
||||
});
|
||||
const enriched = await enrichFilesystem(filesystem);
|
||||
return enriched[0]?.specification.components.schemas;
|
||||
}
|
||||
|
||||
it('drops description fields supplied by the specification', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: {
|
||||
type: 'object',
|
||||
'x-gitbook-description-html': '<b>spec</b>',
|
||||
'x-gitbook-description-document': { nodes: [] },
|
||||
},
|
||||
});
|
||||
expect(schemas.Pet['x-gitbook-description-html']).toBeUndefined();
|
||||
expect(schemas.Pet['x-gitbook-description-document']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sanitizes descriptions of schemas named example', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
example: { type: 'string', description: '<img src=x onerror=alert(1)>' },
|
||||
});
|
||||
const html = schemas.example['x-gitbook-description-html'];
|
||||
expect(html).toContain('<img');
|
||||
expect(html).not.toContain('onerror');
|
||||
});
|
||||
|
||||
it('sanitizes descriptions in example values that could render HTML', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: {
|
||||
type: 'object',
|
||||
example: {
|
||||
description: '<img src=x onerror=alert(1)>',
|
||||
'x-gitbook-description-html': '<img src=x onerror=alert(2)>',
|
||||
},
|
||||
},
|
||||
});
|
||||
const html = schemas.Pet.example['x-gitbook-description-html'];
|
||||
expect(html).toBeDefined();
|
||||
expect(html).not.toContain('onerror');
|
||||
});
|
||||
|
||||
it('keeps example values without HTML as written', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: { type: 'object', example: { description: 'A **good** dog' } },
|
||||
});
|
||||
expect(schemas.Pet.example).toEqual({ description: 'A **good** dog' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,19 +8,21 @@ import { parseMarkdown } from '../markdown';
|
||||
export async function enrichFilesystem(filesystem: Filesystem) {
|
||||
const parseMarkdownWithCache = createMarkdownParser();
|
||||
return traverse(filesystem, async (node, path) => {
|
||||
// Examples included: a `$ref` can render an example value as a schema.
|
||||
delete node['x-gitbook-description-html'];
|
||||
delete node['x-gitbook-description-document'];
|
||||
|
||||
if (
|
||||
path !== undefined &&
|
||||
'description' in node &&
|
||||
typeof node.description === 'string' &&
|
||||
node.description
|
||||
) {
|
||||
const key = path[path.length - 1];
|
||||
// Avoid parsing descriptions in examples.
|
||||
if (key !== 'example') {
|
||||
const description = node.description.trim();
|
||||
if (description) {
|
||||
node['x-gitbook-description-html'] = await parseMarkdownWithCache(description);
|
||||
}
|
||||
const description = node.description.trim();
|
||||
// Examples stay as written, except where their raw description could render a tag.
|
||||
const isExample = path[path.length - 1] === 'example';
|
||||
if (description && (!isExample || description.includes('<'))) {
|
||||
node['x-gitbook-description-html'] = await parseMarkdownWithCache(description);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '@gitbook/openapi-parser';
|
||||
|
||||
import { enrichFilesystem } from './enrich';
|
||||
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
|
||||
import type {
|
||||
AnyOpenAPIOperationsBlock,
|
||||
OpenAPISchemasBlock,
|
||||
@@ -41,7 +42,9 @@ export async function fetchOpenAPIFilesystem(
|
||||
// If the reference is a new OpenAPI reference, we return it.
|
||||
if (ref.kind === 'openapi') {
|
||||
assert(resolved.openapi?.filesystem);
|
||||
return resolved.openapi.filesystem;
|
||||
return resolveOpenAPIDescriptionLinks(resolved.openapi.filesystem, (contentRef) =>
|
||||
resolveContentRef(contentRef, context)
|
||||
);
|
||||
}
|
||||
// For legacy blocks ("swagger"), we need to fetch the file system.
|
||||
return fetchFilesystem(resolved.href, context.space.id);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { parseOpenAPI } from '@gitbook/openapi-parser';
|
||||
|
||||
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
|
||||
|
||||
const APP_URL = 'https://app.gitbook.com/s/space-1/tables';
|
||||
|
||||
describe('resolveOpenAPIDescriptionLinks', () => {
|
||||
it('points tagged links at their resolved URL without mutating the input', async () => {
|
||||
const original =
|
||||
`<p><a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>` +
|
||||
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
|
||||
' <a href="https://example.com">Docs</a></p>';
|
||||
const { filesystem } = await parseOpenAPI({
|
||||
value: JSON.stringify({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 'Test', version: '1.0.0' },
|
||||
paths: {},
|
||||
components: {
|
||||
schemas: {
|
||||
Condition: { type: 'object', 'x-gitbook-description-html': original },
|
||||
},
|
||||
},
|
||||
}),
|
||||
rootURL: null,
|
||||
});
|
||||
|
||||
const resolved = await resolveOpenAPIDescriptionLinks(filesystem, async (ref) =>
|
||||
ref.kind === 'page' && ref.page === 'page-1' ? { href: '/docs/tables' } : null
|
||||
);
|
||||
|
||||
expect(resolved[0]?.specification.components?.schemas?.Condition).toMatchObject({
|
||||
'x-gitbook-description-html':
|
||||
'<p><a href="/docs/tables" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>' +
|
||||
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
|
||||
' <a href="https://example.com">Docs</a></p>',
|
||||
});
|
||||
// The spec content comes from the data cache, shared across sites.
|
||||
expect(filesystem[0]?.specification.components?.schemas?.Condition).toMatchObject({
|
||||
'x-gitbook-description-html': original,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { type DefaultTreeAdapterMap, parseFragment } from 'parse5';
|
||||
import * as React from 'react';
|
||||
|
||||
import type { ContentRef } from '@gitbook/api';
|
||||
import type { Filesystem, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
|
||||
|
||||
import { escapeHTML } from '@/lib/html';
|
||||
import { resolveStringContentRef } from '@/lib/references';
|
||||
|
||||
const DESCRIPTION_HTML_KEY = 'x-gitbook-description-html';
|
||||
// Slate JSON, which never holds description HTML: skipped to keep the walk short.
|
||||
const DESCRIPTION_DOCUMENT_KEY = 'x-gitbook-description-document';
|
||||
// Set by spec processing on links to GitBook content, e.g. `/spaces/{space}/pages/{page}`.
|
||||
const CONTENT_REF_ATTRIBUTE = 'data-gitbook-ref';
|
||||
|
||||
type OpenAPIFilesystem = Filesystem<OpenAPIV3xDocument>;
|
||||
type ResolveContentRef = (ref: ContentRef) => Promise<{ href: string } | null>;
|
||||
|
||||
// Per request: resolved hrefs depend on the site being rendered.
|
||||
const getResolvedFilesystems = React.cache(
|
||||
() => new WeakMap<OpenAPIFilesystem, Promise<OpenAPIFilesystem>>()
|
||||
);
|
||||
|
||||
/**
|
||||
* Point description links that spec processing tagged with a content ref at their URL in the
|
||||
* current site. Links whose ref doesn't resolve keep the href written in the spec.
|
||||
* Returns a copy when something changed: the input may be shared through the data cache.
|
||||
*/
|
||||
export function resolveOpenAPIDescriptionLinks(
|
||||
filesystem: OpenAPIFilesystem,
|
||||
resolveContentRef: ResolveContentRef
|
||||
): Promise<OpenAPIFilesystem> {
|
||||
const resolvedFilesystems = getResolvedFilesystems();
|
||||
let promise = resolvedFilesystems.get(filesystem);
|
||||
if (!promise) {
|
||||
promise = baseResolveOpenAPIDescriptionLinks(filesystem, resolveContentRef);
|
||||
resolvedFilesystems.set(filesystem, promise);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function baseResolveOpenAPIDescriptionLinks(
|
||||
filesystem: OpenAPIFilesystem,
|
||||
resolveContentRef: ResolveContentRef
|
||||
): Promise<OpenAPIFilesystem> {
|
||||
// Tagged HTML → its rewritten version, filled in once the refs resolve.
|
||||
const rewritten = new Map<string, string>();
|
||||
mapDescriptionHTML(filesystem, (html) => {
|
||||
if (html.includes(CONTENT_REF_ATTRIBUTE)) {
|
||||
rewritten.set(html, html);
|
||||
}
|
||||
return html;
|
||||
});
|
||||
|
||||
if (rewritten.size === 0) {
|
||||
return filesystem;
|
||||
}
|
||||
|
||||
const hrefs = new Map<string, Promise<string | null>>();
|
||||
const resolveHref = (source: string) => {
|
||||
let href = hrefs.get(source);
|
||||
if (!href) {
|
||||
const ref = resolveStringContentRef(source);
|
||||
href = ref
|
||||
? resolveContentRef(ref).then((resolved) => resolved?.href ?? null)
|
||||
: Promise.resolve(null);
|
||||
hrefs.set(source, href);
|
||||
}
|
||||
return href;
|
||||
};
|
||||
|
||||
await Promise.all(
|
||||
Array.from(rewritten.keys(), async (html) => {
|
||||
rewritten.set(html, await rewriteLinks(html, resolveHref));
|
||||
})
|
||||
);
|
||||
|
||||
return mapDescriptionHTML(filesystem, (html) => rewritten.get(html) ?? html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the href of each tagged link with its resolved URL.
|
||||
*/
|
||||
async function rewriteLinks(
|
||||
html: string,
|
||||
resolveHref: (source: string) => Promise<string | null>
|
||||
): Promise<string> {
|
||||
const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
|
||||
const replacements: { start: number; end: number; value: string }[] = [];
|
||||
|
||||
await Promise.all(
|
||||
collectLinks(fragment).map(async (link) => {
|
||||
const source = link.attrs.find((attr) => attr.name === CONTENT_REF_ATTRIBUTE)?.value;
|
||||
const location = link.sourceCodeLocation?.attrs?.href;
|
||||
if (!source || !location) {
|
||||
return;
|
||||
}
|
||||
|
||||
const href = await resolveHref(source);
|
||||
if (href) {
|
||||
replacements.push({
|
||||
start: location.startOffset,
|
||||
end: location.endOffset,
|
||||
value: `href="${escapeHTML(href)}"`,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Apply from the end so earlier offsets stay valid.
|
||||
replacements.sort((a, b) => b.start - a.start);
|
||||
let result = html;
|
||||
for (const { start, end, value } of replacements) {
|
||||
result = result.slice(0, start) + value + result.slice(end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectLinks(
|
||||
node: DefaultTreeAdapterMap['node'],
|
||||
links: DefaultTreeAdapterMap['element'][] = []
|
||||
): DefaultTreeAdapterMap['element'][] {
|
||||
if ('tagName' in node && node.tagName === 'a') {
|
||||
links.push(node);
|
||||
}
|
||||
if ('childNodes' in node) {
|
||||
for (const child of node.childNodes) {
|
||||
collectLinks(child, links);
|
||||
}
|
||||
}
|
||||
return links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map every description HTML in a JSON value, copying only the objects on a changed path.
|
||||
*/
|
||||
function mapDescriptionHTML<T>(value: T, transform: (html: string) => string): T {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
let result: unknown[] | null = null;
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const item = value[index];
|
||||
const next = mapDescriptionHTML(item, transform);
|
||||
if (next !== item) {
|
||||
result ??= [...value];
|
||||
result[index] = next;
|
||||
}
|
||||
}
|
||||
return (result ?? value) as T;
|
||||
}
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
let result: Record<string, unknown> | null = null;
|
||||
// `for...in` over plain JSON objects: several times faster than `Object.entries` on large specs.
|
||||
for (const key in record) {
|
||||
if (key === DESCRIPTION_DOCUMENT_KEY) {
|
||||
continue;
|
||||
}
|
||||
const child = record[key];
|
||||
const next =
|
||||
key === DESCRIPTION_HTML_KEY && typeof child === 'string'
|
||||
? transform(child)
|
||||
: mapDescriptionHTML(child, transform);
|
||||
if (next !== child) {
|
||||
result ??= { ...record };
|
||||
result[key] = next;
|
||||
}
|
||||
}
|
||||
return (result ?? record) as T;
|
||||
}
|
||||
@@ -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)),
|
||||
};
|
||||
}
|
||||
@@ -41,6 +41,7 @@ export type DirectSearchProps = {
|
||||
apiURL: string;
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
proxyURL: string;
|
||||
linker: SiteLinkerInput;
|
||||
spaces: SearchSpaceLookup;
|
||||
/** Site route that hands out a search pass. */
|
||||
|
||||
@@ -32,6 +32,7 @@ export function isSiteIndexable(context: GitBookSiteContext) {
|
||||
|
||||
if (
|
||||
context.changeRequest ||
|
||||
context.siteRevision ||
|
||||
context.revisionId !== context.space.revision ||
|
||||
hasRevisionSelector(context.linker.spaceBasePath)
|
||||
) {
|
||||
|
||||
@@ -157,8 +157,7 @@ export async function serveProxyAnalyticsEvent(req: Request) {
|
||||
/**
|
||||
* Extract the real IP address of the client from the request headers, accounting for various proxies and CDNs.
|
||||
*/
|
||||
|
||||
function getXForwardedFor(headers: Headers): string | null {
|
||||
export function getXForwardedFor(headers: Headers): string | null {
|
||||
// We start first with the cloudflare headers
|
||||
if (headers.has('cf-connecting-ip')) {
|
||||
return headers.get('cf-connecting-ip');
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** URL search param carrying the active tag filter, e.g. `?tag=changelog`. */
|
||||
export const UPDATES_FILTER_SEARCH_PARAM = 'tag';
|
||||
|
||||
export const UPDATES_MAX_PAGE = 500;
|
||||
export const UPDATES_PAGE_SEARCH_PARAM = 'page';
|
||||
|
||||
export function parseUpdatesPageParam(raw: string | null | undefined): number | null {
|
||||
const page = Number(raw);
|
||||
if (!Number.isInteger(page) || page < 2 || page > UPDATES_MAX_PAGE || String(page) !== raw) {
|
||||
return null;
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
export function setUpdatesPageParam(params: URLSearchParams, page: number) {
|
||||
if (page > 1) {
|
||||
params.set(UPDATES_PAGE_SEARCH_PARAM, String(page));
|
||||
} else {
|
||||
params.delete(UPDATES_PAGE_SEARCH_PARAM);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import {
|
||||
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
|
||||
import {
|
||||
UPDATES_TAG_FILTER_CAP,
|
||||
countDocumentUpdates,
|
||||
findUpdateAnchorPage,
|
||||
paginateUpdatesDocument,
|
||||
parseUpdatesPageParam,
|
||||
getDocumentFilterableTags,
|
||||
normalizeUpdatesFilterTags,
|
||||
} from './updates';
|
||||
@@ -92,29 +96,212 @@ describe('normalizeUpdatesFilterTags', () => {
|
||||
});
|
||||
});
|
||||
|
||||
function createUpdatesDocument(entryTags: string[][]): JSONDocument {
|
||||
return {
|
||||
object: 'document',
|
||||
data: { schemaVersion: 2 },
|
||||
describe('updates pagination', () => {
|
||||
it('keeps a 50-entry document intact and paginates 51 entries across two blocks', () => {
|
||||
const short = createUpdatesDocument(Array.from({ length: 50 }, () => []));
|
||||
expect(paginateUpdatesDocument(short, undefined, { page: 2 })).toEqual({
|
||||
document: short,
|
||||
pagination: null,
|
||||
});
|
||||
expect(paginateUpdatesDocument(short, undefined, { page: 2 }).document).toBe(short);
|
||||
|
||||
const long = createUpdatesDocument(
|
||||
Array.from({ length: 51 }, () => []),
|
||||
25
|
||||
);
|
||||
expect(countDocumentUpdates(long)).toBe(51);
|
||||
for (const [page, start, end, blockTypes] of [
|
||||
[1, 1, 20, ['updates', 'paragraph']],
|
||||
[2, 21, 40, ['updates', 'paragraph', 'updates']],
|
||||
[3, 41, 51, ['paragraph', 'updates']],
|
||||
] as const) {
|
||||
const result = paginateUpdatesDocument(long, undefined, { page });
|
||||
expect(result.pagination).toEqual({
|
||||
page,
|
||||
totalPages: 3,
|
||||
totalItems: 51,
|
||||
pageSize: 20,
|
||||
start,
|
||||
end,
|
||||
isClamped: false,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(
|
||||
Array.from({ length: end - start + 1 }, (_, i) => `update-${start + i}`)
|
||||
);
|
||||
expect(result.document.nodes.map((block) => block.type)).toEqual([...blockTypes]);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the first and seventh slices of a 260-entry changelog to 20 entries each', () => {
|
||||
const document = createUpdatesDocument(
|
||||
Array.from({ length: 260 }, () => []),
|
||||
135
|
||||
);
|
||||
for (const [page, start] of [
|
||||
[1, 1],
|
||||
[7, 121],
|
||||
] as const) {
|
||||
const result = paginateUpdatesDocument(document, undefined, { page });
|
||||
expect(result.pagination).toMatchObject({
|
||||
page,
|
||||
totalPages: 13,
|
||||
start,
|
||||
end: start + 19,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(
|
||||
Array.from({ length: 20 }, (_, i) => `update-${start + i}`)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('filters by any selected tag before calculating page bounds and clamps to the last match', () => {
|
||||
const revision = {
|
||||
tags: [createTag('odd', 'Odd'), createTag('even', 'Even')],
|
||||
} as unknown as Revision;
|
||||
const document = createUpdatesDocument(
|
||||
Array.from({ length: 61 }, (_, index) => {
|
||||
if (index % 3 === 0) {
|
||||
return ['odd'];
|
||||
}
|
||||
if (index % 3 === 1) {
|
||||
return ['even'];
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
30
|
||||
);
|
||||
|
||||
const result = paginateUpdatesDocument(document, revision, {
|
||||
page: 9,
|
||||
tags: [' odd ', 'even', 'unknown'],
|
||||
});
|
||||
expect(result.pagination).toMatchObject({
|
||||
page: 3,
|
||||
totalPages: 3,
|
||||
totalItems: 41,
|
||||
start: 41,
|
||||
end: 41,
|
||||
isClamped: true,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(['update-61']);
|
||||
expect(countDocumentUpdates(document)).toBe(61);
|
||||
});
|
||||
|
||||
it('finds a nested anchor on the filtered page or clears a filter that excludes it', () => {
|
||||
const revision = { tags: [createTag('fixes', 'Fixes')] } as unknown as Revision;
|
||||
const document = createUpdatesDocument(
|
||||
Array.from({ length: 61 }, (_, index) => {
|
||||
if (index % 2 === 0) {
|
||||
return ['fixes'];
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
26
|
||||
);
|
||||
expect(
|
||||
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
|
||||
).toEqual({ found: true, page: 2, clearTags: false });
|
||||
expect(
|
||||
findUpdateAnchorPage(document, revision, { anchor: 'update-44', tags: ['fixes'] })
|
||||
).toEqual({ found: true, page: 3, clearTags: true });
|
||||
expect(
|
||||
findUpdateAnchorPage(document, revision, { anchor: 'missing', tags: ['fixes'] })
|
||||
).toEqual({ found: false });
|
||||
|
||||
const tabUpdate = document.nodes[0];
|
||||
if (tabUpdate?.type === 'updates' && tabUpdate.nodes[20]?.type === 'update') {
|
||||
tabUpdate.nodes[20].nodes.push({
|
||||
object: 'block',
|
||||
type: 'tabs',
|
||||
key: 'tabs-block',
|
||||
data: {},
|
||||
isVoid: false,
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'tabs-item',
|
||||
key: 'legacy-tab-key',
|
||||
data: { title: 'Tab' },
|
||||
isVoid: false,
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
expect(findUpdateAnchorPage(document, revision, { anchor: 'legacy-tab-key' })).toEqual({
|
||||
found: true,
|
||||
page: 2,
|
||||
clearTags: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseUpdatesPageParam', () => {
|
||||
it.each([null, undefined, '1', '0', '-1', 'abc', '501', '2.5', '2e1', '02', ' 2', '2\n'])(
|
||||
'rejects %s',
|
||||
(param) => {
|
||||
expect(parseUpdatesPageParam(param)).toBeNull();
|
||||
}
|
||||
);
|
||||
|
||||
it.each([2, 500])('accepts %s', (page) => {
|
||||
expect(parseUpdatesPageParam(String(page))).toBe(page);
|
||||
});
|
||||
});
|
||||
|
||||
function getUpdateIds(document: JSONDocument) {
|
||||
return document.nodes.flatMap((block) => {
|
||||
if (block.type !== 'updates') {
|
||||
return [];
|
||||
}
|
||||
return block.nodes.map((entry) => {
|
||||
const heading = entry.nodes[0];
|
||||
if (heading?.type === 'heading-1') {
|
||||
return heading.meta?.id;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
|
||||
const entries = entryTags.map((tags, index) => ({
|
||||
object: 'block' as const,
|
||||
type: 'update' as const,
|
||||
data: {
|
||||
date: '2026-05-01',
|
||||
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
|
||||
},
|
||||
isVoid: false as const,
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'updates',
|
||||
data: { format: 'full' },
|
||||
isVoid: false,
|
||||
nodes: entryTags.map((tags, index) => ({
|
||||
object: 'block',
|
||||
type: 'update',
|
||||
data: {
|
||||
date: `2026-05-${String(index + 1).padStart(2, '0')}`,
|
||||
tags: tags.map((tag) => ({ kind: 'tag', tag })),
|
||||
},
|
||||
isVoid: false,
|
||||
nodes: [],
|
||||
})),
|
||||
object: 'block' as const,
|
||||
type: 'heading-1' as const,
|
||||
meta: { id: `update-${index + 1}` },
|
||||
data: {},
|
||||
isVoid: false as const,
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}));
|
||||
const updates = (nodes: typeof entries) => ({
|
||||
object: 'block' as const,
|
||||
type: 'updates' as const,
|
||||
data: { format: 'full' as const },
|
||||
isVoid: false as const,
|
||||
nodes,
|
||||
});
|
||||
const nodes: JSONDocument['nodes'] = [updates(entries)];
|
||||
if (splitAt !== undefined) {
|
||||
nodes.splice(
|
||||
0,
|
||||
1,
|
||||
updates(entries.slice(0, splitAt)),
|
||||
{ object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] },
|
||||
updates(entries.slice(splitAt))
|
||||
);
|
||||
}
|
||||
|
||||
return { object: 'document', data: { schemaVersion: 2 }, nodes };
|
||||
}
|
||||
|
||||
function createTag(slug: string, label: string): RevisionTag {
|
||||
|
||||
@@ -1,10 +1,34 @@
|
||||
import type { JSONDocument, Revision, RevisionTag } from '@gitbook/api';
|
||||
import type {
|
||||
DocumentBlock,
|
||||
DocumentBlockUpdate,
|
||||
DocumentInline,
|
||||
JSONDocument,
|
||||
Revision,
|
||||
RevisionTag,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { getBlocksByType } from './document';
|
||||
import { getBlocksByType, hasMoreThan } from './document';
|
||||
import { getRevisionTags, resolveBlockTags } from './tags';
|
||||
|
||||
/** URL search param carrying the active tag filter, e.g. `?tag=changelog`. */
|
||||
export const UPDATES_FILTER_SEARCH_PARAM = 'tag';
|
||||
export {
|
||||
UPDATES_FILTER_SEARCH_PARAM,
|
||||
UPDATES_MAX_PAGE,
|
||||
UPDATES_PAGE_SEARCH_PARAM,
|
||||
parseUpdatesPageParam,
|
||||
} from './updates-url';
|
||||
|
||||
export const UPDATES_PAGINATION_THRESHOLD = 50;
|
||||
export const UPDATES_PAGE_SIZE = 20;
|
||||
|
||||
export type UpdatesPageRange = {
|
||||
page: number;
|
||||
totalPages: number;
|
||||
totalItems: number;
|
||||
pageSize: number;
|
||||
start: number;
|
||||
end: number;
|
||||
isClamped: boolean;
|
||||
};
|
||||
|
||||
/** Attribute on `<html>` with the active filter's tag slugs, space-separated (e.g. `"a b"`). */
|
||||
export const UPDATES_TAG_FILTER_ATTR = 'data-updates-tag-filter';
|
||||
@@ -93,6 +117,138 @@ export function getDocumentFilterableTags(
|
||||
return tags;
|
||||
}
|
||||
|
||||
export function countDocumentUpdates(document: JSONDocument): number {
|
||||
return getDocumentUpdates(document).length;
|
||||
}
|
||||
|
||||
export function paginateUpdatesDocument(
|
||||
document: JSONDocument,
|
||||
revision: Revision | undefined,
|
||||
{ page, tags }: { page: number; tags?: string[] }
|
||||
): { document: JSONDocument; pagination: UpdatesPageRange | null } {
|
||||
const updates = getDocumentUpdates(document);
|
||||
if (updates.length <= UPDATES_PAGINATION_THRESHOLD) {
|
||||
return { document, pagination: null };
|
||||
}
|
||||
|
||||
const matching = filterUpdates(updates, document, revision, tags);
|
||||
const pagination = getUpdatesPageRange(page, matching.length);
|
||||
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
|
||||
const nodes: JSONDocument['nodes'] = [];
|
||||
|
||||
for (const block of document.nodes) {
|
||||
if (block.type !== 'updates') {
|
||||
nodes.push(block);
|
||||
continue;
|
||||
}
|
||||
|
||||
const entries = block.nodes.filter((entry) => entry.type === 'update' && slice.has(entry));
|
||||
if (entries.length > 0) {
|
||||
nodes.push({ ...block, nodes: entries });
|
||||
}
|
||||
}
|
||||
|
||||
return { document: { ...document, nodes }, pagination };
|
||||
}
|
||||
|
||||
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
|
||||
const totalPages = Math.max(1, Math.ceil(totalItems / UPDATES_PAGE_SIZE));
|
||||
const page = Math.min(Math.max(1, requestedPage), totalPages);
|
||||
let start = (page - 1) * UPDATES_PAGE_SIZE + 1;
|
||||
if (totalItems === 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
page,
|
||||
totalPages,
|
||||
totalItems,
|
||||
pageSize: UPDATES_PAGE_SIZE,
|
||||
start,
|
||||
end: Math.min(page * UPDATES_PAGE_SIZE, totalItems),
|
||||
isClamped: page !== requestedPage,
|
||||
};
|
||||
}
|
||||
|
||||
export function findUpdateAnchorPage(
|
||||
document: JSONDocument,
|
||||
revision: Revision | undefined,
|
||||
{ anchor, tags }: { anchor: string; tags?: string[] }
|
||||
): { found: true; page: number; clearTags: boolean } | { found: false } {
|
||||
const updates = getDocumentUpdates(document);
|
||||
const index = updates.findIndex((update) =>
|
||||
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
|
||||
);
|
||||
const entry = updates[index];
|
||||
if (!entry) {
|
||||
return { found: false };
|
||||
}
|
||||
|
||||
const filteredIndex = filterUpdates(updates, document, revision, tags).indexOf(entry);
|
||||
if (filteredIndex >= 0) {
|
||||
return {
|
||||
found: true,
|
||||
page: Math.floor(filteredIndex / UPDATES_PAGE_SIZE) + 1,
|
||||
clearTags: false,
|
||||
};
|
||||
}
|
||||
|
||||
return { found: true, page: Math.floor(index / UPDATES_PAGE_SIZE) + 1, clearTags: true };
|
||||
}
|
||||
|
||||
function matchesUpdateAnchor(node: DocumentBlock | DocumentInline, anchor: string): boolean {
|
||||
if (node.object !== 'block') {
|
||||
return false;
|
||||
}
|
||||
if ('meta' in node && node.meta && 'id' in node.meta && node.meta.id === anchor) {
|
||||
return true;
|
||||
}
|
||||
if (node.type === 'tabs-item' && !node.meta?.id && node.key === anchor) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getDocumentUpdates(document: JSONDocument): DocumentBlockUpdate[] {
|
||||
const updates: DocumentBlockUpdate[] = [];
|
||||
for (const block of document.nodes) {
|
||||
if (block.type !== 'updates') {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const entry of block.nodes) {
|
||||
if (entry.type === 'update') {
|
||||
updates.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
function filterUpdates(
|
||||
updates: DocumentBlockUpdate[],
|
||||
document: JSONDocument,
|
||||
revision: Revision | undefined,
|
||||
tags: string[] | undefined
|
||||
): DocumentBlockUpdate[] {
|
||||
if (!tags?.length) {
|
||||
return updates;
|
||||
}
|
||||
|
||||
const availableTags = new Set(
|
||||
getDocumentFilterableTags(document, revision).map((tag) => tag.slug)
|
||||
);
|
||||
const selectedTags = new Set(normalizeUpdatesFilterTags(tags, availableTags));
|
||||
if (!selectedTags.size) {
|
||||
return updates;
|
||||
}
|
||||
|
||||
const revisionTags = getRevisionTags(revision);
|
||||
return updates.filter((update) =>
|
||||
resolveBlockTags(update.data.tags, revisionTags).some((tag) => selectedTags.has(tag.slug))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape a slug for interpolation into a CSS string literal (a quoted attribute-selector value).
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
|
||||
import { RequestCookiesAdapter } from 'next/dist/server/web/spec-extension/adapters/request-cookies';
|
||||
import * as nextHeaders from 'next/headers';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import { middleware } from './middleware';
|
||||
import { GITBOOK_API_URL } from '@/lib/env';
|
||||
import { removeTrailingSlash } from '@/lib/paths';
|
||||
|
||||
const PATH = '/~gitbook/search-direct/orgs/org_1/sites/site-1';
|
||||
const PASS_HEADER = 'x-gitbook-search-pass';
|
||||
const SEARCH_PASS =
|
||||
'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwidHlwIjoic2l0ZS1zZWFyY2gtcGFzcytqd3QifQ..AAAAAAAAAAAAAAAA.AAAA.AAAAAAAAAAAAAAAAAAAAAA';
|
||||
|
||||
let fetchSpy: ReturnType<typeof spyOn<typeof globalThis, 'fetch'>>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(null));
|
||||
});
|
||||
|
||||
afterEach(() => fetchSpy.mockRestore());
|
||||
|
||||
describe('direct site search middleware', () => {
|
||||
it.each([
|
||||
['https://hosted.gitbook.io', '', ''],
|
||||
['https://proxy.gitbook.site', '/sites/site-1', '/'],
|
||||
])('forwards a search from %s%s%s directly to GBX', async (host, prefix, suffix) => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
Response.json(
|
||||
{ items: [] },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=600',
|
||||
'set-cookie': 'upstream=1',
|
||||
'retry-after': '3',
|
||||
'x-ratelimit-scope': 'site',
|
||||
'x-ratelimit-reset': '123',
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
const body = '{"query":"tokens"}';
|
||||
const request = new NextRequest('https://origin.example.com/ignored?ignored=1', {
|
||||
method: 'POST',
|
||||
body: new TextEncoder().encode(body),
|
||||
headers: {
|
||||
'x-gitbook-url': `${host}${prefix}${PATH}${suffix}?also-ignored=1`,
|
||||
'x-gitbook-url-signature': 'internal',
|
||||
'x-gitbook-ip': '192.0.2.1',
|
||||
'cf-connecting-ip': '192.0.2.2',
|
||||
'x-forwarded-for': '192.0.2.3',
|
||||
'content-type': 'text/plain',
|
||||
'user-agent': 'Mozilla/5.0',
|
||||
[PASS_HEADER]: SEARCH_PASS,
|
||||
'x-gitbook-search-fallback': 'network',
|
||||
cookie: 'session=1',
|
||||
authorization: 'Bearer incoming-token',
|
||||
},
|
||||
});
|
||||
const response = await middleware(request);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetchSpy.mock.calls[0] ?? [];
|
||||
expect(String(url)).toBe(
|
||||
`${removeTrailingSlash(GITBOOK_API_URL)}/v1/orgs/org_1/sites/site-1/search`
|
||||
);
|
||||
expect(init).toMatchObject({ method: 'POST', redirect: 'manual', duplex: 'half' });
|
||||
expect(init?.body).toBe(request.body);
|
||||
expect(await new Response(init?.body).text()).toBe(body);
|
||||
expect(Object.fromEntries(new Headers(init?.headers))).toEqual({
|
||||
authorization: `Bearer ${SEARCH_PASS}`,
|
||||
'content-type': 'application/json',
|
||||
'user-agent': 'Mozilla/5.0',
|
||||
'x-forwarded-for': '192.0.2.1',
|
||||
});
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
|
||||
expect(response.headers.get('set-cookie')).toBeNull();
|
||||
expect(response.headers.get('retry-after')).toBe('3');
|
||||
expect(response.headers.get('x-ratelimit-scope')).toBe('site');
|
||||
expect(response.headers.get('x-ratelimit-reset')).toBe('123');
|
||||
expect(await response.text()).toBe('{"items":[]}');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['wrong method', 'GET', PATH, '', 405],
|
||||
['missing pass', 'POST', PATH, '', 401],
|
||||
['personal token', 'POST', PATH, 'personal-api-token', 401],
|
||||
['signed API token', 'POST', PATH, 'eyJhbGciOiJIUzI1NiJ9.e30.c2ln', 401],
|
||||
['invalid organization ID', 'POST', PATH.replace('org_1', 'org%20bad'), SEARCH_PASS, 400],
|
||||
['invalid site ID', 'POST', PATH.replace('site-1', 'site.bad'), SEARCH_PASS, 400],
|
||||
] as const)('rejects %s', async (_name, method, path, pass, status) => {
|
||||
const headers = new Headers({ 'x-forwarded-host': 'docs.example.com' });
|
||||
if (pass) {
|
||||
headers.set(PASS_HEADER, pass);
|
||||
}
|
||||
const response = await middleware(
|
||||
new NextRequest(`https://origin.example.com${path}`, { method, headers })
|
||||
);
|
||||
|
||||
expect(response.status).toBe(status);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns an uncached 502 when the upstream request fails', async () => {
|
||||
fetchSpy.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
||||
const response = await middleware(
|
||||
new NextRequest(`https://origin.example.com${PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'x-forwarded-host': 'docs.example.com', [PASS_HEADER]: SEARCH_PASS },
|
||||
})
|
||||
);
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns an uncached 502 when reading the upstream response body fails', async () => {
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.error(new TypeError('Connection reset'));
|
||||
},
|
||||
});
|
||||
fetchSpy.mockResolvedValueOnce(new Response(body, { status: 200 }));
|
||||
const response = await middleware(
|
||||
new NextRequest(`https://origin.example.com${PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'x-forwarded-host': 'docs.example.com', [PASS_HEADER]: SEARCH_PASS },
|
||||
})
|
||||
);
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('passes through null-body statuses without throwing', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
const response = await middleware(
|
||||
new NextRequest(`https://origin.example.com${PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'x-forwarded-host': 'docs.example.com', [PASS_HEADER]: SEARCH_PASS },
|
||||
})
|
||||
);
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(response.body).toBeNull();
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Updates page middleware', () => {
|
||||
it.each([
|
||||
['/changelog', '', '/changelog', null],
|
||||
['/changelog', '?page=2', '/changelog/2', null],
|
||||
['/changelog', '?page=500&tag=fixes&tag=releases', '/changelog/500', 'noindex, follow'],
|
||||
['/changelog', '?tag=fixes', '/changelog', 'noindex, follow'],
|
||||
['/changelog', '?page=1', '/changelog', null],
|
||||
['/changelog', '?page=0', '/changelog', null],
|
||||
['/changelog', '?page=-1', '/changelog', null],
|
||||
['/changelog', '?page=abc', '/changelog', null],
|
||||
['/changelog', '?page=501', '/changelog', null],
|
||||
['/changelog.md', '?page=2', '/~gitbook/markdown/changelog', null],
|
||||
['/changelog/rss.xml', '?page=2', '/~gitbook/rss/changelog', null],
|
||||
['/llms-full.txt', '?page=2', '/llms-full.txt', null],
|
||||
['/sitemap.xml', '?page=2', '/sitemap.xml', null],
|
||||
['/changelog', '?page=2&tag=fixes&ask=test', '/changelog/2', 'none'],
|
||||
['/~gitbook/embed/page/changelog', '?page=2', '/~gitbook/embed/page/%2Fchangelog/2', null],
|
||||
] as const)(
|
||||
'rewrites %s%s without changing its query',
|
||||
async (path, search, suffix, robots) => {
|
||||
const url = new URL(`https://docs.example.com${path}${search}`);
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
site: 'site',
|
||||
siteSpace: 'variant',
|
||||
space: 'space',
|
||||
organization: 'org',
|
||||
apiToken: 'content-token',
|
||||
pathname: path,
|
||||
basePath: '',
|
||||
siteBasePath: '',
|
||||
canonicalUrl: url.origin + url.pathname,
|
||||
complete: true,
|
||||
})
|
||||
);
|
||||
|
||||
const request = new NextRequest(url, { headers: { 'x-forwarded-host': url.host } });
|
||||
const cookiesSpy = spyOn(nextHeaders, 'cookies').mockResolvedValue(
|
||||
RequestCookiesAdapter.seal(request.cookies)
|
||||
);
|
||||
let response;
|
||||
try {
|
||||
response = await middleware(request);
|
||||
} finally {
|
||||
cookiesSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(response.headers.get('x-gitbook-route-type')).toBe('static');
|
||||
expect(response.headers.get('x-robots-tag')).toBe(robots);
|
||||
const rewrite = response.headers.get('x-middleware-rewrite');
|
||||
expect(rewrite).not.toBeNull();
|
||||
const destination = new URL(rewrite!);
|
||||
expect(destination.pathname).toEndWith(suffix);
|
||||
expect(destination.search).toBe(search);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
|
||||
import {
|
||||
type ServerInsightsEventInput,
|
||||
getXForwardedFor,
|
||||
serveProxyAnalyticsEvent,
|
||||
trackServerInsightsEvents,
|
||||
} from './lib/tracking';
|
||||
@@ -37,7 +38,12 @@ import {
|
||||
normalizeRequestURL,
|
||||
throwIfDataError,
|
||||
} from '@/lib/data';
|
||||
import { GITBOOK_DISABLE_INSIGHTS, isGitBookAssetsHostURL, isGitBookHostURL } from '@/lib/env';
|
||||
import {
|
||||
GITBOOK_API_URL,
|
||||
GITBOOK_DISABLE_INSIGHTS,
|
||||
isGitBookAssetsHostURL,
|
||||
isGitBookHostURL,
|
||||
} from '@/lib/env';
|
||||
import { getImageResizingContextId } from '@/lib/images';
|
||||
import { isAITrainingOrIndexingRequest } from '@/lib/indexing-crawlers';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
@@ -64,6 +70,11 @@ import {
|
||||
createRobotsTxtResponse,
|
||||
isRobotsTxtRequest,
|
||||
} from '@/lib/robots';
|
||||
import {
|
||||
UPDATES_FILTER_SEARCH_PARAM,
|
||||
UPDATES_PAGE_SEARCH_PARAM,
|
||||
parseUpdatesPageParam,
|
||||
} from '@/lib/updates-url';
|
||||
import {
|
||||
type ResponseCookies,
|
||||
getPathScopedCookieName,
|
||||
@@ -86,10 +97,20 @@ export const config = {
|
||||
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
|
||||
|
||||
const REVISION_ROBOTS_TAG = 'noindex, nofollow';
|
||||
const DIRECT_SEARCH_PATH = /\/~gitbook\/search-direct\/orgs\/([^/]*)\/sites\/([^/]*)\/?$/;
|
||||
const DIRECT_SEARCH_ID = /^[a-zA-Z0-9_-]+$/;
|
||||
const DIRECT_SEARCH_PASS =
|
||||
/^[a-zA-Z0-9_-]+\.\.[a-zA-Z0-9_-]{16}\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{22}$/;
|
||||
const DIRECT_SEARCH_TIMEOUT_MS = 5_000;
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
try {
|
||||
const requestURL = new URL(request.url);
|
||||
const siteURL = getSiteURLFromRequest(request);
|
||||
const directSearch = siteURL?.url.pathname.match(DIRECT_SEARCH_PATH);
|
||||
if (directSearch) {
|
||||
return await serveDirectSearch(request, directSearch[1], directSearch[2]);
|
||||
}
|
||||
|
||||
// Reject malicious requests
|
||||
const rejectResponse = await validateServerActionRequest(request);
|
||||
@@ -97,14 +118,10 @@ export async function middleware(request: NextRequest) {
|
||||
return rejectResponse;
|
||||
}
|
||||
|
||||
for (const handler of [serveSiteRoutes, serveSpacePDFRoutes]) {
|
||||
const result = await handler(requestURL, request);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
const siteResponse = await serveSiteRoutes(requestURL, request, siteURL);
|
||||
return (
|
||||
siteResponse ?? (await serveSpacePDFRoutes(requestURL, request)) ?? NextResponse.next()
|
||||
);
|
||||
} catch (error) {
|
||||
return serveErrorResponse(error as Error);
|
||||
}
|
||||
@@ -164,8 +181,7 @@ function shouldFilterMaliciousRequests(requestURL: URL): boolean {
|
||||
/**
|
||||
* Handle request that are targetting the site routes group.
|
||||
*/
|
||||
async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
const match = getSiteURLFromRequest(request);
|
||||
async function serveSiteRoutes(requestURL: URL, request: NextRequest, match: URLWithMode | null) {
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
@@ -183,6 +199,95 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
return response;
|
||||
}
|
||||
|
||||
async function serveDirectSearch(request: NextRequest, organizationId = '', siteId = '') {
|
||||
const responseHeaders = new Headers({
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
if (request.method !== 'POST') {
|
||||
responseHeaders.set('Allow', 'POST');
|
||||
return new Response(null, { status: 405, headers: responseHeaders });
|
||||
}
|
||||
if (!DIRECT_SEARCH_ID.test(organizationId) || !DIRECT_SEARCH_ID.test(siteId)) {
|
||||
return new Response(null, { status: 400, headers: responseHeaders });
|
||||
}
|
||||
const pass = request.headers.get('x-gitbook-search-pass');
|
||||
if (!pass || !DIRECT_SEARCH_PASS.test(pass)) {
|
||||
return new Response(null, { status: 401, headers: responseHeaders });
|
||||
}
|
||||
|
||||
const headers = new Headers({
|
||||
Authorization: `Bearer ${pass}`,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
const userAgent = request.headers.get('User-Agent');
|
||||
if (userAgent) headers.set('User-Agent', userAgent);
|
||||
const ip = request.headers.get('x-gitbook-ip') ?? getXForwardedFor(request.headers);
|
||||
if (ip) headers.set('X-Forwarded-For', ip);
|
||||
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
if (request.signal.aborted) {
|
||||
abort();
|
||||
}
|
||||
request.signal.addEventListener('abort', abort, { once: true });
|
||||
const timeout = setTimeout(abort, DIRECT_SEARCH_TIMEOUT_MS);
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
const upstream = await fetch(
|
||||
`${removeTrailingSlash(GITBOOK_API_URL)}/v1/orgs/${organizationId}/sites/${siteId}/search`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: request.body,
|
||||
redirect: 'manual',
|
||||
signal: controller.signal,
|
||||
duplex: 'half',
|
||||
} as RequestInit
|
||||
);
|
||||
let responseBody: ArrayBuffer | null = null;
|
||||
if (upstream.status !== 204 && upstream.status !== 205 && upstream.status !== 304) {
|
||||
responseBody = await upstream.arrayBuffer();
|
||||
}
|
||||
responseHeaders.set(
|
||||
'Server-Timing',
|
||||
`api;dur=${Math.round(performance.now() - startedAt)}`
|
||||
);
|
||||
for (const name of [
|
||||
'Content-Type',
|
||||
'Retry-After',
|
||||
'X-RateLimit-Scope',
|
||||
'X-RateLimit-Reset',
|
||||
]) {
|
||||
const value = upstream.headers.get(name);
|
||||
if (value !== null) responseHeaders.set(name, value);
|
||||
}
|
||||
const fallback = request.headers.get('x-gitbook-search-fallback');
|
||||
if (upstream.ok && (fallback === 'network' || fallback === 'timeout')) {
|
||||
getLogger().subLogger('directSiteSearch').info('Direct search recovered via proxy', {
|
||||
reason: fallback,
|
||||
organizationId,
|
||||
siteId,
|
||||
});
|
||||
}
|
||||
return new Response(responseBody, { status: upstream.status, headers: responseHeaders });
|
||||
} catch {
|
||||
responseHeaders.set(
|
||||
'Server-Timing',
|
||||
`api;dur=${Math.round(performance.now() - startedAt)}`
|
||||
);
|
||||
getLogger().subLogger('directSiteSearch').warn('Direct search upstream failed', {
|
||||
status: 502,
|
||||
organizationId,
|
||||
siteId,
|
||||
});
|
||||
return new Response(null, { status: 502, headers: responseHeaders });
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
request.signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
|
||||
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
|
||||
const { url: siteRequestURL, mode } = match;
|
||||
|
||||
@@ -449,8 +554,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
|
||||
basePath: siteURLData.basePath,
|
||||
space: siteURLData.space,
|
||||
organization: siteURLData.organization,
|
||||
changeRequest: siteURLData.changeRequest,
|
||||
revision: siteURLData.revision,
|
||||
...getPreviewedContent(siteURLData),
|
||||
shareKey: siteURLData.shareKey,
|
||||
preview: siteURLData.preview,
|
||||
apiToken: siteURLData.apiToken,
|
||||
@@ -647,6 +751,8 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
|
||||
response.headers.set('x-robots-tag', 'none');
|
||||
} else if (hasRevisionSelector(siteURLData.basePath)) {
|
||||
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
|
||||
} else if (rewrittenURL.searchParams.has(UPDATES_FILTER_SEARCH_PARAM)) {
|
||||
response.headers.set('x-robots-tag', 'noindex, follow');
|
||||
}
|
||||
|
||||
// Allow cross-origin requests from the same parent domain as the site.
|
||||
@@ -965,7 +1071,7 @@ function encodePathInSiteContent(
|
||||
siteSpace: siteURLData.siteSpace,
|
||||
siteShareKey: siteURLData.shareKey,
|
||||
space: siteURLData.space,
|
||||
revision: siteURLData.revision,
|
||||
revision: getPreviewedContent(siteURLData).revision,
|
||||
displayContext: SiteInsightsDisplayContext.Server,
|
||||
};
|
||||
|
||||
@@ -1015,7 +1121,7 @@ function encodePathInSiteContent(
|
||||
const embedPage = pathname.match(EMBED_PAGE_PATH_REGEX);
|
||||
if (embedPage) {
|
||||
return {
|
||||
pathname: `~gitbook/embed/page/${encodePagePath(embedPage[1])}`,
|
||||
pathname: `~gitbook/embed/page/${encodeUpdatesPagePath(embedPage[1], request)}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1122,11 +1228,22 @@ function encodePathInSiteContent(
|
||||
],
|
||||
};
|
||||
}
|
||||
return { pathname: encodePagePath(pathname) };
|
||||
return { pathname: encodeUpdatesPagePath(pathname, request) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeUpdatesPagePath(path: string | undefined, request: Request): string {
|
||||
const pathname = encodePagePath(path);
|
||||
const page = parseUpdatesPageParam(
|
||||
new URL(request.url).searchParams.get(UPDATES_PAGE_SEARCH_PARAM)
|
||||
);
|
||||
if (page !== null) {
|
||||
return `${pathname}/${page}`;
|
||||
}
|
||||
return pathname;
|
||||
}
|
||||
|
||||
function encodePagePath(path: string | undefined): string {
|
||||
return encodeURIComponent(path || '/');
|
||||
}
|
||||
@@ -1229,3 +1346,21 @@ function acceptsMarkdown(request: Request): boolean {
|
||||
const htmlIndex = mediaTypes.findIndex((type) => type === 'text/html' || type === '*/*');
|
||||
return htmlIndex === -1 || markdownIndex < htmlIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* The revision, change request or site revision a URL previews: at most one of them.
|
||||
*/
|
||||
function getPreviewedContent(
|
||||
content: PublishedSiteContent
|
||||
): Pick<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
|
||||
if ('revision' in content) {
|
||||
return { revision: content.revision };
|
||||
}
|
||||
if ('changeRequest' in content) {
|
||||
return { changeRequest: content.changeRequest };
|
||||
}
|
||||
if ('siteRevision' in content) {
|
||||
return { siteRevision: content.siteRevision };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -94,6 +94,17 @@ describe('servePageMarkdown', () => {
|
||||
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
|
||||
});
|
||||
|
||||
it('returns not-found markdown instead of looping when a site redirect targets the same markdown path', async () => {
|
||||
const context = createContext({
|
||||
siteRedirect: { target: 'https://docs.example.com/docs/old-page.md', permanent: false },
|
||||
});
|
||||
|
||||
const response = await servePageMarkdown(context, 'old-page');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toContain('# Page Not Found');
|
||||
});
|
||||
|
||||
it('redirects to the markdown version of a space redirect target', async () => {
|
||||
const context = createContext({ spaceRedirectPageId: page.id });
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user