Compare commits

...

43 Commits

Author SHA1 Message Date
Samy Pessé 27532a5f41 Version Packages (#2988)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-03-24 17:43:16 +01:00
Nolann B. 48c18c03b9 Add option to pass scalar plugins (#3027) 2025-03-24 14:11:14 +01:00
Samy Pessé bba2e52e24 Fix support for site redirects that include section/variant paths (#3024) 2025-03-24 10:21:26 +01:00
Valentino Hudhra 54ee0149e1 Add support for custom fonts (#2981) 2025-03-24 08:20:58 +01:00
Greg Bergé 8fda9d2fab Update Argos (#3025) 2025-03-22 23:00:25 +01:00
Samy Pessé 77a72d79ce Update next.js to latest v14 and v15 (#3026) 2025-03-22 20:02:15 +01:00
Nolann B. 73e2b472ef Fix write only properties in request example (#3023) 2025-03-21 19:09:25 +01:00
Samy Pessé 2f28cc1323 v2: improve link and navigation between content in a same site (#3020) 2025-03-21 18:18:34 +01:00
Greg Bergé f5516d4e21 Improve OpenAPI TOC display (#3022) 2025-03-21 14:29:12 +00:00
Greg Bergé d2facb2db1 Mark OpenAPI properties as optional if not required (#3021) 2025-03-21 14:28:53 +00:00
Greg Bergé 6eae764b7c Add support for multiple body content types / examples (#2991) 2025-03-21 14:23:42 +01:00
Greg Bergé 970ef8f886 Add missing token (#3019) 2025-03-21 11:04:57 +01:00
Nolann B. ed0720699e Fix OpenAPI path overflow on mobile (#3018) 2025-03-21 11:02:32 +01:00
Greg Bergé ad94d00d5f Improve markdown parsing (#3017) 2025-03-21 10:53:01 +01:00
Greg Bergé c7843f7f52 Remove bun cache (#3016) 2025-03-21 10:42:57 +01:00
Greg Bergé 1fe3286bdb Fix OpenAPI overflow issue (#3015) 2025-03-21 10:42:09 +01:00
Samy Pessé ce030fdf76 v2: Fix redirect to strip jwt_token in url-host mode (#3014) 2025-03-21 00:46:39 +01:00
Samy Pessé 9ba8783952 v2: Fix the redirection when stripping the jwt_token from url (#3013) 2025-03-21 00:25:34 +01:00
Greg Bergé 2f3966cc53 Fix icons flaky (#3012) 2025-03-20 21:08:46 +00:00
Samy Pessé 8f65a22e13 Accept API token in query parameters for normal v2 routes (#3011) 2025-03-20 19:54:55 +01:00
Greg Bergé 2787d884cd Stabilize images & icons (#3009) 2025-03-20 19:40:42 +01:00
Nolann B. fc00b51683 Remove default value in generateSchemaExample (#3007) 2025-03-20 17:24:23 +01:00
Samy Pessé f80c3a7b37 v2: Fix display of integration blocks (#3010) 2025-03-20 15:56:31 +00:00
Samy Pessé 4e5d6c7487 v2: use static route for VA / adaptive content (#2998) 2025-03-20 15:41:17 +01:00
Greg Bergé 96f84b5917 Fix visual tests v2 (#3006) 2025-03-20 11:34:04 +01:00
Greg Bergé 6b8a5fdd1b Trigger tests (#3005) 2025-03-20 10:00:09 +00:00
Greg Bergé 89083ac790 Stabilize visual tests (#3001) 2025-03-20 09:22:09 +01:00
Nolann B. 70be2c6b2b Stringify default value (#3003) 2025-03-19 21:28:40 +01:00
Samy Pessé bcf877841b Update to latest version of the GitBook API (#3002) 2025-03-19 20:11:44 +01:00
Nolann B. a84b06bb19 Update resolveDescription and add minItems/maxItems (#3000) 2025-03-19 17:21:35 +01:00
Zeno Kapitein 24b7808d9a Fix prominent search bar width on md screens (#2996) 2025-03-19 17:14:07 +01:00
Greg Bergé 8364ee988e Fix Argos flakies (#2999) 2025-03-19 16:04:45 +01:00
Samy Pessé 07f6e2d233 Pass page.computedSeed to getComputedDocument (#2995) 2025-03-19 15:02:49 +01:00
Greg Bergé 7212973f34 Update Scalar client (#2993) 2025-03-18 16:02:40 +01:00
Greg Bergé af44e0436b fix typo (#2992) 2025-03-18 14:20:23 +01:00
Greg Bergé 3f9c35d505 Fix emoji display on other platforms than Mac OS (#2990) 2025-03-17 17:49:13 +01:00
Zeno Kapitein 2c13f8b95c Fix horizontal overscroll issue on large screens (#2989) 2025-03-17 15:38:44 +01:00
Zeno Kapitein 4dab1c56e5 Fix alignment of prominent search bar on full-width pages (#2987) 2025-03-17 15:02:23 +01:00
Zeno Kapitein 4723f03ef1 Restyle section group dropdown (#2985) 2025-03-17 13:22:54 +01:00
Samy Pessé 278689e0a0 Version Packages (#2984)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-03-17 11:06:18 +01:00
Nolann B. 886e204e68 Update OpenAPI operation path design (#2972) 2025-03-17 10:18:24 +01:00
Greg Bergé c59947ab39 Remove Sentry (#2986) 2025-03-17 09:00:58 +01:00
Zeno Kapitein 4f0a772a21 Override tint lightness if supplied color is out of bounds (#2983) 2025-03-14 18:24:25 +01:00
140 changed files with 3385 additions and 2257 deletions
@@ -50,6 +50,7 @@ runs:
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY
GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
GITBOOK_FONTS_URL: ${{ inputs.opItem }}/GITBOOK_FONTS_URL
- name: Build worker - name: Build worker
run: bun run turbo build:v2:cloudflare run: bun run turbo build:v2:cloudflare
shell: bash shell: bash
@@ -55,6 +55,7 @@ runs:
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY
GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
GITBOOK_FONTS_URL: ${{ inputs.opItem }}/GITBOOK_FONTS_URL
- name: Build Project Artifacts - name: Build Project Artifacts
run: bun run vercel build --target=${{ inputs.environment }} --token=${{ inputs.vercelToken }} run: bun run vercel build --target=${{ inputs.environment }} --token=${{ inputs.vercelToken }}
shell: bash shell: bash
@@ -74,3 +75,4 @@ runs:
shell: bash shell: bash
run: | run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}" echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
-9
View File
@@ -3,15 +3,6 @@ description: 'Install Bun and cache dependencies'
runs: runs:
using: 'composite' using: 'composite'
steps: steps:
# We cache dependencies even if Bun is fast to avoid downloading fontawesome too many times
# and impacting bandwidth there.
- name: Cache bun
uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Setup bun - name: Setup bun
uses: oven-sh/setup-bun@v2 uses: oven-sh/setup-bun@v2
with: with:
-10
View File
@@ -35,21 +35,11 @@ jobs:
- name: Sets env vars for production - name: Sets env vars for production
if: github.ref == 'refs/heads/main' if: github.ref == 'refs/heads/main'
run: | run: |
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
echo "GITBOOK_ASSETS_PREFIX=https://static.gitbook.com" >> $GITHUB_ENV echo "GITBOOK_ASSETS_PREFIX=https://static.gitbook.com" >> $GITHUB_ENV
- name: Sets env vars for preview
if: github.ref != 'refs/heads/main'
run: |
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
- name: Build Next.js with next-on-pages - name: Build Next.js with next-on-pages
run: bun run turbo gitbook#build:cloudflare run: bun run turbo gitbook#build:cloudflare
env: env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
SENTRY_RELEASE: ${{ github.sha }}
- id: deploy - id: deploy
name: Deploy to Cloudflare name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3.14.0 uses: cloudflare/wrangler-action@v3.14.0
+3
View File
@@ -5,6 +5,9 @@ on:
branches: branches:
- main - main
env:
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
concurrency: ${{ github.workflow }}-${{ github.ref }} concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs: jobs:
+3
View File
@@ -13,5 +13,8 @@
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.organizeImports.biome": "explicit", "source.organizeImports.biome": "explicit",
"source.fixAll.biome": "explicit" "source.fixAll.biome": "explicit"
},
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
} }
} }
+239 -570
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -7,12 +7,12 @@
"turbo": "^2.4.4", "turbo": "^2.4.4",
"vercel": "^39.3.0" "vercel": "^39.3.0"
}, },
"packageManager": "bun@1.2.4", "packageManager": "bun@1.2.5",
"overrides": { "overrides": {
"@codemirror/state": "6.4.1", "@codemirror/state": "6.4.1",
"react": "18.3.1", "react": "18.3.1",
"react-dom": "18.3.1", "react-dom": "18.3.1",
"@gitbook/api": "0.99.0" "@gitbook/api": "0.102.0"
}, },
"private": true, "private": true,
"scripts": { "scripts": {
+7 -1
View File
@@ -1,7 +1,13 @@
# @gitbook/colors # @gitbook/colors
## 0.3.0
### Minor Changes
- 4f0a772: Override tint lightness if supplied color is out of bounds
## 0.2.0 ## 0.2.0
### Minor Changes ### Minor Changes
- 445baaa: Initial release - 445baaa: Initial release
+1 -1
View File
@@ -8,7 +8,7 @@
"default": "./dist/index.js" "default": "./dist/index.js"
} }
}, },
"version": "0.2.0", "version": "0.3.0",
"devDependencies": { "devDependencies": {
"typescript": "^5.5.3" "typescript": "^5.5.3"
}, },
+15 -1
View File
@@ -184,6 +184,7 @@ export function colorScale(
const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null; const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null;
const foregroundColor = rgbToOklch(hexToRgbArray(foreground)); const foregroundColor = rgbToOklch(hexToRgbArray(foreground));
const backgroundColor = rgbToOklch(hexToRgbArray(background)); const backgroundColor = rgbToOklch(hexToRgbArray(background));
let mapping = darkMode ? colorMixMapping.dark : colorMixMapping.light;
if (mixColor && mix?.ratio && mix.ratio > 0) { if (mixColor && mix?.ratio && mix.ratio > 0) {
// If defined, we mix in a (tiny) bit of the mix color with the base color. // If defined, we mix in a (tiny) bit of the mix color with the base color.
@@ -192,7 +193,20 @@ export function colorScale(
baseColor.H = mix.color === DEFAULT_TINT_COLOR ? baseColor.H : mixColor.H; baseColor.H = mix.color === DEFAULT_TINT_COLOR ? baseColor.H : mixColor.H;
} }
const mapping = darkMode ? colorMixMapping.dark : colorMixMapping.light; if (
(darkMode && baseColor.L < backgroundColor.L) ||
(!darkMode && baseColor.L > backgroundColor.L)
) {
// If the supplied color is outside of our lightness bounds, use the supplied color's lightness.
// This is mostly used to allow darker-than-dark backgrounds for brands that specifically want that look.
const difference = (backgroundColor.L - baseColor.L) / backgroundColor.L;
backgroundColor.L = baseColor.L;
// At the edges of the scale, the subtle lightness changes stop being perceptible. We need to amp up our mapping to still stand out.
const amplifier = 1;
mapping = mapping.map((step, index) =>
index < 9 ? step + step * amplifier * difference : step
);
}
const result = []; const result = [];
+7
View File
@@ -1,5 +1,12 @@
# gitbook-v2 # gitbook-v2
## 0.2.2
### Patch Changes
- 54ee014: Add initial support for loading custom fonts
- bba2e52: Fix site redirects when it includes a section/variant path
## 0.2.1 ## 0.2.1
### Patch Changes ### Patch Changes
+11
View File
@@ -5,7 +5,17 @@
*/ */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
// This is needed to throw "forbidden" when the api token expired during revalidation
authInterrupts: true,
// This is needed to use 'use cache'
useCache: true, useCache: true,
// Content is fully static, we can cache it in the session memory cache for a long time
staleTimes: {
dynamic: 3600, // 1 hour
static: 3600, // 1 hour
},
}, },
env: { env: {
@@ -23,6 +33,7 @@ const nextConfig = {
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX, GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
GITBOOK_SECRET: process.env.GITBOOK_SECRET, GITBOOK_SECRET: process.env.GITBOOK_SECRET,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_SIGNING_KEY: process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_FONTS_URL: process.env.GITBOOK_FONTS_URL,
// Next.js envs // Next.js envs
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
+6 -3
View File
@@ -1,20 +1,23 @@
{ {
"name": "gitbook-v2", "name": "gitbook-v2",
"version": "0.2.1", "version": "0.2.2",
"private": true, "private": true,
"dependencies": { "dependencies": {
"next": "^15.2.1", "next": "^15.2.3",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"@gitbook/api": "*", "@gitbook/api": "*",
"@gitbook/cache-tags": "workspace:*", "@gitbook/cache-tags": "workspace:*",
"@sindresorhus/fnv1a": "^3.1.0", "@sindresorhus/fnv1a": "^3.1.0",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"warn-once": "^0.1.1" "warn-once": "^0.1.1",
"rison": "^0.1.1",
"jwt-decode": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"gitbook": "*", "gitbook": "*",
"@opennextjs/cloudflare": "^0.5.10", "@opennextjs/cloudflare": "^0.5.10",
"@types/rison": "^0.0.9",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
"postcss": "^8" "postcss": "^8"
}, },
@@ -13,20 +13,20 @@ type PageProps = {
export default async function Page(props: PageProps) { export default async function Page(props: PageProps) {
const params = await props.params; const params = await props.params;
const context = await getDynamicSiteContext(params); const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
return <SitePage context={context} pageParams={{ pathname }} />; return <SitePage context={context} pageParams={{ pathname }} />;
} }
export async function generateViewport(props: PageProps): Promise<Viewport> { export async function generateViewport(props: PageProps): Promise<Viewport> {
const context = await getDynamicSiteContext(await props.params); const { context } = await getDynamicSiteContext(await props.params);
return generateSitePageViewport(context); return generateSitePageViewport(context);
} }
export async function generateMetadata(props: PageProps): Promise<Metadata> { export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params; const params = await props.params;
const context = await getDynamicSiteContext(params); const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({ return generateSitePageMetadata({
@@ -6,7 +6,7 @@ import {
} from '@/components/SiteLayout'; } from '@/components/SiteLayout';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils'; import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env'; import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
import { getThemeFromMiddleware, getVisitorAuthTokenFromMiddleware } from '@v2/lib/middleware'; import { getThemeFromMiddleware } from '@v2/lib/middleware';
interface SiteDynamicLayoutProps { interface SiteDynamicLayoutProps {
params: Promise<RouteLayoutParams>; params: Promise<RouteLayoutParams>;
@@ -16,9 +16,8 @@ export default async function SiteDynamicLayout({
params, params,
children, children,
}: React.PropsWithChildren<SiteDynamicLayoutProps>) { }: React.PropsWithChildren<SiteDynamicLayoutProps>) {
const context = await getDynamicSiteContext(await params); const { context, visitorAuthClaims } = await getDynamicSiteContext(await params);
const forcedTheme = await getThemeFromMiddleware(); const forcedTheme = await getThemeFromMiddleware();
const visitorAuthToken = await getVisitorAuthTokenFromMiddleware();
return ( return (
<CustomizationRootLayout customization={context.customization}> <CustomizationRootLayout customization={context.customization}>
@@ -26,7 +25,7 @@ export default async function SiteDynamicLayout({
context={context} context={context}
forcedTheme={forcedTheme} forcedTheme={forcedTheme}
withTracking={!GITBOOK_DISABLE_TRACKING} withTracking={!GITBOOK_DISABLE_TRACKING}
visitorAuthToken={visitorAuthToken} visitorAuthClaims={visitorAuthClaims}
> >
{children} {children}
</SiteLayout> </SiteLayout>
@@ -35,11 +34,11 @@ export default async function SiteDynamicLayout({
} }
export async function generateViewport({ params }: SiteDynamicLayoutProps) { export async function generateViewport({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return generateSiteLayoutViewport(context); return generateSiteLayoutViewport(context);
} }
export async function generateMetadata({ params }: SiteDynamicLayoutProps) { export async function generateMetadata({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return generateSiteLayoutMetadata(context); return generateSiteLayoutMetadata(context);
} }
@@ -7,6 +7,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return serveLLMsTxt(context); return serveLLMsTxt(context);
} }
@@ -7,6 +7,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return serveRobotsTxt(context); return serveRobotsTxt(context);
} }
@@ -7,6 +7,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return servePagesSitemap(context); return servePagesSitemap(context);
} }
@@ -7,6 +7,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return serveRootSitemap(context); return serveRootSitemap(context);
} }
@@ -7,6 +7,6 @@ export async function GET(
request: NextRequest, request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return serveIcon(context, request); return serveIcon(context, request);
} }
@@ -8,6 +8,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> } { params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) { ) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return serveOGImage(context, await params); return serveOGImage(context, await params);
} }
@@ -6,7 +6,7 @@ export default async function RootLayout(props: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { params, children } = props; const { params, children } = props;
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>; return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
} }
@@ -6,7 +6,7 @@ export async function generateMetadata({
}: { }: {
params: Promise<RouteLayoutParams>; params: Promise<RouteLayoutParams>;
}) { }) {
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return generatePDFMetadata(context); return generatePDFMetadata(context);
} }
@@ -15,6 +15,6 @@ export default async function Page(props: {
searchParams: Promise<{ [key: string]: string }>; searchParams: Promise<{ [key: string]: string }>;
}) { }) {
const { params, searchParams } = props; const { params, searchParams } = props;
const context = await getDynamicSiteContext(await params); const { context } = await getDynamicSiteContext(await params);
return <PDFPage context={context} searchParams={await searchParams} />; return <PDFPage context={context} searchParams={await searchParams} />;
} }
@@ -18,7 +18,7 @@ export default async function Page(props: PageProps) {
'use cache'; 'use cache';
const params = await props.params; const params = await props.params;
const context = await getStaticSiteContext(params); const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
cacheTag( cacheTag(
@@ -32,13 +32,13 @@ export default async function Page(props: PageProps) {
} }
export async function generateViewport(props: PageProps): Promise<Viewport> { export async function generateViewport(props: PageProps): Promise<Viewport> {
const context = await getStaticSiteContext(await props.params); const { context } = await getStaticSiteContext(await props.params);
return generateSitePageViewport(context); return generateSitePageViewport(context);
} }
export async function generateMetadata(props: PageProps): Promise<Metadata> { export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params; const params = await props.params;
const context = await getStaticSiteContext(params); const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({ return generateSitePageMetadata({
@@ -19,7 +19,7 @@ export default async function SiteStaticLayout({
}: React.PropsWithChildren<SiteStaticLayoutProps>) { }: React.PropsWithChildren<SiteStaticLayoutProps>) {
'use cache'; 'use cache';
const context = await getStaticSiteContext(await params); const { context, visitorAuthClaims } = await getStaticSiteContext(await params);
cacheTag( cacheTag(
getCacheTag({ getCacheTag({
@@ -33,7 +33,7 @@ export default async function SiteStaticLayout({
<SiteLayout <SiteLayout
context={context} context={context}
withTracking={!GITBOOK_DISABLE_TRACKING} withTracking={!GITBOOK_DISABLE_TRACKING}
visitorAuthToken={null} visitorAuthClaims={visitorAuthClaims}
> >
{children} {children}
</SiteLayout> </SiteLayout>
@@ -42,11 +42,11 @@ export default async function SiteStaticLayout({
} }
export async function generateViewport({ params }: SiteStaticLayoutProps) { export async function generateViewport({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return generateSiteLayoutViewport(context); return generateSiteLayoutViewport(context);
} }
export async function generateMetadata({ params }: SiteStaticLayoutProps) { export async function generateMetadata({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return generateSiteLayoutMetadata(context); return generateSiteLayoutMetadata(context);
} }
@@ -9,6 +9,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return serveLLMsTxt(context); return serveLLMsTxt(context);
} }
@@ -9,6 +9,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return serveRobotsTxt(context); return serveRobotsTxt(context);
} }
@@ -9,6 +9,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return servePagesSitemap(context); return servePagesSitemap(context);
} }
@@ -9,6 +9,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return serveRootSitemap(context); return serveRootSitemap(context);
} }
@@ -9,6 +9,6 @@ export async function GET(
request: NextRequest, request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> } { params }: { params: Promise<RouteLayoutParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return serveIcon(context, request); return serveIcon(context, request);
} }
@@ -10,6 +10,6 @@ export async function GET(
_request: NextRequest, _request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> } { params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) { ) {
const context = await getStaticSiteContext(await params); const { context } = await getStaticSiteContext(await params);
return serveOGImage(context, await params); return serveOGImage(context, await params);
} }
+43 -15
View File
@@ -1,9 +1,9 @@
import { import { getVisitorAuthClaims, getVisitorAuthClaimsFromToken } from '@/lib/adaptive';
fetchSiteContextByURL, import type { PublishedSiteContent, SiteAPIToken } from '@gitbook/api';
fetchSiteContextByURLLookup, import { fetchSiteContextByURLLookup, getBaseContext } from '@v2/lib/context';
getBaseContext, import { jwtDecode } from 'jwt-decode';
} from '@v2/lib/context'; import { forbidden } from 'next/navigation';
import { getSiteURLDataFromMiddleware } from '@v2/lib/middleware'; import rison from 'rison';
export type RouteParamMode = 'url-host' | 'url'; export type RouteParamMode = 'url-host' | 'url';
@@ -12,6 +12,9 @@ export type RouteLayoutParams = {
/** URL encoded site URL */ /** URL encoded site URL */
siteURL: string; siteURL: string;
/** URL and Rison encoded site data from getPublishedContentByUrl */
siteData: string;
}; };
export type RouteParams = RouteLayoutParams & { export type RouteParams = RouteLayoutParams & {
@@ -21,19 +24,30 @@ export type RouteParams = RouteLayoutParams & {
/** /**
* Get the static context when rendering statically a site. * Get the static context when rendering statically a site.
*/ */
export function getStaticSiteContext(params: RouteLayoutParams) { export async function getStaticSiteContext(params: RouteLayoutParams) {
const siteURL = getSiteURLFromParams(params); const siteURL = getSiteURLFromParams(params);
return fetchSiteContextByURL( const siteURLData = getSiteURLDataFromParams(params);
// For static routes, we check the expiration of the JWT token
// as the route might be revalidated after expiration
const decoded = jwtDecode<SiteAPIToken & { exp: number }>(siteURLData.apiToken);
if (decoded.exp && decoded.exp < Date.now() / 1000 + 120) {
forbidden();
}
const context = await fetchSiteContextByURLLookup(
getBaseContext({ getBaseContext({
siteURL, siteURL,
siteURLData,
urlMode: getModeFromParams(params.mode), urlMode: getModeFromParams(params.mode),
}), }),
{ siteURLData
url: siteURL.toString(),
visitorAuthToken: null,
redirectOnError: false,
}
); );
return {
context,
visitorAuthClaims: getVisitorAuthClaimsFromToken(decoded),
};
} }
/** /**
@@ -42,15 +56,21 @@ export function getStaticSiteContext(params: RouteLayoutParams) {
*/ */
export async function getDynamicSiteContext(params: RouteLayoutParams) { export async function getDynamicSiteContext(params: RouteLayoutParams) {
const siteURL = getSiteURLFromParams(params); const siteURL = getSiteURLFromParams(params);
const siteURLData = await getSiteURLDataFromMiddleware(); const siteURLData = getSiteURLDataFromParams(params);
return fetchSiteContextByURLLookup( const context = await fetchSiteContextByURLLookup(
getBaseContext({ getBaseContext({
siteURL, siteURL,
siteURLData,
urlMode: getModeFromParams(params.mode), urlMode: getModeFromParams(params.mode),
}), }),
siteURLData siteURLData
); );
return {
context,
visitorAuthClaims: getVisitorAuthClaims(siteURLData),
};
} }
/** /**
@@ -74,3 +94,11 @@ function getModeFromParams(mode: string): RouteParamMode {
return 'url'; return 'url';
} }
/**
* Get the decoded site data from the params.
*/
function getSiteURLDataFromParams(params: RouteLayoutParams): PublishedSiteContent {
const decoded = decodeURIComponent(params.siteData);
return rison.decode(decoded);
}
+2
View File
@@ -7,6 +7,7 @@ import {
GITBOOK_APP_URL, GITBOOK_APP_URL,
GITBOOK_ASSETS_URL, GITBOOK_ASSETS_URL,
GITBOOK_DISABLE_TRACKING, GITBOOK_DISABLE_TRACKING,
GITBOOK_FONTS_URL,
GITBOOK_ICONS_URL, GITBOOK_ICONS_URL,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_INTEGRATIONS_HOST, GITBOOK_INTEGRATIONS_HOST,
@@ -25,6 +26,7 @@ export async function GET(_req: NextRequest) {
GITBOOK_API_URL, GITBOOK_API_URL,
GITBOOK_API_PUBLIC_URL, GITBOOK_API_PUBLIC_URL,
GITBOOK_ASSETS_URL, GITBOOK_ASSETS_URL,
GITBOOK_FONTS_URL,
GITBOOK_ICONS_URL, GITBOOK_ICONS_URL,
GITBOOK_USER_AGENT, GITBOOK_USER_AGENT,
GITBOOK_INTEGRATIONS_HOST, GITBOOK_INTEGRATIONS_HOST,
@@ -20,8 +20,10 @@ export async function getSpacePDFContext(
const apiToken = await getAPITokenFromMiddleware(); const apiToken = await getAPITokenFromMiddleware();
const basePath = getPDFRoutePath(params);
const linker = createLinker({ const linker = createLinker({
pathname: getPDFRoutePath(params), spaceBasePath: basePath,
siteBasePath: basePath,
}); });
const dataFetcher = createDataFetcher({ const dataFetcher = createDataFetcher({
apiToken: apiToken, apiToken: apiToken,
+42 -94
View File
@@ -1,7 +1,7 @@
import { getSiteStructureSections } from '@/lib/sites'; import { getSiteStructureSections } from '@/lib/sites';
import type { import type {
ChangeRequest, ChangeRequest,
PublishedSiteContentLookup, PublishedSiteContent,
RevisionPage, RevisionPage,
RevisionPageDocument, RevisionPageDocument,
Site, Site,
@@ -14,11 +14,10 @@ import type {
Space, Space,
} from '@gitbook/api'; } from '@gitbook/api';
import { type GitBookDataFetcher, createDataFetcher, throwIfDataError } from '@v2/lib/data'; import { type GitBookDataFetcher, createDataFetcher, throwIfDataError } from '@v2/lib/data';
import { redirect } from 'next/navigation';
import { assert } from 'ts-essentials'; import { assert } from 'ts-essentials';
import { GITBOOK_URL } from './env'; import { GITBOOK_URL } from './env';
import { type ImageResizer, createImageResizer } from './images'; import { type ImageResizer, createImageResizer } from './images';
import { type GitBookSpaceLinker, createLinker } from './links'; import { type GitBookLinker, createLinker } from './links';
/** /**
* Generic context when rendering content. * Generic context when rendering content.
@@ -32,7 +31,7 @@ export type GitBookBaseContext = {
/** /**
* Linker to generate links in the current space. * Linker to generate links in the current space.
*/ */
linker: GitBookSpaceLinker; linker: GitBookLinker;
/** /**
* Image resizer to resize images. * Image resizer to resize images.
@@ -102,27 +101,45 @@ export type GitBookPageContext = (GitBookSpaceContext | GitBookSiteContext) & {
}; };
/** /**
* Get the base context for a request. * Get the base context for a request on a site.
*/ */
export function getBaseContext(input: { export function getBaseContext(input: {
siteURL: URL | string; siteURL: URL | string;
siteURLData: PublishedSiteContent;
urlMode: 'url' | 'url-host'; urlMode: 'url' | 'url-host';
apiToken?: string | null;
}) { }) {
const url = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL; const { urlMode, siteURLData } = input;
const urlMode = input.urlMode; const siteURL = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL;
const dataFetcher = createDataFetcher({ const dataFetcher = createDataFetcher({
apiToken: input.apiToken ?? null, apiToken: siteURLData.apiToken ?? null,
}); });
const linker = getLinkerForSiteURL({ const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
siteURL: url, const linker =
urlMode, urlMode === 'url-host'
}); ? createLinker({
host: siteURL.host,
siteBasePath: siteURLData.siteBasePath,
spaceBasePath: siteURLData.basePath,
})
: createLinker({
protocol: gitbookURL?.protocol,
host: gitbookURL?.host,
siteBasePath: `/url/${siteURL.host}${siteURLData.siteBasePath}`,
spaceBasePath: `/url/${siteURL.host}${siteURLData.basePath}`,
});
if (urlMode === 'url') {
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`;
};
}
const imageResizer = createImageResizer({ const imageResizer = createImageResizer({
host: url.host, host: siteURL.host,
// To ensure image resizing work for proxied sites, // To ensure image resizing work for proxied sites,
// we serve images from the root of the site. // we serve images from the root of the site.
linker: linker, linker: linker,
@@ -135,92 +152,23 @@ export function getBaseContext(input: {
}; };
} }
/**
* Get the linker for a given site URL.
*/
export function getLinkerForSiteURL(input: {
siteURL: URL;
urlMode: 'url' | 'url-host';
}) {
const { siteURL, urlMode } = input;
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
const linker =
urlMode === 'url-host'
? createLinker({
host: siteURL.host,
pathname: siteURL.pathname,
})
: createLinker({
protocol: gitbookURL?.protocol,
host: gitbookURL?.host,
pathname: `/url/${siteURL.host}${siteURL.pathname}`,
});
if (urlMode === 'url') {
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`;
};
}
return linker;
}
/**
* Fetch the context of a site for a given URL and a base context.
*/
export async function fetchSiteContextByURL(
baseContext: GitBookBaseContext,
input: {
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
}
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
const data = await throwIfDataError(
dataFetcher.getPublishedContentByUrl({
url: input.url,
visitorAuthToken: input.visitorAuthToken,
redirectOnError: input.redirectOnError,
})
);
return fetchSiteContextByURLLookup(baseContext, data);
}
/** /**
* Fetch the context of a site using the resolution of a URL * Fetch the context of a site using the resolution of a URL
*/ */
export async function fetchSiteContextByURLLookup( export async function fetchSiteContextByURLLookup(
baseContext: GitBookBaseContext, baseContext: GitBookBaseContext,
data: PublishedSiteContentLookup data: PublishedSiteContent
): Promise<GitBookSiteContext> { ): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext; return await fetchSiteContextByIds(baseContext, {
if ('redirect' in data) { organization: data.organization,
redirect(data.redirect); site: data.site,
} siteSection: data.siteSection,
siteSpace: data.siteSpace,
return await fetchSiteContextByIds( space: data.space,
{ shareKey: data.shareKey,
...baseContext, changeRequest: data.changeRequest,
dataFetcher: dataFetcher.withToken({ revision: data.revision,
apiToken: data.apiToken, });
}),
},
{
organization: data.organization,
site: data.site,
siteSection: data.siteSection,
siteSpace: data.siteSpace,
space: data.space,
shareKey: data.shareKey,
changeRequest: data.changeRequest,
revision: data.revision,
}
);
} }
/** /**
+35 -53
View File
@@ -3,12 +3,9 @@ import {
type ComputedContentSource, type ComputedContentSource,
GitBookAPI, GitBookAPI,
type GitBookAPIServiceBinding, type GitBookAPIServiceBinding,
type RenderIntegrationUI,
} from '@gitbook/api'; } from '@gitbook/api';
import { import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
getCacheTag,
getCacheTagForURL,
getComputedContentSourceCacheTags,
} from '@gitbook/cache-tags';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env'; import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env';
import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache'; import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache';
import { wrapDataFetcherError } from './errors'; import { wrapDataFetcherError } from './errors';
@@ -144,6 +141,7 @@ export function createDataFetcher(
organizationId: params.organizationId, organizationId: params.organizationId,
spaceId: params.spaceId, spaceId: params.spaceId,
source: params.source, source: params.source,
seed: params.seed,
}) })
); );
}, },
@@ -159,6 +157,14 @@ export function createDataFetcher(
return trace('searchSiteContent', () => searchSiteContent(input, params)); return trace('searchSiteContent', () => searchSiteContent(input, params));
}, },
renderIntegrationUi(params) {
return trace('renderIntegrationUi', () =>
renderIntegrationUi(input, {
integrationName: params.integrationName,
request: params.request,
})
);
},
// //
// API that are not tied to the token // API that are not tied to the token
// where the data is the same for all users // where the data is the same for all users
@@ -166,18 +172,6 @@ export function createDataFetcher(
getUserById(userId) { getUserById(userId) {
return trace('getUserById', () => getUserById({ apiToken: null }, { userId })); return trace('getUserById', () => getUserById({ apiToken: null }, { userId }));
}, },
getPublishedContentByUrl(params) {
return trace('getPublishedContentByUrl', () =>
getPublishedContentByUrl(
{ apiToken: null },
{
url: params.url,
visitorAuthToken: params.visitorAuthToken,
redirectOnError: params.redirectOnError,
}
)
);
},
}; };
} }
@@ -360,6 +354,7 @@ async function getComputedDocument(
spaceId: string; spaceId: string;
organizationId: string; organizationId: string;
source: ComputedContentSource; source: ComputedContentSource;
seed: string;
} }
) { ) {
'use cache'; 'use cache';
@@ -380,6 +375,7 @@ async function getComputedDocument(
const api = await apiClient(input); const api = await apiClient(input);
const res = await api.spaces.getComputedDocument(params.spaceId, { const res = await api.spaces.getComputedDocument(params.spaceId, {
source: params.source, source: params.source,
seed: params.seed,
}); });
return res.data; return res.data;
}); });
@@ -436,42 +432,6 @@ async function getLatestOpenAPISpecVersionContent(
}); });
} }
async function getPublishedContentByUrl(
input: DataFetcherInput,
params: {
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
}
) {
'use cache';
const { url, visitorAuthToken, redirectOnError } = params;
cacheTag(getCacheTagForURL(url));
cacheLife('days');
return wrapDataFetcherError(async () => {
const api = await apiClient(input);
const res = await api.urls.getPublishedContentByUrl({
url,
visitorAuthToken: visitorAuthToken ?? undefined,
redirectOnError,
});
if ('site' in res.data) {
cacheTag(
getCacheTag({
tag: 'site',
site: res.data.site,
})
);
}
return res.data;
});
}
async function getPublishedContentSite( async function getPublishedContentSite(
input: DataFetcherInput, input: DataFetcherInput,
params: { params: {
@@ -567,6 +527,28 @@ async function searchSiteContent(
}); });
} }
async function renderIntegrationUi(
input: DataFetcherInput,
params: {
integrationName: string;
request: RenderIntegrationUI;
}
) {
'use cache';
cacheTag(getCacheTag({ tag: 'integration', integration: params.integrationName }));
cacheLife('days');
return wrapDataFetcherError(async () => {
const api = await apiClient(input);
const res = await api.integrations.renderIntegrationUiWithPost(
params.integrationName,
params.request
);
return res.data;
});
}
let loggedServiceBinding = false; let loggedServiceBinding = false;
/** /**
+7 -3
View File
@@ -15,13 +15,14 @@ export async function getPublishedContentByURL(input: {
url: string; url: string;
visitorAuthToken: string | null; visitorAuthToken: string | null;
redirectOnError: boolean; redirectOnError: boolean;
apiToken: string | null;
}): Promise<DataFetcherResponse<PublishedSiteContentLookup>> { }): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
const lookupURL = new URL(input.url); const lookupURL = new URL(input.url);
const url = stripURLSearch(lookupURL); const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url); const lookup = getURLLookupAlternatives(url);
const result = await race(lookup.urls, async (alternative, { signal }) => { const result = await race(lookup.urls, async (alternative, { signal }) => {
const api = await apiClient(); const api = await apiClient({ apiToken: input.apiToken });
const callResult = await trace( const callResult = await trace(
{ {
@@ -94,12 +95,15 @@ export async function getPublishedContentByURL(input: {
* In both cases, the idea is to use the deepest/longest/most inclusive path to resolve the content. * In both cases, the idea is to use the deepest/longest/most inclusive path to resolve the content.
*/ */
if (alternative.primary || ('site' in data && data.complete)) { if (alternative.primary || ('site' in data && data.complete)) {
const changeRequest = data.changeRequest ?? lookup.changeRequest;
const revision = data.revision ?? lookup.revision;
const siteResult: PublishedSiteContentLookup = { const siteResult: PublishedSiteContentLookup = {
...data, ...data,
changeRequest: data.changeRequest ?? lookup.changeRequest,
revision: data.revision ?? lookup.revision,
basePath: joinPath(data.basePath, lookup.basePath ?? ''), basePath: joinPath(data.basePath, lookup.basePath ?? ''),
pathname: joinPath(data.pathname, alternative.extraPath), pathname: joinPath(data.pathname, alternative.extraPath),
...(changeRequest ? { changeRequest } : {}),
...(revision ? { revision } : {}),
}; };
return { data: siteResult }; return { data: siteResult };
} }
+2 -1
View File
@@ -15,12 +15,13 @@ export async function getPageDocument(
dataFetcher.getDocument({ spaceId: space.id, documentId: page.documentId }) dataFetcher.getDocument({ spaceId: space.id, documentId: page.documentId })
); );
} }
if (page.computed) { if ('computed' in page && page.computed) {
return getDataOrNull( return getDataOrNull(
dataFetcher.getComputedDocument({ dataFetcher.getComputedDocument({
organizationId: space.organization, organizationId: space.organization,
spaceId: space.id, spaceId: space.id,
source: page.computed, source: page.computed,
seed: page.computedSeed,
}) })
); );
} }
+9 -9
View File
@@ -37,15 +37,6 @@ export interface GitBookDataFetcher {
*/ */
getUserById(userId: string): Promise<DataFetcherResponse<api.User>>; getUserById(userId: string): Promise<DataFetcherResponse<api.User>>;
/**
* Get a published content by its URL.
*/
getPublishedContentByUrl(params: {
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
}): Promise<DataFetcherResponse<api.PublishedSiteContentLookup>>;
/** /**
* Get a published content site by its organization ID and site ID. * Get a published content site by its organization ID and site ID.
*/ */
@@ -120,6 +111,7 @@ export interface GitBookDataFetcher {
organizationId: string; organizationId: string;
spaceId: string; spaceId: string;
source: api.ComputedContentSource; source: api.ComputedContentSource;
seed: string;
}): Promise<DataFetcherResponse<api.JSONDocument>>; }): Promise<DataFetcherResponse<api.JSONDocument>>;
/** /**
@@ -170,4 +162,12 @@ export interface GitBookDataFetcher {
/** Cache bust to ensure the search results are fresh when the space is updated. */ /** Cache bust to ensure the search results are fresh when the space is updated. */
cacheBust?: string; cacheBust?: string;
}): Promise<DataFetcherResponse<api.SearchSpaceResult[]>>; }): Promise<DataFetcherResponse<api.SearchSpaceResult[]>>;
/**
* Render an integration UI.
*/
renderIntegrationUi(params: {
integrationName: string;
request: api.RenderIntegrationUI;
}): Promise<DataFetcherResponse<api.ContentKitRenderOutput>>;
} }
+5
View File
@@ -64,6 +64,11 @@ export const GITBOOK_DISABLE_TRACKING = Boolean(
export const GITBOOK_INTEGRATIONS_HOST = export const GITBOOK_INTEGRATIONS_HOST =
process.env.GITBOOK_INTEGRATIONS_HOST || 'integrations.gitbook.com'; process.env.GITBOOK_INTEGRATIONS_HOST || 'integrations.gitbook.com';
/**
* Hostname for fonts.
*/
export const GITBOOK_FONTS_URL = process.env.GITBOOK_FONTS_URL || 'https://fonts.gitbook.com';
/** /**
* Endpoint to use for resizing images. * Endpoint to use for resizing images.
* It should be a Cloudflare domain with image resizing enabled. * It should be a Cloudflare domain with image resizing enabled.
@@ -1,7 +1,7 @@
import 'server-only'; import 'server-only';
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env'; import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env';
import type { GitBookSpaceLinker } from '../links'; import type { GitBookLinker } from '../links';
import { type SignatureVersion, generateImageSignature } from './signatures'; import { type SignatureVersion, generateImageSignature } from './signatures';
import type { ImageResizer } from './types'; import type { ImageResizer } from './types';
@@ -37,7 +37,7 @@ export function createImageResizer({
linker, linker,
}: { }: {
/** The linker to use to create URLs. */ /** The linker to use to create URLs. */
linker: GitBookSpaceLinker; linker: GitBookLinker;
/** The host name of the current site. */ /** The host name of the current site. */
host: string; host: string;
}): ImageResizer { }): ImageResizer {
@@ -62,7 +62,7 @@ export function createImageResizer({
url: urlInput, url: urlInput,
}); });
const url = linker.toAbsoluteURL(linker.toPathInContent('/~gitbook/image')); const url = linker.toAbsoluteURL(linker.toPathInSite('/~gitbook/image'));
const searchParams = new URLSearchParams(); const searchParams = new URLSearchParams();
searchParams.set('url', getImageAPIUrl(urlInput)); searchParams.set('url', getImageAPIUrl(urlInput));
+43 -27
View File
@@ -1,25 +1,51 @@
import { describe, expect, it } from 'bun:test'; import { describe, expect, it } from 'bun:test';
import { appendBasePathToLinker, createLinker } from './links'; import { createLinker } from './links';
const root = createLinker({ const root = createLinker({
host: 'docs.company.com', host: 'docs.company.com',
pathname: '/', spaceBasePath: '/',
siteBasePath: '/',
}); });
const variantInSection = createLinker({ const variantInSection = createLinker({
host: 'docs.company.com', host: 'docs.company.com',
pathname: '/section/variant', spaceBasePath: '/section/variant',
siteBasePath: '/',
});
const siteGitBookIO = createLinker({
host: 'org.gitbook.io',
spaceBasePath: '/sitename/variant/',
siteBasePath: '/sitename/',
}); });
describe('toPathInContent', () => { describe('toPathInContent', () => {
it('should return the correct path', () => { it('should return the correct path', () => {
expect(root.toPathInContent('some/path')).toBe('/some/path'); expect(root.toPathInSpace('some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('some/path')).toBe('/section/variant/some/path'); expect(variantInSection.toPathInSpace('some/path')).toBe('/section/variant/some/path');
}); });
it('should handle leading slash', () => { it('should handle leading slash', () => {
expect(root.toPathInContent('/some/path')).toBe('/some/path'); expect(root.toPathInSpace('/some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('/some/path')).toBe('/section/variant/some/path'); expect(variantInSection.toPathInSpace('/some/path')).toBe('/section/variant/some/path');
});
});
describe('toPathInSite', () => {
it('should return the correct path', () => {
expect(root.toPathInSite('some/path')).toBe('/some/path');
expect(siteGitBookIO.toPathInSite('some/path')).toBe('/sitename/some/path');
});
});
describe('toRelativePathInSite', () => {
it('should return the correct path', () => {
expect(root.toRelativePathInSite('/some/path')).toBe('some/path');
expect(siteGitBookIO.toRelativePathInSite('/sitename/some/path')).toBe('some/path');
});
it('should preserve absolute paths outside of the site', () => {
expect(siteGitBookIO.toRelativePathInSite('/outside/some/path')).toBe('/outside/some/path');
}); });
}); });
@@ -32,27 +58,17 @@ describe('toAbsoluteURL', () => {
}); });
}); });
describe('appendBasePathToLinker', () => { describe('toLinkForContent', () => {
const prefixedRoot = appendBasePathToLinker(root, '/section/variant'); it('should return the correct path', () => {
const prefixedVariantInSection = appendBasePathToLinker(variantInSection, '/base'); expect(root.toLinkForContent('https://docs.company.com/some/path')).toBe('/some/path');
expect(siteGitBookIO.toLinkForContent('https://org.gitbook.io/sitename/some/path')).toBe(
describe('toPathInContent', () => { '/sitename/some/path'
it('should return the correct path', () => { );
expect(prefixedRoot.toPathInContent('some/path')).toBe('/section/variant/some/path');
expect(prefixedVariantInSection.toPathInContent('some/path')).toBe(
'/section/variant/base/some/path'
);
});
}); });
describe('toAbsoluteURL', () => { it('should preserve an absolute URL if the site is not the same', () => {
it('should return the correct path', () => { expect(siteGitBookIO.toLinkForContent('https://org.gitbook.io/anothersite/some/path')).toBe(
expect(prefixedRoot.toAbsoluteURL('some/path')).toBe( 'https://org.gitbook.io/anothersite/some/path'
'https://docs.company.com/some/path' );
);
expect(prefixedVariantInSection.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
});
}); });
}); });
+55 -44
View File
@@ -1,4 +1,5 @@
import { getPagePath } from '@/lib/pages'; import { getPagePath } from '@/lib/pages';
import { withLeadingSlash, withTrailingSlash } from '@/lib/paths';
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api'; import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import warnOnce from 'warn-once'; import warnOnce from 'warn-once';
@@ -7,17 +8,28 @@ import warnOnce from 'warn-once';
* *
* URL levels: * URL levels:
* *
* https://docs.company.com/section/variant/page * https://docs.company.com/basename/section/variant/page
* *
* toPathInContent('some/path') => /section/variant/some/path * toPathInSpace('some/path') => /basename/section/variant/some/path
* toPathForPage({ pages, page }) => /section/variant/some/path * toPathInSite('some/path') => /basename/some/path
* toPathForPage({ pages, page }) => /basename/section/variant/some/path
* toAbsoluteURL('some/path') => https://docs.company.com/some/path * toAbsoluteURL('some/path') => https://docs.company.com/some/path
*/ */
export interface GitBookSpaceLinker { export interface GitBookLinker {
/** /**
* Generate an absolute path for a relative path to the current content. * Generate an absolute path for a relative path to the current content.
*/ */
toPathInContent(relativePath: string): string; toPathInSpace(relativePath: string): string;
/**
* Generate an absolute path for a relative path to the current site.
*/
toPathInSite(relativePath: string): string;
/**
* Transform an absolute path in a site, to a relative path from the root of the site.
*/
toRelativePathInSite(absolutePath: string): string;
/** /**
* Generate an absolute path for a page in the current content. * Generate an absolute path for a page in the current content.
@@ -48,14 +60,36 @@ export function createLinker(
servedOn: { servedOn: {
protocol?: string; protocol?: string;
host?: string; host?: string;
pathname: string;
/** The base path of the space */
spaceBasePath: string;
/** The base path of the site */
siteBasePath: string;
} }
): GitBookSpaceLinker { ): GitBookLinker {
warnOnce(!servedOn.host, 'No host provided to createLinker. It can lead to issues with links.'); warnOnce(!servedOn.host, 'No host provided to createLinker. It can lead to issues with links.');
const linker: GitBookSpaceLinker = { const siteBasePath = withTrailingSlash(withLeadingSlash(servedOn.siteBasePath));
toPathInContent(relativePath: string): string { const spaceBasePath = withTrailingSlash(withLeadingSlash(servedOn.spaceBasePath));
return joinPaths(servedOn.pathname, relativePath);
const linker: GitBookLinker = {
toPathInSpace(relativePath: string): string {
return joinPaths(spaceBasePath, relativePath);
},
toPathInSite(relativePath: string): string {
return joinPaths(siteBasePath, relativePath);
},
toRelativePathInSite(absolutePath: string): string {
const normalizedPath = withLeadingSlash(absolutePath);
if (!normalizedPath.startsWith(servedOn.siteBasePath)) {
return normalizedPath;
}
return normalizedPath.slice(servedOn.siteBasePath.length);
}, },
toAbsoluteURL(absolutePath: string): string { toAbsoluteURL(absolutePath: string): string {
@@ -67,48 +101,25 @@ export function createLinker(
}, },
toPathForPage({ pages, page, anchor }) { toPathForPage({ pages, page, anchor }) {
return linker.toPathInContent(getPagePath(pages, page)) + (anchor ? `#${anchor}` : ''); return linker.toPathInSpace(getPagePath(pages, page)) + (anchor ? `#${anchor}` : '');
}, },
toLinkForContent(url: string): string { toLinkForContent(rawURL: string): string {
return url; const url = new URL(rawURL);
// If the link points to a content in the same site, we return an absolute path
// instead of a full URL; it makes it possible to use router navigation
if (url.hostname === servedOn.host && url.pathname.startsWith(servedOn.siteBasePath)) {
return url.pathname;
}
return rawURL;
}, },
}; };
return linker; return linker;
} }
/**
* Append a prefix to a linker.
*/
export function appendBasePathToLinker(
linker: GitBookSpaceLinker,
basePath: string
): GitBookSpaceLinker {
const linkerWithPrefix: GitBookSpaceLinker = {
toPathInContent(relativePath: string): string {
return linker.toPathInContent(joinPaths(basePath, relativePath));
},
toAbsoluteURL(absolutePath: string): string {
return linker.toAbsoluteURL(absolutePath);
},
toPathForPage({ pages, page, anchor }) {
return (
linkerWithPrefix.toPathInContent(getPagePath(pages, page)) +
(anchor ? `#${anchor}` : '')
);
},
toLinkForContent(url: string): string {
return linker.toLinkForContent(url);
},
};
return linkerWithPrefix;
}
function joinPaths(prefix: string, path: string): string { function joinPaths(prefix: string, path: string): string {
const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`; const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`;
const suffixPath = path.startsWith('/') ? path.slice(1) : path; const suffixPath = path.startsWith('/') ? path.slice(1) : path;
-19
View File
@@ -32,11 +32,6 @@ export enum MiddlewareHeaders {
*/ */
Customization = 'x-gitbook-customization', Customization = 'x-gitbook-customization',
/**
* The visitor token used to access this content
*/
VisitorAuthToken = 'x-gitbook-visitor-token',
/** /**
* The API token used to fetch the content. * The API token used to fetch the content.
* This should only be passed for non-site dynamic routes. * This should only be passed for non-site dynamic routes.
@@ -105,20 +100,6 @@ export async function getThemeFromMiddleware() {
: CustomizationThemeMode.Dark; : CustomizationThemeMode.Dark;
} }
/**
* Get the visitor auth token from the middleware headers.
* This function should only be called in a dynamic route.
*/
export async function getVisitorAuthTokenFromMiddleware(): Promise<string | null> {
const headersList = await headers();
const visitorAuthToken = headersList.get(MiddlewareHeaders.VisitorAuthToken);
if (!visitorAuthToken) {
return null;
}
return visitorAuthToken;
}
/** /**
* Get the API token from the middleware headers. * Get the API token from the middleware headers.
* This function should only be called in a dynamic route. * This function should only be called in a dynamic route.
@@ -16,8 +16,8 @@ export async function getServerActionBaseContext() {
return getBaseContext({ return getBaseContext({
siteURL, siteURL,
siteURLData,
urlMode, urlMode,
apiToken: siteURLData.apiToken,
}); });
} }
+197 -156
View File
@@ -1,6 +1,7 @@
import { CustomizationThemeMode } from '@gitbook/api'; import { CustomizationThemeMode } from '@gitbook/api';
import type { NextRequest } from 'next/server'; import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import rison from 'rison';
import { getContentSecurityPolicy } from '@/lib/csp'; import { getContentSecurityPolicy } from '@/lib/csp';
import { validateSerializedCustomization } from '@/lib/customization'; import { validateSerializedCustomization } from '@/lib/customization';
@@ -13,7 +14,6 @@ import {
normalizeVisitorAuthURL, normalizeVisitorAuthURL,
} from '@/lib/visitor-token'; } from '@/lib/visitor-token';
import { serveResizedImage } from '@/routes/image'; import { serveResizedImage } from '@/routes/image';
import { getLinkerForSiteURL } from '@v2/lib/context';
import { import {
DataFetcherError, DataFetcherError,
getPublishedContentByURL, getPublishedContentByURL,
@@ -41,7 +41,7 @@ export async function middleware(request: NextRequest) {
return NextResponse.redirect(normalized.toString()); return NextResponse.redirect(normalized.toString());
} }
for (const handler of [serveSiteRoutes, servePreviewRoutes]) { for (const handler of [serveSiteRoutes, serveSpacePDFRoutes]) {
const result = await handler(requestURL, request); const result = await handler(requestURL, request);
if (result) { if (result) {
return result; return result;
@@ -83,181 +83,182 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
// Detect and extract the visitor authentication token from the request // Detect and extract the visitor authentication token from the request
// //
// @ts-ignore - request typing // @ts-ignore - request typing
const visitorToken = getVisitorToken(request, siteURL); const visitorToken = getVisitorToken({
cookies: request.cookies.getAll(),
url: siteURL,
});
const data = await throwIfDataError( const withAPIToken = async (apiToken: string | null) => {
getPublishedContentByURL({ const siteURLData = await throwIfDataError(
url: siteURL.toString(), getPublishedContentByURL({
visitorAuthToken: visitorToken?.token ?? null, url: siteURL.toString(),
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow visitorAuthToken: visitorToken?.token ?? null,
// redirecting when the token is invalid as we could be dealing with stale token stored in the cookie. // When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// For example when the VA backend signature has changed but the token stored in the cookie is not yet expired. // redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
redirectOnError: visitorToken?.source === 'visitor-auth-cookie', // For example when the VA backend signature has changed but the token stored in the cookie is not yet expired.
}) redirectOnError: visitorToken?.source === 'visitor-auth-cookie',
);
let cookies: ResponseCookies = {};
// // Use the API token passed in the request, if any
// Handle redirects // as it could be used for .preview hostnames
// apiToken,
if ('redirect' in data) { })
// biome-ignore lint/suspicious/noConsole: we want to log the redirect );
console.log('redirect', data.redirect); const cookies: ResponseCookies = [];
if (data.target === 'content') {
// For content redirects, we use the linker to redirect the optimal URL
// during development and testing in 'url' mode.
const linker = getLinkerForSiteURL({
siteURL,
urlMode: mode,
});
const contentRedirect = new URL(linker.toLinkForContent(data.redirect), request.url); //
// Handle redirects
//
if ('redirect' in siteURLData) {
// biome-ignore lint/suspicious/noConsole: we want to log the redirect
console.log('redirect', siteURLData.redirect);
if (siteURLData.target === 'content') {
let contentRedirect = new URL(siteURLData.redirect, request.url);
// Keep the same search params as the original request // For content redirects, we redirect using the /url/:url format
// as it might contain a VA token // during development and testing in 'url' mode.
contentRedirect.search = request.nextUrl.search; if (mode === 'url') {
const urlObject = new URL(siteURLData.redirect);
contentRedirect = new URL(
`/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`,
request.url
);
}
return NextResponse.redirect(contentRedirect); // Keep the same search params as the original request
// as it might contain a VA token
contentRedirect.search = request.nextUrl.search;
return NextResponse.redirect(contentRedirect);
}
return NextResponse.redirect(siteURLData.redirect);
} }
return NextResponse.redirect(data.redirect); cookies.push(...getResponseCookiesForVisitorAuth(siteURLData.siteBasePath, visitorToken));
}
cookies = { //
...cookies, // Make sure the URL is clean of any va token after a successful lookup
...getResponseCookiesForVisitorAuth(data.basePath, visitorToken), // The token is stored in a cookie that is set on the redirect response
//
const incomingURL = mode === 'url' ? requestURL : siteURL;
const requestURLWithoutToken = normalizeVisitorAuthURL(incomingURL);
if (
requestURLWithoutToken !== incomingURL &&
requestURLWithoutToken.toString() !== incomingURL.toString()
) {
return writeResponseCookies(
NextResponse.redirect(requestURLWithoutToken.toString()),
cookies
);
}
//
// Render and serve the content
//
// The route is static, except when using dynamic parameters from query params
// (customization override, theme, etc)
let routeType: 'dynamic' | 'static' = 'static';
const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${siteURL.origin}${siteURLData.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(siteURLData));
// Preview of customization/theme
const customization = siteURL.searchParams.get('customization');
if (customization && validateSerializedCustomization(customization)) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Customization, customization);
}
const theme = siteURL.searchParams.get('theme');
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Theme, theme);
}
// We support forcing dynamic routes by setting a `gitbook-dynamic-route` cookie
// This is useful for testing dynamic routes.
if (request.cookies.has('gitbook-dynamic-route')) {
routeType = 'dynamic';
}
// Pass a x-forwarded-host and origin that are equal to ensure Next doesn't block server actions when proxied
requestHeaders.set('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin);
const siteURLWithoutProtocol = `${siteURL.host}${siteURLData.basePath}`;
const { pathname, routeType: routeTypeFromPathname } = encodePathInSiteContent(
siteURLData.pathname
);
routeType = routeTypeFromPathname ?? routeType;
const route = [
'sites',
routeType,
mode,
encodeURIComponent(siteURLWithoutProtocol),
encodeURIComponent(rison.encode(siteURLData)),
pathname,
].join('/');
console.log(`rewriting ${request.nextUrl.toString()} to ${route}`);
const rewrittenURL = new URL(`/${route}`, request.nextUrl.toString());
const response = NextResponse.rewrite(rewrittenURL, {
request: {
headers: requestHeaders,
},
});
// Add Content Security Policy header
response.headers.set('content-security-policy', getContentSecurityPolicy());
// Basic security headers
response.headers.set('strict-transport-security', 'max-age=31536000');
response.headers.set('referrer-policy', 'no-referrer-when-downgrade');
response.headers.set('x-content-type-options', 'nosniff');
// Debug header
response.headers.set('x-gitbook-route-type', routeType);
response.headers.set('x-gitbook-route-site', siteURLWithoutProtocol);
return writeResponseCookies(response, cookies);
}; };
// // For https://preview/<siteURL> requests,
// Make sure the URL is clean of any va token after a successful lookup if (siteURL.hostname === 'preview') {
// The token is stored in a cookie that is set on the redirect response return serveWithQueryAPIToken(
// // We scope the API token to the site ID.
const requestURLWithoutToken = normalizeVisitorAuthURL(requestURL); `${siteURL.hostname}/${requestURL.pathname.slice(1).split('/')[0]}`,
if (requestURLWithoutToken.toString() !== requestURL.toString()) { request,
return writeResponseCookies( withAPIToken
NextResponse.redirect(requestURLWithoutToken.toString()),
cookies
); );
} }
// return withAPIToken(null);
// Render and serve the content
//
// When visitor has authentication (adaptive content or VA), we serve dynamic routes.
let routeType = visitorToken ? 'dynamic' : 'static';
const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${siteURL.origin}${data.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data));
// Preview of customization/theme
const customization = siteURL.searchParams.get('customization');
if (customization && validateSerializedCustomization(customization)) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Customization, customization);
}
const theme = siteURL.searchParams.get('theme');
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Theme, theme);
}
// We support forcing dynamic routes by setting a `gitbook-dynamic-route` cookie
// This is useful for testing dynamic routes.
if (request.cookies.has('gitbook-dynamic-route')) {
routeType = 'dynamic';
}
// Pass a x-forwarded-host and origin that are equal to ensure Next doesn't block server actions when proxied
requestHeaders.set('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin);
const siteURLWithoutProtocol = `${siteURL.host}${data.basePath}`;
const { pathname, routeType: routeTypeFromPathname } = encodePathInSiteContent(data.pathname);
routeType = routeTypeFromPathname ?? routeType;
const route = [
'sites',
routeType,
mode,
encodeURIComponent(siteURLWithoutProtocol),
pathname,
].join('/');
console.log(`rewriting ${request.nextUrl.toString()} to ${route}`);
const rewrittenURL = new URL(`/${route}`, request.nextUrl.toString());
const response = NextResponse.rewrite(rewrittenURL, {
request: {
headers: requestHeaders,
},
});
// Add Content Security Policy header
response.headers.set('content-security-policy', getContentSecurityPolicy());
// Basic security headers
response.headers.set('strict-transport-security', 'max-age=31536000');
response.headers.set('referrer-policy', 'no-referrer-when-downgrade');
response.headers.set('x-content-type-options', 'nosniff');
// Debug header
response.headers.set('x-gitbook-route-type', routeType);
response.headers.set('x-gitbook-route-site', siteURLWithoutProtocol);
return writeResponseCookies(response, cookies);
} }
/** /**
* Serve routes for previewing unpublished content. * Serve routes for PDF export for a space: /~space/:spaceId/~gitbook/pdf
* Routes are:
* - PDF export for a space: /~space/:spaceId/~gitbook/pdf
* - Preview of an unpublished site: /~site/:siteId/
*/ */
async function servePreviewRoutes(requestURL: URL, request: NextRequest) { async function serveSpacePDFRoutes(requestURL: URL, request: NextRequest) {
const pathnameParts = requestURL.pathname.slice(1).split('/'); const pathnameParts = requestURL.pathname.slice(1).split('/');
if (pathnameParts[0] !== '~space' && pathnameParts[0] !== '~site') { if (pathnameParts[0] !== '~space' && pathnameParts[0] !== '~site') {
return null; return null;
} }
// We store the API token in a cookie that is scoped to the specific preview route return serveWithQueryAPIToken(
// to avoid errors when multiple previews are opened in different tabs. pathnameParts.slice(0, 2).join('/'),
const cookieName = getPathScopedCookieName( request,
'gitbook-api-token', async (apiToken) => {
pathnameParts.slice(0, 2).join('/') // Handle the rest with the router default logic
); return NextResponse.next({
headers: {
// Extract a potential GitBook API token passed in the request [MiddlewareHeaders.APIToken]: apiToken,
// If found, we redirect to the same URL but with the token in the cookie
const queryAPIToken = requestURL.searchParams.get('token');
if (queryAPIToken) {
requestURL.searchParams.delete('token');
return writeResponseCookies(NextResponse.redirect(requestURL.toString()), {
[cookieName]: {
value: queryAPIToken,
options: {
httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60, // 1 hour
}, },
}, });
}); }
} );
const apiToken = request.cookies.get(cookieName)?.value;
if (!apiToken) {
throw new DataFetcherError('Missing API token', 400);
}
// Handle the rest with the router default logic
return NextResponse.next({
headers: {
[MiddlewareHeaders.APIToken]: apiToken,
},
});
} }
/** /**
@@ -274,6 +275,45 @@ function serveErrorResponse(error: Error) {
throw error; throw error;
} }
/**
* Server a response with an API token obtained from the query params.
*/
async function serveWithQueryAPIToken(
scopePath: string,
request: NextRequest,
serve: (apiToken: string) => Promise<NextResponse>
) {
// We store the API token in a cookie that is scoped to the specific route
// to avoid errors when multiple previews are opened in different tabs.
const cookieName = getPathScopedCookieName('gitbook-api-token', scopePath);
// Extract a potential GitBook API token passed in the request
// If found, we redirect to the same URL but with the token in the cookie
const queryAPIToken = request.nextUrl.searchParams.get('token');
if (queryAPIToken) {
request.nextUrl.searchParams.delete('token');
return writeResponseCookies(NextResponse.redirect(request.nextUrl.toString()), [
{
name: cookieName,
value: queryAPIToken,
options: {
httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60, // 1 hour
},
},
]);
}
const apiToken = request.cookies.get(cookieName)?.value;
if (!apiToken) {
throw new DataFetcherError('Missing API token', 400);
}
return serve(apiToken);
}
/** /**
* The URL of the GitBook content can be passed in 3 different ways (in order of priority): * The URL of the GitBook content can be passed in 3 different ways (in order of priority):
* - The request has a `X-GitBook-URL` header: * - The request has a `X-GitBook-URL` header:
@@ -346,6 +386,7 @@ function encodePathInSiteContent(rawPathname: string): {
case '~gitbook/icon': case '~gitbook/icon':
case 'llms.txt': case 'llms.txt':
case 'sitemap.xml': case 'sitemap.xml':
case 'sitemap-pages.xml':
case 'robots.txt': case 'robots.txt':
return { pathname }; return { pathname };
case '~gitbook/pdf': case '~gitbook/pdf':
@@ -371,8 +412,8 @@ function appendQueryParams(url: URL, from: URLSearchParams) {
* Write the cookies to a response. * Write the cookies to a response.
*/ */
function writeResponseCookies<R extends NextResponse>(response: R, cookies: ResponseCookies): R { function writeResponseCookies<R extends NextResponse>(response: R, cookies: ResponseCookies): R {
Object.entries(cookies).forEach(([key, { value, options }]) => { cookies.forEach((cookie) => {
response.cookies.set(key, value, options); response.cookies.set(cookie.name, cookie.value, cookie.options);
}); });
return response; return response;
-3
View File
@@ -23,8 +23,5 @@
## Caching ## Caching
# GITBOOK_OUTPUT_CACHE=true # GITBOOK_OUTPUT_CACHE=true
### Sentry ###
# SENTRY_DSN=xxx
### Silent logs ### Silent logs
# SILENT=true # SILENT=true
-3
View File
@@ -23,9 +23,6 @@ next-env.d.ts
# visual tests # visual tests
screenshots/ screenshots/
# Sentry Config File
.sentryclirc
/test-results/ /test-results/
/playwright-report/ /playwright-report/
/blob-report/ /blob-report/
+34
View File
@@ -1,5 +1,39 @@
# gitbook # gitbook
## 0.8.2
### Patch Changes
- ed07206: Fix OpenAPI path overflow on mobile
- 4dab1c5: Fix alignment of `prominent` search bar on full-width pages
- 6eae764: Support body examples
- 54ee014: Add initial support for loading custom fonts
- d2facb2: Mark properties as optional if not required
- bba2e52: Fix site redirects when it includes a section/variant path
- 4723f03: Restyle section group dropdown
- 24b7808: Fix `prominent` search bar width on `md` screens
- 1fe3286: Fix OpenAPI block overflow issue
- Updated dependencies [48c18c0]
- Updated dependencies [6eae764]
- Updated dependencies [7212973]
- Updated dependencies [d2facb2]
- Updated dependencies [73e2b47]
- Updated dependencies [70be2c6]
- Updated dependencies [fc00b51]
- Updated dependencies [a84b06b]
- @gitbook/openapi-parser@2.1.1
- @gitbook/react-openapi@1.1.6
## 0.8.1
### Patch Changes
- 886e204: Update OpenAPI operation path design
- Updated dependencies [886e204]
- Updated dependencies [4f0a772]
- @gitbook/react-openapi@1.1.5
- @gitbook/colors@0.3.0
## 0.8.0 ## 0.8.0
### Minor Changes ### Minor Changes
+34 -20
View File
@@ -1,4 +1,4 @@
import { type TestsCase, runTestCases } from './util'; import { type TestsCase, runTestCases, waitForCookiesDialog } from './util';
/** A list of test cases to run on the customers' docs sites. */ /** A list of test cases to run on the customers' docs sites. */
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
@@ -6,14 +6,21 @@ const testCases: TestsCase[] = [
name: 'Snyk', name: 'Snyk',
contentBaseURL: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [ tests: [
{ name: 'Home', url: '/' }, { name: 'Home', url: '/', run: waitForCookiesDialog },
{ name: 'OpenAPI', url: '/snyk-api/reference/apps' }, { name: 'OpenAPI', url: '/snyk-api/reference/apps', run: waitForCookiesDialog },
], ],
}, },
{ {
name: 'Nexthink', name: 'Nexthink',
contentBaseURL: 'https://docs.nexthink.com', contentBaseURL: 'https://docs.nexthink.com',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }], tests: [
{
name: 'Home',
url: '/',
screenshot: { waitForTOCScrolling: false },
run: waitForCookiesDialog,
},
],
}, },
{ {
name: 'asiksupport-stg.dto.kemkes.go.id', name: 'asiksupport-stg.dto.kemkes.go.id',
@@ -33,7 +40,7 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.dify.ai', name: 'docs.dify.ai',
contentBaseURL: 'https://docs.dify.ai', contentBaseURL: 'https://docs.dify.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'seeddao.gitbook.io', name: 'seeddao.gitbook.io',
@@ -63,27 +70,27 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.portainer.io', name: 'docs.portainer.io',
contentBaseURL: 'https://docs.portainer.io', contentBaseURL: 'https://docs.portainer.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.chirptoken.io', name: 'docs.chirptoken.io',
contentBaseURL: 'https://docs.chirptoken.io', contentBaseURL: 'https://docs.chirptoken.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.dexscreener.com', name: 'docs.dexscreener.com',
contentBaseURL: 'https://docs.dexscreener.com', contentBaseURL: 'https://docs.dexscreener.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.pancakeswap.finance', name: 'docs.pancakeswap.finance',
contentBaseURL: 'https://docs.pancakeswap.finance', contentBaseURL: 'https://docs.pancakeswap.finance',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'book.character.ai', name: 'book.character.ai',
contentBaseURL: 'https://book.character.ai', contentBaseURL: 'https://book.character.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.tradeonnova.io', name: 'docs.tradeonnova.io',
@@ -103,7 +110,7 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.keeper.io', name: 'docs.keeper.io',
contentBaseURL: 'https://docs.keeper.io', contentBaseURL: 'https://docs.keeper.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'adiblar.gitbook.io', name: 'adiblar.gitbook.io',
@@ -138,12 +145,12 @@ const testCases: TestsCase[] = [
{ {
name: 'meshnet.nordvpn.com', name: 'meshnet.nordvpn.com',
contentBaseURL: 'https://meshnet.nordvpn.com', contentBaseURL: 'https://meshnet.nordvpn.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'manual.bubble.io', name: 'manual.bubble.io',
contentBaseURL: 'https://manual.bubble.io', contentBaseURL: 'https://manual.bubble.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.tickettool.xyz', name: 'docs.tickettool.xyz',
@@ -158,12 +165,12 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.cherry-ai.com', name: 'docs.cherry-ai.com',
contentBaseURL: 'https://docs.cherry-ai.com', contentBaseURL: 'https://docs.cherry-ai.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.snyk.io', name: 'docs.snyk.io',
contentBaseURL: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.realapp.link', name: 'docs.realapp.link',
@@ -188,7 +195,14 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.umbraco.com', name: 'docs.umbraco.com',
contentBaseURL: 'https://docs.umbraco.com', contentBaseURL: 'https://docs.umbraco.com',
tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }], tests: [
{
name: 'Home',
url: '/welcome',
run: waitForCookiesDialog,
screenshot: { waitForTOCScrolling: false },
},
],
}, },
{ {
name: 'sosovalue-white-paper.gitbook.io', name: 'sosovalue-white-paper.gitbook.io',
@@ -198,12 +212,12 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.revrobotics.com', name: 'docs.revrobotics.com',
contentBaseURL: 'https://docs.revrobotics.com', contentBaseURL: 'https://docs.revrobotics.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'chartschool.stockcharts.com', name: 'chartschool.stockcharts.com',
contentBaseURL: 'https://chartschool.stockcharts.com', contentBaseURL: 'https://chartschool.stockcharts.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.soniclabs.com', name: 'docs.soniclabs.com',
@@ -218,7 +232,7 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.thousandeyes.com', name: 'docs.thousandeyes.com',
contentBaseURL: 'https://docs.thousandeyes.com', contentBaseURL: 'https://docs.thousandeyes.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
{ {
name: 'docs.raydium.io', name: 'docs.raydium.io',
@@ -228,7 +242,7 @@ const testCases: TestsCase[] = [
{ {
name: 'docs.fluentbit.io', name: 'docs.fluentbit.io',
contentBaseURL: 'https://docs.fluentbit.io', contentBaseURL: 'https://docs.fluentbit.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
}, },
]; ];
+45 -3
View File
@@ -367,6 +367,29 @@ const testCases: TestsCase[] = [
}, },
], ],
}, },
{
name: 'Site Preview',
skip: process.env.ARGOS_BUILD_NAME !== 'v2-vercel',
tests: [
{
name: 'Main content',
url: async () => {
const data = await getSiteAPIToken(
'https://gitbook.gitbook.io/test-gitbook-open/'
);
const searchParams = new URLSearchParams();
searchParams.set('token', data.apiToken);
return `url/preview/${data.site}/?${searchParams.toString()}`;
},
screenshot: false,
run: async (page) => {
await expect(page.locator('[data-testid="table-of-contents"]')).toBeVisible();
},
},
],
},
{ {
name: 'Content tests', name: 'Content tests',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
@@ -386,7 +409,7 @@ const testCases: TestsCase[] = [
url: 'blocks/block-images', url: 'blocks/block-images',
run: waitForCookiesDialog, run: waitForCookiesDialog,
fullPage: true, fullPage: true,
screenshot: { threshold: 0.8 }, screenshot: { threshold: 0.9 },
}, },
{ {
name: 'Images (with zoom)', name: 'Images (with zoom)',
@@ -397,7 +420,6 @@ const testCases: TestsCase[] = [
await zoomImage.first().click(); await zoomImage.first().click();
await expect(page.getByTestId('zoom-image-modal')).toBeVisible(); await expect(page.getByTestId('zoom-image-modal')).toBeVisible();
}, },
fullPage: true,
screenshot: { threshold: 0.8 }, screenshot: { threshold: 0.8 },
}, },
{ {
@@ -432,7 +454,12 @@ const testCases: TestsCase[] = [
{ {
name: 'Integration Blocks', name: 'Integration Blocks',
url: 'blocks/integrations', url: 'blocks/integrations',
run: waitForCookiesDialog, run: async (page) => {
await waitForCookiesDialog(page);
const mermaidIframe = page.locator('iframe[title*="mermaid"]').contentFrame();
await expect(mermaidIframe.getByText('Mermaid', { exact: true })).toBeVisible();
await expect(mermaidIframe.getByText('Diagram', { exact: true })).toBeVisible();
},
}, },
{ {
name: 'Tables', name: 'Tables',
@@ -781,6 +808,21 @@ const testCases: TestsCase[] = [
}, },
], ],
}, },
{
name: 'Site Redirects with sections',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
tests: [
{
// This test that a redirect that incudes a section path works
name: 'Redirect to Quickstart page',
url: 'sections-2/redirect-test',
run: async (page) => {
await expect(page.locator('h1')).toHaveText('Quickstart');
},
screenshot: false,
},
],
},
{ {
name: 'Share links', name: 'Share links',
contentBaseURL: 'https://gitbook.gitbook.io/gbo-tests-share-links/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
+71 -31
View File
@@ -63,6 +63,7 @@ export interface Test {
export type TestsCase = { export type TestsCase = {
name: string; name: string;
skip?: boolean;
tests: Array<Test>; tests: Array<Test>;
contentBaseURL?: string; contentBaseURL?: string;
}; };
@@ -133,11 +134,8 @@ export const headerLinks: CustomizationHeaderItem[] = [
]; ];
export async function waitForCookiesDialog(page: Page) { export async function waitForCookiesDialog(page: Page) {
const dialog = page.getByRole('dialog', { name: 'Cookies' }); const dialog = page.getByTestId('cookies-dialog');
const accept = dialog.getByRole('button', { name: 'Accept' }); await expect(dialog).toBeVisible();
const reject = dialog.getByRole('button', { name: 'Reject' });
await expect(accept).toBeVisible();
await expect(reject).toBeVisible();
} }
/** /**
@@ -145,6 +143,10 @@ export async function waitForCookiesDialog(page: Page) {
*/ */
export function runTestCases(testCases: TestsCase[]) { export function runTestCases(testCases: TestsCase[]) {
for (const testCase of testCases) { for (const testCase of testCases) {
if (testCase.skip) {
continue;
}
test.describe(testCase.name, () => { test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) { for (const testEntry of testCase.tests) {
const testFn = testEntry.only ? test.only : test; const testFn = testEntry.only ? test.only : test;
@@ -190,14 +192,15 @@ export function runTestCases(testCases: TestsCase[]) {
await argosScreenshot(page, `${testCase.name} - ${testEntry.name}`, { await argosScreenshot(page, `${testCase.name} - ${testEntry.name}`, {
viewports: ['macbook-16', 'macbook-13', 'ipad-2', 'iphone-x'], viewports: ['macbook-16', 'macbook-13', 'ipad-2', 'iphone-x'],
argosCSS: ` argosCSS: `
/* Hide Intercom */ /* Hide Intercom */
.intercom-lightweight-app { .intercom-lightweight-app {
display: none !important; display: none !important;
} }
`, `,
threshold: screenshotOptions?.threshold ?? undefined, threshold: screenshotOptions?.threshold ?? undefined,
fullPage: testEntry.fullPage ?? false, fullPage: testEntry.fullPage ?? false,
beforeScreenshot: async () => { beforeScreenshot: async ({ runStabilization }) => {
await runStabilization();
await waitForIcons(page); await waitForIcons(page);
if (screenshotOptions?.waitForTOCScrolling !== false) { if (screenshotOptions?.waitForTOCScrolling !== false) {
await waitForTOCScrolling(page); await waitForTOCScrolling(page);
@@ -319,29 +322,66 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
* Wait for all icons present on the page to be loaded. * Wait for all icons present on the page to be loaded.
*/ */
async function waitForIcons(page: Page) { async function waitForIcons(page: Page) {
await page.waitForFunction(async () => { await page.waitForFunction(() => {
function loadImage(src: string) { const urls = new Set<string>();
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = (_error) => reject(new Error(`Failed to load image: ${src}`));
img.src = src;
});
}
const icons = Array.from(document.querySelectorAll('svg.gb-icon')); const icons = Array.from(document.querySelectorAll('svg.gb-icon'));
await Promise.all( const results = icons.map((icon) => {
icons.map(async (icon) => { if (!(icon instanceof SVGElement)) {
// url("https://ka-p.fontawesome.com/releases/v6.6.0/svgs/light/moon.svg?v=2&token=a463935e93") throw new Error('Icon is not an SVGElement');
const maskImage = window.getComputedStyle(icon).getPropertyValue('mask-image'); }
const urlMatch = maskImage.match(/url\("([^"]+)"\)/);
const url = urlMatch ? urlMatch[1] : null; // If loaded, good it passes the test.
if (!url) { if (icon.dataset.loadingState === 'loaded') {
throw new Error('No mask-image'); return true;
} }
await loadImage(url);
}) // If not loaded yet, we need to load it.
); if (icon.dataset.loadingState === 'pending') {
return false;
}
// Ignore icons that are not visible.
if (!icon.checkVisibility()) {
return true;
}
// url("https://ka-p.fontawesome.com/releases/v6.6.0/svgs/light/moon.svg?v=2&token=a463935e93")
const maskImage = window.getComputedStyle(icon).getPropertyValue('mask-image');
const urlMatch = maskImage.match(/url\("([^"]+)"\)/);
const url = urlMatch ? urlMatch[1] : null;
// If URL is invalid we throw an error.
if (!url) {
throw new Error('No mask-image');
}
// If the URL is already loaded, we just mark it as loaded.
if (urls.has(url)) {
icon.dataset.loadingState = 'loaded';
return true;
}
// Mark the icon as pending and load the image.
icon.dataset.loadingState = 'pending';
// Mark the URL as seen.
urls.add(url);
const img = new Image();
img.src = url;
img.decode().then(() => {
// Wait two frames to let the time to the icon to repaint.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
icon.dataset.loadingState = 'loaded';
});
});
});
return false;
});
return results.every((x) => x);
}); });
} }
+47 -81
View File
@@ -1,83 +1,49 @@
const { withSentryConfig } = require('@sentry/nextjs'); module.exports = {
env: {
module.exports = withSentryConfig( BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7),
{ GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
env: { GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7), GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
SENTRY_RELEASE: process.env.SENTRY_RELEASE ?? '', NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
SENTRY_DSN: process.env.SENTRY_DSN ?? '',
SENTRY_ENVIRONMENT: process.env.SENTRY_ENVIRONMENT ?? 'development',
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
},
webpack(config, { dev, webpack }) {
config.resolve.fallback = {
...config.resolve.fallback,
// Required for `swagger2openapi` to work:
fs: false,
path: false,
http: false,
};
// Tree shake debug code for Sentry
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-with-nextjs
if (!dev) {
config.plugins.push(
new webpack.DefinePlugin({
__SENTRY_DEBUG__: false,
// We always init Sentry with enableTracing: false for now, so this is useless
__SENTRY_TRACING__: false,
__RRWEB_EXCLUDE_IFRAME__: true,
__RRWEB_EXCLUDE_SHADOW_DOM__: true,
__SENTRY_EXCLUDE_REPLAY_WORKER__: true,
})
);
}
return config;
},
async headers() {
return [
// Cache all static assets for 1 year
{
source: '/~gitbook/static/:path*',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
},
],
},
];
},
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
poweredByHeader: false,
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '*.gitbook.io',
},
],
},
}, },
{
release: process.env.SENTRY_RELEASE,
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
// Upload a larger set of source maps for prettier stack traces (increases build time) webpack(config) {
widenClientFileUpload: true, config.resolve.fallback = {
// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load) ...config.resolve.fallback,
tunnelRoute: '/~gitbook/monitoring',
disableLogger: true, // Required for `swagger2openapi` to work:
} fs: false,
); path: false,
http: false,
};
return config;
},
async headers() {
return [
// Cache all static assets for 1 year
{
source: '/~gitbook/static/:path*',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
},
],
},
];
},
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
poweredByHeader: false,
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '*.gitbook.io',
},
],
},
};
+16 -12
View File
@@ -1,6 +1,6 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.8.0", "version": "0.8.2",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev", "dev": "env-cmd --silent -f ../../.env.local next dev",
@@ -29,11 +29,11 @@
"@radix-ui/react-checkbox": "^1.0.4", "@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-navigation-menu": "^1.2.3", "@radix-ui/react-navigation-menu": "^1.2.3",
"@radix-ui/react-popover": "^1.0.7", "@radix-ui/react-popover": "^1.0.7",
"@sentry/nextjs": "8.35.0",
"@sindresorhus/fnv1a": "^3.1.0", "@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1", "@tailwindcss/container-queries": "^0.1.1",
"@tailwindcss/typography": "^0.5.16", "@tailwindcss/typography": "^0.5.16",
"@upstash/redis": "^1.27.1", "@upstash/redis": "^1.27.1",
"ai": "^4.1.46",
"ajv": "^8.12.0", "ajv": "^8.12.0",
"assert-never": "^1.2.1", "assert-never": "^1.2.1",
"bun-types": "^1.1.20", "bun-types": "^1.1.20",
@@ -41,13 +41,12 @@
"framer-motion": "^10.16.14", "framer-motion": "^10.16.14",
"js-cookie": "^3.0.5", "js-cookie": "^3.0.5",
"jsontoxml": "^1.0.1", "jsontoxml": "^1.0.1",
"jwt-decode": "^4.0.0",
"katex": "^0.16.9", "katex": "^0.16.9",
"mathjax": "^3.2.2", "mathjax": "^3.2.2",
"mdast-util-to-markdown": "^2.1.2", "mdast-util-to-markdown": "^2.1.2",
"memoizee": "^0.4.15", "memoizee": "^0.4.15",
"micromark": "^4.0.1", "next": "14.2.25",
"micromark-extension-gfm": "^3.0.0",
"next": "14.2.23",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"nuqs": "^2.2.3", "nuqs": "^2.2.3",
"object-hash": "^3.0.0", "object-hash": "^3.0.0",
@@ -57,22 +56,25 @@
"react": "18.3.1", "react": "18.3.1",
"react-dom": "18.3.1", "react-dom": "18.3.1",
"react-hotkeys-hook": "^4.4.1", "react-hotkeys-hook": "^4.4.1",
"rehype-sanitize": "^6.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.1",
"rison": "^0.1.1", "rison": "^0.1.1",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"shiki": "^3.2.0", "shiki": "^3.2.0",
"tailwind-merge": "^2.2.0", "tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2", "tailwind-shades": "^1.1.2",
"unified": "^11.0.5",
"url-join": "^5.0.0", "url-join": "^5.0.0",
"usehooks-ts": "^3.1.0", "usehooks-ts": "^3.1.0"
"ai": "^4.1.46",
"jwt-decode": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@argos-ci/playwright": "^3.10.0", "@argos-ci/playwright": "^4.3.0",
"@cloudflare/next-on-pages": "1.13.7", "@cloudflare/next-on-pages": "1.13.7",
"vercel": "^39.3.0",
"@cloudflare/workers-types": "^4.20241230.0", "@cloudflare/workers-types": "^4.20241230.0",
"@playwright/test": "^1.49.1", "@playwright/test": "^1.51.1",
"@types/js-cookie": "^3.0.6", "@types/js-cookie": "^3.0.6",
"@types/jsontoxml": "^1.0.5", "@types/jsontoxml": "^1.0.5",
"@types/jsonwebtoken": "^9.0.6", "@types/jsonwebtoken": "^9.0.6",
@@ -90,8 +92,10 @@
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"postcss": "^8", "postcss": "^8",
"psi": "^4.1.0", "psi": "^4.1.0",
"stylelint": "^16.16.0",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
"ts-essentials": "^10.0.1", "ts-essentials": "^10.0.1",
"typescript": "^5.5.3" "typescript": "^5.5.3",
"vercel": "^39.3.0"
} }
} }
+3
View File
@@ -18,5 +18,8 @@ export default defineConfig({
use: { use: {
trace: 'on-first-retry', trace: 'on-first-retry',
screenshot: 'only-on-failure', screenshot: 'only-on-failure',
contextOptions: {
reducedMotion: 'reduce',
},
}, },
}); });
-18
View File
@@ -1,18 +0,0 @@
import * as Sentry from '@sentry/browser';
const dsn = process.env.SENTRY_DSN;
if (dsn) {
Sentry.init({
dsn,
release: process.env.SENTRY_RELEASE,
// Disable tracing as it creates additional requests in an env where subrequests are limited.
tracesSampleRate: 0,
// Disable transactions as it creates additional requests in an env where subrequests are limited.
// https://docs.sentry.io/platforms/node/configuration/filtering/#using--3
beforeSendTransaction: () => {
return null;
},
});
}
+1 -7
View File
@@ -1,14 +1,8 @@
'use client'; 'use client';
import { captureException } from '@sentry/nextjs';
import NextError from 'next/error'; import NextError from 'next/error';
import { useEffect } from 'react';
export default function GlobalError({ error }: { error: Error }) {
useEffect(() => {
captureException(error);
}, [error]);
export default function GlobalError() {
return ( return (
<html lang="en"> <html lang="en">
<body> <body>
@@ -1,4 +1,4 @@
import { getThemeFromMiddleware, getVisitorAuthTokenFromMiddleware } from '@v2/lib/middleware'; import { getSiteURLDataFromMiddleware, getThemeFromMiddleware } from '@v2/lib/middleware';
import type { Metadata, Viewport } from 'next'; import type { Metadata, Viewport } from 'next';
import type React from 'react'; import type React from 'react';
@@ -7,6 +7,7 @@ import {
generateSiteLayoutMetadata, generateSiteLayoutMetadata,
generateSiteLayoutViewport, generateSiteLayoutViewport,
} from '@/components/SiteLayout'; } from '@/components/SiteLayout';
import { getVisitorAuthClaims } from '@/lib/adaptive';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { shouldTrackEvents } from '@/lib/tracking'; import { shouldTrackEvents } from '@/lib/tracking';
import { fetchV1ContextForSitePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer } from '@/lib/v1';
@@ -22,14 +23,14 @@ export default async function ContentLayout(props: { children: React.ReactNode }
const context = await fetchLayoutData(); const context = await fetchLayoutData();
const queryStringTheme = await getThemeFromMiddleware(); const queryStringTheme = await getThemeFromMiddleware();
const visitorAuthToken = await getVisitorAuthTokenFromMiddleware(); const siteData = await getSiteURLDataFromMiddleware();
return ( return (
<SiteLayout <SiteLayout
context={context} context={context}
forcedTheme={queryStringTheme} forcedTheme={queryStringTheme}
withTracking={await shouldTrackEvents()} withTracking={await shouldTrackEvents()}
visitorAuthToken={visitorAuthToken} visitorAuthClaims={getVisitorAuthClaims(siteData)}
> >
{children} {children}
</SiteLayout> </SiteLayout>
@@ -1,8 +1,5 @@
'use client'; 'use client';
import { captureException, withScope } from '@sentry/nextjs';
import React from 'react';
import { Button } from '@/components/primitives/Button'; import { Button } from '@/components/primitives/Button';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -11,18 +8,9 @@ export default function ErrorPage(props: {
error: Error & { digest?: string }; error: Error & { digest?: string };
reset: () => void; reset: () => void;
}) { }) {
const { error, reset } = props; const { reset } = props;
const language = useLanguage(); const language = useLanguage();
React.useEffect(() => {
withScope((scope) => {
if ('_componentStack' in error && error._componentStack) {
scope.setExtra('componentStack', error._componentStack);
}
captureException(error);
});
}, [error]);
return ( return (
<div <div
className={tcls( className={tcls(
@@ -1,47 +1,13 @@
import type { ContentKitContext, DocumentBlockIntegration } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import {
ContentKit,
ContentKitOutput,
type ContentKitServerContext,
} from '@gitbook/react-contentkit';
import { renderIntegrationUi } from '@/lib/api';
import { parseMarkdown } from '@/lib/markdown';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { ContentKit, ContentKitOutput } from '@gitbook/react-contentkit';
import { GITBOOK_INTEGRATIONS_HOST } from '@v2/lib/env'; import { GITBOOK_INTEGRATIONS_HOST } from '@v2/lib/env';
import type { BlockProps } from '../Block'; import type { BlockProps } from '../Block';
import { PlainCodeBlock } from '../CodeBlock';
import './contentkit.css'; import './contentkit.css';
import { ignoreAllThrownError } from '@v2/lib/data'; import { getDataOrNull } from '@v2/lib/data';
import { contentKitServerContext } from './contentkit';
const outputContext: ContentKitServerContext = { import { renderIntegrationUi } from './server-actions';
icons: {
maximize: (props) => <Icon icon="maximize" {...props} />,
edit: (props) => <Icon icon="edit" {...props} />,
github: (props) => <Icon icon="github" {...props} />,
gitlab: (props) => <Icon icon="gitlab" {...props} />,
close: (props) => <Icon icon="x" {...props} />,
email: (props) => <Icon icon="envelope" {...props} />,
settings: (props) => <Icon icon="gear" {...props} />,
search: (props) => <Icon icon="magnifying-glass" {...props} />,
delete: (props) => <Icon icon="trash" {...props} />,
star: (props) => <Icon icon="star" {...props} />,
warning: (props) => <Icon icon="triangle-exclamation" {...props} />,
link: (props) => <Icon icon="link" {...props} />,
'link-external': (props) => <Icon icon="arrow-up-right-from-square" {...props} />,
eye: (props) => <Icon icon="eye" {...props} />,
lock: (props) => <Icon icon="lock" {...props} />,
},
codeBlock: (props) => {
return <PlainCodeBlock code={props.code} syntax={props.syntax} />;
},
markdown: async ({ className, markdown }) => {
const parsed = await parseMarkdown(markdown);
return <div className={className} dangerouslySetInnerHTML={{ __html: parsed }} />;
},
};
export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegration>) { export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegration>) {
const { block, context, style } = props; const { block, context, style } = props;
@@ -50,22 +16,25 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
throw new Error('integration block requires a content.spaceId'); throw new Error('integration block requires a content.spaceId');
} }
const contentKitContext: ContentKitContext = { const { dataFetcher } = context.contentContext;
type: 'document',
spaceId: context.contentContext?.space.id,
editable: false,
theme: 'light', // TODO: how to handle this without moving rendering to the client side?
};
const initialInput = { const initialInput: RenderIntegrationUI = {
componentId: block.data.block, componentId: block.data.block,
props: block.data.props, props: block.data.props,
action: block.data.action, action: block.data.action,
context: contentKitContext, context: {
type: 'document',
spaceId: context.contentContext?.space.id,
editable: false,
theme: 'light', // TODO: how to handle this without moving rendering to the client side?
},
}; };
const initialOutput = await ignoreAllThrownError( const initialOutput = await getDataOrNull(
renderIntegrationUi(block.data.integration, initialInput) dataFetcher.renderIntegrationUi({
integrationName: block.data.integration,
request: initialInput,
})
); );
if (!initialOutput || initialOutput.type === 'complete') { if (!initialOutput || initialOutput.type === 'complete') {
return null; return null;
@@ -74,21 +43,15 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
return ( return (
<div className={tcls(style)}> <div className={tcls(style)}>
<ContentKit <ContentKit
renderContext={{
integrationName: block.data.integration,
}}
security={{ firstPartyDomains: [GITBOOK_INTEGRATIONS_HOST] }} security={{ firstPartyDomains: [GITBOOK_INTEGRATIONS_HOST] }}
initialInput={initialInput} initialInput={initialInput}
initialOutput={initialOutput} initialOutput={initialOutput}
render={async (request) => { render={renderIntegrationUi}
'use server';
const output = await renderIntegrationUi(block.data.integration, request);
return {
children: <ContentKitOutput output={output} context={outputContext} />,
output: output,
};
}}
> >
<ContentKitOutput output={initialOutput} context={outputContext} /> <ContentKitOutput output={initialOutput} context={contentKitServerContext} />
</ContentKit> </ContentKit>
</div> </div>
); );
@@ -0,0 +1,31 @@
import { parseMarkdown } from '@/lib/markdown';
import { Icon } from '@gitbook/icons';
import type { ContentKitServerContext } from '@gitbook/react-contentkit';
import { PlainCodeBlock } from '../CodeBlock';
export const contentKitServerContext: ContentKitServerContext = {
icons: {
maximize: (props) => <Icon icon="maximize" {...props} />,
edit: (props) => <Icon icon="edit" {...props} />,
github: (props) => <Icon icon="github" {...props} />,
gitlab: (props) => <Icon icon="gitlab" {...props} />,
close: (props) => <Icon icon="x" {...props} />,
email: (props) => <Icon icon="envelope" {...props} />,
settings: (props) => <Icon icon="gear" {...props} />,
search: (props) => <Icon icon="magnifying-glass" {...props} />,
delete: (props) => <Icon icon="trash" {...props} />,
star: (props) => <Icon icon="star" {...props} />,
warning: (props) => <Icon icon="triangle-exclamation" {...props} />,
link: (props) => <Icon icon="link" {...props} />,
'link-external': (props) => <Icon icon="arrow-up-right-from-square" {...props} />,
eye: (props) => <Icon icon="eye" {...props} />,
lock: (props) => <Icon icon="lock" {...props} />,
},
codeBlock: (props) => {
return <PlainCodeBlock code={props.code} syntax={props.syntax} />;
},
markdown: async ({ className, markdown }) => {
const parsed = await parseMarkdown(markdown);
return <div className={className} dangerouslySetInnerHTML={{ __html: parsed }} />;
},
};
@@ -0,0 +1,37 @@
'use server';
import { getV1BaseContext } from '@/lib/v1';
import { isV2 } from '@/lib/v2';
import type { RenderIntegrationUI } from '@gitbook/api';
import { ContentKitOutput } from '@gitbook/react-contentkit';
import { throwIfDataError } from '@v2/lib/data';
import { getServerActionBaseContext } from '@v2/lib/server-actions';
import { contentKitServerContext } from './contentkit';
/**
* Server action to render an integration UI request from <ContentKit />.
* See `render` prop in <ContentKit /> for more details.
*/
export async function renderIntegrationUi({
renderContext,
request,
}: {
renderContext: {
integrationName: string;
};
request: RenderIntegrationUI;
}) {
const serverAction = isV2() ? await getServerActionBaseContext() : await getV1BaseContext();
const output = await throwIfDataError(
serverAction.dataFetcher.renderIntegrationUi({
integrationName: renderContext.integrationName,
request,
})
);
return {
children: <ContentKitOutput output={output} context={contentKitServerContext} />,
output: output,
};
}
@@ -20,7 +20,7 @@ import type { AnyOpenAPIOperationsBlock } from '@/lib/openapi/types';
export async function OpenAPIOperation(props: BlockProps<AnyOpenAPIOperationsBlock>) { export async function OpenAPIOperation(props: BlockProps<AnyOpenAPIOperationsBlock>) {
const { style } = props; const { style } = props;
return ( return (
<div className={tcls('flex w-full', style, 'max-w-full')}> <div className={tcls('flex w-full min-w-0', style, 'max-w-full')}>
<OpenAPIOperationBody {...props} /> <OpenAPIOperationBody {...props} />
</div> </div>
); );
@@ -264,14 +264,18 @@
gap: 6px; gap: 6px;
} }
.scalar-activate-button { .scalar-activate-button {
@apply flex gap-1.5 items-center; @apply flex gap-2 items-center;
@apply bg-primary-solid text-contrast-primary-solid hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-md straight-corners:rounded-none place-self-start; @apply bg-primary-solid text-contrast-primary-solid hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-md straight-corners:rounded-none place-self-start;
@apply ring-1 ring-tint hover:ring-tint-hover; @apply ring-1 ring-tint hover:ring-tint-hover;
@apply shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none; @apply shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none;
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12; @apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
@apply hover:scale-105 active:scale-100 transition-all; @apply hover:scale-105 active:scale-100 transition-all;
@apply grow-0 shrink-0 truncate; @apply grow-0 shrink-0 truncate;
@apply text-sm px-2.5 py-1; @apply text-[13px] px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
}
.scalar-activate-button svg {
@apply size-2.5;
} }
.scalar-app-loading { .scalar-app-loading {
@@ -1,6 +1,6 @@
/* Layout Components */ /* Layout Components */
.openapi-operation { .openapi-operation {
@apply flex-1 flex flex-col gap-4 mb-14; @apply flex-1 flex flex-col gap-8 mb-14 min-w-0;
} }
.openapi-schemas { .openapi-schemas {
@@ -17,7 +17,7 @@
} }
.openapi-summary { .openapi-summary {
@apply flex flex-col items-start justify-start gap-2; @apply flex flex-col items-start justify-start gap-3;
} }
.openapi-deprecated { .openapi-deprecated {
@@ -201,6 +201,10 @@
@apply text-warning-subtle text-[0.813rem]; @apply text-warning-subtle text-[0.813rem];
} }
.openapi-schema-optional {
@apply text-info-subtle text-[0.813rem];
}
.openapi-schema-readonly { .openapi-schema-readonly {
@apply text-primary-subtle/9 text-[0.813rem]; @apply text-primary-subtle/9 text-[0.813rem];
} }
@@ -391,19 +395,37 @@
@apply flex flex-row items-center h-fit; @apply flex flex-row items-center h-fit;
} }
.openapi-codesample-footer {
@apply flex gap-3 w-full justify-between flex-wrap;
}
.openapi-codesample-selectors {
@apply flex flex-row items-center gap-3 flex-wrap;
}
/* Path */ /* Path */
.openapi-path { .openapi-path {
@apply flex items-center bg-transparent text-sm gap-2 p-2 border rounded-md border-tint-subtle; @apply flex items-start text-sm gap-2 h-fit overflow-x-auto min-w-0 max-w-full;
scrollbar-width: none;
-ms-overflow-style: none;
}
.openapi-path-variable {
@apply p-px min-w-[1.625rem] text-tint-strong font-normal w-fit justify-center items-center ring-1 ring-inset ring-tint bg-tint rounded text-sm leading-none before:!content-none after:!content-none;
}
.openapi-path-server {
@apply text-tint hidden md:inline;
} }
.openapi-path .openapi-method { .openapi-path .openapi-method {
@apply text-[0.813rem] m-0 px-1; @apply text-[0.813rem] m-0 mt-0.5 items-center flex px-2;
} }
.openapi-path-title { .openapi-path-title {
@apply flex-1 relative font-normal whitespace-nowrap overflow-x-auto font-mono text-tint-strong; @apply flex-1 relative font-normal text-left font-mono text-tint-strong/10;
scrollbar-width: none; @apply py-0.5 px-1 rounded hover:bg-tint cursor-pointer transition-colors;
-ms-overflow-style: none; @apply whitespace-nowrap md:whitespace-normal;
} }
.openapi-path-title[data-deprecated="true"] { .openapi-path-title[data-deprecated="true"] {
@@ -520,6 +542,10 @@
@apply px-3 py-2 pt-2.5 border-t border-tint-subtle text-[0.813rem] text-tint; @apply px-3 py-2 pt-2.5 border-t border-tint-subtle text-[0.813rem] text-tint;
} }
.openapi-tabs-footer .openapi-markdown {
@apply text-[0.813rem] text-tint;
}
/* Disclosure group */ /* Disclosure group */
.openapi-disclosure-group { .openapi-disclosure-group {
@apply border-b border-tint-subtle relative; @apply border-b border-tint-subtle relative;
@@ -631,3 +657,37 @@
.openapi-section-schemas > .openapi-section-body > .openapi-schema-properties > .openapi-schema { .openapi-section-schemas > .openapi-section-body > .openapi-schema-properties > .openapi-schema {
@apply p-2.5; @apply p-2.5;
} }
.openapi-tooltip {
@apply flex items-center gap-1 bg-tint-base border border-tint-subtle text-tint-strong rounded-md font-medium px-1.5 py-0.5 shadow-sm text-[13px];
}
.openapi-tooltip svg {
@apply size-3 text-tint-strong;
}
.openapi-tooltip[data-entering] {
animation: tooltip-enter 0.2s ease-in-out forwards;
}
.openapi-tooltip[data-exiting] {
animation: tooltip-leave 0.2s ease-in-out forwards;
}
@keyframes tooltip-enter {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes tooltip-leave {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@@ -42,11 +42,11 @@ export function CurrentContentIcon(
} }
: { : {
light: { light: {
src: linker.toPathInContent('~gitbook/icon?size=medium&theme=light'), src: linker.toPathInSpace('~gitbook/icon?size=medium&theme=light'),
size: { width: 256, height: 256 }, size: { width: 256, height: 256 },
}, },
dark: { dark: {
src: linker.toPathInContent('~gitbook/icon?size=medium&theme=dark'), src: linker.toPathInSpace('~gitbook/icon?size=medium&theme=dark'),
size: { width: 256, height: 256 }, size: { width: 256, height: 256 },
}, },
} }
@@ -123,7 +123,6 @@ export function DropdownMenuItem(
return ( return (
<Link <Link
href={href} href={href}
prefetch={false}
insights={insights} insights={insights}
className={tcls( className={tcls(
'rounded straight-corners:rounded-sm px-3 py-1 text-sm', 'rounded straight-corners:rounded-sm px-3 py-1 text-sm',
@@ -102,12 +102,14 @@ export function Header(props: { context: GitBookSiteContext; withTopHeader?: boo
? [ ? [
'md:grow-[0.8]', 'md:grow-[0.8]',
'lg:basis-40', 'lg:basis-40',
'max-w-lg', 'md:max-w-[40%]',
'lg:max-w-lg',
'lg:ml-[max(calc((100%-18rem-48rem-3rem)/2),1.5rem)]', // container (100%) - sidebar (18rem) - content (48rem) - margin (3rem) 'lg:ml-[max(calc((100%-18rem-48rem-3rem)/2),1.5rem)]', // container (100%) - sidebar (18rem) - content (48rem) - margin (3rem)
'xl:ml-[max(calc((100%-18rem-48rem-14rem-3rem)/2),1.5rem)]', // container (100%) - sidebar (18rem) - content (48rem) - outline (14rem) - margin (3rem) 'xl:ml-[max(calc((100%-18rem-48rem-14rem-3rem)/2),1.5rem)]', // container (100%) - sidebar (18rem) - content (48rem) - outline (14rem) - margin (3rem)
'page-no-toc:lg:ml-[max(calc((100%-18rem-48rem-18rem-3rem)/2),0rem)]', 'page-no-toc:lg:ml-[max(calc((100%-18rem-48rem-18rem-3rem)/2),0rem)]',
'page-full-width:lg:ml-6', 'page-full-width:lg:ml-[max(calc((100%-18rem-103rem-3rem)/2),1.5rem)]',
'lg:mr-auto', 'page-full-width:2xl:ml-[max(calc((100%-18rem-96rem-14rem+3rem)/2),1.5rem)]',
'md:mr-auto',
'order-last', 'order-last',
'md:order-[unset]', 'md:order-[unset]',
] ]
@@ -179,44 +181,46 @@ export function Header(props: { context: GitBookSiteContext; withTopHeader?: boo
</div> </div>
{sections || siteSpaces.length > 1 ? ( {sections || siteSpaces.length > 1 ? (
<div <div className="scroll-nojump">
className={tcls(
'w-full',
'overflow-x-scroll',
'overflow-y-hidden',
'hide-scroll',
'-mb-4 pb-4', // Positive padding / negative margin allows the navigation menu indicator to show in a scroll viewƒ
!sections ? ['hidden', 'page-no-toc:flex'] : 'flex'
)}
>
<div <div
className={tcls( className={tcls(
CONTAINER_STYLE, 'w-full',
'page-default-width:max-w-[unset]', 'overflow-x-scroll',
'grow', 'overflow-y-hidden',
'flex', 'hide-scroll',
'items-end', '-mb-4 pb-4', // Positive padding / negative margin allows the navigation menu indicator to show in a scroll viewƒ
'page-default-width:2xl:px-[calc((100%-1536px+4rem)/2)]' !sections ? ['hidden', 'page-no-toc:flex'] : 'flex'
)} )}
> >
{siteSpaces.length > 1 && ( <div
<div className={tcls(
id="variants" CONTAINER_STYLE,
className="my-2 mr-5 page-no-toc:flex hidden grow border-tint border-r pr-5 *:grow only:mr-0 only:border-none only:pr-0 sm:max-w-64" 'page-default-width:max-w-[unset]',
> 'grow',
<SpacesDropdown 'flex',
context={context} 'items-end',
siteSpace={siteSpace} 'page-default-width:2xl:px-[calc((100%-1536px+4rem)/2)]'
siteSpaces={siteSpaces} )}
className="w-full grow py-1" >
{siteSpaces.length > 1 && (
<div
id="variants"
className="my-2 mr-5 page-no-toc:flex hidden grow border-tint border-r pr-5 *:grow only:mr-0 only:border-none only:pr-0 sm:max-w-64"
>
<SpacesDropdown
context={context}
siteSpace={siteSpace}
siteSpaces={siteSpaces}
className="w-full grow py-1"
/>
</div>
)}
{sections && (
<SiteSectionTabs
sections={encodeClientSiteSections(context, sections)}
/> />
</div> )}
)} </div>
{sections && (
<SiteSectionTabs
sections={encodeClientSiteSections(context, sections)}
/>
)}
</div> </div>
</div> </div>
) : null} ) : null}
@@ -20,7 +20,7 @@ export async function HeaderLogo(props: HeaderLogoProps) {
return ( return (
<Link <Link
href={linker.toAbsoluteURL(linker.toPathInContent(''))} href={linker.toAbsoluteURL(linker.toPathInSpace(''))}
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')} className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')}
> >
{customization.header.logo ? ( {customization.header.logo ? (
@@ -47,17 +47,11 @@ export function HeaderMobileMenu(props: Partial<React.ButtonHTMLAttributes<HTMLB
aria-label={tString(language, 'table_of_contents_button_label')} aria-label={tString(language, 'table_of_contents_button_label')}
onClick={toggleNavigation} onClick={toggleNavigation}
className={tcls( className={tcls(
'flex', 'flex flex-row items-center rounded straight-corners:rounded-sm px-2 py-1',
'flex-row',
'items-center',
'py-1',
'px-2',
'rounded',
'straight-corners:rounded-sm',
props.className props.className
)} )}
> >
<Icon icon="bars" className={tcls('size-4', 'text-inherit')} /> <Icon icon="bars" className="size-4 text-inherit" />
</button> </button>
); );
} }
@@ -5,8 +5,8 @@ import { OpenAPIOperationContextProvider } from '@gitbook/react-openapi';
import * as React from 'react'; import * as React from 'react';
import { useDebounceCallback, useEventCallback } from 'usehooks-ts'; import { useDebounceCallback, useEventCallback } from 'usehooks-ts';
import * as cookies from '@/lib/cookies'; import type { VisitorAuthClaims } from '@/lib/adaptive';
import { getAllBrowserCookiesMap } from '@/lib/browser-cookies';
import { getSession } from './sessions'; import { getSession } from './sessions';
import { getVisitorId } from './visitorId'; import { getVisitorId } from './visitorId';
@@ -23,6 +23,7 @@ type InsightsEventContext = {
siteShareKey: string | null; siteShareKey: string | null;
spaceId: string; spaceId: string;
revisionId: string; revisionId: string;
visitorAuthClaims: VisitorAuthClaims;
}; };
/** /**
@@ -65,7 +66,6 @@ interface InsightsProviderProps extends InsightsEventContext {
enabled: boolean; enabled: boolean;
appURL: string; appURL: string;
apiHost: string; apiHost: string;
visitorAuthToken: string | null;
children: React.ReactNode; children: React.ReactNode;
} }
@@ -73,7 +73,7 @@ interface InsightsProviderProps extends InsightsEventContext {
* Wrap the content of the app with the InsightsProvider to track events. * Wrap the content of the app with the InsightsProvider to track events.
*/ */
export function InsightsProvider(props: InsightsProviderProps) { export function InsightsProvider(props: InsightsProviderProps) {
const { enabled, appURL, apiHost, visitorAuthToken, children, ...context } = props; const { enabled, appURL, apiHost, children, ...context } = props;
const visitorIdRef = React.useRef<string | null>(null); const visitorIdRef = React.useRef<string | null>(null);
const eventsRef = React.useRef<{ const eventsRef = React.useRef<{
@@ -116,7 +116,6 @@ export function InsightsProvider(props: InsightsProviderProps) {
pageContext: eventsForPathname.pageContext, pageContext: eventsForPathname.pageContext,
visitorId, visitorId,
sessionId: session.id, sessionId: session.id,
visitorAuthToken,
}) })
); );
@@ -253,16 +252,15 @@ function transformEvents(input: {
pageContext: InsightsEventPageContext; pageContext: InsightsEventPageContext;
visitorId: string; visitorId: string;
sessionId: string; sessionId: string;
visitorAuthToken: string | null;
}): api.SiteInsightsEvent[] { }): api.SiteInsightsEvent[] {
const session: api.SiteInsightsEventSession = { const session: api.SiteInsightsEventSession = {
sessionId: input.sessionId, sessionId: input.sessionId,
visitorId: input.visitorId, visitorId: input.visitorId,
userAgent: window.navigator.userAgent, userAgent: window.navigator.userAgent,
language: window.navigator.language, language: window.navigator.language,
cookies: cookies.getAll(), cookies: getAllBrowserCookiesMap(),
referrer: document.referrer || null, referrer: document.referrer || null,
visitorAuthToken: input.visitorAuthToken ?? null, visitorAuthClaims: input.context.visitorAuthClaims,
}; };
const location: api.SiteInsightsEventLocation = { const location: api.SiteInsightsEventLocation = {
@@ -1,6 +1,6 @@
'use client'; 'use client';
import * as cookies from '@/lib/cookies'; import { getBrowserCookie, setBrowserCookie } from '@/lib/browser-cookies';
const GRANTED_COOKIE = '__gitbook_cookie_granted'; const GRANTED_COOKIE = '__gitbook_cookie_granted';
@@ -8,7 +8,7 @@ const GRANTED_COOKIE = '__gitbook_cookie_granted';
* Accept or reject cookies. * Accept or reject cookies.
*/ */
export function setCookiesTracking(enabled: boolean) { export function setCookiesTracking(enabled: boolean) {
cookies.set(GRANTED_COOKIE, enabled ? 'yes' : 'no', { setBrowserCookie(GRANTED_COOKIE, enabled ? 'yes' : 'no', {
expires: 365, expires: 365,
sameSite: 'none', sameSite: 'none',
secure: true, secure: true,
@@ -20,7 +20,7 @@ export function setCookiesTracking(enabled: boolean) {
* Return `undefined` if state is not known. * Return `undefined` if state is not known.
*/ */
export function isCookiesTrackingDisabled() { export function isCookiesTrackingDisabled() {
const state = cookies.get(GRANTED_COOKIE); const state = getBrowserCookie(GRANTED_COOKIE);
if (state === 'yes') { if (state === 'yes') {
return false; return false;
@@ -1,6 +1,6 @@
'use client'; 'use client';
import * as cookies from '@/lib/cookies'; import { getBrowserCookie } from '@/lib/browser-cookies';
import { isCookiesTrackingDisabled } from './cookies'; import { isCookiesTrackingDisabled } from './cookies';
import { generateRandomId } from './utils'; import { generateRandomId } from './utils';
@@ -37,7 +37,7 @@ async function fetchVisitorID(appURL: string): Promise<string> {
return generateRandomId(); return generateRandomId();
} }
const existingTrackingCookie = cookies.get(VISITORID_COOKIE); const existingTrackingCookie = getBrowserCookie(VISITORID_COOKIE);
if (existingTrackingCookie) { if (existingTrackingCookie) {
// If the cookie already exists, we'll just use that. Avoids a server request. // If the cookie already exists, we'll just use that. Avoids a server request.
@@ -11,7 +11,7 @@ import {
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context'; import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data'; import { getPageDocument } from '@v2/lib/data';
import type { GitBookSpaceLinker } from '@v2/lib/links'; import type { GitBookLinker } from '@v2/lib/links';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import * as React from 'react'; import * as React from 'react';
@@ -67,7 +67,7 @@ export async function PDFPage(props: {
); );
// Build a linker that create anchor links for the pages rendered in the PDF page. // Build a linker that create anchor links for the pages rendered in the PDF page.
const linker: GitBookSpaceLinker = { const linker: GitBookLinker = {
...baseContext.linker, ...baseContext.linker,
toPathForPage(input) { toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) { if (pages.some((p) => p.page.id === input.page.id)) {
@@ -93,7 +93,7 @@ export async function PDFPage(props: {
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}> <div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a <a
title={tString(language, 'pdf_goback')} title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))} href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInSpace(''))}
className={tcls( className={tcls(
'flex', 'flex',
'flex-row', 'flex-row',
@@ -35,7 +35,7 @@ export function PageAside(props: {
const { customization, site, space } = context; const { customization, site, space } = context;
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInContent( const pdfHref = context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({ `~gitbook/pdf?${getPDFURLSearchParams({
page: page.id, page: page.id,
only: true, only: true,
@@ -70,9 +70,6 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
href={`#${section.id}`} href={`#${section.id}`}
className={tcls( className={tcls(
'relative', 'relative',
'flex',
'flex-row',
'items-baseline',
'z-10', 'z-10',
'text-sm', 'text-sm',
@@ -126,7 +123,7 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
> >
{section.tag ? ( {section.tag ? (
<span <span
className={`openapi-method openapi-method-${section.tag.toLowerCase()}`} className={`-mt-0.5 openapi-method openapi-method-${section.tag.toLowerCase()}`}
> >
{section.tag} {section.tag}
</span> </span>
@@ -35,25 +35,19 @@ export function PageBody(props: {
return ( return (
<> <>
<main <main
className={ className={tcls(
tcls( 'relative min-w-0 flex-1',
'flex-1', 'py-8 lg:px-12',
'relative', // Allow words to break if they are too long.
'py-8', 'break-anywhere',
'lg:px-12', // When in api page mode without the aside, we align with the border of the main content
// Allow words to break if they are too long. 'page-api-block:xl:max-2xl:pr-0',
'break-anywhere', // Max size to ensure one column in api is aligned with rest of content (2 x 3xl) + (gap-3 + 2) * px-12
// When in api page mode without the aside, we align with the border of the main content 'page-api-block:mx-auto page-api-block:max-w-screen-2xl',
'page-api-block:xl:max-2xl:pr-0', // page.layout.tableOfContents ? null : 'xl:ml-56',
// Max size to ensure one column in api is aligned with rest of content (2 x 3xl) + (gap-3 + 2) * px-12 asFullWidth ? 'page-full-width' : 'page-default-width',
'page-api-block:max-w-[1654px]', page.layout.tableOfContents ? 'page-has-toc' : 'page-no-toc'
'page-api-block:mx-auto' )}
// page.layout.tableOfContents ? null : 'xl:ml-56'
) +
(asFullWidth ? ' page-full-width' : ' page-default-width') +
(!page.layout.tableOfContents ? ' page-no-toc' : ' page-has-toc')
}
> >
<PreservePageLayout asFullWidth={asFullWidth} /> <PreservePageLayout asFullWidth={asFullWidth} />
{page.cover && page.layout.cover && page.layout.coverSize === 'hero' ? ( {page.cover && page.layout.cover && page.layout.coverSize === 'hero' ? (
@@ -66,14 +60,14 @@ export function PageBody(props: {
fallback={ fallback={
<DocumentViewSkeleton <DocumentViewSkeleton
document={document} document={document}
blockStyle={['page-api-block:ml-0']} blockStyle="page-api-block:ml-0"
/> />
} }
> >
<DocumentView <DocumentView
document={document} document={document}
style={['[&>*+*]:mt-5', 'grid']} style="grid [&>*+*]:mt-5"
blockStyle={['page-api-block:ml-0']} blockStyle="page-api-block:ml-0"
context={{ context={{
mode: 'default', mode: 'default',
contentContext: context, contentContext: context,
@@ -88,23 +82,9 @@ export function PageBody(props: {
<PageFooterNavigation context={context} page={page} /> <PageFooterNavigation context={context} page={page} />
) : null} ) : null}
<div <div className="mx-auto mt-6 page-api-block:ml-0 flex max-w-3xl flex-row flex-wrap items-center gap-4 text-tint contrast-more:text-tint-strong">
className={tcls(
'flex',
'flex-row',
'flex-wrap',
'gap-4',
'items-center',
'mt-6',
'max-w-3xl',
'mx-auto',
'page-api-block:ml-0',
'text-tint',
'contrast-more:text-tint-strong'
)}
>
{updatedAt ? ( {updatedAt ? (
<p className={tcls('mr-auto text-sm')}> <p className="mr-auto text-sm">
{t(language, 'page_last_modified', <DateRelative value={updatedAt} />)} {t(language, 'page_last_modified', <DateRelative value={updatedAt} />)}
</p> </p>
) : null} ) : null}
@@ -21,8 +21,10 @@ import {
hexToRgb, hexToRgb,
} from '@gitbook/colors'; } from '@gitbook/colors';
import { IconStyle, IconsProvider } from '@gitbook/icons'; import { IconStyle, IconsProvider } from '@gitbook/icons';
import * as ReactDOM from 'react-dom';
import { fontNotoColorEmoji, fonts, ibmPlexMono } from '@/fonts'; import { getFontData } from '@/fonts';
import { fontNotoColorEmoji, ibmPlexMono } from '@/fonts/default';
import { getSpaceLanguage } from '@/intl/server'; import { getSpaceLanguage } from '@/intl/server';
import { getAssetURL } from '@/lib/assets'; import { getAssetURL } from '@/lib/assets';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -31,7 +33,7 @@ import { ClientContexts } from './ClientContexts';
import '@gitbook/icons/style.css'; import '@gitbook/icons/style.css';
import './globals.css'; import './globals.css';
import { GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_URL } from '@v2/lib/env'; import { GITBOOK_FONTS_URL, GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_URL } from '@v2/lib/env';
/** /**
* Layout shared between the content and the PDF renderer. * Layout shared between the content and the PDF renderer.
@@ -48,6 +50,22 @@ export async function CustomizationRootLayout(props: {
const mixColor = getTintMixColor(customization.styling.primaryColor, tintColor); const mixColor = getTintMixColor(customization.styling.primaryColor, tintColor);
const sidebarStyles = getSidebarStyles(customization); const sidebarStyles = getSidebarStyles(customization);
const { infoColor, successColor, warningColor, dangerColor } = getSemanticColors(customization); const { infoColor, successColor, warningColor, dangerColor } = getSemanticColors(customization);
const fontData = getFontData(customization.styling.font);
// Preconnect and preload custom fonts if needed
if (fontData.type === 'custom') {
ReactDOM.preconnect(GITBOOK_FONTS_URL);
fontData.preloadSources
.flatMap((face) => face.sources)
.forEach(({ url, format }) => {
ReactDOM.preload(url, {
as: 'font',
crossOrigin: 'anonymous',
fetchPriority: 'high',
type: format ? `font/${format}` : undefined,
});
});
}
return ( return (
<html <html
@@ -66,14 +84,18 @@ export async function CustomizationRootLayout(props: {
sidebarStyles.list && `sidebar-list-${sidebarStyles.list}`, sidebarStyles.list && `sidebar-list-${sidebarStyles.list}`,
'links' in customization.styling && `links-${customization.styling.links}`, 'links' in customization.styling && `links-${customization.styling.links}`,
fontNotoColorEmoji.variable, fontNotoColorEmoji.variable,
fonts[customization.styling.font].variable, ibmPlexMono.variable,
ibmPlexMono.variable fontData.type === 'default' ? fontData.variable : 'font-custom'
)} )}
> >
<head> <head>
{customization.privacyPolicy.url ? ( {customization.privacyPolicy.url ? (
<link rel="privacy-policy" href={customization.privacyPolicy.url} /> <link rel="privacy-policy" href={customization.privacyPolicy.url} />
) : null} ) : null}
{/* Inject custom font @font-face rules */}
{fontData.type === 'custom' ? <style>{fontData.fontFaceRules}</style> : null}
<style <style
nonce={ nonce={
//Since I can't get the nonce to work for inline styles, we need to allow unsafe-inline //Since I can't get the nonce to work for inline styles, we need to allow unsafe-inline
@@ -143,6 +143,10 @@
margin-right: 0; margin-right: 0;
width: calc(100% - var(--scrollbar-width)); width: calc(100% - var(--scrollbar-width));
} }
body:has(.page-full-width) .scroll-nojump {
margin-left: 0;
width: 100%;
}
} }
} }
@@ -236,7 +236,6 @@ function AnswerSources(props: {
'focus-within:text-primary' 'focus-within:text-primary'
)} )}
href={source.href} href={source.href}
prefetch={false}
> >
<Icon <Icon
icon="arrow-up-right" icon="arrow-up-right"
@@ -99,7 +99,7 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
); );
} }
const Shortcut = () => { function Shortcut() {
const [operatingSystem, setOperatingSystem] = useState<string | null>(null); const [operatingSystem, setOperatingSystem] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
@@ -115,21 +115,14 @@ const Shortcut = () => {
setOperatingSystem(getOperatingSystem()); setOperatingSystem(getOperatingSystem());
}, []); }, []);
return operatingSystem ? ( return (
<div <div
aria-busy={operatingSystem === null ? 'true' : undefined}
className={tcls( className={tcls(
'shortcut', `shortcut -mr-1 hidden justify-end gap-0.5 whitespace-nowrap text-tint text-xs [font-feature-settings:"calt",_"case"] contrast-more:text-tint-strong md:flex`,
'hidden', operatingSystem
'md:flex', ? 'motion-safe:animate-fadeIn motion-reduce:opacity-100'
'gap-0.5', : 'opacity-0'
'-mr-1',
'justify-end',
'text-xs',
'text-tint',
'contrast-more:text-tint-strong',
'whitespace-nowrap',
`[font-feature-settings:"calt",_"case"]`,
'animate-fadeIn'
)} )}
> >
<kbd <kbd
@@ -141,5 +134,5 @@ const Shortcut = () => {
K K
</kbd> </kbd>
</div> </div>
) : null; );
}; }
@@ -1,6 +1,5 @@
'use client'; 'use client';
import { captureException } from '@sentry/nextjs';
import { readStreamableValue } from 'ai/rsc'; import { readStreamableValue } from 'ai/rsc';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
import React from 'react'; import React from 'react';
@@ -132,12 +131,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
} }
if (!results) { if (!results) {
captureException(
new Error(
`corrupt-cache: ${global ? 'searchAllSiteContent' : 'searchSiteSpaceContent'} is ${results}`
),
{ extra: { results } }
);
setResultsState({ results: [], fetching: false }); setResultsState({ results: [], fetching: false });
return; return;
} }
@@ -12,6 +12,7 @@ import { SpaceLayout } from '@/components/SpaceLayout';
import { buildVersion } from '@/lib/build'; import { buildVersion } from '@/lib/build';
import { isSiteIndexable } from '@/lib/seo'; import { isSiteIndexable } from '@/lib/seo';
import type { VisitorAuthClaims } from '@/lib/adaptive';
import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@v2/lib/env'; import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@v2/lib/env';
import { getResizedImageURL } from '@v2/lib/images'; import { getResizedImageURL } from '@v2/lib/images';
import { ClientContexts } from './ClientContexts'; import { ClientContexts } from './ClientContexts';
@@ -25,10 +26,10 @@ export async function SiteLayout(props: {
context: GitBookSiteContext; context: GitBookSiteContext;
forcedTheme?: CustomizationThemeMode | null; forcedTheme?: CustomizationThemeMode | null;
withTracking: boolean; withTracking: boolean;
visitorAuthToken: string | null; visitorAuthClaims: VisitorAuthClaims;
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { context, nonce, forcedTheme, withTracking, visitorAuthToken, children } = props; const { context, nonce, forcedTheme, withTracking, visitorAuthClaims, children } = props;
const { scripts, customization } = context; const { scripts, customization } = context;
@@ -57,7 +58,7 @@ export async function SiteLayout(props: {
<SpaceLayout <SpaceLayout
context={context} context={context}
withTracking={withTracking} withTracking={withTracking}
visitorAuthToken={visitorAuthToken} visitorAuthClaims={visitorAuthClaims}
> >
{children} {children}
</SpaceLayout> </SpaceLayout>
@@ -109,7 +110,7 @@ export async function generateSiteLayoutMetadata(context: GitBookSiteContext): P
height: faviconSize, height: faviconSize,
}) })
: linker.toAbsoluteURL( : linker.toAbsoluteURL(
linker.toPathInContent('~gitbook/icon?size=small&theme=light') linker.toPathInSpace('~gitbook/icon?size=small&theme=light')
), ),
type: 'image/png', type: 'image/png',
media: '(prefers-color-scheme: light)', media: '(prefers-color-scheme: light)',
@@ -120,9 +121,7 @@ export async function generateSiteLayoutMetadata(context: GitBookSiteContext): P
width: faviconSize, width: faviconSize,
height: faviconSize, height: faviconSize,
}) })
: linker.toAbsoluteURL( : linker.toAbsoluteURL(linker.toPathInSpace('~gitbook/icon?size=small&theme=dark')),
linker.toPathInContent('~gitbook/icon?size=small&theme=dark')
),
type: 'image/png', type: 'image/png',
media: '(prefers-color-scheme: dark)', media: '(prefers-color-scheme: dark)',
}, },
@@ -12,7 +12,7 @@ import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { getResizedImageURL } from '@v2/lib/images'; import { getResizedImageURL } from '@v2/lib/images';
import { PageClientLayout } from './PageClientLayout'; import { PageClientLayout } from './PageClientLayout';
import { type PagePathParams, fetchPageData, getPathnameParam, normalizePathname } from './fetch'; import { type PagePathParams, fetchPageData, getPathnameParam } from './fetch';
export const runtime = 'edge'; export const runtime = 'edge';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -33,11 +33,11 @@ export async function SitePage(props: SitePageProps) {
const rawPathname = getPathnameParam(props.pageParams); const rawPathname = getPathnameParam(props.pageParams);
if (!pageTarget) { if (!pageTarget) {
const pathname = normalizePathname(rawPathname); const pathname = rawPathname.toLowerCase();
if (pathname !== rawPathname) { if (pathname !== rawPathname) {
// If the pathname was not normalized, redirect to the normalized version // If the pathname was not normalized, redirect to the normalized version
// before trying to resolve the page again // before trying to resolve the page again
redirect(context.linker.toPathInContent(pathname)); redirect(context.linker.toPathInSpace(pathname));
} else { } else {
notFound(); notFound();
} }
@@ -137,7 +137,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
width: 1200, width: 1200,
height: 630, height: 630,
}) })
: linker.toAbsoluteURL(linker.toPathInContent(`~gitbook/ogimage/${page.id}`)), : linker.toAbsoluteURL(linker.toPathInSpace(`~gitbook/ogimage/${page.id}`)),
], ],
}, },
robots: robots:
@@ -2,6 +2,7 @@ import type { GitBookSiteContext } from '@v2/lib/context';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { resolvePageId, resolvePagePath } from '@/lib/pages'; import { resolvePageId, resolvePagePath } from '@/lib/pages';
import { withLeadingSlash } from '@/lib/paths';
import { getDataOrNull } from '@v2/lib/data'; import { getDataOrNull } from '@v2/lib/data';
export interface PagePathParams { export interface PagePathParams {
@@ -35,14 +36,14 @@ export async function fetchPageData(context: GitBookSiteContext, params: PagePar
* If the path can't be found, we try to resolve it from the API to handle redirects. * If the path can't be found, we try to resolve it from the API to handle redirects.
*/ */
async function resolvePage(context: GitBookSiteContext, params: PagePathParams | PageIdParams) { async function resolvePage(context: GitBookSiteContext, params: PagePathParams | PageIdParams) {
const { organizationId, site, space, revisionId, pages, shareKey } = context; const { organizationId, site, space, revisionId, pages, shareKey, linker } = context;
if ('pageId' in params) { if ('pageId' in params) {
return resolvePageId(pages, params.pageId); return resolvePageId(pages, params.pageId);
} }
const rawPathname = getPathnameParam(params); const rawPathname = getPathnameParam(params);
const pathname = normalizePathname(rawPathname); const pathname = rawPathname.toLowerCase();
// When resolving a page, we use the lowercased pathname // When resolving a page, we use the lowercased pathname
const page = resolvePagePath(pages, pathname); const page = resolvePagePath(pages, pathname);
@@ -67,16 +68,31 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
} }
// If a page still can't be found, we try with the API, in case we have a redirect at site level. // If a page still can't be found, we try with the API, in case we have a redirect at site level.
const resolvedSiteRedirect = await getDataOrNull( const redirectPathname = withLeadingSlash(rawPathname);
context.dataFetcher.getSiteRedirectBySource({ if (/^\/[a-zA-Z0-9-_.\/]+[a-zA-Z0-9-_.]$/.test(redirectPathname)) {
organizationId, const redirectSources = new Set<string>([
siteId: site.id, // Test the pathname relative to the root
source: rawPathname.startsWith('/') ? rawPathname : `/${rawPathname}`, // For example hello/world -> section/variant/hello/world
siteShareKey: shareKey, withLeadingSlash(
}) linker.toRelativePathInSite(linker.toPathInSpace(redirectPathname))
); ),
if (resolvedSiteRedirect) { // Test the pathname relative to the content/space
return redirect(resolvedSiteRedirect.target); // For example hello/world -> /hello/world
redirectPathname,
]);
for (const source of redirectSources) {
const resolvedSiteRedirect = await getDataOrNull(
context.dataFetcher.getSiteRedirectBySource({
organizationId,
siteId: site.id,
source,
siteShareKey: shareKey,
})
);
if (resolvedSiteRedirect) {
return redirect(linker.toLinkForContent(resolvedSiteRedirect.target));
}
}
} }
} }
@@ -99,10 +115,3 @@ export function getPathnameParam(params: PagePathParams): string {
return pathname.map((part) => decodeURIComponent(part)).join('/'); return pathname.map((part) => decodeURIComponent(part)).join('/');
} }
/**
* Normalize the URL pathname into the format used in the revision page path.
*/
export function normalizePathname(pathname: string) {
return pathname.toLowerCase();
}
@@ -1,19 +1,20 @@
import { Icon, type IconName } from '@gitbook/icons'; import { Icon, type IconName } from '@gitbook/icons';
import { tcls } from '@/lib/tailwind'; import { type ClassValue, tcls } from '@/lib/tailwind';
/** /**
* Icon shown beside a section in the site section tabs. * Icon shown beside a section in the site section tabs.
*/ */
export function SectionIcon(props: { icon: IconName; isActive: boolean }) { export function SectionIcon(props: { icon: IconName; isActive: boolean; className?: ClassValue }) {
const { icon, isActive } = props; const { icon, isActive, className } = props;
return ( return (
<Icon <Icon
icon={icon} icon={icon}
className={tcls( className={tcls(
'size-[1em] shrink-0 text-inherit opacity-8', 'size-[1em] shrink-0 text-inherit opacity-8',
isActive && 'text-inherit opacity-10' isActive && 'text-inherit opacity-10',
className
)} )}
/> />
); );
@@ -112,10 +112,10 @@ export function SiteSectionTabs(props: { sections: ClientSiteSections }) {
); );
})} })}
<NavigationMenu.Indicator <NavigationMenu.Indicator
className="top-full z-0 flex h-3 items-end justify-center duration-150 motion-safe:transition-[width,_transform] data-[state=hidden]:motion-safe:animate-fadeOut data-[state=visible]:motion-safe:animate-fadeIn" className="fixed top-full z-50 flex h-3 items-end justify-center duration-150 motion-safe:transition-[width,_transform] data-[state=hidden]:motion-safe:animate-fadeOut data-[state=visible]:motion-safe:animate-fadeIn"
aria-hidden aria-hidden
> >
<div className="relative top-[70%] size-3 rotate-[225deg] rounded-tl-sm bg-tint shadow-1xs shadow-dark/1 dark:shadow-dark/4" /> <div className="relative top-1/2 size-3 rotate-45 rounded-tl-sm border-tint-subtle border-t border-l bg-tint-base" />
</NavigationMenu.Indicator> </NavigationMenu.Indicator>
</NavigationMenu.List> </NavigationMenu.List>
</div> </div>
@@ -127,7 +127,7 @@ export function SiteSectionTabs(props: { sections: ClientSiteSections }) {
}} }}
> >
<NavigationMenu.Viewport <NavigationMenu.Viewport
className="relative mt-3 h-[var(--radix-navigation-menu-viewport-height)] w-[calc(100vw_-_2rem)] origin-[top_center] overflow-hidden rounded straight-corners:rounded-none bg-tint shadow-1xs shadow-dark/1 duration-250 data-[state=closed]:duration-150 motion-safe:transition-[width,_height,_transform] data-[state=closed]:motion-safe:animate-scaleOut data-[state=open]:motion-safe:animate-scaleIn md:mx-0 md:w-[var(--radix-navigation-menu-viewport-width)] dark:shadow-dark/4" className="relative mt-3 h-[var(--radix-navigation-menu-viewport-height)] w-[calc(100vw_-_2rem)] origin-[top_center] overflow-hidden rounded-lg straight-corners:rounded-sm bg-tint-base shadow-lg shadow-tint-10/6 ring-1 ring-tint-subtle duration-250 data-[state=closed]:duration-150 motion-safe:transition-[width,_height,_transform] data-[state=closed]:motion-safe:animate-scaleOut data-[state=open]:motion-safe:animate-scaleIn md:mx-0 md:w-[var(--radix-navigation-menu-viewport-width)] dark:shadow-tint-1/6"
style={{ style={{
translate: translate:
undefined /* don't move this to a Tailwind class as Radix renders viewport incorrectly for a few frames */, undefined /* don't move this to a Tailwind class as Radix renders viewport incorrectly for a few frames */,
@@ -220,7 +220,7 @@ function SectionGroupTileList(props: {
return ( return (
<ul <ul
className={tcls( className={tcls(
'grid w-full p-2 sm:grid-cols-1 md:w-max', 'grid w-full gap-1 p-2 sm:grid-cols-1 md:w-max',
sections.length < MIN_ITEMS_FOR_COLS ? 'md:grid-cols-1' : 'md:grid-cols-2' sections.length < MIN_ITEMS_FOR_COLS ? 'md:grid-cols-1' : 'md:grid-cols-2'
)} )}
> >
@@ -246,17 +246,23 @@ function SectionGroupTile(props: { section: ClientSiteSection; isActive: boolean
<Link <Link
href={url} href={url}
className={tcls( className={tcls(
'flex min-h-12 w-full select-none flex-col gap-2 rounded p-3 transition-colors hover:bg-tint-hover', 'flex w-full select-none flex-col gap-1 rounded straight-corners:rounded-none px-3 py-2 transition-colors hover:bg-tint-hover',
isActive isActive ? 'text-primary' : 'text-tint-strong'
? 'text-primary hover:text-primary-strong focus:text-primary-strong'
: 'text-tint hover:text-tint-strong focus:text-tint-strong'
)} )}
> >
<div className="flex w-full items-center gap-2 font-medium light:text-dark dark:text-light"> <div className="flex w-full gap-2">
{icon ? <SectionIcon isActive={false} icon={icon as IconName} /> : null} {icon ? (
<span className="min-w-0 truncate">{title}</span> <SectionIcon
className="mt-[3px]"
isActive={false}
icon={icon as IconName}
/>
) : null}
{title}
</div> </div>
<p className="text-tint-subtle">{section.description}</p> {section.description ? (
<p className="text-tint-subtle">{section.description}</p>
) : null}
</Link> </Link>
</li> </li>
); );
@@ -11,6 +11,7 @@ import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate'; import { t } from '@/intl/translate';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import type { VisitorAuthClaims } from '@/lib/adaptive';
import { GITBOOK_API_PUBLIC_URL, GITBOOK_APP_URL } from '@v2/lib/env'; import { GITBOOK_API_PUBLIC_URL, GITBOOK_APP_URL } from '@v2/lib/env';
import { SpacesDropdown } from '../Header/SpacesDropdown'; import { SpacesDropdown } from '../Header/SpacesDropdown';
import { InsightsProvider } from '../Insights'; import { InsightsProvider } from '../Insights';
@@ -26,13 +27,13 @@ export function SpaceLayout(props: {
/** Whether to enable tracking of events into site insights. */ /** Whether to enable tracking of events into site insights. */
withTracking: boolean; withTracking: boolean;
/** The visitor token used to access this content */ /** The visitor auth claims. */
visitorAuthToken: string | null; visitorAuthClaims: VisitorAuthClaims;
/** The children of the layout. */ /** The children of the layout. */
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { context, withTracking, visitorAuthToken, children } = props; const { context, withTracking, visitorAuthClaims, children } = props;
const { siteSpace, customization, sections, siteSpaces } = context; const { siteSpace, customization, sections, siteSpaces } = context;
const withTopHeader = customization.header.preset !== CustomizationHeaderPreset.None; const withTopHeader = customization.header.preset !== CustomizationHeaderPreset.None;
@@ -47,12 +48,11 @@ export function SpaceLayout(props: {
customization.footer.groups?.length; customization.footer.groups?.length;
return ( return (
<SpaceLayoutContextProvider basePath={context.linker.toPathInContent('')}> <SpaceLayoutContextProvider basePath={context.linker.toPathInSpace('')}>
<InsightsProvider <InsightsProvider
enabled={withTracking} enabled={withTracking}
appURL={GITBOOK_APP_URL} appURL={GITBOOK_APP_URL}
apiHost={GITBOOK_API_PUBLIC_URL} apiHost={GITBOOK_API_PUBLIC_URL}
visitorAuthToken={visitorAuthToken}
organizationId={context.organizationId} organizationId={context.organizationId}
siteId={context.site.id} siteId={context.site.id}
siteSectionId={context.sections?.current?.id ?? null} siteSectionId={context.sections?.current?.id ?? null}
@@ -60,81 +60,84 @@ export function SpaceLayout(props: {
siteShareKey={context.shareKey ?? null} siteShareKey={context.shareKey ?? null}
revisionId={context.revisionId} revisionId={context.revisionId}
spaceId={context.space.id} spaceId={context.space.id}
visitorAuthClaims={visitorAuthClaims}
> >
<Header withTopHeader={withTopHeader} context={context} /> <Header withTopHeader={withTopHeader} context={context} />
<div <div className="scroll-nojump">
className={tcls( <div
'flex', className={tcls(
'flex-col', 'flex',
'lg:flex-row', 'flex-col',
CONTAINER_STYLE, 'lg:flex-row',
CONTAINER_STYLE,
// Ensure the footer is display below the viewport even if the content is not enough // Ensure the footer is display below the viewport even if the content is not enough
withFooter && 'min-h-[calc(100vh-64px)]', withFooter && 'min-h-[calc(100vh-64px)]',
withTopHeader ? null : 'lg:min-h-screen' withTopHeader ? null : 'lg:min-h-screen'
)} )}
> >
<TableOfContents <TableOfContents
context={context} context={context}
header={ header={
withTopHeader ? null : ( withTopHeader ? null : (
<div <div
className={tcls(
'hidden',
'pr-4',
'lg:flex',
'grow-0',
'flex-wrap',
'dark:shadow-light/1',
'text-base/tight'
)}
>
<HeaderLogo context={context} />
</div>
)
}
innerHeader={
// displays the search button and/or the space dropdown in the ToC according to the header/variant settings. E.g if there is no header, the search button will be displayed in the ToC.
<>
{!withTopHeader && (
<div className={tcls('hidden', 'lg:block')}>
<React.Suspense fallback={null}>
<SearchButton>
<span className={tcls('flex-1')}>
{t(
getSpaceLanguage(customization),
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
...
</span>
</SearchButton>
</React.Suspense>
</div>
)}
{!withTopHeader && withSections && sections && (
<SiteSectionList
className={tcls('hidden', 'lg:block')}
sections={encodeClientSiteSections(context, sections)}
/>
)}
{isMultiVariants && (
<SpacesDropdown
context={context}
siteSpace={siteSpace}
siteSpaces={siteSpaces}
className={tcls( className={tcls(
'w-full', 'hidden',
'page-no-toc:hidden', 'pr-4',
'site-header-none:page-no-toc:flex' 'lg:flex',
'grow-0',
'flex-wrap',
'dark:shadow-light/1',
'text-base/tight'
)} )}
/> >
)} <HeaderLogo context={context} />
</> </div>
} )
/> }
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div> innerHeader={
// displays the search button and/or the space dropdown in the ToC according to the header/variant settings. E.g if there is no header, the search button will be displayed in the ToC.
<>
{!withTopHeader && (
<div className={tcls('hidden', 'lg:block')}>
<React.Suspense fallback={null}>
<SearchButton>
<span className={tcls('flex-1')}>
{t(
getSpaceLanguage(customization),
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
...
</span>
</SearchButton>
</React.Suspense>
</div>
)}
{!withTopHeader && withSections && sections && (
<SiteSectionList
className={tcls('hidden', 'lg:block')}
sections={encodeClientSiteSections(context, sections)}
/>
)}
{isMultiVariants && (
<SpacesDropdown
context={context}
siteSpace={siteSpace}
siteSpaces={siteSpaces}
className={tcls(
'w-full',
'page-no-toc:hidden',
'site-header-none:page-no-toc:flex'
)}
/>
)}
</>
}
/>
<div className="flex min-w-0 flex-1 flex-col">{children}</div>
</div>
</div> </div>
{withFooter ? <Footer context={context} /> : null} {withFooter ? <Footer context={context} /> : null}
+280
View File
@@ -0,0 +1,280 @@
import { describe, expect, test } from 'bun:test';
import type { CustomizationFontDefinition } from '@gitbook/api';
import stylelint from 'stylelint';
import { generateFontFacesCSS, getFontSourcesToPreload } from './custom';
const TEST_FONTS: { [key in string]: CustomizationFontDefinition } = {
basic: {
id: 'open-sans',
fontFamily: 'Open Sans',
fontFaces: [
{
weight: 400,
sources: [
{
url: 'https://example.com/fonts/opensans-regular.woff2',
format: 'woff2',
},
],
},
{
weight: 700,
sources: [
{
url: 'https://example.com/fonts/opensans-bold.woff2',
format: 'woff2',
},
],
},
],
},
multiWeight: {
id: 'roboto',
fontFamily: 'Roboto',
fontFaces: [
{
weight: 300,
sources: [
{
url: 'https://example.com/fonts/roboto-light.woff2',
format: 'woff2',
},
],
},
{
weight: 400,
sources: [
{
url: 'https://example.com/fonts/roboto-regular.woff2',
format: 'woff2',
},
],
},
{
weight: 500,
sources: [
{
url: 'https://example.com/fonts/roboto-medium.woff2',
format: 'woff2',
},
],
},
{
weight: 700,
sources: [
{
url: 'https://example.com/fonts/roboto-bold.woff2',
format: 'woff2',
},
],
},
{
weight: 900,
sources: [
{
url: 'https://example.com/fonts/roboto-black.woff2',
format: 'woff2',
},
],
},
],
},
multiSource: {
id: 'lato',
fontFamily: 'Lato',
fontFaces: [
{
weight: 400,
sources: [
{
url: 'https://example.com/fonts/lato-regular.woff2',
format: 'woff2',
},
{ url: 'https://example.com/fonts/lato-regular.woff', format: 'woff' },
],
},
],
},
missingFormat: {
id: 'source-sans',
fontFamily: 'Source Sans Pro',
fontFaces: [
{
weight: 400,
sources: [
{ url: 'https://example.com/fonts/sourcesans-regular.woff2' },
{
url: 'https://example.com/fonts/sourcesans-regular.woff',
format: 'woff',
},
],
},
],
},
empty: {
id: 'empty-font',
fontFamily: 'Empty Font',
fontFaces: [],
},
specialChars: {
id: 'special-font',
fontFamily: 'Special Font & Co.',
fontFaces: [
{
weight: 400,
sources: [{ url: 'https://example.com/fonts/special.woff2', format: 'woff2' }],
},
],
},
complex: {
id: 'complex-font',
fontFamily: 'Complex Font',
fontFaces: [
{
weight: 400,
sources: [
{ url: 'https://example.com/fonts/regular.woff2' },
{ url: 'https://example.com/fonts/regular.woff' },
],
},
{
weight: 700,
sources: [
{ url: 'https://example.com/fonts/bold.woff2' },
{ url: 'https://example.com/fonts/bold.woff' },
],
},
],
},
variousURLs: {
id: 'various-urls',
fontFamily: 'Various URLs Font',
fontFaces: [
{
weight: 400,
sources: [
{ url: 'https://example.com/fonts.woff2' },
{ url: 'https://example.com/fonts.woff' },
{ url: 'https://example.com/fonts.woff2' },
],
},
],
},
};
// Helper function to validate CSS with stylelint
async function isCSSValid(css: string): Promise<boolean> {
try {
const stylelintResult = await stylelint.lint({
code: css,
config: {
rules: {
'at-rule-no-unknown': true,
'declaration-block-no-duplicate-properties': true,
'property-no-unknown': true,
'selector-pseudo-class-no-unknown': true,
'selector-pseudo-element-no-unknown': true,
'no-duplicate-selectors': true,
'no-empty-source': true,
'no-invalid-double-slash-comments': true,
},
},
});
return !stylelintResult.errored;
} catch (error) {
console.error('Error while linting CSS:', error);
return false;
}
}
describe('generateFontFacesCSS', () => {
test('basic case with regular and bold weights', async () => {
const css = generateFontFacesCSS(TEST_FONTS.basic);
const isValid = await isCSSValid(css);
expect(isValid).toBe(true);
expect(css).toContain('font-weight: 400');
expect(css).toContain('font-weight: 700');
expect(css).toContain(
"url(https://example.com/fonts/opensans-regular.woff2) format('woff2')"
);
expect(css).toContain("url(https://example.com/fonts/opensans-bold.woff2) format('woff2')");
expect(css).toContain('--font-custom: CustomFont');
});
test('multiple font weights', async () => {
const css = generateFontFacesCSS(TEST_FONTS.multiWeight);
const isValid = await isCSSValid(css);
expect(isValid).toBe(true);
[300, 400, 500, 700, 900].forEach((weight) => {
expect(css).toContain(`font-weight: ${weight}`);
});
});
test('multiple sources for a single weight', async () => {
const css = generateFontFacesCSS(TEST_FONTS.multiSource);
const isValid = await isCSSValid(css);
expect(isValid).toBe(true);
expect(css).toContain(
"url(https://example.com/fonts/lato-regular.woff2) format('woff2'), url(https://example.com/fonts/lato-regular.woff) format('woff')"
);
});
test('missing format property', async () => {
const css = generateFontFacesCSS(TEST_FONTS.missingFormat);
const isValid = await isCSSValid(css);
expect(isValid).toBe(true);
expect(css).toContain(
"url(https://example.com/fonts/sourcesans-regular.woff2), url(https://example.com/fonts/sourcesans-regular.woff) format('woff')"
);
});
test('empty font faces array', async () => {
const css = generateFontFacesCSS(TEST_FONTS.empty);
expect(css).toBe('');
});
test('font with special characters in name', async () => {
const css = generateFontFacesCSS(TEST_FONTS.specialChars);
// Validate CSS syntax
const isValid = await isCSSValid(css);
expect(isValid).toBe(true);
});
});
describe('getFontSourcesToPreload', () => {
const preloadTestCases = [
{ name: 'basic case', font: TEST_FONTS.basic, expectedCount: 2 },
{ name: 'multiple weights', font: TEST_FONTS.multiWeight, expectedCount: 2 },
{ name: 'multiple sources', font: TEST_FONTS.multiSource, expectedCount: 2 },
{ name: 'missing format', font: TEST_FONTS.missingFormat, expectedCount: 2 },
{ name: 'empty font faces', font: TEST_FONTS.empty, expectedCount: 0 },
{ name: 'special characters', font: TEST_FONTS.specialChars, expectedCount: 1 },
{ name: 'complex case', font: TEST_FONTS.complex, expectedCount: 4 },
];
preloadTestCases.forEach(({ name, font, expectedCount }) => {
test(`extracts ${expectedCount} URLs from ${name}`, () => {
const result = getFontSourcesToPreload(font).flatMap((face) => face.sources);
expect(result).toBeArray();
expect(result.length).toBe(expectedCount);
});
});
});
+53
View File
@@ -0,0 +1,53 @@
import type { CustomizationFontDefinition } from '@gitbook/api';
/**
* Define the custom font faces and set the --font-custom to the custom font name
*/
export function generateFontFacesCSS(customFont: CustomizationFontDefinition): string {
const { fontFaces } = customFont;
// Generate font face declarations for all weights
const fontFaceDeclarations = fontFaces
.map((face) => {
const srcAttr = face.sources
.map((source) => {
let srcDefinition = `url(${source.url})`;
if (source.format) {
srcDefinition += ` format('${source.format}')`;
}
return srcDefinition;
})
.join(', ');
// We could use the customFont.fontFamily name here, but to avoid extra normalization we're using 'CustomFont'
return `
@font-face {
font-family: CustomFont;
font-style: normal;
font-weight: ${face.weight};
font-display: swap;
src: ${srcAttr};
}
`;
})
.join('\n');
return fontFaceDeclarations
? `${fontFaceDeclarations}
:root {
--font-custom: CustomFont;
}`
: '';
}
/**
* Get a list of font sources to preload (only 400 and 700 weights)
*/
export function getFontSourcesToPreload(customFont: CustomizationFontDefinition) {
return customFont.fontFaces.filter(
(face): face is typeof face & { weight: 400 | 700 } =>
face.weight === 400 || face.weight === 700
);
}
+207
View File
@@ -0,0 +1,207 @@
import { CustomizationDefaultFont } from '@gitbook/api';
import {
Fira_Sans_Extra_Condensed,
IBM_Plex_Mono,
IBM_Plex_Serif,
Inter,
Lato,
Merriweather,
Noto_Color_Emoji,
Noto_Sans,
Open_Sans,
Overpass,
Poppins,
Raleway,
Roboto,
Roboto_Slab,
Source_Sans_3,
Ubuntu,
} from 'next/font/google';
import localFont from 'next/font/local';
export const fontNotoColorEmoji = Noto_Color_Emoji({
variable: '--font-noto-color-emoji',
weight: ['400'],
preload: false,
display: 'swap',
});
/*
Fonts are downloaded and loaded by next/font.
We can't use "preload: true" as otherwise Next will preload all the fonts on the page
while spaces only use one font at a time.
*/
const inter = Inter({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
export const ibmPlexMono = IBM_Plex_Mono({
weight: ['400', '500', '600', '700'],
variable: '--font-mono',
style: 'normal',
display: 'swap',
preload: false,
fallback: ['monospace'],
adjustFontFallback: false,
});
const firaSans = Fira_Sans_Extra_Condensed({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const ibmPlexSerif = IBM_Plex_Serif({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['serif'],
});
const lato = Lato({
weight: ['400', '700', '900'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const merriweather = Merriweather({
weight: ['400', '700', '900'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['serif'],
});
const notoSans = Noto_Sans({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const openSans = Open_Sans({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const overpass = Overpass({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const poppins = Poppins({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const raleway = Raleway({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const roboto = Roboto({
weight: ['400', '500', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const robotoSlab = Roboto_Slab({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const sourceSansPro = Source_Sans_3({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const ubuntu = Ubuntu({
weight: ['400', '500', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const abcFavorit = localFont({
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
src: [
{
path: './ABCFavorit/ABCFavorit-Variable.woff2',
weight: '400 700',
style: 'normal',
},
{
path: './ABCFavorit/ABCFavorit-BoldItalic.woff2',
weight: '700',
style: 'italic',
},
{
path: './ABCFavorit/ABCFavorit-MediumItalic.woff2',
weight: '500',
style: 'italic',
},
{
path: './ABCFavorit/ABCFavorit-RegularItalic.woff2',
weight: '400',
style: 'italic',
},
],
declarations: [{ prop: 'ascent-override', value: '100%' }],
});
/**
* Font definitions.
*/
export const fonts: { [fontName in CustomizationDefaultFont]: { variable: string } } = {
[CustomizationDefaultFont.Inter]: inter,
[CustomizationDefaultFont.FiraSans]: firaSans,
[CustomizationDefaultFont.IBMPlexSerif]: ibmPlexSerif,
[CustomizationDefaultFont.Lato]: lato,
[CustomizationDefaultFont.Merriweather]: merriweather,
[CustomizationDefaultFont.NotoSans]: notoSans,
[CustomizationDefaultFont.OpenSans]: openSans,
[CustomizationDefaultFont.Overpass]: overpass,
[CustomizationDefaultFont.Poppins]: poppins,
[CustomizationDefaultFont.Raleway]: raleway,
[CustomizationDefaultFont.Roboto]: roboto,
[CustomizationDefaultFont.RobotoSlab]: robotoSlab,
[CustomizationDefaultFont.SourceSansPro]: sourceSansPro,
[CustomizationDefaultFont.Ubuntu]: ubuntu,
[CustomizationDefaultFont.ABCFavorit]: abcFavorit,
};
+40 -204
View File
@@ -1,207 +1,43 @@
import { CustomizationDefaultFont } from '@gitbook/api'; import type { CustomizationFont, CustomizationFontDefinition } from '@gitbook/api';
import { import { generateFontFacesCSS, getFontSourcesToPreload } from './custom';
Fira_Sans_Extra_Condensed, import { fonts } from './default';
IBM_Plex_Mono,
IBM_Plex_Serif,
Inter,
Lato,
Merriweather,
Noto_Color_Emoji,
Noto_Sans,
Open_Sans,
Overpass,
Poppins,
Raleway,
Roboto,
Roboto_Slab,
Source_Sans_3,
Ubuntu,
} from 'next/font/google';
import localFont from 'next/font/local';
export const fontNotoColorEmoji = Noto_Color_Emoji({
variable: '--font-noto-color-emoji',
weight: ['400'],
preload: false,
display: 'swap',
});
/*
Fonts are downloaded and loaded by next/font.
We can't use "preload: true" as otherwise Next will preload all the fonts on the page
while spaces only use one font at a time.
*/
const inter = Inter({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
export const ibmPlexMono = IBM_Plex_Mono({
weight: ['400', '500', '600', '700'],
variable: '--font-mono',
style: 'normal',
display: 'swap',
preload: false,
fallback: ['monospace'],
adjustFontFallback: false,
});
const firaSans = Fira_Sans_Extra_Condensed({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const ibmPlexSerif = IBM_Plex_Serif({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['serif'],
});
const lato = Lato({
weight: ['400', '700', '900'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const merriweather = Merriweather({
weight: ['400', '700', '900'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['serif'],
});
const notoSans = Noto_Sans({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const openSans = Open_Sans({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const overpass = Overpass({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const poppins = Poppins({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const raleway = Raleway({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const roboto = Roboto({
weight: ['400', '500', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const robotoSlab = Roboto_Slab({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const sourceSansPro = Source_Sans_3({
weight: ['400', '500', '600', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const ubuntu = Ubuntu({
weight: ['400', '500', '700'],
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
});
const abcFavorit = localFont({
variable: '--font-content',
preload: false,
display: 'swap',
fallback: ['system-ui', 'arial'],
src: [
{
path: './ABCFavorit/ABCFavorit-Variable.woff2',
weight: '400 700',
style: 'normal',
},
{
path: './ABCFavorit/ABCFavorit-BoldItalic.woff2',
weight: '700',
style: 'italic',
},
{
path: './ABCFavorit/ABCFavorit-MediumItalic.woff2',
weight: '500',
style: 'italic',
},
{
path: './ABCFavorit/ABCFavorit-RegularItalic.woff2',
weight: '400',
style: 'italic',
},
],
declarations: [{ prop: 'ascent-override', value: '100%' }],
});
/** /**
* Font definitions. * Represents font data for either a default font or a custom font
*/ */
export const fonts: { [fontName in CustomizationDefaultFont]: { variable: string } } = { type FontData = DefaultFontData | CustomFontData;
[CustomizationDefaultFont.Inter]: inter,
[CustomizationDefaultFont.FiraSans]: firaSans, /**
[CustomizationDefaultFont.IBMPlexSerif]: ibmPlexSerif, * Font data for a default font, currently handle with next/font
[CustomizationDefaultFont.Lato]: lato, */
[CustomizationDefaultFont.Merriweather]: merriweather, interface DefaultFontData {
[CustomizationDefaultFont.NotoSans]: notoSans, type: 'default';
[CustomizationDefaultFont.OpenSans]: openSans, variable: string;
[CustomizationDefaultFont.Overpass]: overpass, }
[CustomizationDefaultFont.Poppins]: poppins,
[CustomizationDefaultFont.Raleway]: raleway, /**
[CustomizationDefaultFont.Roboto]: roboto, * Font data for a custom font with @font-face rules
[CustomizationDefaultFont.RobotoSlab]: robotoSlab, */
[CustomizationDefaultFont.SourceSansPro]: sourceSansPro, interface CustomFontData {
[CustomizationDefaultFont.Ubuntu]: ubuntu, type: 'custom';
[CustomizationDefaultFont.ABCFavorit]: abcFavorit, fontFaceRules: string;
}; preloadSources: CustomizationFontDefinition['fontFaces'];
}
/**
* Get the appropriate font data for a given font configuration
*/
export function getFontData(font: CustomizationFont): FontData {
if (typeof font === 'string') {
return {
type: 'default',
variable: fonts[font].variable,
};
}
return {
type: 'custom',
fontFaceRules: generateFontFacesCSS(font),
preloadSources: getFontSourcesToPreload(font),
};
}
@@ -89,14 +89,14 @@ A serialnumbers value governs its order within the given token.id</p>
<td>lt(e)</td> <td>lt(e)</td>
<td>Y</td> <td>Y</td>
<td>Single occurrence only. Requires the presence of an <strong>lte</strong> or <strong>eq</strong> <strong>token.id</strong> query</td> <td>Single occurrence only. Requires the presence of an <strong>lte</strong> or <strong>eq</strong> <strong>token.id</strong> query</td>
<td>?token.id=lte:X&amp;serialnumber=lt:Y</td> <td>?token.id=lte:X&#x26;serialnumber=lt:Y</td>
</tr> </tr>
<tr> <tr>
<td></td> <td></td>
<td>gt(e)</td> <td>gt(e)</td>
<td>Y</td> <td>Y</td>
<td>Single occurrence only. Requires the presence of an <strong>gte</strong> or <strong>eq</strong> <strong>token.id</strong> query</td> <td>Single occurrence only. Requires the presence of an <strong>gte</strong> or <strong>eq</strong> <strong>token.id</strong> query</td>
<td>?token.id=gte:X&amp;serialnumber=gt:Y</td> <td>?token.id=gte:X&#x26;serialnumber=gt:Y</td>
</tr> </tr>
<tr> <tr>
<td>spender.id</td> <td>spender.id</td>
@@ -131,3 +131,16 @@ A serialnumbers value governs its order within the given token.id</p>
<p>Note: When searching across a range for individual NFTs a <strong>serialnumber</strong> with an additional <strong>token.id</strong> query filter must be provided. <p>Note: When searching across a range for individual NFTs a <strong>serialnumber</strong> with an additional <strong>token.id</strong> query filter must be provided.
Both filters must be a single occurrence of <strong>gt(e)</strong> or <strong>lt(e)</strong> which provide a lower and or upper boundary for search.</p>" Both filters must be a single occurrence of <strong>gt(e)</strong> or <strong>lt(e)</strong> which provide a lower and or upper boundary for search.</p>"
`; `;
exports[`parseMarkdown should parse html 1`] = `
"<p>Returns trending events for the given time frame.</p>
<p>The events are sorted by <code>trending score</code>.</p>
<p>To calculate trending score for an event, each bet placed on this event
contributes a value determined by how recently the bet was placed.</p>
<p>Recent bets add more value than older ones.</p>
<p>The normalized value of its score is also assigned to each event as its confidence.</p>
<p>In this example we get all trending events where <code>league</code> is <code>UEFA Champions League</code>.</p>
<pre><code class="language-bash">$ curl --request GET \\
--url 'https://api.vaix.ai/api/sports/events/trending?filters=league%3Aeq%3AUEFA%20Champions%20League'
</code></pre>"
`;
+23
View File
@@ -0,0 +1,23 @@
import type { PublishedSiteContent, SiteAPIToken } from '@gitbook/api';
import { jwtDecode } from 'jwt-decode';
/**
* Claims about the visitor, stored in the VA and auth token.
*/
export type VisitorAuthClaims = Record<string, any>;
/**
* Get the visitor auth claims from the API response obtained from `getPublishedContentByUrl`.
*/
export function getVisitorAuthClaims(siteData: PublishedSiteContent): VisitorAuthClaims {
const { apiToken } = siteData;
return getVisitorAuthClaimsFromToken(jwtDecode<SiteAPIToken>(apiToken));
}
/**
* Get the visitor auth claims from a decoded API token.
*/
export function getVisitorAuthClaimsFromToken(token: SiteAPIToken): VisitorAuthClaims {
return token.claims ?? {};
}
+6 -2
View File
@@ -153,7 +153,7 @@ export function withAPI<T>(client: GitBookAPIContext, fn: () => Promise<T>): Pro
type SpaceContentLookup = Pick< type SpaceContentLookup = Pick<
PublishedSiteContent, PublishedSiteContent,
'space' | 'changeRequest' | 'revision' | 'pathname' | 'basePath' | 'apiToken' 'space' | 'changeRequest' | 'revision' | 'pathname' | 'basePath' | 'siteBasePath' | 'apiToken'
> & { kind: 'space' }; > & { kind: 'space' };
export type PublishedContentWithCache = export type PublishedContentWithCache =
@@ -732,12 +732,16 @@ export const getComputedDocument = cache({
_organizationId: string, _organizationId: string,
spaceId: string, spaceId: string,
source: ComputedContentSource, source: ComputedContentSource,
seed: string,
options: CacheFunctionOptions options: CacheFunctionOptions
) => { ) => {
const apiCtx = await api(); const apiCtx = await api();
const response = await apiCtx.client.spaces.getComputedDocument( const response = await apiCtx.client.spaces.getComputedDocument(
spaceId, spaceId,
{ source }, {
source,
seed,
},
{}, {},
{ {
signal: options.signal, signal: options.signal,
@@ -0,0 +1,56 @@
'use client';
import cookies from 'js-cookie';
import { checkIsSecurityError } from './security-error';
/**
* Get all cookies.
* @returns A map of cookie names to their values.
*/
export function getAllBrowserCookies(): Array<{
name: string;
value: string;
}> {
try {
const all = cookies.get();
return Object.entries(all).map(([name, value]) => ({ name, value }));
} catch (error) {
if (checkIsSecurityError(error)) {
return [];
}
throw error;
}
}
/**
* Get a map of cookie names to their values.
* @returns A map of cookie names to their values.
*/
export function getAllBrowserCookiesMap(): Record<string, string> {
return Object.fromEntries(getAllBrowserCookies().map(({ name, value }) => [name, value]));
}
/**
* Get a cookie by name.
* @param name - The name of the cookie to get.
* @returns The value of the cookie or undefined if the cookie does not exist.
*/
export function getBrowserCookie(name: string): string | undefined {
try {
return cookies.get(name);
} catch (error) {
if (checkIsSecurityError(error)) {
return undefined;
}
throw error;
}
}
/**
* Set a cookie.
* @param name - The name of the cookie to set.
* @param value - The value of the cookie to set.
* @param options - The options for the cookie to set.
*/
export const setBrowserCookie = cookies.set;

Some files were not shown because too many files have changed in this diff Show More