Compare commits

..

5 Commits

Author SHA1 Message Date
Peter White 9d300985bc Merge remote-tracking branch 'origin/main' into peter/updates-pagination 2026-11-26 09:18:38 +00:00
Peter White 9f2701c616 changeset 2026-11-26 09:18:38 +00:00
Peter White 0173636ced Paginate long Updates pages at 20 entries per page 2026-11-26 09:18:38 +00:00
conico974 a3d37f341a Bump @opennextjs/aws to 4.2.1 and @opennextjs/cloudflare to 1.20.19 (#4846)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:23:05 +01:00
Peter White 68e3dace27 Fallback to same-domain direct site search when the API host is blocked (#4844) 2026-11-26 04:04:28 +00:00
93 changed files with 2439 additions and 2179 deletions
+5
View File
@@ -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.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load Shiki languages and themes from static assets instead of bundling them.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Paginate published Updates pages with more than 50 entries into 20-entry pages.
+9 -7
View File
@@ -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=="],
+28 -4
View File
@@ -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);
},
},
-5
View File
@@ -120,11 +120,6 @@ const nextConfig = {
],
},
// Shiki grammars and themes are read from disk at runtime, see shiki-assets.server.ts.
outputFileTracingIncludes: {
'/**': ['./public/~gitbook/static/shiki/**/*'],
},
webpack(config, { isServer }) {
if (isServer) {
// mcp-handler only needs redis for SSE, which we disable: keep the client out of the server bundle.
@@ -12,13 +12,6 @@
"observability": {
"enabled": false,
},
// Lets the server read Shiki grammars and themes without a network hop.
// run_worker_first keeps every request going to the worker, as before.
"assets": {
"directory": "../../.open-next/assets",
"binding": "ASSETS",
"run_worker_first": true,
},
"vars": {
"NEXT_CACHE_DO_QUEUE_DISABLE_SQLITE": "true",
},
+4 -4
View File
@@ -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",
@@ -119,9 +119,9 @@
},
"scripts": {
"generate": "./scripts/generate.sh",
"generate:assets": "bun ./scripts/generate-shiki-assets.ts && bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:fonts": "bun ./scripts/generate-font-faces.ts",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts && rm -rf ./public/~gitbook/static/shiki",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts",
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
"build": "bun run generate:assets && next build --webpack",
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
@@ -1,60 +0,0 @@
import { spawn } from 'bun';
import type { DocumentBlockCode } from '@gitbook/api';
/**
* Time the first highlights in fresh processes, where grammars and themes are loaded.
* Usage: bun scripts/bench-highlight-cold.ts [runs]
*/
const SAMPLES: Record<string, string> = {
javascript: 'const answer = await fetch("/api").then((r) => r.json());',
python: 'def greet(name: str) -> str:\n return f"Hello {name}"',
vue: '<template><p>{{ msg }}</p></template>\n<script setup>\nconst msg = "hi";\n</script>',
};
function codeBlock(syntax: string, code: string): DocumentBlockCode {
return {
object: 'block',
type: 'code',
data: { syntax },
nodes: code.split('\n').map((text) => ({
object: 'block',
type: 'code-line',
data: {},
nodes: [{ object: 'text', leaves: [{ object: 'leaf', marks: [], text }] }],
})),
} as DocumentBlockCode;
}
if (process.env.BENCH_CHILD) {
const importStart = performance.now();
const { highlight } = await import('../src/components/DocumentView/CodeBlock/highlight');
const importMs = performance.now() - importStart;
const start = performance.now();
await Promise.all(
Object.entries(SAMPLES).map(([syntax, code]) => highlight(codeBlock(syntax, code), []))
);
const firstMs = performance.now() - start;
console.log(JSON.stringify({ importMs, firstMs, rssMB: process.memoryUsage().rss / 1e6 }));
} else {
const runs = Number(process.argv[2] ?? 5);
const results: { importMs: number; firstMs: number; rssMB: number }[] = [];
for (let i = 0; i < runs; i++) {
const child = spawn(['bun', import.meta.path], {
env: { ...process.env, BENCH_CHILD: '1' },
stdout: 'pipe',
});
results.push(JSON.parse(await new Response(child.stdout).text()));
}
const median = (values: number[]) =>
values.sort((a, b) => a - b)[Math.floor(values.length / 2)]!;
console.log(
JSON.stringify({
runs,
importMsMedian: Math.round(median(results.map((r) => r.importMs))),
firstHighlightMsMedian: Math.round(median(results.map((r) => r.firstMs))),
rssMBMedian: Math.round(median(results.map((r) => r.rssMB))),
})
);
}
@@ -1,110 +0,0 @@
import { $ } from 'bun';
import { createHash } from 'node:crypto';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { bundledLanguagesInfo } from 'shiki/langs';
import { bundledThemesInfo } from 'shiki/themes';
/**
* Write every Shiki language and theme as static JSON, so the app loads them on demand
* instead of bundling them, and generate the catalog of their names.
*/
const scriptDir = dirname(fileURLToPath(import.meta.url));
const staticDir = join(scriptDir, '../public/~gitbook/static');
const codeBlockDir = join(scriptDir, '../src/components/DocumentView/CodeBlock');
const require = createRequire(import.meta.url);
const { version } = require('shiki/package.json') as { version: string };
const languages: Record<string, string> = {};
const languageGrammars: Record<string, string[]> = {};
const grammars = new Map<string, string>();
for (const info of bundledLanguagesInfo) {
// A language module exports its embedded grammars followed by its own, in registration order.
const registrations = (await info.import()).default;
for (const registration of registrations) {
const json = JSON.stringify(registration);
const existing = grammars.get(registration.name);
if (existing !== undefined && existing !== json) {
throw new Error(`Grammar "${registration.name}" differs between languages`);
}
grammars.set(registration.name, json);
}
languageGrammars[info.id] = registrations.map((registration) => registration.name);
languages[info.id] = info.id;
for (const alias of info.aliases ?? []) {
languages[alias] ??= info.id;
}
}
const themes: Record<string, { type: 'light' | 'dark' }> = {};
const themeFiles = new Map<string, string>();
for (const info of bundledThemesInfo) {
themeFiles.set(info.id, JSON.stringify((await info.import()).default));
themes[info.id] = { type: info.type };
}
// Hash the content into the path: assets are served immutable, so any change needs a new URL.
const hash = createHash('sha256');
for (const [name, json] of [...grammars, ...themeFiles].sort(compareEntries)) {
hash.update(name).update('\0').update(json).update('\0');
}
const assetsPath = `shiki/${version}-${hash.digest('hex').slice(0, 8)}`;
await rm(join(staticDir, 'shiki'), { force: true, recursive: true });
await mkdir(join(staticDir, assetsPath, 'grammars'), { recursive: true });
await mkdir(join(staticDir, assetsPath, 'themes'), { recursive: true });
// One file per grammar so embedded grammars are stored and downloaded once.
for (const [name, json] of grammars) {
await writeFile(join(staticDir, assetsPath, 'grammars', `${name}.json`), json);
}
for (const [id, json] of themeFiles) {
await writeFile(join(staticDir, assetsPath, 'themes', `${id}.json`), json);
}
await writeFile(
join(codeBlockDir, 'shiki-catalog.ts'),
`// Generated by scripts/generate-shiki-assets.ts, do not edit.
export const SHIKI_ASSETS_PATH = ${JSON.stringify(assetsPath)};
/** Every Shiki language id and alias, mapped to the id of its asset. */
export const SHIKI_LANGUAGES: Record<string, string> = ${JSON.stringify(sorted(languages), null, 4)};
/** Grammars to register for each language, embedded ones first. */
export const SHIKI_LANGUAGE_GRAMMARS: Record<string, string[]> = ${JSON.stringify(sorted(languageGrammars), null, 4)};
export function getShikiGrammarAssetPath(name: string): string {
return \`\${SHIKI_ASSETS_PATH}/grammars/\${name}.json\`;
}
export function getShikiThemeAssetPath(id: string): string {
return \`\${SHIKI_ASSETS_PATH}/themes/\${id}.json\`;
}
`
);
// Separate from the catalog: plain highlighting only needs theme types and ships in the eager chunk.
await writeFile(
join(codeBlockDir, 'shiki-themes.ts'),
`// Generated by scripts/generate-shiki-assets.ts, do not edit.
/** Every bundled Shiki theme id, with its type. */
export const SHIKI_THEMES: Record<string, { type: 'light' | 'dark' }> = ${JSON.stringify(sorted(themes), null, 4)};
`
);
// Format like the rest of the repo so regenerating doesn't leave the committed files modified.
await $`bunx oxfmt ${join(codeBlockDir, 'shiki-catalog.ts')} ${join(codeBlockDir, 'shiki-themes.ts')}`.quiet();
function compareEntries([a]: [string, unknown], [b]: [string, unknown]) {
// Code-point order keeps the output identical whatever the machine's locale.
return a < b ? -1 : a > b ? 1 : 0;
}
function sorted<T>(record: Record<string, T>) {
return Object.fromEntries(Object.entries(record).sort(compareEntries));
}
@@ -1,115 +0,0 @@
import { $, Glob, file, gzipSync } from 'bun';
import { stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
/**
* Measure how much of the build output is made of Shiki grammars and themes.
* Usage: bun scripts/measure-shiki-bundles.ts next|cloudflare
*/
const appPath = join(import.meta.dir, '..');
const mode = process.argv[2];
// Every Shiki grammar carries a scopeName, so it is a cheap marker for grammar chunks.
const GRAMMAR_MARKER = 'scopeName';
async function measureFiles(root: string, pattern: string) {
let bytes = 0;
let count = 0;
let grammarBytes = 0;
let grammarCount = 0;
for await (const path of new Glob(pattern).scan({ cwd: root, onlyFiles: true })) {
const content = await file(join(root, path)).text();
const size = Buffer.byteLength(content);
bytes += size;
count += 1;
if (content.includes(GRAMMAR_MARKER)) {
grammarBytes += size;
grammarCount += 1;
}
}
return { bytes, count, grammarBytes, grammarCount };
}
// Next keeps shiki external on the server, so its files reach the function through the trace.
async function measurePageTrace() {
const nftPath = join(
appPath,
'.next/server/app/sites/dynamic/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/page.js.nft.json'
);
const { files } = (await file(nftPath).json()) as { files: string[] };
let bytes = 0;
let shikiBytes = 0;
for (const relative of files) {
const size = (await stat(join(dirname(nftPath), relative))).size;
bytes += size;
if (/@shikijs\/(langs|themes)|shiki\/dist\/(langs|themes)/.test(relative)) {
shikiBytes += size;
}
}
return { bytes, shikiBytes, count: files.length };
}
async function measureNext() {
const client = await measureFiles(join(appPath, '.next/static/chunks'), '**/*.js');
const server = await measureFiles(join(appPath, '.next/server'), '**/*.js');
const serverAll = await measureFiles(join(appPath, '.next/server'), '**/*');
const trace = await measurePageTrace();
return {
pageTraceBytes: trace.bytes,
pageTraceFiles: trace.count,
pageTraceShikiAssetBytes: trace.shikiBytes,
clientChunksBytes: client.bytes,
clientChunksCount: client.count,
clientGrammarChunksBytes: client.grammarBytes,
clientGrammarChunksCount: client.grammarCount,
serverBytes: serverAll.bytes,
serverGrammarBytes: server.grammarBytes,
serverGrammarFiles: server.grammarCount,
};
}
async function measureCloudflare() {
const handlerPath = join(
appPath,
'.open-next/server-functions/default/packages/gitbook/handler.mjs'
);
const metafile = (await file(`${handlerPath}.meta.json`).json()) as {
outputs: Record<string, { inputs: Record<string, { bytesInOutput: number }> }>;
};
const output = Object.values(metafile.outputs)[0];
if (!output) {
throw new Error('No output in handler metafile');
}
const shikiBytes = Object.entries(output.inputs).reduce(
(total, [path, input]) =>
path.includes('@shikijs/langs') || path.includes('@shikijs/themes')
? total + input.bytesInOutput
: total,
0
);
const dryRun =
await $`bunx wrangler deploy --dry-run --config openNext/customWorkers/defaultWrangler.jsonc --env dev`
.cwd(appPath)
.quiet()
.nothrow()
.text();
const upload = dryRun.match(/Total Upload: ([\d.]+) KiB \/ gzip: ([\d.]+) KiB/);
return {
handlerBytes: (await stat(handlerPath)).size,
handlerGzipBytes: gzipSync(await file(handlerPath).arrayBuffer()).byteLength,
shikiBytes,
uploadKiB: upload ? Number(upload[1]) : null,
uploadGzipKiB: upload ? Number(upload[2]) : null,
};
}
if (mode === 'next') {
console.log(JSON.stringify(await measureNext(), null, 2));
} else if (mode === 'cloudflare') {
console.log(JSON.stringify(await measureCloudflare(), null, 2));
} else {
throw new Error('Usage: bun scripts/measure-shiki-bundles.ts next|cloudflare');
}
@@ -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,
});
}
@@ -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 });
}
@@ -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,
});
}
@@ -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 });
}
@@ -23,8 +23,6 @@ export type ClientBlockProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'st
evaluateInlineExpression?: (expression: string) => string;
mode: BlockProps<DocumentBlockCode>['context']['mode'];
themes?: CustomizationThemedCodeTheme;
/** Base URL of `~gitbook/static`, where the Shiki assets are loaded from. */
staticAssetsURL: string;
embedded?: boolean;
/** Node key for comments, set only where commenting is possible. */
commentKey?: string;
@@ -37,17 +35,8 @@ export const CODE_BLOCK_DEFAULT_COLLAPSED_LINE_COUNT = 10;
* It allows us to defer some load to avoid blocking the rendering of the whole page with block highlighting.
*/
export function ClientCodeBlock(props: ClientBlockProps) {
const {
block,
mode,
style,
inlines,
evaluateInlineExpression,
themes,
staticAssetsURL,
embedded,
commentKey,
} = props;
const { block, mode, style, inlines, evaluateInlineExpression, themes, embedded, commentKey } =
props;
const blockRef = useRef<HTMLDivElement>(null);
const isInViewportRef = useRef(false);
const [isInViewport, setIsInViewport] = useState(false);
@@ -61,10 +50,8 @@ export function ClientCodeBlock(props: ClientBlockProps) {
// Preload the highlighter when the block is mounted.
useEffect(() => {
import('./highlight-client').then(({ getClientHighlight }) =>
getClientHighlight(staticAssetsURL).preloadHighlight(block, themes)
);
}, [block, themes, staticAssetsURL]);
import('./highlight').then(({ preloadHighlight }) => preloadHighlight(block, themes));
}, [block, themes]);
// When user scrolls, we need to wait for the scroll to finish before running the highlight
const isScrollingRef = useRef(false);
@@ -112,8 +99,7 @@ export function ClientCodeBlock(props: ClientBlockProps) {
if (typeof window !== 'undefined') {
setHighlighting(true);
import('./highlight-client').then(({ getClientHighlight }) => {
const { highlight } = getClientHighlight(staticAssetsURL);
import('./highlight').then(({ highlight }) => {
highlight(block, inlines, { evaluateInlineExpression, themes }).then(
(theme) => {
if (cancelled) {
@@ -134,7 +120,7 @@ export function ClientCodeBlock(props: ClientBlockProps) {
// Otherwise if the block is not in viewport, we reset to the plain lines
setTheme(null);
}, [isInViewport, block, inlines, evaluateInlineExpression, themes, staticAssetsURL]);
}, [isInViewport, block, inlines, evaluateInlineExpression, themes]);
const expandable = block.data.expandable;
@@ -15,9 +15,8 @@ export function ClientPlainCodeBlock(props: {
syntax: string;
mode?: DocumentContext['mode'];
themes?: CustomizationThemedCodeTheme;
staticAssetsURL: string;
}) {
const { code, syntax, mode = 'default', themes, staticAssetsURL } = props;
const { code, syntax, mode = 'default', themes } = props;
const id = useId();
const block = convertCodeStringToBlock({ key: id, code, syntax });
@@ -29,7 +28,6 @@ export function ClientPlainCodeBlock(props: {
inlineExprVariables={{}}
mode={mode}
themes={themes}
staticAssetsURL={staticAssetsURL}
/>
);
}
@@ -122,7 +122,6 @@ export async function CodeBlock(
inlineExprVariables: variables,
mode: context.mode,
themes,
staticAssetsURL: getAssetURL(''),
embedded,
...getCommentKeyProp(context, block.key),
};
@@ -1,61 +0,0 @@
import { afterAll, describe, expect, it } from 'bun:test';
import { join } from 'node:path';
import { getClientHighlight } from './highlight-client';
import { getShikiGrammarAssetPath } from './shiki-catalog';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
const requested: string[] = [];
// Stands in for the CDN serving `~gitbook/static`.
const server = Bun.serve({
port: 0,
fetch(request) {
const { pathname } = new URL(request.url);
requested.push(pathname);
const prefix = '/~gitbook/static/';
if (!pathname.startsWith(prefix)) {
return new Response('not found', { status: 404 });
}
const file = Bun.file(join(staticDir, pathname.slice(prefix.length)));
return new Response(file);
},
});
afterAll(() => server.stop(true));
const jsBlock = {
object: 'block',
type: 'code',
data: { syntax: 'javascript' },
nodes: [
{
object: 'block',
type: 'code-line',
data: {},
nodes: [
{ object: 'text', leaves: [{ object: 'leaf', marks: [], text: 'const a = 1;' }] },
],
},
],
} as never;
describe('getClientHighlight', () => {
it('fetches assets relative to the given static assets URL', async () => {
const { highlight } = getClientHighlight(`${server.url}~gitbook/static/`);
const result = await highlight(jsBlock, []);
expect(result.lines[0]?.tokens.some((token) => token.type === 'shiki')).toBe(true);
expect(requested).toContain(`/~gitbook/static/${getShikiGrammarAssetPath('javascript')}`);
});
it('reuses one highlighter per assets URL', () => {
const url = `${server.url}~gitbook/static/`;
expect(getClientHighlight(url)).toBe(getClientHighlight(url));
});
it('falls back to plain when the assets host answers an error', async () => {
const { highlight } = getClientHighlight(`${server.url}missing/`);
const result = await highlight(jsBlock, []);
expect(result.lines[0]?.tokens.map((token) => token.type)).toEqual(['plain']);
});
});
@@ -1,23 +0,0 @@
import { createHighlight } from './highlighter';
import { joinPathWithBaseURL } from '@/lib/paths';
const highlighters = new Map<string, ReturnType<typeof createHighlight>>();
/**
* Highlighting functions for the browser, loading Shiki assets from the static assets URL.
* The URL comes from the server because the client build doesn't know the runtime assets host.
*/
export function getClientHighlight(staticAssetsURL: string) {
let highlighter = highlighters.get(staticAssetsURL);
if (!highlighter) {
highlighter = createHighlight(async (path) => {
const response = await fetch(joinPathWithBaseURL(staticAssetsURL, path));
if (!response.ok) {
throw new Error(`Failed to fetch ${path}: ${response.status}`);
}
return response.json();
});
highlighters.set(staticAssetsURL, highlighter);
}
return highlighter;
}
@@ -1,7 +1,178 @@
import { createHighlight } from './highlighter';
import { loadShikiAssetOnServer } from './shiki-assets.server';
import { createSingletonShorthands, createdBundledHighlighter } from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import { type BundledLanguage, bundledLanguages } from 'shiki/langs';
import { bundledThemes } from 'shiki/themes';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
import {
DEFAULT_THEMES,
type HighlightTheme,
type HighlightToken,
type PositionedToken,
type RenderedInline,
getPlainCodeBlock,
matchTokenAndInlines,
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { plainHighlight } from './plain-highlight';
export * from './highlight-tokens';
export { getLanguageForSyntax } from './highlighter';
export const { highlight, preloadHighlight } = createHighlight(loadShikiAssetOnServer);
// Merge bundled Shiki themes with our custom themes so both are available to the highlighter
const { getSingletonHighlighter } = createSingletonShorthands(
createdBundledHighlighter<any, any>({
langs: bundledLanguages,
themes: { ...bundledThemes, ...customThemes },
engine: () => createJavaScriptRegexEngine({ forgiving: true, target: 'ES2018' }),
})
);
/**
* Preload the highlighter for a code block.
*/
export async function preloadHighlight(
block: DocumentBlockCode,
themes: CustomizationThemedCodeTheme = DEFAULT_THEMES
) {
const langName = getBlockLang(block);
if (langName) {
await getSingletonHighlighter({
langs: [langName],
themes: [themes.light, themes.dark],
});
}
}
/**
* Highlight a code block while preserving inline elements.
*/
export async function highlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
options?: {
evaluateInlineExpression?: (expr: string) => string;
themes?: CustomizationThemedCodeTheme;
}
): Promise<HighlightTheme> {
const langName = getBlockLang(block);
if (!langName) {
// Fallback to plain highlighting if language is not found
return plainHighlight(block, inlines, options);
}
const themes = options?.themes ?? DEFAULT_THEMES;
const code = getPlainCodeBlock(block, undefined, options);
const highlighter = await getSingletonHighlighter({
langs: [langName],
themes: [themes.light, themes.dark],
});
const resolvedThemes = {
light: highlighter.getTheme(themes.light),
dark: highlighter.getTheme(themes.dark),
};
let tokenizeMaxLineLength = 400;
// In some cases, people will use unindented code blocks with a single line.
// In this case, we can safely increase the max line length to avoid not highlighting the code.
if (block.nodes.length === 1) {
tokenizeMaxLineLength = 5000;
}
const result = highlighter.codeToTokens(code, {
lang: langName,
themes: resolvedThemes,
// Shiki's light-dark() CSS function provides different colors for light/dark modes based on the resolved themes
defaultColor: 'light-dark()',
tokenizeMaxLineLength,
});
const lines = result.tokens;
let currentIndex = 0;
return {
bg: result.bg,
fg: result.fg,
themes: resolvedThemes,
lines: lines.map((tokens, index) => {
const lineBlock = block.nodes[index];
const result: HighlightToken[] = [];
const lineText = tokens.map((token) => token.content).join('');
const notation = parseDiffNotation(lineText);
const eatToken = (): PositionedToken | null => {
const token = tokens.shift();
if (token) {
currentIndex += token.content.length;
}
return token
? { ...token, start: currentIndex - token.content.length, end: currentIndex }
: null;
};
while (tokens.length > 0) {
result.push(...matchTokenAndInlines(eatToken, inlines));
}
currentIndex += 1; // for the \n
const finalTokens = notation
? truncateHighlightTokens(result, notation.markerStart)
: result;
return {
highlighted: Boolean(lineBlock?.data.highlighted),
diff: notation?.diff ?? null,
tokens: finalTokens,
};
}),
};
}
/**
* Get the language of a code block.
*/
function getBlockLang(block: DocumentBlockCode): string | null {
return block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
}
const syntaxAliases: Record<string, BundledLanguage> = {
// "Parser" language does not exist in Shiki, but it's used in GitBook
// The closest language is "Blade"
parser: 'blade',
// From GitBook App we receive "objectivec" instead of "objective-c"
objectivec: 'objective-c',
};
function checkIsBundledLanguage(lang: string): lang is BundledLanguage {
return lang in bundledLanguages;
}
/**
* Validate a language name.
*/
function getLanguageForSyntax(syntax: string): BundledLanguage | null {
// Normalize the syntax to lowercase.
syntax = syntax.toLowerCase();
// Check if the syntax is a bundled language.
if (checkIsBundledLanguage(syntax)) {
return syntax;
}
// Check if there is a valid alias for the syntax.
const alias = syntaxAliases[syntax];
if (alias && checkIsBundledLanguage(alias)) {
return alias;
}
return null;
}
@@ -1,109 +0,0 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { DocumentBlockCode } from '@gitbook/api';
import type { HighlightTheme } from './highlight-tokens';
import { type ShikiAssetLoader, createHighlight } from './highlighter';
import { getShikiGrammarAssetPath } from './shiki-catalog';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
let calls: Map<string, number>;
const readAsset: ShikiAssetLoader = async (path) =>
JSON.parse(await readFile(join(staticDir, path), 'utf8'));
const countingLoader: ShikiAssetLoader = async (path) => {
calls.set(path, (calls.get(path) ?? 0) + 1);
return readAsset(path);
};
beforeEach(() => {
calls = new Map();
});
function codeBlock(syntax: string, code: string): DocumentBlockCode {
return {
object: 'block',
type: 'code',
data: { syntax },
nodes: code.split('\n').map((text) => ({
object: 'block',
type: 'code-line',
data: {},
nodes: [{ object: 'text', leaves: [{ object: 'leaf', marks: [], text }] }],
})),
} as DocumentBlockCode;
}
const jsBlock = codeBlock('javascript', 'const answer = 42;');
function isHighlighted(result: HighlightTheme) {
return result.lines.some((line) => line.tokens.some((token) => token.type === 'shiki'));
}
function colorOf(result: HighlightTheme, content: string) {
for (const line of result.lines) {
for (const token of line.tokens) {
if (token.type === 'shiki' && token.token.content.trim() === content) {
// light-dark() output puts the colour in htmlStyle rather than color.
const style = token.token.htmlStyle;
return typeof style === 'object' ? style.color : undefined;
}
}
}
return undefined;
}
describe('createHighlight', () => {
it('loads each grammar once under concurrency', async () => {
const { highlight } = createHighlight(countingLoader);
const results = await Promise.all(Array.from({ length: 10 }, () => highlight(jsBlock, [])));
expect(results.every(isHighlighted)).toBe(true);
expect(calls.get(getShikiGrammarAssetPath('javascript'))).toBe(1);
});
it('falls back to plain highlighting and retries after a failure', async () => {
let failed = false;
const failOnceLoader: ShikiAssetLoader = async (path) => {
if (!failed && path === getShikiGrammarAssetPath('javascript')) {
failed = true;
throw new Error('asset unavailable');
}
return readAsset(path);
};
const { highlight } = createHighlight(failOnceLoader);
const first = await highlight(jsBlock, []);
expect(isHighlighted(first)).toBe(false);
expect(first.lines[0]?.tokens.map((token) => token.type)).toEqual(['plain']);
const second = await highlight(jsBlock, []);
expect(isHighlighted(second)).toBe(true);
});
it('highlights embedded languages', async () => {
const { highlight } = createHighlight(countingLoader);
const result = await highlight(
codeBlock('vue', '<template><p>hi</p></template>\n<script>\nconst msg = 1;\n</script>'),
[]
);
const keywordColor = colorOf(result, 'const');
expect(keywordColor).toBeDefined();
expect(keywordColor).not.toBe(colorOf(result, 'msg'));
});
it('loads custom themes from code, not from assets', async () => {
const { highlight } = createHighlight(countingLoader);
const result = await highlight(jsBlock, [], {
themes: { light: 'default-light', dark: 'github-dark' } as never,
});
expect(isHighlighted(result)).toBe(true);
expect([...calls.keys()].some((path) => path.includes('default-light'))).toBe(false);
expect([...calls.keys()].some((path) => path.endsWith('themes/github-dark.json'))).toBe(
true
);
});
});
@@ -1,247 +0,0 @@
import {
type HighlighterCore,
type LanguageRegistration,
type ThemeRegistrationAny,
createHighlighterCore,
} from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
import {
DEFAULT_THEMES,
type HighlightTheme,
type HighlightToken,
type PositionedToken,
type RenderedInline,
getPlainCodeBlock,
matchTokenAndInlines,
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { plainHighlight } from './plain-highlight';
import {
SHIKI_LANGUAGES,
SHIKI_LANGUAGE_GRAMMARS,
getShikiGrammarAssetPath,
getShikiThemeAssetPath,
} from './shiki-catalog';
import { SHIKI_THEMES } from './shiki-themes';
/**
* Read a Shiki asset (grammar or theme JSON) from its path relative to `~gitbook/static`.
*/
export type ShikiAssetLoader = (path: string) => Promise<unknown>;
// Syntaxes sent by GitBook that are not Shiki ids or aliases.
const syntaxAliases: Record<string, string> = {
// "Parser" language does not exist in Shiki, but it's used in GitBook
// The closest language is "Blade"
parser: 'blade',
// From GitBook App we receive "objectivec" instead of "objective-c"
objectivec: 'objective-c',
};
/**
* Resolve a code block syntax to a canonical Shiki language id.
*/
export function getLanguageForSyntax(syntax: string): string | null {
const normalized = syntax.toLowerCase();
return SHIKI_LANGUAGES[normalized] ?? SHIKI_LANGUAGES[syntaxAliases[normalized] ?? ''] ?? null;
}
function getBlockLang(block: DocumentBlockCode): string | null {
return block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
}
/**
* Create the highlighting functions, loading grammars and themes on demand through `loadAsset`.
*/
export function createHighlight(loadAsset: ShikiAssetLoader) {
let highlighterPromise: Promise<HighlighterCore> | null = null;
const pending = new Map<string, Promise<unknown>>();
// Share in-flight and finished loads; forget failures so a later render retries.
function once<T>(key: string, load: () => Promise<T>): Promise<T> {
let promise = pending.get(key) as Promise<T> | undefined;
if (!promise) {
promise = load();
pending.set(key, promise);
promise.catch(() => pending.delete(key));
}
return promise;
}
function getHighlighter() {
highlighterPromise ??= createHighlighterCore({
engine: createJavaScriptRegexEngine({ forgiving: true, target: 'ES2018' }),
});
return highlighterPromise;
}
function loadLanguage(highlighter: HighlighterCore, lang: string) {
return once(`lang:${lang}`, async () => {
const names = SHIKI_LANGUAGE_GRAMMARS[lang];
if (!names) {
throw new Error(`Unknown language "${lang}"`);
}
const grammars = await Promise.all(
names.map(
(name) =>
once(`grammar:${name}`, () =>
loadAsset(getShikiGrammarAssetPath(name))
) as Promise<LanguageRegistration>
)
);
const loaded = new Set(highlighter.getLoadedLanguages());
await highlighter.loadLanguage(
...grammars.filter((grammar) => !loaded.has(grammar.name))
);
});
}
function loadTheme(highlighter: HighlighterCore, theme: string) {
return once(`theme:${theme}`, async () => {
const custom = customThemes[theme];
if (custom) {
await highlighter.loadTheme(custom);
return;
}
if (!SHIKI_THEMES[theme]) {
throw new Error(`Unknown theme "${theme}"`);
}
await highlighter.loadTheme(
(await loadAsset(getShikiThemeAssetPath(theme))) as ThemeRegistrationAny
);
});
}
async function loadHighlighter(lang: string, themes: CustomizationThemedCodeTheme) {
const highlighter = await getHighlighter();
await Promise.all([
loadLanguage(highlighter, lang),
loadTheme(highlighter, themes.light),
loadTheme(highlighter, themes.dark),
]);
return highlighter;
}
/**
* Preload the highlighter for a code block.
*/
async function preloadHighlight(
block: DocumentBlockCode,
themes: CustomizationThemedCodeTheme = DEFAULT_THEMES
) {
const langName = getBlockLang(block);
if (langName) {
await loadHighlighter(langName, themes).catch(() => {
// Rendering retries and reports the failure.
});
}
}
/**
* Highlight a code block while preserving inline elements.
*/
async function highlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
options?: {
evaluateInlineExpression?: (expr: string) => string;
themes?: CustomizationThemedCodeTheme;
}
): Promise<HighlightTheme> {
const langName = getBlockLang(block);
if (!langName) {
// Fallback to plain highlighting if language is not found
return plainHighlight(block, inlines, options);
}
const themes = options?.themes ?? DEFAULT_THEMES;
const code = getPlainCodeBlock(block, undefined, options);
let highlighter: HighlighterCore;
try {
highlighter = await loadHighlighter(langName, themes);
} catch (error) {
console.error(
`Failed to load the "${langName}" highlighter, falling back to plain`,
error
);
return plainHighlight(block, inlines, options);
}
const resolvedThemes = {
light: highlighter.getTheme(themes.light),
dark: highlighter.getTheme(themes.dark),
};
let tokenizeMaxLineLength = 400;
// In some cases, people will use unindented code blocks with a single line.
// In this case, we can safely increase the max line length to avoid not highlighting the code.
if (block.nodes.length === 1) {
tokenizeMaxLineLength = 5000;
}
const result = highlighter.codeToTokens(code, {
lang: langName,
themes: resolvedThemes,
// Shiki's light-dark() CSS function provides different colors for light/dark modes based on the resolved themes
defaultColor: 'light-dark()',
tokenizeMaxLineLength,
});
const lines = result.tokens;
let currentIndex = 0;
return {
bg: result.bg,
fg: result.fg,
themes: resolvedThemes,
lines: lines.map((tokens, index) => {
const lineBlock = block.nodes[index];
const result: HighlightToken[] = [];
const lineText = tokens.map((token) => token.content).join('');
const notation = parseDiffNotation(lineText);
const eatToken = (): PositionedToken | null => {
const token = tokens.shift();
if (token) {
currentIndex += token.content.length;
}
return token
? {
...token,
start: currentIndex - token.content.length,
end: currentIndex,
}
: null;
};
while (tokens.length > 0) {
result.push(...matchTokenAndInlines(eatToken, inlines));
}
currentIndex += 1; // for the \n
const finalTokens = notation
? truncateHighlightTokens(result, notation.markerStart)
: result;
return {
highlighted: Boolean(lineBlock?.data.highlighted),
diff: notation?.diff ?? null,
tokens: finalTokens,
};
}),
};
}
return { highlight, preloadHighlight };
}
@@ -1,3 +1,5 @@
import { bundledThemesInfo } from 'shiki/themes';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
@@ -9,7 +11,6 @@ import {
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { SHIKI_THEMES } from './shiki-themes';
import { getNodeText } from '@/lib/document';
/**
@@ -28,11 +29,11 @@ export function plainHighlight(
// Resolve theme objects: first check bundled Shiki themes, then custom themes, finally fallback to type-only
// The type-only fallback ensures HighlightTheme always has valid theme objects even when theme names don't match
const themes = {
light: getBundledThemeInfo(options?.themes?.light) ??
light: bundledThemesInfo.find((theme) => theme.id === options?.themes?.light) ??
Object.values(customThemes).find((theme) => theme.name === options?.themes?.light) ?? {
type: 'light',
},
dark: getBundledThemeInfo(options?.themes?.dark) ??
dark: bundledThemesInfo.find((theme) => theme.id === options?.themes?.dark) ??
Object.values(customThemes).find((theme) => theme.name === options?.themes?.dark) ?? {
type: 'dark',
},
@@ -81,8 +82,3 @@ export function plainHighlight(
}),
};
}
function getBundledThemeInfo(name: string | undefined) {
const info = name ? SHIKI_THEMES[name] : undefined;
return info ? { name, type: info.type } : undefined;
}
@@ -1,40 +0,0 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { ShikiAssetLoader } from './highlighter';
import { getCloudflareContext } from '@/lib/data/cloudflare';
const SHIKI_PREFIX = 'shiki/';
/**
* Read a Shiki asset on the server without a network hop.
*/
export const loadShikiAssetOnServer: ShikiAssetLoader = async (path) => {
if (!path.startsWith(SHIKI_PREFIX)) {
throw new Error(`Not a Shiki asset: ${path}`);
}
const cloudflare = getCloudflareContext();
if (cloudflare) {
const assets = cloudflare.env.ASSETS;
if (!assets) {
throw new Error('The ASSETS binding is missing on this worker');
}
// The host is ignored by the assets binding, only the path matters.
const response = await assets.fetch(
new URL(`/~gitbook/static/${path}`, 'https://assets.local')
);
if (!response.ok) {
throw new Error(`Failed to read ${path} from assets: ${response.status}`);
}
return response.json();
}
// Keep `shiki` in the literal so file tracing only pulls this folder, not all of `static`.
const file = join(
process.cwd(),
'public/~gitbook/static/shiki',
path.slice(SHIKI_PREFIX.length)
);
return JSON.parse(await readFile(file, 'utf8'));
};
@@ -1,69 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { join } from 'node:path';
import { getLanguageForSyntax } from './highlight';
import {
SHIKI_ASSETS_PATH,
SHIKI_LANGUAGES,
SHIKI_LANGUAGE_GRAMMARS,
getShikiGrammarAssetPath,
getShikiThemeAssetPath,
} from './shiki-catalog';
import { SHIKI_THEMES } from './shiki-themes';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
describe('shiki catalog', () => {
it('maps ids and aliases to canonical ids', () => {
expect(SHIKI_LANGUAGES.javascript).toBe('javascript');
expect(SHIKI_LANGUAGES.js).toBe('javascript');
expect(SHIKI_LANGUAGES['objective-c']).toBe('objective-c');
});
it('lists embedded grammars before the language grammar', () => {
const vue = SHIKI_LANGUAGE_GRAMMARS.vue ?? [];
expect(vue.at(-1)).toBe('vue');
expect(vue).toEqual(expect.arrayContaining(['html', 'css', 'javascript']));
});
it('writes one JSON file per grammar, including internal ones', async () => {
const grammar = await Bun.file(
join(staticDir, getShikiGrammarAssetPath('cpp-macro'))
).json();
expect(grammar.name).toBe('cpp-macro');
expect(grammar.scopeName).toBeString();
});
it('writes every bundled theme', async () => {
expect(SHIKI_THEMES['github-dark']?.type).toBe('dark');
expect(
await Bun.file(join(staticDir, getShikiThemeAssetPath('github-dark'))).exists()
).toBe(true);
});
});
describe('shiki assets path', () => {
it('changes with the generated content, not only the shiki version', () => {
// Assets are served immutable, so a format change must move them to a new URL.
expect(SHIKI_ASSETS_PATH).toMatch(/^shiki\/\d+\.\d+\.\d+-[0-9a-f]{8}$/);
});
});
describe('client bundle', () => {
it('keeps the language catalog out of plain highlighting', async () => {
// plain-highlight is in the eager ClientCodeBlock chunk; only theme types are needed there.
const source = await Bun.file(join(import.meta.dir, 'plain-highlight.ts')).text();
expect(source).not.toContain("'./shiki-catalog'");
expect(source).toContain("'./shiki-themes'");
});
});
describe('getLanguageForSyntax', () => {
it('resolves GitBook syntaxes to canonical ids', () => {
expect(getLanguageForSyntax('JSON')).toBe('json');
expect(getLanguageForSyntax('js')).toBe('javascript');
expect(getLanguageForSyntax('objectivec')).toBe('objective-c');
expect(getLanguageForSyntax('parser')).toBe('blade');
expect(getLanguageForSyntax('not-a-language')).toBeNull();
});
});
@@ -1,902 +0,0 @@
// Generated by scripts/generate-shiki-assets.ts, do not edit.
export const SHIKI_ASSETS_PATH = 'shiki/3.21.0-f9eb29ba';
/** Every Shiki language id and alias, mapped to the id of its asset. */
export const SHIKI_LANGUAGES: Record<string, string> = {
'1c': 'bsl',
'1c-query': 'sdbl',
abap: 'abap',
'actionscript-3': 'actionscript-3',
ada: 'ada',
adoc: 'asciidoc',
'angular-html': 'angular-html',
'angular-ts': 'angular-ts',
apache: 'apache',
apex: 'apex',
apl: 'apl',
applescript: 'applescript',
ara: 'ara',
asciidoc: 'asciidoc',
asm: 'asm',
astro: 'astro',
awk: 'awk',
ballerina: 'ballerina',
bash: 'shellscript',
bat: 'bat',
batch: 'bat',
be: 'berry',
beancount: 'beancount',
berry: 'berry',
bibtex: 'bibtex',
bicep: 'bicep',
blade: 'blade',
bsl: 'bsl',
c: 'c',
'c#': 'csharp',
'c++': 'cpp',
c3: 'c3',
cadence: 'cadence',
cairo: 'cairo',
cdc: 'cadence',
cjs: 'javascript',
clarity: 'clarity',
clj: 'clojure',
clojure: 'clojure',
'closure-templates': 'soy',
cmake: 'cmake',
cmd: 'vb',
cobol: 'cobol',
codeowners: 'codeowners',
codeql: 'codeql',
coffee: 'coffee',
coffeescript: 'coffee',
'common-lisp': 'common-lisp',
console: 'shellsession',
coq: 'coq',
cpp: 'cpp',
cql: 'cypher',
crystal: 'crystal',
cs: 'csharp',
csharp: 'csharp',
css: 'css',
csv: 'csv',
cts: 'typescript',
cue: 'cue',
cypher: 'cypher',
d: 'd',
dart: 'dart',
dax: 'dax',
desktop: 'desktop',
diff: 'diff',
docker: 'docker',
dockerfile: 'docker',
dotenv: 'dotenv',
'dream-maker': 'dream-maker',
edge: 'edge',
elisp: 'emacs-lisp',
elixir: 'elixir',
elm: 'elm',
'emacs-lisp': 'emacs-lisp',
erb: 'erb',
erl: 'erlang',
erlang: 'erlang',
f: 'fortran-fixed-form',
'f#': 'fsharp',
f03: 'fortran-free-form',
f08: 'fortran-free-form',
f18: 'fortran-free-form',
f77: 'fortran-fixed-form',
f90: 'fortran-free-form',
f95: 'fortran-free-form',
fennel: 'fennel',
fish: 'fish',
fluent: 'fluent',
for: 'fortran-fixed-form',
'fortran-fixed-form': 'fortran-fixed-form',
'fortran-free-form': 'fortran-free-form',
fs: 'fsharp',
fsharp: 'fsharp',
fsl: 'jssm',
ftl: 'fluent',
gdresource: 'gdresource',
gdscript: 'gdscript',
gdshader: 'gdshader',
genie: 'genie',
gherkin: 'gherkin',
'git-commit': 'git-commit',
'git-rebase': 'git-rebase',
gjs: 'glimmer-js',
gleam: 'gleam',
'glimmer-js': 'glimmer-js',
'glimmer-ts': 'glimmer-ts',
glsl: 'glsl',
gn: 'gn',
gnuplot: 'gnuplot',
go: 'go',
gql: 'graphql',
graphql: 'graphql',
groovy: 'groovy',
gts: 'glimmer-ts',
hack: 'hack',
haml: 'haml',
handlebars: 'handlebars',
haskell: 'haskell',
haxe: 'haxe',
hbs: 'handlebars',
hcl: 'hcl',
hjson: 'hjson',
hlsl: 'hlsl',
hs: 'haskell',
html: 'html',
'html-derivative': 'html-derivative',
http: 'http',
hurl: 'hurl',
hxml: 'hxml',
hy: 'hy',
imba: 'imba',
ini: 'ini',
jade: 'pug',
java: 'java',
javascript: 'javascript',
jinja: 'jinja',
jison: 'jison',
jl: 'julia',
js: 'javascript',
json: 'json',
json5: 'json5',
jsonc: 'jsonc',
jsonl: 'jsonl',
jsonnet: 'jsonnet',
jssm: 'jssm',
jsx: 'jsx',
julia: 'julia',
kdl: 'kdl',
kotlin: 'kotlin',
kql: 'kusto',
kt: 'kotlin',
kts: 'kotlin',
kusto: 'kusto',
latex: 'latex',
lean: 'lean',
lean4: 'lean',
less: 'less',
liquid: 'liquid',
lisp: 'common-lisp',
lit: 'ts-tags',
llvm: 'llvm',
log: 'log',
logo: 'logo',
lua: 'lua',
luau: 'luau',
make: 'make',
makefile: 'make',
markdown: 'markdown',
marko: 'marko',
matlab: 'matlab',
mbt: 'moonbit',
mbti: 'moonbit',
md: 'markdown',
mdc: 'mdc',
mdx: 'mdx',
mediawiki: 'wikitext',
mermaid: 'mermaid',
mips: 'mipsasm',
mipsasm: 'mipsasm',
mjs: 'javascript',
mmd: 'mermaid',
mojo: 'mojo',
moonbit: 'moonbit',
move: 'move',
mts: 'typescript',
nar: 'narrat',
narrat: 'narrat',
nextflow: 'nextflow',
nf: 'nextflow',
nginx: 'nginx',
nim: 'nim',
nix: 'nix',
nu: 'nushell',
nushell: 'nushell',
objc: 'objective-c',
'objective-c': 'objective-c',
'objective-cpp': 'objective-cpp',
ocaml: 'ocaml',
openscad: 'openscad',
pascal: 'pascal',
perl: 'perl',
perl6: 'raku',
php: 'php',
pkl: 'pkl',
plsql: 'plsql',
po: 'po',
polar: 'polar',
postcss: 'postcss',
pot: 'po',
potx: 'po',
powerquery: 'powerquery',
powershell: 'powershell',
prisma: 'prisma',
prolog: 'prolog',
properties: 'ini',
proto: 'proto',
protobuf: 'proto',
ps: 'powershell',
ps1: 'powershell',
pug: 'pug',
puppet: 'puppet',
purescript: 'purescript',
py: 'python',
python: 'python',
ql: 'codeql',
qml: 'qml',
qmldir: 'qmldir',
qss: 'qss',
r: 'r',
racket: 'racket',
raku: 'raku',
razor: 'razor',
rb: 'ruby',
reg: 'reg',
regex: 'regexp',
regexp: 'regexp',
rel: 'rel',
riscv: 'riscv',
rosmsg: 'rosmsg',
rs: 'rust',
rst: 'rst',
ruby: 'ruby',
rust: 'rust',
sas: 'sas',
sass: 'sass',
scad: 'openscad',
scala: 'scala',
scheme: 'scheme',
scss: 'scss',
sdbl: 'sdbl',
sh: 'shellscript',
shader: 'shaderlab',
shaderlab: 'shaderlab',
shell: 'shellscript',
shellscript: 'shellscript',
shellsession: 'shellsession',
smalltalk: 'smalltalk',
solidity: 'solidity',
soy: 'soy',
sparql: 'sparql',
spl: 'splunk',
splunk: 'splunk',
sql: 'sql',
'ssh-config': 'ssh-config',
stata: 'stata',
styl: 'stylus',
stylus: 'stylus',
svelte: 'svelte',
swift: 'swift',
'system-verilog': 'system-verilog',
systemd: 'systemd',
talon: 'talonscript',
talonscript: 'talonscript',
tasl: 'tasl',
tcl: 'tcl',
templ: 'templ',
terraform: 'terraform',
tex: 'tex',
tf: 'terraform',
tfvars: 'terraform',
toml: 'toml',
ts: 'typescript',
'ts-tags': 'ts-tags',
tsp: 'typespec',
tsv: 'tsv',
tsx: 'tsx',
turtle: 'turtle',
twig: 'twig',
typ: 'typst',
typescript: 'typescript',
typespec: 'typespec',
typst: 'typst',
v: 'v',
vala: 'vala',
vb: 'vb',
verilog: 'verilog',
vhdl: 'vhdl',
vim: 'viml',
viml: 'viml',
vimscript: 'viml',
vue: 'vue',
'vue-html': 'vue-html',
'vue-vine': 'vue-vine',
vy: 'vyper',
vyper: 'vyper',
wasm: 'wasm',
wenyan: 'wenyan',
wgsl: 'wgsl',
wiki: 'wikitext',
wikitext: 'wikitext',
wit: 'wit',
wl: 'wolfram',
wolfram: 'wolfram',
xml: 'xml',
xsl: 'xsl',
yaml: 'yaml',
yml: 'yaml',
zenscript: 'zenscript',
zig: 'zig',
zsh: 'shellscript',
文言: 'wenyan',
};
/** Grammars to register for each language, embedded ones first. */
export const SHIKI_LANGUAGE_GRAMMARS: Record<string, string[]> = {
abap: ['abap'],
'actionscript-3': ['actionscript-3'],
ada: ['ada'],
'angular-html': [
'javascript',
'css',
'html',
'angular-expression',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-html',
],
'angular-ts': [
'angular-expression',
'css',
'scss',
'angular-inline-style',
'javascript',
'css',
'html',
'angular-expression',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-html',
'angular-expression',
'angular-template',
'angular-inline-template',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-ts',
],
apache: ['apache'],
apex: ['apex'],
apl: ['javascript', 'css', 'html', 'java', 'xml', 'css', 'javascript', 'json', 'apl'],
applescript: ['applescript'],
ara: ['ara'],
asciidoc: ['asciidoc'],
asm: ['asm'],
astro: ['json', 'javascript', 'typescript', 'css', 'postcss', 'tsx', 'astro'],
awk: ['awk'],
ballerina: ['ballerina'],
bat: ['bat'],
beancount: ['beancount'],
berry: ['berry'],
bibtex: ['bibtex'],
bicep: ['bicep'],
blade: [
'javascript',
'css',
'html',
'html-derivative',
'javascript',
'css',
'html',
'java',
'xml',
'sql',
'javascript',
'json',
'css',
'blade',
],
bsl: ['sdbl', 'bsl'],
c: ['c'],
c3: ['c3'],
cadence: ['cadence'],
cairo: ['python', 'cairo'],
clarity: ['clarity'],
clojure: ['clojure'],
cmake: ['cmake'],
cobol: ['javascript', 'css', 'html', 'java', 'cobol'],
codeowners: ['codeowners'],
codeql: ['codeql'],
coffee: ['javascript', 'coffee'],
'common-lisp': ['common-lisp'],
coq: ['coq'],
cpp: ['regexp', 'c', 'glsl', 'sql', 'cpp-macro', 'regexp', 'c', 'glsl', 'sql', 'cpp'],
crystal: [
'javascript',
'css',
'html',
'sql',
'css',
'c',
'javascript',
'shellscript',
'crystal',
],
csharp: ['csharp'],
css: ['css'],
csv: ['csv'],
cue: ['cue'],
cypher: ['cypher'],
d: ['d'],
dart: ['dart'],
dax: ['dax'],
desktop: ['desktop'],
diff: ['diff'],
docker: ['docker'],
dotenv: ['dotenv'],
'dream-maker': ['dream-maker'],
edge: [
'typescript',
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'html-derivative',
'edge',
],
elixir: ['javascript', 'css', 'html', 'elixir'],
elm: ['c', 'glsl', 'elm'],
'emacs-lisp': ['emacs-lisp'],
erb: [
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'erb',
],
erlang: ['markdown', 'erlang'],
fennel: ['fennel'],
fish: ['fish'],
fluent: ['fluent'],
'fortran-fixed-form': ['fortran-free-form', 'fortran-fixed-form'],
'fortran-free-form': ['fortran-free-form'],
fsharp: ['markdown', 'fsharp'],
gdresource: ['gdshader', 'gdscript', 'gdresource'],
gdscript: ['gdscript'],
gdshader: ['gdshader'],
genie: ['genie'],
gherkin: ['gherkin'],
'git-commit': ['diff', 'git-commit'],
'git-rebase': ['shellscript', 'git-rebase'],
gleam: ['gleam'],
'glimmer-js': ['javascript', 'typescript', 'css', 'javascript', 'css', 'html', 'glimmer-js'],
'glimmer-ts': ['typescript', 'css', 'javascript', 'javascript', 'css', 'html', 'glimmer-ts'],
glsl: ['c', 'glsl'],
gn: ['gn'],
gnuplot: ['gnuplot'],
go: ['go'],
graphql: ['javascript', 'typescript', 'jsx', 'tsx', 'graphql'],
groovy: ['groovy'],
hack: ['javascript', 'css', 'html', 'sql', 'hack'],
haml: ['javascript', 'css', 'haml'],
handlebars: ['javascript', 'css', 'html', 'css', 'javascript', 'yaml', 'handlebars'],
haskell: ['haskell'],
haxe: ['haxe'],
hcl: ['hcl'],
hjson: ['hjson'],
hlsl: ['hlsl'],
html: ['javascript', 'css', 'html'],
'html-derivative': ['javascript', 'css', 'html', 'html-derivative'],
http: [
'shellscript',
'json',
'java',
'xml',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'http',
],
hurl: ['javascript', 'typescript', 'jsx', 'tsx', 'graphql', 'java', 'xml', 'csv', 'hurl'],
hxml: ['haxe', 'hxml'],
hy: ['hy'],
imba: ['imba'],
ini: ['ini'],
java: ['java'],
javascript: ['javascript'],
jinja: ['javascript', 'css', 'html', 'jinja-html', 'jinja'],
jison: ['javascript', 'jison'],
json: ['json'],
json5: ['json5'],
jsonc: ['jsonc'],
jsonl: ['jsonl'],
jsonnet: ['jsonnet'],
jssm: ['jssm'],
jsx: ['jsx'],
julia: [
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'python',
'javascript',
'r',
'sql',
'julia',
],
kdl: ['kdl'],
kotlin: ['kotlin'],
kusto: ['kusto'],
latex: ['r', 'tex', 'latex'],
lean: ['lean'],
less: ['less'],
liquid: ['javascript', 'css', 'html', 'css', 'json', 'javascript', 'liquid'],
llvm: ['llvm'],
log: ['log'],
logo: ['logo'],
lua: ['c', 'lua'],
luau: ['luau'],
make: ['make'],
markdown: ['markdown'],
marko: ['css', 'less', 'css', 'scss', 'typescript', 'marko'],
matlab: ['matlab'],
mdc: ['markdown', 'yaml', 'javascript', 'css', 'html', 'html-derivative', 'mdc'],
mdx: ['mdx'],
mermaid: ['mermaid'],
mipsasm: ['mipsasm'],
mojo: ['mojo'],
moonbit: ['moonbit'],
move: ['move'],
narrat: ['narrat'],
nextflow: ['nextflow'],
nginx: ['c', 'lua', 'nginx'],
nim: [
'c',
'javascript',
'css',
'html',
'java',
'xml',
'javascript',
'css',
'c',
'glsl',
'markdown',
'nim',
],
nix: ['markdown-nix', 'nix'],
nushell: ['nushell'],
'objective-c': ['objective-c'],
'objective-cpp': ['objective-cpp'],
ocaml: ['ocaml'],
openscad: ['openscad'],
pascal: ['pascal'],
perl: ['javascript', 'css', 'html', 'java', 'xml', 'css', 'javascript', 'sql', 'perl'],
php: ['javascript', 'css', 'html', 'java', 'xml', 'sql', 'javascript', 'json', 'css', 'php'],
pkl: ['pkl'],
plsql: ['plsql'],
po: ['po'],
polar: ['polar'],
postcss: ['postcss'],
powerquery: ['powerquery'],
powershell: ['powershell'],
prisma: ['prisma'],
prolog: ['prolog'],
proto: ['proto'],
pug: ['javascript', 'css', 'javascript', 'css', 'html', 'pug'],
puppet: ['puppet'],
purescript: ['purescript'],
python: ['python'],
qml: ['javascript', 'qml'],
qmldir: ['qmldir'],
qss: ['qss'],
r: ['r'],
racket: ['racket'],
raku: ['raku'],
razor: ['javascript', 'css', 'html', 'csharp', 'razor'],
reg: ['reg'],
regexp: ['regexp'],
rel: ['rel'],
riscv: ['riscv'],
rosmsg: ['rosmsg'],
rst: [
'javascript',
'css',
'html',
'html-derivative',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'python',
'javascript',
'shellscript',
'yaml',
'cmake',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'rst',
],
ruby: [
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
],
rust: ['rust'],
sas: ['sql', 'sas'],
sass: ['sass'],
scala: ['scala'],
scheme: ['scheme'],
scss: ['css', 'scss'],
sdbl: ['sdbl'],
shaderlab: ['hlsl', 'shaderlab'],
shellscript: ['shellscript'],
shellsession: ['shellscript', 'shellsession'],
smalltalk: ['smalltalk'],
solidity: ['solidity'],
soy: ['javascript', 'css', 'html', 'soy'],
sparql: ['turtle', 'sparql'],
splunk: ['splunk'],
sql: ['sql'],
'ssh-config': ['ssh-config'],
stata: ['sql', 'stata'],
stylus: ['stylus'],
svelte: ['javascript', 'typescript', 'css', 'postcss', 'svelte'],
swift: ['swift'],
'system-verilog': ['system-verilog'],
systemd: ['systemd'],
talonscript: ['talonscript'],
tasl: ['tasl'],
tcl: ['tcl'],
templ: ['go', 'javascript', 'css', 'templ'],
terraform: ['terraform'],
tex: ['r', 'tex'],
toml: ['toml'],
'ts-tags': [
'typescript',
'typescript',
'css',
'javascript',
'es-tag-css',
'typescript',
'c',
'glsl',
'javascript',
'es-tag-glsl',
'typescript',
'javascript',
'css',
'html',
'javascript',
'es-tag-html',
'typescript',
'sql',
'es-tag-sql',
'java',
'xml',
'es-tag-xml',
'ts-tags',
],
tsv: ['tsv'],
tsx: ['tsx'],
turtle: ['turtle'],
twig: [
'css',
'javascript',
'css',
'scss',
'javascript',
'css',
'html',
'java',
'xml',
'sql',
'javascript',
'json',
'css',
'php',
'python',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'twig',
],
typescript: ['typescript'],
typespec: ['typespec'],
typst: ['typst'],
v: ['v'],
vala: ['vala'],
vb: ['vb'],
verilog: ['verilog'],
vhdl: ['vhdl'],
viml: ['viml'],
vue: [
'css',
'javascript',
'typescript',
'json',
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'html-derivative',
'markdown-vue',
'vue-directives',
'vue-interpolations',
'javascript',
'vue-sfc-style-variable-injection',
'vue',
],
'vue-html': ['javascript', 'vue-html'],
'vue-vine': ['css', 'css', 'scss', 'less', 'stylus', 'postcss', 'javascript', 'vue-vine'],
vyper: ['vyper'],
wasm: ['wasm'],
wenyan: ['wenyan'],
wgsl: ['wgsl'],
wikitext: ['wikitext'],
wit: ['wit'],
wolfram: ['wolfram'],
xml: ['java', 'xml'],
xsl: ['java', 'xml', 'xsl'],
yaml: ['yaml'],
zenscript: ['zenscript'],
zig: ['zig'],
};
export function getShikiGrammarAssetPath(name: string): string {
return `${SHIKI_ASSETS_PATH}/grammars/${name}.json`;
}
export function getShikiThemeAssetPath(id: string): string {
return `${SHIKI_ASSETS_PATH}/themes/${id}.json`;
}
@@ -1,185 +0,0 @@
// Generated by scripts/generate-shiki-assets.ts, do not edit.
/** Every bundled Shiki theme id, with its type. */
export const SHIKI_THEMES: Record<string, { type: 'light' | 'dark' }> = {
andromeeda: {
type: 'dark',
},
'aurora-x': {
type: 'dark',
},
'ayu-dark': {
type: 'dark',
},
'catppuccin-frappe': {
type: 'dark',
},
'catppuccin-latte': {
type: 'light',
},
'catppuccin-macchiato': {
type: 'dark',
},
'catppuccin-mocha': {
type: 'dark',
},
'dark-plus': {
type: 'dark',
},
dracula: {
type: 'dark',
},
'dracula-soft': {
type: 'dark',
},
'everforest-dark': {
type: 'dark',
},
'everforest-light': {
type: 'light',
},
'github-dark': {
type: 'dark',
},
'github-dark-default': {
type: 'dark',
},
'github-dark-dimmed': {
type: 'dark',
},
'github-dark-high-contrast': {
type: 'dark',
},
'github-light': {
type: 'light',
},
'github-light-default': {
type: 'light',
},
'github-light-high-contrast': {
type: 'light',
},
'gruvbox-dark-hard': {
type: 'dark',
},
'gruvbox-dark-medium': {
type: 'dark',
},
'gruvbox-dark-soft': {
type: 'dark',
},
'gruvbox-light-hard': {
type: 'light',
},
'gruvbox-light-medium': {
type: 'light',
},
'gruvbox-light-soft': {
type: 'light',
},
houston: {
type: 'dark',
},
'kanagawa-dragon': {
type: 'dark',
},
'kanagawa-lotus': {
type: 'light',
},
'kanagawa-wave': {
type: 'dark',
},
laserwave: {
type: 'dark',
},
'light-plus': {
type: 'light',
},
'material-theme': {
type: 'dark',
},
'material-theme-darker': {
type: 'dark',
},
'material-theme-lighter': {
type: 'light',
},
'material-theme-ocean': {
type: 'dark',
},
'material-theme-palenight': {
type: 'dark',
},
'min-dark': {
type: 'dark',
},
'min-light': {
type: 'light',
},
monokai: {
type: 'dark',
},
'night-owl': {
type: 'dark',
},
nord: {
type: 'dark',
},
'one-dark-pro': {
type: 'dark',
},
'one-light': {
type: 'light',
},
plastic: {
type: 'dark',
},
poimandres: {
type: 'dark',
},
red: {
type: 'dark',
},
'rose-pine': {
type: 'dark',
},
'rose-pine-dawn': {
type: 'light',
},
'rose-pine-moon': {
type: 'dark',
},
'slack-dark': {
type: 'dark',
},
'slack-ochin': {
type: 'light',
},
'snazzy-light': {
type: 'light',
},
'solarized-dark': {
type: 'dark',
},
'solarized-light': {
type: 'light',
},
'synthwave-84': {
type: 'dark',
},
'tokyo-night': {
type: 'dark',
},
vesper: {
type: 'dark',
},
'vitesse-black': {
type: 'dark',
},
'vitesse-dark': {
type: 'dark',
},
'vitesse-light': {
type: 'light',
},
};
@@ -39,7 +39,6 @@ export type OpenAPIBlockClientContextProps = {
headingNode: React.ReactNode;
descriptionNode: React.ReactNode;
scalarRuntimeURL: string;
staticAssetsURL: string;
};
type OpenAPIBlockVariant =
@@ -66,13 +65,7 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
id: props.id,
blockKey: props.blockKey,
renderCodeBlock: ({ code, syntax }) => (
<ClientPlainCodeBlock
code={code}
syntax={syntax}
mode={mode}
themes={codeTheme}
staticAssetsURL={props.staticAssetsURL}
/>
<ClientPlainCodeBlock code={code} syntax={syntax} mode={mode} themes={codeTheme} />
),
renderDocument: () => descriptionNode,
renderHeading: () => headingNode,
@@ -166,7 +166,6 @@ export function getOpenAPIBlockClientProps(args: {
return {
...serializable,
mode: props.context.mode,
staticAssetsURL: getAssetURL(''),
codeTheme:
context && 'customization' in context
? context.customization.styling.codeTheme.openapi
@@ -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,
};
}
@@ -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: '这有帮助吗?',
+1 -1
View File
@@ -151,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'>;
};
/**
@@ -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. */
+1 -2
View File
@@ -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');
+21
View File
@@ -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);
}
}
+206 -19
View File
@@ -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 {
+160 -4
View File
@@ -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).
*/
+219
View File
@@ -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);
}
);
});
+131 -13
View File
@@ -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;
@@ -646,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.
@@ -1014,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)}`,
};
}
@@ -1121,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 || '/');
}