Compare commits

..

7 Commits

Author SHA1 Message Date
Samy Pessé a92cb49445 Version Packages (#2958)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-03-11 09:38:39 +00:00
Greg Bergé 88f64b0d63 Support Node.js v20 with @gitbook/icons (#2960) 2025-03-11 09:27:26 +00:00
Nolann B. 844059f9a5 Fix spacing in OpenAPISecurities (#2954) 2025-03-11 09:37:34 +01:00
Nolann B. eaf2d68308 OpenAPI operation title fallback in sections (#2955) 2025-03-11 09:37:00 +01:00
Nolann B. 12bdbf988d Fix react-openapi tests (#2956) 2025-03-11 09:20:24 +01:00
Samy Pessé 29bab79005 v2: PDF export for sites and spaces (#2949) 2025-03-10 00:08:33 +01:00
Samy Pessé 8d5de97ddf v2: fix fallback and VA redirects (#2948) 2025-03-08 11:21:49 +01:00
63 changed files with 1303 additions and 799 deletions
+6 -4
View File
@@ -190,7 +190,8 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e run: bun e2e
env: env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/ BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }} ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'v2-vercel' ARGOS_BUILD_NAME: 'v2-vercel'
visual-testing-customers-v1: visual-testing-customers-v1:
@@ -230,7 +231,8 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e-customers run: bun e2e-customers
env: env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/ BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }} ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers-v2' ARGOS_BUILD_NAME: 'customers-v2'
pagespeed-testing-v1: pagespeed-testing-v1:
@@ -247,7 +249,7 @@ jobs:
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 PUPPETEER_SKIP_DOWNLOAD: 1
- name: Run pagespeed tests - name: Run pagespeed tests
run: bun ./packages/gitbook/tests/pagespeed-testing.ts $DEPLOYMENT_URL run: bun ./packages/gitbook/tests/pagespeed-testing.ts
env: env:
DEPLOYMENT_URL: ${{needs.deploy-v1-cloudflare.outputs.deployment-url}} BASE_URL: ${{needs.deploy-v1-cloudflare.outputs.deployment-url}}
PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }} PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
+6 -7
View File
@@ -49,7 +49,7 @@
}, },
"packages/gitbook": { "packages/gitbook": {
"name": "gitbook", "name": "gitbook",
"version": "0.6.5", "version": "0.7.2",
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/cache-do": "workspace:*", "@gitbook/cache-do": "workspace:*",
@@ -132,7 +132,7 @@
}, },
"packages/gitbook-v2": { "packages/gitbook-v2": {
"name": "gitbook-v2", "name": "gitbook-v2",
"version": "0.1.2", "version": "0.2.0",
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/cache-tags": "workspace:*", "@gitbook/cache-tags": "workspace:*",
@@ -144,7 +144,7 @@
"warn-once": "^0.1.1", "warn-once": "^0.1.1",
}, },
"devDependencies": { "devDependencies": {
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d", "@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d",
"gitbook": "*", "gitbook": "*",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
@@ -172,7 +172,7 @@
}, },
"packages/openapi-parser": { "packages/openapi-parser": {
"name": "@gitbook/openapi-parser", "name": "@gitbook/openapi-parser",
"version": "2.0.2", "version": "2.1.0",
"dependencies": { "dependencies": {
"@scalar/openapi-parser": "^0.10.9", "@scalar/openapi-parser": "^0.10.9",
"@scalar/openapi-types": "^0.1.9", "@scalar/openapi-types": "^0.1.9",
@@ -198,7 +198,6 @@
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/icons": "workspace:*", "@gitbook/icons": "workspace:*",
"assert-never": "^1.2.1",
"classnames": "^2.5.1", "classnames": "^2.5.1",
}, },
"devDependencies": { "devDependencies": {
@@ -227,7 +226,7 @@
}, },
"packages/react-openapi": { "packages/react-openapi": {
"name": "@gitbook/react-openapi", "name": "@gitbook/react-openapi",
"version": "1.0.5", "version": "1.1.2",
"dependencies": { "dependencies": {
"@gitbook/openapi-parser": "workspace:*", "@gitbook/openapi-parser": "workspace:*",
"@scalar/api-client-react": "^1.1.36", "@scalar/api-client-react": "^1.1.36",
@@ -793,7 +792,7 @@
"@opennextjs/aws": ["@opennextjs/aws@https://pkg.pr.new/@opennextjs/aws@756", { "dependencies": { "@aws-sdk/client-cloudfront": "3.398.0", "@aws-sdk/client-dynamodb": "^3.398.0", "@aws-sdk/client-lambda": "^3.398.0", "@aws-sdk/client-s3": "^3.398.0", "@aws-sdk/client-sqs": "^3.398.0", "@node-minify/core": "^8.0.6", "@node-minify/terser": "^8.0.6", "@tsconfig/node18": "^1.0.1", "aws4fetch": "^1.0.18", "chalk": "^5.3.0", "esbuild": "0.19.2", "express": "5.0.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.0.0" }, "bin": { "open-next": "./dist/index.js" } }], "@opennextjs/aws": ["@opennextjs/aws@https://pkg.pr.new/@opennextjs/aws@756", { "dependencies": { "@aws-sdk/client-cloudfront": "3.398.0", "@aws-sdk/client-dynamodb": "^3.398.0", "@aws-sdk/client-lambda": "^3.398.0", "@aws-sdk/client-s3": "^3.398.0", "@aws-sdk/client-sqs": "^3.398.0", "@node-minify/core": "^8.0.6", "@node-minify/terser": "^8.0.6", "@tsconfig/node18": "^1.0.1", "aws4fetch": "^1.0.18", "chalk": "^5.3.0", "esbuild": "0.19.2", "express": "5.0.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.0.0" }, "bin": { "open-next": "./dist/index.js" } }],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d", { "dependencies": { "@ast-grep/napi": "^0.34.1", "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "https://pkg.pr.new/@opennextjs/aws@756", "enquirer": "^2.4.1", "glob": "^11.0.0", "yaml": "^2.7.0" }, "peerDependencies": { "wrangler": "^3.111.0" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }], "@opennextjs/cloudflare": ["@opennextjs/cloudflare@https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d", { "dependencies": { "@ast-grep/napi": "^0.34.1", "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "https://pkg.pr.new/@opennextjs/aws@756", "enquirer": "^2.4.1", "glob": "^11.0.0", "yaml": "^2.7.0" }, "peerDependencies": { "wrangler": "^3.111.0" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }],
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="], "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+1 -1
View File
@@ -14,7 +14,7 @@
}, },
"devDependencies": { "devDependencies": {
"gitbook": "*", "gitbook": "*",
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d", "@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
"postcss": "^8" "postcss": "^8"
}, },
@@ -16,7 +16,7 @@ export default async function Page(props: PageProps) {
const context = await getDynamicSiteContext(params); const context = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />; return <SitePage context={context} pageParams={{ pathname }} />;
} }
export async function generateViewport(props: PageProps): Promise<Viewport> { export async function generateViewport(props: PageProps): Promise<Viewport> {
@@ -25,14 +25,12 @@ export async function generateViewport(props: PageProps): Promise<Viewport> {
} }
export async function generateMetadata(props: PageProps): Promise<Metadata> { export async function generateMetadata(props: PageProps): Promise<Metadata> {
const [params, searchParams] = await Promise.all([props.params, props.searchParams]); 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({
context, context,
pageParams: { pathname }, pageParams: { pathname },
redirectOnFallback: true,
fallback: !!searchParams.fallback,
}); });
} }
@@ -0,0 +1,12 @@
import { PDFRootLayout } from '@/components/PDF';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export default async function RootLayout(props: {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
const { params, children } = props;
const context = await getDynamicSiteContext(await params);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
}
@@ -0,0 +1,20 @@
import { PDFPage, generatePDFMetadata } from '@/components/PDF';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function generateMetadata({
params,
}: {
params: Promise<RouteLayoutParams>;
}) {
const context = await getDynamicSiteContext(await params);
return generatePDFMetadata(context);
}
export default async function Page(props: {
params: Promise<RouteLayoutParams>;
searchParams: Promise<{ [key: string]: string }>;
}) {
const { params, searchParams } = props;
const context = await getDynamicSiteContext(await params);
return <PDFPage context={context} searchParams={await searchParams} />;
}
@@ -28,7 +28,7 @@ export default async function Page(props: PageProps) {
}) })
); );
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />; return <SitePage context={context} pageParams={{ pathname }} />;
} }
export async function generateViewport(props: PageProps): Promise<Viewport> { export async function generateViewport(props: PageProps): Promise<Viewport> {
@@ -44,6 +44,5 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
return generateSitePageMetadata({ return generateSitePageMetadata({
context, context,
pageParams: { pathname }, pageParams: { pathname },
redirectOnFallback: true,
}); });
} }
@@ -0,0 +1,59 @@
import {
type GitBookBaseContext,
type GitBookSpaceContext,
fetchSpaceContextByIds,
} from '@v2/lib/context';
import { createDataFetcher } from '@v2/lib/data';
import { GITBOOK_API_URL } from '@v2/lib/env';
import { createLinker } from '@v2/lib/links';
import { getAPITokenFromMiddleware } from '@v2/lib/middleware';
export type SpacePDFRouteParams = {
spaceId: string;
changeRequestId?: string;
revisionId?: string;
};
export async function getSpacePDFContext(
params: SpacePDFRouteParams
): Promise<GitBookSpaceContext> {
const { spaceId } = params;
const apiToken = await getAPITokenFromMiddleware();
const linker = createLinker({
pathname: getPDFRoutePath(params),
});
const dataFetcher = createDataFetcher({
apiToken: apiToken,
apiEndpoint: GITBOOK_API_URL,
});
const baseContext: GitBookBaseContext = {
linker,
dataFetcher,
};
return await fetchSpaceContextByIds(baseContext, {
space: spaceId,
shareKey: undefined,
changeRequest: params.changeRequestId,
revision: params.revisionId,
});
}
function getPDFRoutePath(params: SpacePDFRouteParams) {
let path = `/~space/${params.spaceId}`;
if (params.changeRequestId) {
path += `/~/changes/${params.changeRequestId}`;
}
if (params.revisionId) {
path += `/~/revisions/${params.revisionId}`;
}
path += '~gitbook/pdf';
return path;
}
@@ -0,0 +1,2 @@
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
export default RootLayout;
@@ -0,0 +1,4 @@
import PDFPage, { generateMetadata } from '@v2/app/~space/[spaceId]/~gitbook/pdf/page';
export default PDFPage;
export { generateMetadata };
@@ -0,0 +1,2 @@
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
export default RootLayout;
@@ -0,0 +1,4 @@
import PDFPage, { generateMetadata } from '@v2/app/~space/[spaceId]/~gitbook/pdf/page';
export default PDFPage;
export { generateMetadata };
@@ -0,0 +1,12 @@
import { PDFRootLayout } from '@/components/PDF';
import { type SpacePDFRouteParams, getSpacePDFContext } from '@v2/app/~space/[spaceId]/pdf';
export default async function RootLayout(props: {
params: Promise<SpacePDFRouteParams>;
children: React.ReactNode;
}) {
const { params, children } = props;
const context = await getSpacePDFContext(await params);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
}
@@ -0,0 +1,20 @@
import { PDFPage, generatePDFMetadata } from '@/components/PDF';
import { type SpacePDFRouteParams, getSpacePDFContext } from '@v2/app/~space/[spaceId]/pdf';
export async function generateMetadata({
params,
}: {
params: Promise<SpacePDFRouteParams>;
}) {
const context = await getSpacePDFContext(await params);
return generatePDFMetadata(context);
}
export default async function Page(props: {
params: Promise<SpacePDFRouteParams>;
searchParams: Promise<{ [key: string]: string }>;
}) {
const { params, searchParams } = props;
const context = await getSpacePDFContext(await params);
return <PDFPage context={context} searchParams={await searchParams} />;
}
+37 -20
View File
@@ -116,27 +116,11 @@ export function getBaseContext(input: {
apiToken: input.apiToken ?? GITBOOK_API_TOKEN, apiToken: input.apiToken ?? GITBOOK_API_TOKEN,
apiEndpoint: GITBOOK_API_URL, apiEndpoint: GITBOOK_API_URL,
}); });
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
const linker = const linker = getLinkerForSiteURL({
urlMode === 'url-host' siteURL: url,
? createLinker({ urlMode,
host: url.host, });
pathname: url.pathname,
})
: createLinker({
protocol: gitbookURL?.protocol,
host: gitbookURL?.host,
pathname: `/url/${url.host}${url.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}`;
};
}
const imageResizer = createImageResizer({ const imageResizer = createImageResizer({
host: url.host, host: url.host,
@@ -152,6 +136,39 @@ 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. * Fetch the context of a site for a given URL and a base context.
*/ */
+4 -1
View File
@@ -93,7 +93,10 @@ export async function wrapDataFetcherError<T>(
} }
} }
function getExposableError(error: Error): DataFetcherErrorData { /**
* Get a data fetcher exposable error from a JS error.
*/
export function getExposableError(error: Error): DataFetcherErrorData {
if (error instanceof GitBookAPIError) { if (error instanceof GitBookAPIError) {
return { return {
code: error.code, code: error.code,
+24 -7
View File
@@ -1,7 +1,9 @@
import { race, tryCatch } from '@/lib/async'; import { race, tryCatch } from '@/lib/async';
import { joinPath } from '@/lib/paths'; import { joinPath } from '@/lib/paths';
import { GitBookAPI, type GitBookAPIError, type PublishedSiteContentLookup } from '@gitbook/api'; import { GitBookAPI, type PublishedSiteContentLookup } from '@gitbook/api';
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 { getExposableError } from './errors';
import type { DataFetcherResponse } from './types';
import { getURLLookupAlternatives, stripURLSearch } from './urls'; import { getURLLookupAlternatives, stripURLSearch } from './urls';
/** /**
@@ -12,10 +14,7 @@ export async function getPublishedContentByURL(input: {
url: string; url: string;
visitorAuthToken: string | null; visitorAuthToken: string | null;
redirectOnError: boolean; redirectOnError: boolean;
}): Promise< }): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
| { data: PublishedSiteContentLookup; error?: undefined }
| { data?: undefined; error: Error | GitBookAPIError }
> {
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);
@@ -27,6 +26,7 @@ export async function getPublishedContentByURL(input: {
userAgent: GITBOOK_USER_AGENT, userAgent: GITBOOK_USER_AGENT,
}); });
const startTime = performance.now();
const callResult = await tryCatch( const callResult = await tryCatch(
api.urls.getPublishedContentByUrl( api.urls.getPublishedContentByUrl(
{ {
@@ -43,6 +43,12 @@ export async function getPublishedContentByURL(input: {
} }
) )
); );
const endTime = performance.now();
// biome-ignore lint/suspicious/noConsole: we want to log performance data
console.log(
`getPublishedContentByURL(${alternative.url}) Time taken: ${endTime - startTime}ms`
);
if (callResult.error) { if (callResult.error) {
if (alternative.primary) { if (alternative.primary) {
@@ -110,9 +116,20 @@ export async function getPublishedContentByURL(input: {
if (!result) { if (!result) {
return { return {
error: new Error('No content found'), error: {
code: 404,
message: 'No content found',
},
}; };
} }
return result; if (result.error) {
return {
error: getExposableError(result.error),
};
}
return {
data: result.data,
};
} }
+20
View File
@@ -36,6 +36,12 @@ export enum MiddlewareHeaders {
* The visitor token used to access this content * The visitor token used to access this content
*/ */
VisitorAuthToken = 'x-gitbook-visitor-token', VisitorAuthToken = 'x-gitbook-visitor-token',
/**
* The API token used to fetch the content.
* This should only be passed for non-site dynamic routes.
*/
APIToken = 'x-gitbook-api-token',
} }
/** /**
@@ -112,3 +118,17 @@ export async function getVisitorAuthTokenFromMiddleware(): Promise<string | null
return visitorAuthToken; return visitorAuthToken;
} }
/**
* Get the API token from the middleware headers.
* This function should only be called in a dynamic route.
*/
export async function getAPITokenFromMiddleware(): Promise<string> {
const headersList = await headers();
const apiToken = headersList.get(MiddlewareHeaders.APIToken);
if (!apiToken) {
throw new Error('API token is not set by the middleware');
}
return apiToken;
}
+190 -61
View File
@@ -1,13 +1,25 @@
import { CustomizationThemeMode, GitBookAPIError } 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 { getContentSecurityPolicy } from '@/lib/csp'; import { getContentSecurityPolicy } from '@/lib/csp';
import { validateSerializedCustomization } from '@/lib/customization'; import { validateSerializedCustomization } from '@/lib/customization';
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths'; import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import { getResponseCookiesForVisitorAuth, getVisitorToken } from '@/lib/visitor-token'; import {
type ResponseCookies,
getPathScopedCookieName,
getResponseCookiesForVisitorAuth,
getVisitorToken,
normalizeVisitorAuthURL,
} from '@/lib/visitor-token';
import { serveResizedImage } from '@/routes/image'; import { serveResizedImage } from '@/routes/image';
import { getPublishedContentByURL } from '@v2/lib/data'; import { getLinkerForSiteURL } from '@v2/lib/context';
import {
DataFetcherError,
getPublishedContentByURL,
normalizeURL,
throwIfDataError,
} from '@v2/lib/data';
import { isGitBookAssetsHostURL, isGitBookHostURL } from '@v2/lib/env'; import { isGitBookAssetsHostURL, isGitBookHostURL } from '@v2/lib/env';
import { MiddlewareHeaders } from '@v2/lib/middleware'; import { MiddlewareHeaders } from '@v2/lib/middleware';
@@ -21,27 +33,21 @@ type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
try { try {
// Route all requests to a site const requestURL = new URL(request.url);
const extracted = getSiteURLFromRequest(request);
if (extracted) {
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (extracted.url.pathname.endsWith('/~gitbook/image')) {
return await serveResizedImage(request, {
host: extracted.url.host,
});
}
return await serveSiteByURL(request, extracted); // Redirect to normalize the URL
const normalized = normalizeURL(requestURL);
if (normalized.toString() !== requestURL.toString()) {
return NextResponse.redirect(normalized.toString());
}
for (const handler of [serveSiteRoutes, servePreviewRoutes]) {
const result = await handler(requestURL, request);
if (result) {
return result;
}
} }
// Handle the rest with the router default logic
return NextResponse.next(); return NextResponse.next();
} catch (error) { } catch (error) {
return serveErrorResponse(error as Error); return serveErrorResponse(error as Error);
@@ -49,50 +55,111 @@ export async function middleware(request: NextRequest) {
} }
/** /**
* Serve site by URL. * Handle request that are targetting the site routes group.
*/ */
async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) { async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
const { url, mode } = urlWithMode; const match = getSiteURLFromRequest(request);
if (!match) {
// Visitor authentication return null;
// @ts-ignore - request typing
const visitorToken = getVisitorToken(request, url);
const result = await getPublishedContentByURL({
url: url.toString(),
visitorAuthToken: visitorToken?.token ?? null,
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the 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',
});
if (result.error) {
throw result.error;
} }
const { data } = result; const { url: siteURL, mode } = match;
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (siteURL.pathname.endsWith('/~gitbook/image')) {
return await serveResizedImage(request, {
host: siteURL.host,
});
}
//
// Detect and extract the visitor authentication token from the request
//
// @ts-ignore - request typing
const visitorToken = getVisitorToken(request, siteURL);
const data = await throwIfDataError(
getPublishedContentByURL({
url: siteURL.toString(),
visitorAuthToken: visitorToken?.token ?? null,
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the 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 = {};
//
// Handle redirects
//
if ('redirect' in data) { if ('redirect' in data) {
// biome-ignore lint/suspicious/noConsole: we want to log the redirect
console.log('redirect', data.redirect);
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);
// 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(data.redirect); return NextResponse.redirect(data.redirect);
} }
cookies = {
...cookies,
...getResponseCookiesForVisitorAuth(data.basePath, visitorToken),
};
//
// Make sure the URL is clean of any va token after a successful lookup
// The token is stored in a cookie that is set on the redirect response
//
const requestURLWithoutToken = normalizeVisitorAuthURL(requestURL);
if (requestURLWithoutToken.toString() !== requestURL.toString()) {
return writeResponseCookies(
NextResponse.redirect(requestURLWithoutToken.toString()),
cookies
);
}
//
// Render and serve the content
//
// When visitor has authentication (adaptive content or VA), we serve dynamic routes. // When visitor has authentication (adaptive content or VA), we serve dynamic routes.
let routeType = visitorToken ? 'dynamic' : 'static'; let routeType = visitorToken ? 'dynamic' : 'static';
const requestHeaders = new Headers(request.headers); const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType); requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode); requestHeaders.set(MiddlewareHeaders.URLMode, mode);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${url.origin}${data.basePath}`); requestHeaders.set(MiddlewareHeaders.SiteURL, `${siteURL.origin}${data.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data)); requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data));
// Preview of customization/theme // Preview of customization/theme
const customization = url.searchParams.get('customization'); const customization = siteURL.searchParams.get('customization');
if (customization && validateSerializedCustomization(customization)) { if (customization && validateSerializedCustomization(customization)) {
routeType = 'dynamic'; routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Customization, customization); requestHeaders.set(MiddlewareHeaders.Customization, customization);
} }
const theme = url.searchParams.get('theme'); const theme = siteURL.searchParams.get('theme');
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) { if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
routeType = 'dynamic'; routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Theme, theme); requestHeaders.set(MiddlewareHeaders.Theme, theme);
@@ -108,14 +175,16 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
requestHeaders.set('x-forwarded-host', request.nextUrl.host); requestHeaders.set('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin); requestHeaders.set('origin', request.nextUrl.origin);
const siteURL = `${url.host}${data.basePath}`; const siteURLWithoutProtocol = `${siteURL.host}${data.basePath}`;
const { pathname, routeType: routeTypeFromPathname } = encodePathInSiteContent(data.pathname);
routeType = routeTypeFromPathname ?? routeType;
const route = [ const route = [
'sites', 'sites',
routeType, routeType,
mode, mode,
encodeURIComponent(siteURL), encodeURIComponent(siteURLWithoutProtocol),
encodePathInSiteContent(data.pathname), pathname,
].join('/'); ].join('/');
console.log(`rewriting ${request.nextUrl.toString()} to ${route}`); console.log(`rewriting ${request.nextUrl.toString()} to ${route}`);
@@ -135,24 +204,68 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
response.headers.set('x-content-type-options', 'nosniff'); response.headers.set('x-content-type-options', 'nosniff');
// Debug header // Debug header
response.headers.set('x-gitbook-route-type', routeType); response.headers.set('x-gitbook-route-type', routeType);
response.headers.set('x-gitbook-site-url', siteURL); response.headers.set('x-gitbook-route-site', siteURLWithoutProtocol);
if (visitorToken) { return writeResponseCookies(response, cookies);
const cookies = getResponseCookiesForVisitorAuth(data.basePath, visitorToken); }
for (const [key, value] of Object.entries(cookies)) {
response.cookies.set(key, value.value, value.options); /**
} * Serve routes for previewing unpublished content.
* 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) {
const pathnameParts = requestURL.pathname.slice(1).split('/');
if (pathnameParts[0] !== '~space' && pathnameParts[0] !== '~site') {
return null;
} }
return response; // We store the API token in a cookie that is scoped to the specific preview route
// to avoid errors when multiple previews are opened in different tabs.
const cookieName = getPathScopedCookieName(
'gitbook-api-token',
pathnameParts.slice(0, 2).join('/')
);
// 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 = 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,
},
});
} }
/** /**
* Serve an error response. * Serve an error response.
*/ */
function serveErrorResponse(error: Error) { function serveErrorResponse(error: Error) {
if (error instanceof GitBookAPIError) { if (error instanceof DataFetcherError) {
return new Response(error.errorMessage, { return new Response(error.message, {
status: error.code, status: error.code,
headers: { 'content-type': 'text/plain' }, headers: { 'content-type': 'text/plain' },
}); });
@@ -219,22 +332,27 @@ function getSiteURLFromRequest(request: NextRequest): URLWithMode | null {
* Encode path in a site content. * Encode path in a site content.
* Special paths are not encoded and passed to be handled by the route handlers. * Special paths are not encoded and passed to be handled by the route handlers.
*/ */
function encodePathInSiteContent(rawPathname: string) { function encodePathInSiteContent(rawPathname: string): {
pathname: string;
routeType?: 'static' | 'dynamic';
} {
const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname)); const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname));
if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) { if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) {
return pathname; return { pathname };
} }
switch (pathname) { switch (pathname) {
case '~gitbook/icon': case '~gitbook/icon':
case '~gitbook/image':
case 'llms.txt': case 'llms.txt':
case 'sitemap.xml': case 'sitemap.xml':
case 'robots.txt': case 'robots.txt':
return pathname; return { pathname };
case '~gitbook/pdf':
// PDF routes are always dynamic as they depend on the search params.
return { pathname, routeType: 'dynamic' };
default: default:
return encodeURIComponent(pathname || '/'); return { pathname: encodeURIComponent(pathname || '/') };
} }
} }
@@ -248,3 +366,14 @@ function appendQueryParams(url: URL, from: URLSearchParams) {
return url; return url;
} }
/**
* Write the cookies to a response.
*/
function writeResponseCookies<R extends NextResponse>(response: R, cookies: ResponseCookies): R {
Object.entries(cookies).forEach(([key, { value, options }]) => {
response.cookies.set(key, value, options);
});
return response;
}
+11
View File
@@ -1,5 +1,16 @@
# gitbook # gitbook
## 0.7.3
### Patch Changes
- eaf2d68: OpenAPI operation title fallback in sections
- Updated dependencies [844059f]
- Updated dependencies [88f64b0]
- @gitbook/react-openapi@1.1.3
- @gitbook/icons@0.2.0
- @gitbook/react-contentkit@0.6.2
## 0.7.2 ## 0.7.2
### Patch Changes ### Patch Changes
+45 -45
View File
@@ -4,7 +4,7 @@ import { type TestsCase, runTestCases } from './util';
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
{ {
name: 'Snyk', name: 'Snyk',
baseUrl: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [ tests: [
{ name: 'Home', url: '/' }, { name: 'Home', url: '/' },
{ name: 'OpenAPI', url: '/snyk-api/reference/apps' }, { name: 'OpenAPI', url: '/snyk-api/reference/apps' },
@@ -12,222 +12,222 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Nexthink', name: 'Nexthink',
baseUrl: 'https://docs.nexthink.com', contentBaseURL: 'https://docs.nexthink.com',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'asiksupport-stg.dto.kemkes.go.id', name: 'asiksupport-stg.dto.kemkes.go.id',
baseUrl: 'https://asiksupport-stg.dto.kemkes.go.id', contentBaseURL: 'https://asiksupport-stg.dto.kemkes.go.id',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'jasons-tutorials.gitbook.io', name: 'jasons-tutorials.gitbook.io',
baseUrl: 'https://jasons-tutorials.gitbook.io', contentBaseURL: 'https://jasons-tutorials.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'faq.deltaemulator.com', name: 'faq.deltaemulator.com',
baseUrl: 'https://faq.deltaemulator.com', contentBaseURL: 'https://faq.deltaemulator.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.dify.ai', name: 'docs.dify.ai',
baseUrl: 'https://docs.dify.ai', contentBaseURL: 'https://docs.dify.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'seeddao.gitbook.io', name: 'seeddao.gitbook.io',
baseUrl: 'https://seeddao.gitbook.io', contentBaseURL: 'https://seeddao.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'faq.altstore.io', name: 'faq.altstore.io',
baseUrl: 'https://faq.altstore.io', contentBaseURL: 'https://faq.altstore.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'support.audacityteam.org', name: 'support.audacityteam.org',
baseUrl: 'https://support.audacityteam.org', contentBaseURL: 'https://support.audacityteam.org',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.gmgn.ai', name: 'docs.gmgn.ai',
baseUrl: 'https://docs.gmgn.ai', contentBaseURL: 'https://docs.gmgn.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.spicychat.ai', name: 'docs.spicychat.ai',
baseUrl: 'https://docs.spicychat.ai', contentBaseURL: 'https://docs.spicychat.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.portainer.io', name: 'docs.portainer.io',
baseUrl: 'https://docs.portainer.io', contentBaseURL: 'https://docs.portainer.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.chirptoken.io', name: 'docs.chirptoken.io',
baseUrl: 'https://docs.chirptoken.io', contentBaseURL: 'https://docs.chirptoken.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.dexscreener.com', name: 'docs.dexscreener.com',
baseUrl: 'https://docs.dexscreener.com', contentBaseURL: 'https://docs.dexscreener.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.pancakeswap.finance', name: 'docs.pancakeswap.finance',
baseUrl: 'https://docs.pancakeswap.finance', contentBaseURL: 'https://docs.pancakeswap.finance',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'book.character.ai', name: 'book.character.ai',
baseUrl: 'https://book.character.ai', contentBaseURL: 'https://book.character.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.tradeonnova.io', name: 'docs.tradeonnova.io',
baseUrl: 'https://docs.tradeonnova.io', contentBaseURL: 'https://docs.tradeonnova.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'azcoiner.gitbook.io', name: 'azcoiner.gitbook.io',
baseUrl: 'https://azcoiner.gitbook.io', contentBaseURL: 'https://azcoiner.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.midas.app', name: 'docs.midas.app',
baseUrl: 'https://docs.midas.app', contentBaseURL: 'https://docs.midas.app',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.keeper.io', name: 'docs.keeper.io',
baseUrl: 'https://docs.keeper.io', contentBaseURL: 'https://docs.keeper.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'adiblar.gitbook.io', name: 'adiblar.gitbook.io',
baseUrl: 'https://adiblar.gitbook.io', contentBaseURL: 'https://adiblar.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.gradient.network', name: 'docs.gradient.network',
baseUrl: 'https://docs.gradient.network', contentBaseURL: 'https://docs.gradient.network',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'mygate-network.gitbook.io', name: 'mygate-network.gitbook.io',
baseUrl: 'https://mygate-network.gitbook.io', contentBaseURL: 'https://mygate-network.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'treasurenft.gitbook.io', name: 'treasurenft.gitbook.io',
baseUrl: 'https://treasurenft.gitbook.io', contentBaseURL: 'https://treasurenft.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'browndust2.gitbook.io', name: 'browndust2.gitbook.io',
baseUrl: 'https://browndust2.gitbook.io', contentBaseURL: 'https://browndust2.gitbook.io',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'junookyo.gitbook.io', name: 'junookyo.gitbook.io',
baseUrl: 'https://junookyo.gitbook.io', contentBaseURL: 'https://junookyo.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'meshnet.nordvpn.com', name: 'meshnet.nordvpn.com',
baseUrl: 'https://meshnet.nordvpn.com', contentBaseURL: 'https://meshnet.nordvpn.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'manual.bubble.io', name: 'manual.bubble.io',
baseUrl: 'https://manual.bubble.io', contentBaseURL: 'https://manual.bubble.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.tickettool.xyz', name: 'docs.tickettool.xyz',
baseUrl: 'https://docs.tickettool.xyz', contentBaseURL: 'https://docs.tickettool.xyz',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'wiki.redmodding.org', name: 'wiki.redmodding.org',
baseUrl: 'https://wiki.redmodding.org', contentBaseURL: 'https://wiki.redmodding.org',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.cherry-ai.com', name: 'docs.cherry-ai.com',
baseUrl: 'https://docs.cherry-ai.com', contentBaseURL: 'https://docs.cherry-ai.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.snyk.io', name: 'docs.snyk.io',
baseUrl: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.realapp.link', name: 'docs.realapp.link',
baseUrl: 'https://docs.realapp.link', contentBaseURL: 'https://docs.realapp.link',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.plaza.finance', name: 'docs.plaza.finance',
baseUrl: 'https://docs.plaza.finance', contentBaseURL: 'https://docs.plaza.finance',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.publicai.io', name: 'docs.publicai.io',
baseUrl: 'https://docs.publicai.io', contentBaseURL: 'https://docs.publicai.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'hyperliquid.gitbook.io', name: 'hyperliquid.gitbook.io',
baseUrl: 'https://hyperliquid.gitbook.io', contentBaseURL: 'https://hyperliquid.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.umbraco.com', name: 'docs.umbraco.com',
baseUrl: 'https://docs.umbraco.com', contentBaseURL: 'https://docs.umbraco.com',
tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'sosovalue-white-paper.gitbook.io', name: 'sosovalue-white-paper.gitbook.io',
baseUrl: 'https://sosovalue-white-paper.gitbook.io', contentBaseURL: 'https://sosovalue-white-paper.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.revrobotics.com', name: 'docs.revrobotics.com',
baseUrl: 'https://docs.revrobotics.com', contentBaseURL: 'https://docs.revrobotics.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'chartschool.stockcharts.com', name: 'chartschool.stockcharts.com',
baseUrl: 'https://chartschool.stockcharts.com', contentBaseURL: 'https://chartschool.stockcharts.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.soniclabs.com', name: 'docs.soniclabs.com',
baseUrl: 'https://docs.soniclabs.com', contentBaseURL: 'https://docs.soniclabs.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.meshchain.ai', name: 'docs.meshchain.ai',
baseUrl: 'https://docs.meshchain.ai', contentBaseURL: 'https://docs.meshchain.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.thousandeyes.com', name: 'docs.thousandeyes.com',
baseUrl: 'https://docs.thousandeyes.com', contentBaseURL: 'https://docs.thousandeyes.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.raydium.io', name: 'docs.raydium.io',
baseUrl: 'https://docs.raydium.io', contentBaseURL: 'https://docs.raydium.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.fluentbit.io', name: 'docs.fluentbit.io',
baseUrl: 'https://docs.fluentbit.io', contentBaseURL: 'https://docs.fluentbit.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
]; ];
+113 -63
View File
@@ -14,6 +14,7 @@ import {
getVisitorAuthCookieValue, getVisitorAuthCookieValue,
} from '@/lib/visitor-token'; } from '@/lib/visitor-token';
import { getSiteAPIToken } from '../tests/utils';
import { import {
type TestsCase, type TestsCase,
allDeprecatedThemePresets, allDeprecatedThemePresets,
@@ -31,7 +32,7 @@ import {
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
{ {
name: 'GitBook Site (Single Variant)', name: 'GitBook Site (Single Variant)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [ tests: [
{ {
name: 'Home', name: 'Home',
@@ -84,7 +85,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'GitBook Site (Multi Variants)', name: 'GitBook Site (Multi Variants)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/multi-variants/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/multi-variants/',
tests: [ tests: [
{ {
name: 'Variants dropdown', name: 'Variants dropdown',
@@ -135,7 +136,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'GitBook Site (Navigation when switching variant)', name: 'GitBook Site (Navigation when switching variant)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/',
tests: [ tests: [
{ {
name: 'Keep navigation path/route when switching variant (Public)', name: 'Keep navigation path/route when switching variant (Public)',
@@ -155,8 +156,8 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true' url.pathname.includes('api-multi-versions/2.0/reference/api-reference/pets')
); );
}, },
}, },
@@ -178,15 +179,17 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true' url.pathname.includes(
'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets'
)
); );
}, },
}, },
{ {
name: 'Keep navigation path/route when switching variant (VA)', name: 'Keep navigation path/route when switching variant (VA)',
screenshot: false, screenshot: false,
url: (() => { url: () => {
const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953'; const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -198,7 +201,7 @@ const testCases: TestsCase[] = [
} }
); );
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`; return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const spaceDrowpdown = await page const spaceDrowpdown = await page
.locator('[data-testid="space-dropdown-button"]') .locator('[data-testid="space-dropdown-button"]')
@@ -213,8 +216,10 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true' url.pathname.includes(
'api-multi-versions-va/2.0/reference/api-reference/pets'
)
); );
}, },
}, },
@@ -222,7 +227,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'GitBook Site (Sections and Section Groups)', name: 'GitBook Site (Sections and Section Groups)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/sections/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
tests: [ tests: [
{ {
name: 'Site with sections and section groups', name: 'Site with sections and section groups',
@@ -244,16 +249,14 @@ const testCases: TestsCase[] = [
const sectionGroupDropdown = await page.getByText('Test Section Group 1'); const sectionGroupDropdown = await page.getByText('Test Section Group 1');
await sectionGroupDropdown.hover(); await sectionGroupDropdown.hover();
await page.getByText('Section B').click(); await page.getByText('Section B').click();
await page.waitForURL( await page.waitForURL((url) => url.pathname.includes('/sections/sections-4'));
'https://gitbook-open-e2e-sites.gitbook.io/sections/sections-4'
);
}, },
}, },
], ],
}, },
{ {
name: 'GitBook', name: 'GitBook',
baseUrl: 'https://docs.gitbook.com', contentBaseURL: 'https://docs.gitbook.com',
tests: [ tests: [
{ {
name: 'Home', name: 'Home',
@@ -297,7 +300,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Versioning', name: 'Versioning',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Revision', name: 'Revision',
@@ -308,7 +311,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'PDF', name: 'PDF',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'PDF', name: 'PDF',
@@ -316,12 +319,56 @@ const testCases: TestsCase[] = [
screenshot: { screenshot: {
waitForTOCScrolling: false, waitForTOCScrolling: false,
}, },
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
},
],
},
{
name: 'Space PDF',
tests: [
{
name: 'Main content',
url: async () => {
const data = await getSiteAPIToken(
'https://gitbook.gitbook.io/test-gitbook-open/'
);
const searchParams = new URLSearchParams();
searchParams.set('limit', '10');
searchParams.set('token', data.apiToken);
return `~space/${data.space}/~gitbook/pdf?${searchParams.toString()}`;
},
screenshot: false,
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
},
{
name: 'Change request',
url: async () => {
const data = await getSiteAPIToken(
'https://gitbook.gitbook.io/test-gitbook-open/'
);
const searchParams = new URLSearchParams();
searchParams.set('limit', '10');
searchParams.set('token', data.apiToken);
return `~space/${data.space}/~/changes/HrtgUd5MlFusCMv1elA7/~gitbook/pdf?${searchParams.toString()}`;
},
screenshot: false,
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
}, },
], ],
}, },
{ {
name: 'Content tests', name: 'Content tests',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Text', name: 'Text',
@@ -484,7 +531,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Page options', name: 'Page options',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Hidden', name: 'Hidden',
@@ -518,7 +565,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Customization', name: 'Customization',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allThemeModes.flatMap((themeMode) => [ tests: allThemeModes.flatMap((themeMode) => [
{ {
name: `Without header - Theme mode ${themeMode}`, name: `Without header - Theme mode ${themeMode}`,
@@ -652,7 +699,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Ads', name: 'Ads',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Without previewed ads', name: 'Without previewed ads',
@@ -663,7 +710,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Shared space navigation (first site)', name: 'Shared space navigation (first site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
tests: [ tests: [
{ {
name: 'Navigation to shared space', name: 'Navigation to shared space',
@@ -684,7 +731,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Shared space navigation (second site)', name: 'Shared space navigation (second site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
tests: [ tests: [
{ {
name: 'Navigation to shared space', name: 'Navigation to shared space',
@@ -704,7 +751,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Site Redirects', name: 'Site Redirects',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [ tests: [
{ {
name: 'Redirect to SSO page', name: 'Redirect to SSO page',
@@ -718,7 +765,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Share links', name: 'Share links',
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
tests: [ tests: [
{ {
name: 'Valid link', name: 'Valid link',
@@ -738,11 +785,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Space', name: 'Visitor Auth - Space',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-space/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-space/',
tests: [ tests: [
{ {
name: 'First', name: 'First',
url: (() => { url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537'; const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -754,7 +801,7 @@ const testCases: TestsCase[] = [
} }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }) page.getByRole('heading', { level: 1, name: 'first' })
@@ -764,7 +811,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Second', name: 'Second',
url: (() => { url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537'; const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -776,7 +823,7 @@ const testCases: TestsCase[] = [
} }
); );
return `second?jwt_token=${token}`; return `second?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'second' }) page.getByRole('heading', { level: 1, name: 'second' })
@@ -788,11 +835,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Collection', name: 'Visitor Auth - Collection',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-collection/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-collection/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -804,12 +851,12 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Primary (Space A)', name: 'Primary (Space A)',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -820,13 +867,16 @@ const testCases: TestsCase[] = [
expiresIn: '24h', expiresIn: '24h',
} }
); );
// Test that when accessing the non-canonical URL, we are redirected to the canonical URL
// with the jwt token in the query string
return `spacea?jwt_token=${token}`; return `spacea?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Space B', name: 'Space B',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -838,12 +888,12 @@ const testCases: TestsCase[] = [
} }
); );
return `spaceb?jwt_token=${token}`; return `spaceb?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Space C', name: 'Space C',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -855,18 +905,18 @@ const testCases: TestsCase[] = [
} }
); );
return `spacec?jwt_token=${token}`; return `spacec?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
], ],
}, },
{ {
name: 'Visitor Auth - Space (custom domain)', name: 'Visitor Auth - Space (custom domain)',
baseUrl: 'https://test.gitbook.community/', contentBaseURL: 'https://test.gitbook.community/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -878,12 +928,12 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'First', name: 'First',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -895,7 +945,7 @@ const testCases: TestsCase[] = [
} }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }) page.getByRole('heading', { level: 1, name: 'first' })
@@ -905,7 +955,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Custom page', name: 'Custom page',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -917,12 +967,12 @@ const testCases: TestsCase[] = [
} }
); );
return `custom-page?jwt_token=${token}`; return `custom-page?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Inner page', name: 'Inner page',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -934,14 +984,14 @@ const testCases: TestsCase[] = [
} }
); );
return `custom-page/inner-page?jwt_token=${token}`; return `custom-page/inner-page?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
], ],
}, },
{ {
name: 'Visitor Auth - Site (redirects to fallback/auth URL)', name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/',
tests: [ tests: [
{ {
name: 'Redirect to fallback on invalid token pulled from cookie', name: 'Redirect to fallback on invalid token pulled from cookie',
@@ -973,7 +1023,7 @@ const testCases: TestsCase[] = [
{ {
name: 'Show error message when invalid token is passed to url', name: 'Show error message when invalid token is passed to url',
screenshot: false, screenshot: false,
url: (() => { url: () => {
const token = jwt.sign( const token = jwt.sign(
{ {
name: 'gitbook-open-tests', name: 'gitbook-open-tests',
@@ -984,7 +1034,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect(page.locator('pre')).toContainText( await expect(page.locator('pre')).toContainText(
'Error while validating the JWT token. Reason: The token signature is invalid.' 'Error while validating the JWT token. Reason: The token signature is invalid.'
@@ -995,7 +1045,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Languages', name: 'Languages',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allLocales.map((locale) => ({ tests: allLocales.map((locale) => ({
name: locale, name: locale,
url: getCustomizationURL({ url: getCustomizationURL({
@@ -1011,7 +1061,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'SEO', name: 'SEO',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Index by default', name: 'Index by default',
@@ -1062,11 +1112,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - VA', name: 'Adaptive Content - VA',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/',
tests: [ tests: [
{ {
name: 'isAlphaUser', name: 'isAlphaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1079,7 +1129,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1093,7 +1143,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'isBetaUser', name: 'isBetaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1106,7 +1156,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1120,7 +1170,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'isAlphaUser & isBetaUser', name: 'isAlphaUser & isBetaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1134,7 +1184,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1150,7 +1200,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - Public', name: 'Adaptive Content - Public',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/',
tests: [ tests: [
{ {
name: 'No custom cookie', name: 'No custom cookie',
@@ -1293,7 +1343,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Tables', name: 'Tables',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Default table', name: 'Default table',
+13 -8
View File
@@ -20,14 +20,14 @@ import deepMerge from 'deepmerge';
import rison from 'rison'; import rison from 'rison';
import type { DeepPartial } from 'ts-essentials'; import type { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils'; import { getContentTestURL, getTestURL } from '../tests/utils';
export interface Test { export interface Test {
name: string; name: string;
/** /**
* URL to visit for testing. * URL to visit for testing.
*/ */
url: string; url: string | (() => string | Promise<string>);
cookies?: Parameters<BrowserContext['addCookies']>[0]; cookies?: Parameters<BrowserContext['addCookies']>[0];
/** /**
* Test to run * Test to run
@@ -60,11 +60,11 @@ export interface Test {
only?: boolean; only?: boolean;
} }
export interface TestsCase { export type TestsCase = {
name: string; name: string;
baseUrl: string;
tests: Array<Test>; tests: Array<Test>;
} contentBaseURL?: string;
};
export const allLocales: CustomizationLocale[] = [ export const allLocales: CustomizationLocale[] = [
CustomizationLocale.Fr, CustomizationLocale.Fr,
@@ -142,9 +142,14 @@ export function runTestCases(testCases: TestsCase[]) {
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;
testFn(testEntry.name, async ({ page, baseURL, context }) => { testFn(testEntry.name, async ({ page, context }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl); const testEntryPathname =
const url = getContentTestURL(contentUrl.toString(), baseURL); typeof testEntry.url === 'function' ? await testEntry.url() : testEntry.url;
const url = testCase.contentBaseURL
? getContentTestURL(
new URL(testEntryPathname, testCase.contentBaseURL).toString()
)
: getTestURL(testEntryPathname);
if (testEntry.cookies) { if (testEntry.cookies) {
await context.addCookies( await context.addCookies(
testEntry.cookies.map((cookie) => ({ testEntry.cookies.map((cookie) => ({
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.7.2", "version": "0.7.3",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev", "dev": "env-cmd --silent -f ../../.env.local next dev",
-1
View File
@@ -16,7 +16,6 @@ export default defineConfig({
}, },
], ],
use: { use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry', trace: 'on-first-retry',
screenshot: 'only-on-failure', screenshot: 'only-on-failure',
}, },
@@ -38,10 +38,9 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
} }
async function getSitePageProps(props: PageProps) { async function getSitePageProps(props: PageProps) {
const { params: rawParams, searchParams: rawSearchParams } = props; const { params: rawParams } = props;
const params = await rawParams; const params = await rawParams;
const searchParams = await rawSearchParams;
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer); const context = await fetchV1ContextForSitePointer(pointer);
@@ -49,7 +48,5 @@ async function getSitePageProps(props: PageProps) {
return { return {
context, context,
pageParams: params, pageParams: params,
redirectOnFallback: true,
fallback: !!searchParams.fallback,
}; };
} }
@@ -1,24 +1,9 @@
import { CustomizationRootLayout } from '@/components/RootLayout'; import { PDFRootLayout } from '@/components/PDF';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { getV1ContextForPDF } from './pointer'; import { getV1ContextForPDF } from './pointer';
/** export default async function RootLayout(props: { children: React.ReactNode }) {
* Layout to be used for the site root. It fetches the customization data for the
* site or space and initializes the CustomizationRootLayout with it.
*/
export default async function PDFRootLayout(props: { children: React.ReactNode }) {
const { children } = props; const { children } = props;
const context = await getV1ContextForPDF(); const context = await getV1ContextForPDF();
return ( return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
<CustomizationRootLayout
customization={
'customization' in context ? context.customization : defaultCustomizationForSpace()
}
>
{children}
</CustomizationRootLayout>
);
} }
@@ -1,361 +1,17 @@
import { import { PDFPage, generatePDFMetadata } from '@/components/PDF';
type CustomizationSettings,
type Revision,
type RevisionPageDocument,
type RevisionPageGroup,
RevisionPageType,
type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data';
import type { GitBookSpaceLinker } from '@v2/lib/links';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate';
import { getAbsoluteHref, getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { type PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { PageControlButtons } from './PageControlButtons';
import { PrintButton } from './PrintButton';
import './pdf.css';
import { getV1ContextForPDF } from './pointer'; import { getV1ContextForPDF } from './pointer';
const DEFAULT_LIMIT = 100;
export const runtime = 'edge'; export const runtime = 'edge';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata() {
const context = await getV1ContextForPDF(); const context = await getV1ContextForPDF();
return generatePDFMetadata(context);
return {
title: 'site' in context ? context.site.title : context.space.title,
robots: 'noindex, nofollow',
};
} }
/** export default async function Page(props: {
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export default async function PDFHTMLOutput(props: {
searchParams: Promise<{ [key: string]: string }>; searchParams: Promise<{ [key: string]: string }>;
}) { }) {
const searchParams = new URLSearchParams(await props.searchParams); const context = await getV1ContextForPDF();
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams)); return <PDFPage context={context} searchParams={await props.searchParams} />;
// Build current PDF URL and preserve all search params
let currentPDFUrl = await getAbsoluteHref('~gitbook/pdf', true);
currentPDFUrl += `?${searchParams.toString()}`;
// Fetch the context
const baseContext = await getV1ContextForPDF();
const customization =
'customization' in baseContext ? baseContext.customization : defaultCustomizationForSpace();
const language = getSpaceLanguage(customization);
// Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
);
// Build a linker that create anchor links for the pages rendered in the PDF page.
const linker: GitBookSpaceLinker = {
...baseContext.linker,
toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) {
return `#${getPagePDFContainerId(input.page, input.anchor)}`;
}
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
},
};
const context: GitBookSpaceContext = {
...baseContext,
linker,
};
return (
<div className="print-mode">
{pdfParams.back !== 'false' ? (
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a
title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="arrow-left" className={tcls('size-6')} />
</a>
</div>
) : null}
<div className={tcls('fixed', 'right-12', 'top-12', 'print:hidden', 'z-50')}>
<PrintButton
title={tString(language, 'pdf_print')}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="print" className={tcls('size-6')} />
</PrintButton>
</div>
<PageControlButtons
pageIds={pageIds}
pdfHref={currentPDFUrl}
singlePageMode={!!pdfParams.only}
total={total}
limit={pdfParams.limit ?? DEFAULT_LIMIT}
trademark={
customization.trademark.enabled ? (
<TrademarkLink
space={context.space}
customization={customization}
placement={SiteInsightsTrademarkPlacement.Pdf}
/>
) : null
}
/>
{pdfParams.only ? null : (
<PDFSpaceIntro space={context.space} customization={customization} />
)}
{pages.map(({ page }) =>
page.type === 'group' ? (
<PDFPageGroup key={page.id} space={context.space} page={page} />
) : (
<React.Suspense
key={page.id}
fallback={
<PrintPage id={getPagePDFContainerId(page)}>
<p>Loading...</p>
</PrintPage>
}
>
<PDFPageDocument page={page} context={context} />
</React.Suspense>
)
)}
</div>
);
}
async function PDFSpaceIntro(props: {
space: Space;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { space, customization } = props;
return (
<PrintPage isFirst>
<div className={tcls('flex', 'items-center', 'justify-center', 'py-12')}>
<h1 className={tcls('text-6xl', 'font-bold')}>
{customization.title ?? space.title}
</h1>
</div>
</PrintPage>
);
}
async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
const { page } = props;
return (
<PrintPage id={getPagePDFContainerId(page)}>
<div
className={tcls(
'break-before-page',
'mt-10',
'print:mt-0',
'flex',
'items-center',
'justify-center',
'py-12'
)}
>
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
</div>
</PrintPage>
);
}
async function PDFPageDocument(props: {
page: RevisionPageDocument;
context: GitBookSpaceContext;
}) {
const { page, context } = props;
const { space } = context;
const document = await getPageDocument(context.dataFetcher, space, page);
return (
<PrintPage id={getPagePDFContainerId(page)}>
<h1 className={tcls('text-4xl', 'font-bold')}>{page.title}</h1>
{page.description ? (
<p className={tcls('decoration-primary/6', 'mt-2', 'mb-3')}>{page.description}</p>
) : null}
{document ? (
<DocumentView
document={document}
style="mt-6 space-y-6"
blockStyle="max-w-full"
context={{
mode: 'print',
contentContext: {
...context,
page,
},
getId: (id) => getPagePDFContainerId(page, id),
}}
/>
) : null}
</PrintPage>
);
}
function PrintPage(
props: PolymorphicComponentProp<
'div',
{
isFirst?: boolean;
}
>
) {
const { children, isFirst, className, ...rest } = props;
return (
<div
{...rest}
className={tcls(
className,
'my-11',
'print:my-0',
'mx-auto',
'max-w-4xl',
'w-full',
'p-12',
'print:p-0',
'shadow-xl',
'print:shadow-none',
'rounded-sm',
'bg-white',
'min-h-[29.7cm]',
'print:min-h-0',
isFirst ? null : 'break-before-page',
'break-anywhere'
)}
>
{children}
</div>
);
}
type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: number };
/**
* Compute the ordered flat set of pages to render.
*/
function selectPages(
rootPages: Revision['pages'],
params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number
): FlatPageEntry[] => {
return [
{ page, depth },
...page.pages.flatMap((child) => {
if (child.type !== 'document') {
return [];
}
if (child.hidden) {
return [];
}
return flattenPage(child, depth + 1);
}),
];
};
const limitTo = (entries: FlatPageEntry[]) => {
return {
// Apply a soft-limit, the limit can be controlled by the URL to allow testing
pages: entries.slice(0, params.limit ?? DEFAULT_LIMIT),
total: entries.length,
};
};
if (params.page) {
const found = resolvePageId(rootPages, params.page);
if (!found) {
notFound();
}
if (!params.only) {
return limitTo([{ page: found.page, depth: 0 }]);
}
return limitTo(flattenPage(found.page, 0));
}
const allPages = rootPages.flatMap((page) => {
if (page.type !== 'document' && page.type !== 'group') {
return [];
}
if (page.hidden) {
return [];
}
return flattenPage(page, 0);
});
return limitTo(allPages);
} }
@@ -4,23 +4,6 @@ import type { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer'; import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1'; import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1';
/**
* PDF generation can be done at the site level (e.g. docs.foo.com/~gitbook/pdf) or
* at the space level (e.g. open.gitbook.com/~space/:spaceId/~gitbook/pdf) which is
* for PDF export of in-app private spaces.
*
* This function returns the pointer depending on the context.
*/
export async function getSiteOrSpacePointerForPDF(): Promise<
SiteContentPointer | SpaceContentPointer
> {
try {
return await getSiteContentPointer();
} catch (_error) {
return getSpacePointer();
}
}
/** /**
* Get the context for the PDF pointer. * Get the context for the PDF pointer.
*/ */
@@ -31,3 +14,18 @@ export async function getV1ContextForPDF(): Promise<GitBookSiteContext | GitBook
? await fetchV1ContextForSitePointer(pointer) ? await fetchV1ContextForSitePointer(pointer)
: await fetchV1ContextForSpacePointer(pointer); : await fetchV1ContextForSpacePointer(pointer);
} }
/**
* PDF generation can be done at the site level (e.g. docs.foo.com/~gitbook/pdf) or
* at the space level (e.g. open.gitbook.com/~space/:spaceId/~gitbook/pdf) which is
* for PDF export of in-app private spaces.
*
* This function returns the pointer depending on the context.
*/
async function getSiteOrSpacePointerForPDF(): Promise<SiteContentPointer | SpaceContentPointer> {
try {
return await getSiteContentPointer();
} catch (_error) {
return getSpacePointer();
}
}
@@ -48,7 +48,7 @@ function ToolbarLayout(props: { children: React.ReactNode }) {
*/ */
export async function AdminToolbar(props: AdminToolbarProps) { export async function AdminToolbar(props: AdminToolbarProps) {
const { context } = props; const { context } = props;
const mode = await headers().get('x-gitbook-mode'); const mode = (await headers()).get('x-gitbook-mode');
if (mode === 'multi-id') { if (mode === 'multi-id') {
// We don't show the admin toolbar in multi-id mode, as it's used for previewing in the dashboard. // We don't show the admin toolbar in multi-id mode, as it's used for previewing in the dashboard.
@@ -42,16 +42,18 @@ type UnwrappedBlocksProps<TBlock extends DocumentBlock> = DocumentContextProps &
/** Style passed to all blocks */ /** Style passed to all blocks */
blockStyle?: ClassValue; blockStyle?: ClassValue;
/** True if all blocks should be considered offscreen */
isOffscreen?: boolean;
}; };
/** /**
* Renders a list of blocks without a wrapper element. * Renders a list of blocks without a wrapper element.
*/ */
export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) { export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) {
const { nodes, blockStyle, ...contextProps } = props; const { nodes, blockStyle, isOffscreen: defaultIsOffscreen = false, ...contextProps } = props;
let isOffscreen = false;
let isOffscreen = defaultIsOffscreen;
return nodes.map((node) => { return nodes.map((node) => {
isOffscreen = isOffscreen =
isOffscreen || isOffscreen ||
@@ -46,9 +46,12 @@ export function DocumentView(
/** Style passed to all blocks */ /** Style passed to all blocks */
blockStyle?: ClassValue; blockStyle?: ClassValue;
/** True if the document should be considered offscreen */
isOffscreen?: boolean;
} }
) { ) {
const { document, style, blockStyle = [], context } = props; const { document, style, blockStyle = [], context, isOffscreen = false } = props;
return ( return (
<Blocks <Blocks
@@ -62,6 +65,7 @@ export function DocumentView(
'whitespace-pre-wrap', 'whitespace-pre-wrap',
]} ]}
context={context} context={context}
isOffscreen={isOffscreen}
/> />
); );
} }
@@ -0,0 +1,356 @@
import {
type CustomizationSettings,
type Revision,
type RevisionPageDocument,
type RevisionPageGroup,
RevisionPageType,
type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data';
import type { GitBookSpaceLinker } from '@v2/lib/links';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate';
import { getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { type PDFSearchParams, getPDFSearchParams } from './urls';
import { PageControlButtons } from './PageControlButtons';
import { PrintButton } from './PrintButton';
import './pdf.css';
const DEFAULT_LIMIT = 100;
/**
* Generate the metadata for the PDF page.
*/
export async function generatePDFMetadata(
context: GitBookSpaceContext | GitBookSiteContext
): Promise<Metadata> {
return {
title: 'site' in context ? context.site.title : context.space.title,
robots: 'noindex, nofollow',
};
}
/**
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export async function PDFPage(props: {
context: GitBookSpaceContext | GitBookSiteContext;
searchParams: { [key: string]: string };
}) {
const baseContext = props.context;
const searchParams = new URLSearchParams(props.searchParams);
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
const customization =
'customization' in baseContext ? baseContext.customization : defaultCustomizationForSpace();
const language = getSpaceLanguage(customization);
// Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
);
// Build a linker that create anchor links for the pages rendered in the PDF page.
const linker: GitBookSpaceLinker = {
...baseContext.linker,
toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) {
return `#${getPagePDFContainerId(input.page, input.anchor)}`;
}
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
},
};
const context: GitBookSpaceContext = {
...baseContext,
linker,
};
return (
<div className="print-mode">
{pdfParams.back !== 'false' ? (
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a
title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="arrow-left" className={tcls('size-6')} />
</a>
</div>
) : null}
<div className={tcls('fixed', 'right-12', 'top-12', 'print:hidden', 'z-50')}>
<PrintButton
title={tString(language, 'pdf_print')}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="print" className={tcls('size-6')} />
</PrintButton>
</div>
<PageControlButtons
params={pdfParams}
pageIds={pageIds}
total={total}
trademark={
customization.trademark.enabled ? (
<TrademarkLink
space={context.space}
customization={customization}
placement={SiteInsightsTrademarkPlacement.Pdf}
/>
) : null
}
/>
{pdfParams.only ? null : (
<PDFSpaceIntro space={context.space} customization={customization} />
)}
{pages.map(({ page }) =>
page.type === 'group' ? (
<PDFPageGroup key={page.id} space={context.space} page={page} />
) : (
<React.Suspense
key={page.id}
fallback={
<PrintPage id={getPagePDFContainerId(page)}>
<p>Loading...</p>
</PrintPage>
}
>
<PDFPageDocument page={page} context={context} />
</React.Suspense>
)
)}
</div>
);
}
async function PDFSpaceIntro(props: {
space: Space;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { space, customization } = props;
return (
<PrintPage isFirst>
<div className={tcls('flex', 'items-center', 'justify-center', 'py-12')}>
<h1 className={tcls('text-6xl', 'font-bold')}>
{customization.title ?? space.title}
</h1>
</div>
</PrintPage>
);
}
async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
const { page } = props;
return (
<PrintPage id={getPagePDFContainerId(page)}>
<div
className={tcls(
'break-before-page',
'mt-10',
'print:mt-0',
'flex',
'items-center',
'justify-center',
'py-12'
)}
>
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
</div>
</PrintPage>
);
}
async function PDFPageDocument(props: {
page: RevisionPageDocument;
context: GitBookSpaceContext;
}) {
const { page, context } = props;
const { space } = context;
const document = await getPageDocument(context.dataFetcher, space, page);
return (
<PrintPage id={getPagePDFContainerId(page)}>
<h1 className={tcls('text-4xl', 'font-bold')}>{page.title}</h1>
{page.description ? (
<p className={tcls('decoration-primary/6', 'mt-2', 'mb-3')}>{page.description}</p>
) : null}
{document ? (
<DocumentView
document={document}
style="mt-6 space-y-6"
blockStyle="max-w-full"
context={{
mode: 'print',
contentContext: {
...context,
page,
},
getId: (id) => getPagePDFContainerId(page, id),
}}
// We consider all pages as offscreen in PDF mode
// to ensure we can efficiently render as many pages as possible
isOffscreen={true}
/>
) : null}
</PrintPage>
);
}
function PrintPage(
props: PolymorphicComponentProp<
'div',
{
isFirst?: boolean;
}
>
) {
const { children, isFirst, className, ...rest } = props;
return (
<div
{...rest}
className={tcls(
className,
'my-11',
'print:my-0',
'mx-auto',
'max-w-4xl',
'w-full',
'p-12',
'print:p-0',
'shadow-xl',
'print:shadow-none',
'rounded-sm',
'bg-white',
'min-h-[29.7cm]',
'print:min-h-0',
isFirst ? null : 'break-before-page',
'break-anywhere'
)}
>
{children}
</div>
);
}
type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: number };
/**
* Compute the ordered flat set of pages to render.
*/
function selectPages(
rootPages: Revision['pages'],
params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number
): FlatPageEntry[] => {
return [
{ page, depth },
...page.pages.flatMap((child) => {
if (child.type !== 'document') {
return [];
}
if (child.hidden) {
return [];
}
return flattenPage(child, depth + 1);
}),
];
};
const limitTo = (entries: FlatPageEntry[]) => {
return {
// Apply a soft-limit, the limit can be controlled by the URL to allow testing
pages: entries.slice(0, params.limit ?? DEFAULT_LIMIT),
total: entries.length,
};
};
if (params.page) {
const found = resolvePageId(rootPages, params.page);
if (!found) {
notFound();
}
if (!params.only) {
return limitTo([{ page: found.page, depth: 0 }]);
}
return limitTo(flattenPage(found.page, 0));
}
const allPages = rootPages.flatMap((page) => {
if (page.type !== 'document' && page.type !== 'group') {
return [];
}
if (page.hidden) {
return [];
}
return flattenPage(page, 0);
});
return limitTo(allPages);
}
@@ -0,0 +1,23 @@
import { CustomizationRootLayout } from '@/components/RootLayout';
import { defaultCustomizationForSpace } from '@/lib/utils';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
/**
* Layout to be used for rendering the PDF.
*/
export async function PDFRootLayout(props: {
context: GitBookSpaceContext | GitBookSiteContext;
children: React.ReactNode;
}) {
const { context, children } = props;
return (
<CustomizationRootLayout
customization={
'customization' in context ? context.customization : defaultCustomizationForSpace()
}
>
{children}
</CustomizationRootLayout>
);
}
@@ -7,7 +7,7 @@ import { useScrollActiveId } from '@/components/hooks';
import { Button } from '@/components/primitives'; import { Button } from '@/components/primitives';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { getPDFUrl } from '@/lib/urls'; import { type PDFSearchParams, getPDFURLSearchParams } from './urls';
const limitExtend = 50; const limitExtend = 50;
@@ -15,18 +15,15 @@ const limitExtend = 50;
* Dynamic controls to show active page and to let the user select between modes. * Dynamic controls to show active page and to let the user select between modes.
*/ */
export function PageControlButtons(props: { export function PageControlButtons(props: {
pdfHref: string; params: PDFSearchParams;
singlePageMode: boolean;
/** Array of the [pageId, divId] */ /** Array of the [pageId, divId] */
pageIds: Array<[string, string]>; pageIds: Array<[string, string]>;
/** Current limit */
limit: number;
/** Total number of pages targetted by the generation */ /** Total number of pages targetted by the generation */
total: number; total: number;
/** Trademark to display */ /** Trademark to display */
trademark?: React.ReactNode; trademark?: React.ReactNode;
}) { }) {
const { pdfHref, singlePageMode, pageIds, limit, total, trademark } = props; const { params, pageIds, total, trademark } = props;
const language = useLanguage(); const language = useLanguage();
@@ -53,19 +50,24 @@ export function PageControlButtons(props: {
'z-50' 'z-50'
)} )}
> >
{singlePageMode ? null : ( {params.only ? null : (
<Button <Button
href={getPDFUrl(new URL(pdfHref), { href={`?${getPDFURLSearchParams({
...params,
page: activePageId, page: activePageId,
only: true, only: true,
}).toString()} }).toString()}`}
variant="secondary" variant="secondary"
> >
{t(language, 'pdf_mode_only_page')} {t(language, 'pdf_mode_only_page')}
</Button> </Button>
)} )}
<Button <Button
href={getPDFUrl(new URL(pdfHref), { page: undefined, only: false }).toString()} href={`?${getPDFURLSearchParams({
...params,
page: undefined,
only: false,
}).toString()}`}
variant="secondary" variant="secondary"
> >
{t(language, 'pdf_mode_all')} {t(language, 'pdf_mode_all')}
@@ -113,11 +115,12 @@ export function PageControlButtons(props: {
<div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div> <div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div>
<div> <div>
<a <a
href={getPDFUrl(new URL(pdfHref), { href={`?${getPDFURLSearchParams({
...params,
page: undefined, page: undefined,
only: false, only: false,
limit: limit + limitExtend, limit: params.limit + limitExtend,
}).toString()} }).toString()}`}
className={tcls('underline')} className={tcls('underline')}
> >
{t(language, 'pdf_limit_reached_continue', limitExtend)} {t(language, 'pdf_limit_reached_continue', limitExtend)}
@@ -12,7 +12,7 @@ export function PrintButton(props: PolymorphicComponentProp<'button'>) {
}, []); }, []);
return ( return (
<button {...rest} onClick={onClick} className={className}> <button {...rest} data-testid="print-button" onClick={onClick} className={className}>
{children} {children}
</button> </button>
); );
@@ -0,0 +1,3 @@
export * from './PDFRootLayout';
export * from './PDFPage';
export * from './urls';
@@ -1,10 +1,12 @@
const DEFAULT_LIMIT = 100;
export interface PDFSearchParams { export interface PDFSearchParams {
/** Page to export. If none is passed, all pages are exported. */ /** Page to export. If none is passed, all pages are exported. */
page?: string; page?: string;
/** If true, only the `page` is exported, and not its descendant */ /** If true, only the `page` is exported, and not its descendant */
only?: boolean; only?: boolean;
/** Limit the number of pages */ /** Limit the number of pages */
limit?: number; limit: number;
/** URL to redirect back to */ /** URL to redirect back to */
back?: string; back?: string;
} }
@@ -13,7 +15,9 @@ export interface PDFSearchParams {
* Get the PDF export params from the URL serch params. * Get the PDF export params from the URL serch params.
*/ */
export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchParams { export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchParams {
const params: PDFSearchParams = {}; const params: PDFSearchParams = {
limit: DEFAULT_LIMIT,
};
if (searchParams.has('page')) { if (searchParams.has('page')) {
params.page = searchParams.get('page') ?? ''; params.page = searchParams.get('page') ?? '';
@@ -32,15 +36,9 @@ export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchPara
} }
/** /**
* Update the URL with the PDF export params. * Get the URL search params to use for a PDF export.
*/ */
export function getPDFUrl(url: URL, params: PDFSearchParams): URL { export function getPDFURLSearchParams(
const copy = new URL(url);
getPDFUrlSearchParams(params, copy.searchParams);
return copy;
}
export function getPDFUrlSearchParams(
params: PDFSearchParams, params: PDFSearchParams,
searchParams = new URLSearchParams({}) searchParams = new URLSearchParams({})
): URLSearchParams { ): URLSearchParams {
@@ -13,9 +13,9 @@ import urlJoin from 'url-join';
import { getSpaceLanguage, t } from '@/intl/server'; import { getSpaceLanguage, t } from '@/intl/server';
import { getDocumentSections } from '@/lib/document-sections'; import { getDocumentSections } from '@/lib/document-sections';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { getPDFUrlSearchParams } from '@/lib/urls';
import { Ad } from '../Ads'; import { Ad } from '../Ads';
import { getPDFURLSearchParams } from '../PDF';
import { PageFeedbackForm } from '../PageFeedback'; import { PageFeedbackForm } from '../PageFeedback';
import { ThemeToggler } from '../ThemeToggler'; import { ThemeToggler } from '../ThemeToggler';
import { ScrollSectionsList } from './ScrollSectionsList'; import { ScrollSectionsList } from './ScrollSectionsList';
@@ -36,9 +36,10 @@ export function PageAside(props: {
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInContent( const pdfHref = context.linker.toPathInContent(
`~gitbook/pdf?${getPDFUrlSearchParams({ `~gitbook/pdf?${getPDFURLSearchParams({
page: page.id, page: page.id,
only: true, only: true,
limit: 100,
}).toString()}` }).toString()}`
); );
return ( return (
@@ -101,7 +101,6 @@ export async function generateSiteLayoutMetadata(context: GitBookSiteContext): P
return { return {
title: site.title, title: site.title,
generator: `GitBook (${buildVersion()})`, generator: `GitBook (${buildVersion()})`,
// metadataBase: new URL(await getBaseUrl()),
icons: { icons: {
icon: [ icon: [
{ {
@@ -7,7 +7,7 @@ import React from 'react';
import { PageAside } from '@/components/PageAside'; import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody'; import { PageBody, PageCover } from '@/components/PageBody';
import { getPagePath, resolveFirstDocument } from '@/lib/pages'; import { getPagePath } from '@/lib/pages';
import { isPageIndexable, isSiteIndexable } from '@/lib/seo'; import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { PageClientLayout } from './PageClientLayout'; import { PageClientLayout } from './PageClientLayout';
@@ -19,8 +19,6 @@ export const dynamic = 'force-dynamic';
export type SitePageProps = { export type SitePageProps = {
context: GitBookSiteContext; context: GitBookSiteContext;
pageParams: PagePathParams; pageParams: PagePathParams;
redirectOnFallback: boolean;
fallback?: boolean;
}; };
/** /**
@@ -30,8 +28,6 @@ export async function SitePage(props: SitePageProps) {
const { context, pageTarget } = await getPageDataWithFallback({ const { context, pageTarget } = await getPageDataWithFallback({
context: props.context, context: props.context,
pagePathParams: props.pageParams, pagePathParams: props.pageParams,
fallback: props.fallback,
redirectOnFallback: props.redirectOnFallback,
}); });
const rawPathname = getPathnameParam(props.pageParams); const rawPathname = getPathnameParam(props.pageParams);
@@ -115,7 +111,6 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
const { context, pageTarget } = await getPageDataWithFallback({ const { context, pageTarget } = await getPageDataWithFallback({
context: props.context, context: props.context,
pagePathParams: props.pageParams, pagePathParams: props.pageParams,
fallback: props.fallback,
}); });
if (!pageTarget) { if (!pageTarget) {
@@ -153,28 +148,9 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
async function getPageDataWithFallback(args: { async function getPageDataWithFallback(args: {
context: GitBookSiteContext; context: GitBookSiteContext;
pagePathParams: PagePathParams; pagePathParams: PagePathParams;
fallback?: boolean;
redirectOnFallback?: boolean;
}) { }) {
const { context: baseContext, pagePathParams, fallback, redirectOnFallback = false } = args; const { context: baseContext, pagePathParams } = args;
const { context, pageTarget } = await fetchPageData(baseContext, pagePathParams);
let { context, pageTarget } = await fetchPageData(baseContext, pagePathParams);
const canFallback = !!fallback;
if (!pageTarget && canFallback) {
const rootPage = resolveFirstDocument(context.pages, []);
if (redirectOnFallback && rootPage?.page) {
redirect(
context.linker.toPathForPage({
pages: context.pages,
page: rootPage?.page,
})
);
}
pageTarget = rootPage;
}
return { return {
context: { context: {
@@ -3,12 +3,26 @@
import { TrackPageViewEvent } from '@/components/Insights'; import { TrackPageViewEvent } from '@/components/Insights';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';
import { useSpaceBasePath } from '../SpaceLayout/SpaceLayoutContext';
/** /**
* Component that displays a "page not found" message. * Component that displays a "page not found" message.
*/ */
export function SitePageNotFound() { export function SitePageNotFound() {
const basePath = useSpaceBasePath();
const language = useLanguage(); const language = useLanguage();
const router = useRouter();
const searchParams = useSearchParams();
// If ?fallback=true, redirect to the root page.
const fallback = searchParams.get('fallback');
useEffect(() => {
if (fallback) {
router.replace(basePath);
}
}, [basePath, fallback, router]);
return ( return (
<div <div
@@ -15,6 +15,7 @@ import { 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';
import { SiteSectionList, encodeClientSiteSections } from '../SiteSections'; import { SiteSectionList, encodeClientSiteSections } from '../SiteSections';
import { SpaceLayoutContextProvider } from './SpaceLayoutContext';
/** /**
* Render the entire layout of the space (header, table of contents, footer). * Render the entire layout of the space (header, table of contents, footer).
@@ -46,98 +47,100 @@ export function SpaceLayout(props: {
customization.footer.groups?.length; customization.footer.groups?.length;
return ( return (
<InsightsProvider <SpaceLayoutContextProvider basePath={context.linker.toPathInContent('')}>
enabled={withTracking} <InsightsProvider
appURL={GITBOOK_APP_URL} enabled={withTracking}
apiHost={context.dataFetcher.apiEndpoint} appURL={GITBOOK_APP_URL}
visitorAuthToken={visitorAuthToken} apiHost={context.dataFetcher.apiEndpoint}
organizationId={context.organizationId} visitorAuthToken={visitorAuthToken}
siteId={context.site.id} organizationId={context.organizationId}
siteSectionId={context.sections?.current?.id ?? null} siteId={context.site.id}
siteSpaceId={context.siteSpace.id} siteSectionId={context.sections?.current?.id ?? null}
siteShareKey={context.shareKey ?? null} siteSpaceId={context.siteSpace.id}
revisionId={context.revisionId} siteShareKey={context.shareKey ?? null}
spaceId={context.space.id} revisionId={context.revisionId}
> spaceId={context.space.id}
<Header withTopHeader={withTopHeader} context={context} />
<div
className={tcls(
'flex',
'flex-col',
'lg:flex-row',
CONTAINER_STYLE,
// Ensure the footer is display below the viewport even if the content is not enough
withFooter && 'min-h-[calc(100vh-64px)]',
withTopHeader ? null : 'lg:min-h-screen'
)}
> >
<TableOfContents <Header withTopHeader={withTopHeader} context={context} />
context={context} <div
header={ className={tcls(
withTopHeader ? null : ( 'flex',
<div 'flex-col',
className={tcls( 'lg:flex-row',
'hidden', CONTAINER_STYLE,
'pr-4',
'lg:flex', // Ensure the footer is display below the viewport even if the content is not enough
'grow-0', withFooter && 'min-h-[calc(100vh-64px)]',
'flex-wrap', withTopHeader ? null : 'lg:min-h-screen'
'dark:shadow-light/1' )}
)} >
> <TableOfContents
<HeaderLogo context={context} /> context={context}
</div> header={
) withTopHeader ? null : (
} <div
innerHeader={ className={tcls(
// 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. 'hidden',
<> 'pr-4',
{!withTopHeader && ( 'lg:flex',
<div className={tcls('hidden', 'lg:block')}> 'grow-0',
<React.Suspense fallback={null}> 'flex-wrap',
<SearchButton> 'dark:shadow-light/1'
<span className={tcls('flex-1')}> )}
{t( >
getSpaceLanguage(customization), <HeaderLogo context={context} />
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
</span>
</SearchButton>
</React.Suspense>
</div> </div>
)} )
{!withTopHeader && withSections && sections && ( }
<SiteSectionList innerHeader={
className={tcls('hidden', 'lg:block')} // 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.
sections={encodeClientSiteSections(context, sections)} <>
/> {!withTopHeader && (
)} <div className={tcls('hidden', 'lg:block')}>
{isMultiVariants && ( <React.Suspense fallback={null}>
<SpacesDropdown <SearchButton>
context={context} <span className={tcls('flex-1')}>
siteSpace={siteSpace} {t(
siteSpaces={siteSpaces} getSpaceLanguage(customization),
className={tcls('w-full')} customization.aiSearch.enabled
/> ? 'search_or_ask'
)} : 'search'
</> )}
} </span>
/> </SearchButton>
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div> </React.Suspense>
</div> </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')}
/>
)}
</>
}
/>
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div>
</div>
{withFooter ? <Footer context={context} /> : null} {withFooter ? <Footer context={context} /> : null}
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<SearchModal <SearchModal
spaceTitle={siteSpace.title} spaceTitle={siteSpace.title}
withAsk={customization.aiSearch.enabled} withAsk={customization.aiSearch.enabled}
isMultiVariants={isMultiVariants} isMultiVariants={isMultiVariants}
/> />
</React.Suspense> </React.Suspense>
</InsightsProvider> </InsightsProvider>
</SpaceLayoutContextProvider>
); );
} }
@@ -0,0 +1,33 @@
'use client';
import React from 'react';
const SpaceLayoutContext = React.createContext({
basePath: '',
});
/**
* Provide the client context about the currently rendered space.
*/
export function SpaceLayoutContextProvider(
props: React.PropsWithChildren<{
basePath: string;
}>
) {
const { basePath, children } = props;
const value = React.useMemo(() => ({ basePath }), [basePath]);
return <SpaceLayoutContext.Provider value={value}>{children}</SpaceLayoutContext.Provider>;
}
/**
* Return the base path of the currently rendered space.
*/
export function useSpaceBasePath() {
const context = React.useContext(SpaceLayoutContext);
if (!context) {
throw new Error('SpaceLayoutContext not found');
}
return context.basePath;
}
@@ -46,7 +46,7 @@ export async function getDocumentSections(
sections.push({ sections.push({
id: block.meta.id, id: block.meta.id,
tag: operation.method.toUpperCase(), tag: operation.method.toUpperCase(),
title: operation.operation.summary ?? operation.path, title: operation.operation.summary || operation.path,
depth: 1, depth: 1,
deprecated: operation.operation.deprecated, deprecated: operation.operation.deprecated,
}); });
+9 -2
View File
@@ -3,7 +3,6 @@ import type { NextRequest } from 'next/server';
import hash from 'object-hash'; import hash from 'object-hash';
const VISITOR_AUTH_PARAM = 'jwt_token'; const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_AUTH_COOKIE_ROOT = 'gitbook-visitor-token~';
export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token'; export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token';
export type ResponseCookie = { export type ResponseCookie = {
@@ -127,7 +126,7 @@ export function getResponseCookiesForVisitorAuth(
* different content hosted on the same subdomain. * different content hosted on the same subdomain.
*/ */
export function getVisitorAuthCookieName(basePath: string): string { export function getVisitorAuthCookieName(basePath: string): string {
return `${VISITOR_AUTH_COOKIE_ROOT}${hash(basePath)}`; return getPathScopedCookieName(VISITOR_TOKEN_COOKIE, basePath);
} }
/** /**
@@ -147,6 +146,14 @@ export function normalizeVisitorAuthURL(url: URL): URL {
return withoutVAParam; return withoutVAParam;
} }
/**
* Get the name of a cookie to be scoped to a given path.
* It is used to avoid conflict between used of similar cookies under a same domain.
*/
export function getPathScopedCookieName(prefix: string, path: string): string {
return `${prefix}~${hash(path)}`;
}
/** /**
* Get all possible basePaths for a given URL. This is used to find the visitor * Get all possible basePaths for a given URL. This is used to find the visitor
* authentication cookie token. * authentication cookie token.
+55 -14
View File
@@ -1,25 +1,34 @@
import { GitBookAPI } from '@gitbook/api';
/** /**
* Get the target URL from the command line arguments. * Get the base URL of the deployment to test.
*/ */
export function getTargetURL() { function getBaseURL() {
const targetUrl = Bun.argv[2]; const baseUrl = process.env.BASE_URL;
if (!targetUrl) { if (!baseUrl) {
process.exit(1); throw new Error('BASE_URL is not set');
} }
return targetUrl; return baseUrl;
}
export function getContentPathName(input: string): string {
const contentUrl = new URL(input);
return `${contentUrl.host}${contentUrl.pathname}`;
} }
/** /**
* Get the URL to load for a content * Get the site base URL of the deployment to test.
*/ */
export function getContentTestURL(input: string, baseUrl: string = getTargetURL()): string { function getSiteBaseURL() {
const url = new URL(baseUrl); const siteBaseUrl = process.env.SITE_BASE_URL;
if (!siteBaseUrl) {
return getBaseURL();
}
return siteBaseUrl;
}
/**
* Get the URL to load for a site
*/
export function getContentTestURL(input: string): string {
const url = new URL(getSiteBaseURL());
const contentUrl = new URL(input); const contentUrl = new URL(input);
url.pathname = `${url.pathname.replace(/\/$/, '')}/${contentUrl.host}${contentUrl.pathname}`; url.pathname = `${url.pathname.replace(/\/$/, '')}/${contentUrl.host}${contentUrl.pathname}`;
@@ -27,3 +36,35 @@ export function getContentTestURL(input: string, baseUrl: string = getTargetURL(
return url.toString(); return url.toString();
} }
/**
* Get the URL to load on the deployment being tested.
*/
export function getTestURL(urlRest: string): string {
const url = new URL(urlRest, getBaseURL());
return url.toString();
}
/**
* Get an API token for a site by its URL.
*/
export async function getSiteAPIToken(url: string) {
const api = new GitBookAPI();
const { data } = await api.urls.getPublishedContentByUrl(
{
url,
cache: true,
},
{
headers: {
'x-gitbook-force-cache': 'true',
},
}
);
if ('redirect' in data) {
throw new Error(`Invalid site URL, it resulted in a redirect: ${data.redirect}`);
}
return data;
}
+6
View File
@@ -1,5 +1,11 @@
# @gitbook/icons # @gitbook/icons
## 0.2.0
### Minor Changes
- 88f64b0: Fix the build to support Node.js v20
## 0.1.0 ## 0.1.0
### Minor Changes ### Minor Changes
+5 -2
View File
@@ -16,7 +16,7 @@
"default": "./src/style.css" "default": "./src/style.css"
} }
}, },
"version": "0.1.0", "version": "0.2.0",
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.6.0", "@fortawesome/fontawesome-svg-core": "^6.6.0",
"@fortawesome/fontawesome-free": "^6.6.0" "@fortawesome/fontawesome-free": "^6.6.0"
@@ -41,5 +41,8 @@
"bin": { "bin": {
"gitbook-icons": "./bin/gitbook-icons.js" "gitbook-icons": "./bin/gitbook-icons.js"
}, },
"files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"] "files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"],
"engines": {
"node": ">=20.0.0"
}
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import stylesMap from './data/styles-map.json'; import stylesMap from './data/styles-map.json' with { type: 'json' };
import type { IconName, IconStyle } from './types'; import type { IconName, IconStyle } from './types';
const cache = new Map<IconName, Map<IconStyle, [string, IconName]>>(); const cache = new Map<IconName, Map<IconStyle, [string, IconName]>>();
+1 -1
View File
@@ -1,4 +1,4 @@
import rawIcons from './data/icons.json'; import rawIcons from './data/icons.json' with { type: 'json' };
import type { IconName, IconStyle } from './types'; import type { IconName, IconStyle } from './types';
export interface IconStyleDefinition { export interface IconStyleDefinition {
+7 -7
View File
@@ -1,16 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "esnext", "lib": ["es2023"],
"lib": ["dom", "dom.iterable", "esnext"], "module": "ESNext",
"allowJs": true, "target": "es2022",
"skipLibCheck": true,
"strict": true, "strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowJs": true,
"noEmit": false, "noEmit": false,
"declaration": true, "declaration": true,
"outDir": "dist", "outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "react-jsx", "jsx": "react-jsx",
+7
View File
@@ -1,5 +1,12 @@
# @gitbook/react-contentkit # @gitbook/react-contentkit
## 0.6.2
### Patch Changes
- Updated dependencies [88f64b0]
- @gitbook/icons@0.2.0
## 0.6.1 ## 0.6.1
### Patch Changes ### Patch Changes
+1 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gitbook/react-contentkit", "name": "@gitbook/react-contentkit",
"version": "0.6.1", "version": "0.6.2",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
@@ -11,7 +11,6 @@
"dependencies": { "dependencies": {
"classnames": "^2.5.1", "classnames": "^2.5.1",
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"assert-never": "^1.2.1",
"@gitbook/icons": "workspace:*" "@gitbook/icons": "workspace:*"
}, },
"peerDependencies": { "peerDependencies": {
+6
View File
@@ -1,5 +1,11 @@
# @gitbook/react-openapi # @gitbook/react-openapi
## 1.1.3
### Patch Changes
- 844059f: Fix spacing in OpenAPISecurities
## 1.1.2 ## 1.1.2
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -8,7 +8,7 @@
"default": "./dist/index.js" "default": "./dist/index.js"
} }
}, },
"version": "1.1.2", "version": "1.1.3",
"sideEffects": false, "sideEffects": false,
"dependencies": { "dependencies": {
"@gitbook/openapi-parser": "workspace:*", "@gitbook/openapi-parser": "workspace:*",
@@ -31,7 +31,7 @@ export function OpenAPISecurities(props: {
key: key, key: key,
label: key, label: key,
body: ( body: (
<div className="openapi-schema-body"> <div className="openapi-schema">
<div className="openapi-schema-presentation"> <div className="openapi-schema-presentation">
{getLabelForType(security)} {getLabelForType(security)}
@@ -80,8 +80,8 @@ describe('#resolveOpenAPIOperation', () => {
it('should resolve circular refs', async () => { it('should resolve circular refs', async () => {
const filesystem = await fetchFilesystem('https://api.gitbook.com/openapi.json'); const filesystem = await fetchFilesystem('https://api.gitbook.com/openapi.json');
const resolved = await resolveOpenAPIOperation(filesystem, { const resolved = await resolveOpenAPIOperation(filesystem, {
method: 'post', method: 'get',
path: '/search/ask', path: '/spaces/{spaceId}/content/page/{pageId}',
}); });
expect(resolved).toMatchObject({ expect(resolved).toMatchObject({
@@ -91,7 +91,7 @@ describe('#resolveOpenAPIOperation', () => {
}, },
], ],
operation: { operation: {
operationId: 'askQuery', operationId: 'getPageById',
}, },
}); });
}); });
+2 -2
View File
@@ -50,12 +50,12 @@
// Run end-to-end tests // Run end-to-end tests
"e2e": { "e2e": {
"dependsOn": ["^e2e"], "dependsOn": ["^e2e"],
"env": ["BASE_URL"] "env": ["BASE_URL", "SITE_BASE_URL"]
}, },
// Run end-to-end tests for customers // Run end-to-end tests for customers
"e2e-customers": { "e2e-customers": {
"dependsOn": ["^e2e-customers"], "dependsOn": ["^e2e-customers"],
"env": ["BASE_URL"] "env": ["BASE_URL", "SITE_BASE_URL"]
}, },
// Start the package in development mode // Start the package in development mode
"dev": { "dev": {