mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-24 17:22:39 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9cf7ab6265 | |||
| 0052c19b48 | |||
| 8512a29ac1 | |||
| 0db6c62be8 | |||
| 2e45304130 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Run the Cloudflare server worker next to the GitBook API.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Start the requests a site page needs as soon as their inputs are known, instead of when each component renders.
|
||||
@@ -30,7 +30,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: deployments status --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -49,7 +49,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ steps.extract_current_version.outputs.version_id }}@100% ${{ inputs.serverVersionId }}@0% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -61,7 +61,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ inputs.middlewareVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
|
||||
|
||||
@@ -71,7 +71,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: versions deploy ${{ inputs.serverVersionId }}@100% -y --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: deploy --config ./packages/gitbook/openNext/customWorkers/doWrangler.jsonc
|
||||
|
||||
@@ -89,7 +89,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/defaultWrangler.jsonc
|
||||
|
||||
@@ -112,7 +112,7 @@ runs:
|
||||
apiToken: ${{ inputs.apiToken }}
|
||||
accountId: ${{ inputs.accountId }}
|
||||
workingDirectory: ./
|
||||
wranglerVersion: '4.43.0'
|
||||
wranglerVersion: '4.80.0'
|
||||
environment: ${{ inputs.environment }}
|
||||
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook/openNext/customWorkers/middlewareWrangler.jsonc
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"observability": {
|
||||
"enabled": false,
|
||||
},
|
||||
// Run the server next to the GitBook API so its request waterfall stays short; the middleware stays at the edge.
|
||||
"placement": { "region": "gcp:us-central1" },
|
||||
"vars": {
|
||||
"NEXT_CACHE_DO_QUEUE_DISABLE_SQLITE": "true",
|
||||
},
|
||||
|
||||
+4
-1
@@ -5,6 +5,7 @@ import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
startSitePagePlan,
|
||||
} from '@/components/SitePage';
|
||||
|
||||
type PageProps = {
|
||||
@@ -21,7 +22,9 @@ export default async function Page(props: PageProps) {
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const { context } = await getDynamicSiteContext(await props.params);
|
||||
const params = await props.params;
|
||||
const { context } = await getDynamicSiteContext(params);
|
||||
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -5,6 +5,7 @@ import {
|
||||
SitePage,
|
||||
generateSitePageMetadata,
|
||||
generateSitePageViewport,
|
||||
startSitePagePlan,
|
||||
} from '@/components/SitePage';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
@@ -22,7 +23,9 @@ export default async function Page(props: PageProps) {
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const { context } = await getStaticSiteContext(await props.params);
|
||||
const params = await props.params;
|
||||
const { context } = await getStaticSiteContext(params);
|
||||
startSitePagePlan(context, { pathname: getPagePathFromParams(params) });
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,12 @@ import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
|
||||
await import('./fetch');
|
||||
const {
|
||||
getLowercasePathnameRedirect,
|
||||
startSitePagePlan,
|
||||
resolveMissingPagePath,
|
||||
resolveSitePageFromURL,
|
||||
} = await import('./fetch');
|
||||
const { normalizeURL } = await import('@/lib/data/urls');
|
||||
const { createLinker } = await import('@/lib/links');
|
||||
|
||||
@@ -205,3 +209,45 @@ describe('getLowercasePathnameRedirect', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('startSitePagePlan', () => {
|
||||
function createContext(getRevisionPageDocument: (params: unknown) => Promise<unknown>) {
|
||||
return {
|
||||
space: { id: 'space-1' },
|
||||
revisionId: 'revision-1',
|
||||
revision: { pages: [page] },
|
||||
siteSpace: { id: 'site-space-1', pageId: null },
|
||||
dataFetcher: { getRevisionPageDocument: mock(getRevisionPageDocument) },
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
|
||||
it('requests the document of the page at the lowercased path', () => {
|
||||
const context = createContext(async () => ({ data: {} }));
|
||||
startSitePagePlan(context, { pathname: 'ReadMe' });
|
||||
expect(context.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing when the path does not resolve to a page', () => {
|
||||
const context = createContext(async () => ({ data: {} }));
|
||||
startSitePagePlan(context, { pathname: 'missing' });
|
||||
expect(context.dataFetcher.getRevisionPageDocument).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not leak a rejection when the request fails', async () => {
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown) => unhandled.push(reason);
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
try {
|
||||
const context = createContext(async () => ({ error: { code: 500, message: 'boom' } }));
|
||||
startSitePagePlan(context, { pathname: 'readme' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
expect(unhandled).toEqual([]);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { runSitePagePlan } from './plan';
|
||||
import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/context';
|
||||
import { getDataOrNull } from '@/lib/data';
|
||||
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
|
||||
@@ -40,6 +41,17 @@ export async function fetchPageData(context: GitBookSiteContext, params: PagePar
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the site page plan from `generateViewport`, which Next runs before the page itself.
|
||||
*/
|
||||
export function startSitePagePlan(context: GitBookSiteContext, params: PagePathParams) {
|
||||
const pathname = getPathnameParam(params).toLowerCase();
|
||||
const resolved = resolveSiteSpacePagePath(context.siteSpace, context.revision.pages, pathname);
|
||||
if (resolved) {
|
||||
void runSitePagePlan(context, resolved.page);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a page from the params.
|
||||
* If the path can't be found, we try to resolve it from the API to handle redirects.
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { runSitePagePlan } = await import('./plan');
|
||||
|
||||
const page = { id: 'page-1', type: 'document' } as RevisionPageDocument;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function setup(options: {
|
||||
document?: unknown;
|
||||
metaLinks?: unknown;
|
||||
documentPromise?: Promise<unknown>;
|
||||
resolveRefError?: boolean;
|
||||
}) {
|
||||
const dataFetcher = {
|
||||
getRevisionPageDocument: mock(
|
||||
() => options.documentPromise ?? Promise.resolve({ data: options.document ?? null })
|
||||
),
|
||||
listRevisionPageMetaLinks: mock(async () => ({ data: options.metaLinks ?? null })),
|
||||
getEmbedByUrl: mock(async () => ({ data: {} })),
|
||||
getRevision: mock(async () => ({ data: {} })),
|
||||
};
|
||||
const imageResizer = { getImageSize: mock(async () => ({ width: 1, height: 1 })) };
|
||||
const context = {
|
||||
space: { id: 'space-1' },
|
||||
revisionId: 'revision-1',
|
||||
customization: { styling: { icons: 'regular' } },
|
||||
structure: {
|
||||
type: 'siteSpaces',
|
||||
structure: [
|
||||
{ id: 'ss-1', space: { id: 'space-1', revision: 'revision-1' } },
|
||||
{ id: 'ss-2', space: { id: 'space-2', revision: 'revision-2' } },
|
||||
],
|
||||
},
|
||||
dataFetcher,
|
||||
imageResizer,
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
const resolveRef = mock(
|
||||
async (_doc: unknown, ref: { kind: string }, _ctx?: unknown, _opts?: unknown) => {
|
||||
if (options.resolveRefError) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
return ref.kind === 'file'
|
||||
? { href: 'https://files/image.png', file: { dimensions: undefined } }
|
||||
: { href: '/x' };
|
||||
}
|
||||
);
|
||||
const loadIcons = mock(async () => ({}));
|
||||
return { context, dataFetcher, imageResizer, resolveRef, loadIcons };
|
||||
}
|
||||
|
||||
const doc = (nodes: unknown[]) => ({ object: 'document', nodes }) as unknown as JSONDocument;
|
||||
|
||||
describe('runSitePagePlan', () => {
|
||||
it('requests the document and the meta links in parallel', async () => {
|
||||
const pending = deferred<unknown>();
|
||||
const s = setup({ documentPromise: pending.promise });
|
||||
const done = runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevisionPageDocument).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
expect(s.dataFetcher.listRevisionPageMetaLinks).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
pageId: 'page-1',
|
||||
});
|
||||
pending.resolve({ data: null });
|
||||
await done;
|
||||
});
|
||||
|
||||
it('starts embeds from the document with the page space', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{ object: 'block', type: 'embed', data: { url: 'https://a.example' }, nodes: [] },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
|
||||
url: 'https://a.example',
|
||||
spaceId: 'space-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves network refs of nested blocks and inlines, with anchor text for mentions', async () => {
|
||||
const link = { kind: 'page', space: 'space-2', page: 'p2' };
|
||||
const mention = { kind: 'anchor', page: 'p3', anchor: 'a' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{ object: 'inline', type: 'link', data: { ref: link }, nodes: [] },
|
||||
{ object: 'inline', type: 'mention', data: { ref: mention }, nodes: [] },
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
|
||||
expect(calls).toContainEqual([link, {}]);
|
||||
expect(calls).toContainEqual([mention, { resolveAnchorText: true }]);
|
||||
});
|
||||
|
||||
it('skips refs that resolve without a request', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [
|
||||
{
|
||||
object: 'inline',
|
||||
type: 'link',
|
||||
data: { ref: { kind: 'page', page: 'p2' } },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('measures images without known dimensions like the image block does', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'images',
|
||||
nodes: [
|
||||
{
|
||||
object: 'block',
|
||||
type: 'image',
|
||||
data: { ref: { kind: 'file', file: 'f1' } },
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledWith('https://files/image.png', {
|
||||
dpr: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('starts the revision of cross-space image files in the site', async () => {
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'image',
|
||||
data: { ref: { kind: 'file', space: 'space-2', file: 'f1' } },
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
});
|
||||
|
||||
it('measures card covers and resolves cross-space card targets', async () => {
|
||||
const target = { kind: 'page', space: 'space-2', page: 'p2' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'table',
|
||||
data: {
|
||||
view: {
|
||||
type: 'cards',
|
||||
columns: [],
|
||||
coverDefinition: 'cover',
|
||||
coverDefinitionDark: 'coverDark',
|
||||
targetDefinition: 'target',
|
||||
},
|
||||
definition: {},
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
cover: { kind: 'file', file: 'f1' },
|
||||
coverDark: { kind: 'file', file: 'f2' },
|
||||
target,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const refs = s.resolveRef.mock.calls.map(([, ref]) => ref);
|
||||
expect(refs).toContainEqual({ kind: 'file', file: 'f1' });
|
||||
expect(refs).toContainEqual({ kind: 'file', file: 'f2' });
|
||||
expect(refs).toContainEqual(target);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(2);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
});
|
||||
|
||||
it('starts the requests of visible table columns only', async () => {
|
||||
const anchor = { kind: 'anchor', page: 'p3', anchor: 'a' };
|
||||
const s = setup({
|
||||
document: doc([
|
||||
{
|
||||
object: 'block',
|
||||
type: 'table',
|
||||
data: {
|
||||
view: { type: 'grid', columns: ['people', 'link', 'picture'] },
|
||||
definition: {
|
||||
people: { type: 'users' },
|
||||
link: { type: 'content-ref' },
|
||||
picture: { type: 'image' },
|
||||
hidden: { type: 'users' },
|
||||
},
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
people: ['u1'],
|
||||
link: anchor,
|
||||
picture: { ref: { kind: 'file', file: 'f1' } },
|
||||
hidden: ['u2'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
nodes: [],
|
||||
},
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
const calls = s.resolveRef.mock.calls.map(([, ref, , opts]) => [ref, opts]);
|
||||
expect(calls).toContainEqual([{ kind: 'user', user: 'u1' }, {}]);
|
||||
expect(calls).toContainEqual([anchor, { resolveAnchorText: true }]);
|
||||
expect(calls).toContainEqual([{ kind: 'file', file: 'f1' }, {}]);
|
||||
expect(calls).not.toContainEqual([{ kind: 'user', user: 'u2' }, {}]);
|
||||
expect(s.imageResizer.getImageSize).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps planning after a malformed table and skips values the render skips', async () => {
|
||||
const table = (data: unknown) => ({ object: 'block', type: 'table', data, nodes: [] });
|
||||
const s = setup({
|
||||
document: doc([
|
||||
table({ view: { type: 'grid', columns: ['a'] }, records: { r1: {} } }),
|
||||
table({
|
||||
view: {
|
||||
type: 'cards',
|
||||
columns: ['img', 'people'],
|
||||
coverDefinitionDark: 'dark',
|
||||
},
|
||||
definition: { img: { type: 'image' }, people: { type: 'users' } },
|
||||
records: {
|
||||
r1: {
|
||||
orderIndex: 'a',
|
||||
values: {
|
||||
img: { ref: undefined },
|
||||
people: ['u1', 2],
|
||||
dark: { kind: 'file', file: 'f2' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ object: 'block', type: 'embed', data: { url: 'https://after' }, nodes: [] },
|
||||
]),
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getEmbedByUrl).toHaveBeenCalledWith({
|
||||
url: 'https://after',
|
||||
spaceId: 'space-1',
|
||||
});
|
||||
expect(s.resolveRef).not.toHaveBeenCalled();
|
||||
expect(s.imageResizer.getImageSize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts the revision of meta-link alternates in the site alongside their space', async () => {
|
||||
const alternate = { kind: 'page', space: 'space-2', page: 'p9' };
|
||||
const s = setup({ metaLinks: { canonical: null, alternates: [alternate] } });
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
expect(s.dataFetcher.getRevision).toHaveBeenCalledWith({
|
||||
spaceId: 'space-2',
|
||||
revisionId: 'revision-2',
|
||||
});
|
||||
expect(s.resolveRef.mock.calls.map(([, ref]) => ref)).toContainEqual(alternate);
|
||||
});
|
||||
|
||||
it('settles without unhandled rejections when every branch fails', async () => {
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown) => unhandled.push(reason);
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
try {
|
||||
const s = setup({
|
||||
resolveRefError: true,
|
||||
metaLinks: { alternates: [{ kind: 'page', space: 'space-2', page: 'p' }] },
|
||||
document: doc([
|
||||
{ object: 'block', type: 'embed', data: { url: 'u' }, nodes: [] },
|
||||
{
|
||||
object: 'block',
|
||||
type: 'paragraph',
|
||||
nodes: [{ object: 'inline', type: 'link', data: { ref: { kind: 'url' } } }],
|
||||
},
|
||||
]),
|
||||
});
|
||||
s.dataFetcher.getEmbedByUrl.mockImplementation(async () => {
|
||||
throw new Error('embed');
|
||||
});
|
||||
s.loadIcons.mockImplementation(async () => {
|
||||
throw new Error('icons');
|
||||
});
|
||||
await runSitePagePlan(s.context, page, s);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(unhandled).toEqual([]);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import type {
|
||||
ContentRef,
|
||||
DocumentBlockTable,
|
||||
JSONDocument,
|
||||
RevisionPageDocument,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import {
|
||||
getRecordCardCovers,
|
||||
isDocumentTableImageRecord,
|
||||
isStringArray,
|
||||
} from '@/components/DocumentView/Table/utils';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getDataOrNull, getPageDocument } from '@/lib/data';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
getCustomizationIconStyle,
|
||||
getInlineIconSources,
|
||||
} from '@/lib/icons/inline';
|
||||
import {
|
||||
type ResolveContentRefOptions,
|
||||
resolveContentRef,
|
||||
resolveContentRefInDocument,
|
||||
} from '@/lib/references';
|
||||
import { findSiteSpaceBy } from '@/lib/sites';
|
||||
|
||||
type Deps = {
|
||||
/** `document` is null for refs that don't come from the page document (meta links). */
|
||||
resolveRef: (
|
||||
document: JSONDocument | null,
|
||||
ref: ContentRef,
|
||||
context: GitBookSiteContext,
|
||||
options: ResolveContentRefOptions
|
||||
) => Promise<unknown>;
|
||||
loadIcons: (context: GitBookSiteContext, document: JSONDocument) => Promise<unknown>;
|
||||
};
|
||||
|
||||
const defaultDeps: Deps = {
|
||||
resolveRef: (document, ref, context, options) =>
|
||||
document
|
||||
? resolveContentRefInDocument(document, ref, context, options)
|
||||
: resolveContentRef(ref, context, options),
|
||||
loadIcons: (context, document) =>
|
||||
getInlineIconSources(
|
||||
getContentInlineIconSourceRequests({
|
||||
iconStyle: getCustomizationIconStyle(context.customization),
|
||||
document,
|
||||
})
|
||||
),
|
||||
};
|
||||
|
||||
type Node = { object?: string; type?: string; data?: Record<string, unknown>; nodes?: unknown };
|
||||
|
||||
/** Node types the render resolves with `resolveAnchorText: true` (an extra page document). */
|
||||
const ANCHOR_TEXT_TYPES = new Set(['mention', 'content-ref']);
|
||||
|
||||
/**
|
||||
* Start every request a site page render will make, as soon as its input is known, instead of
|
||||
* when React reaches the component that needs it. Each call is the one the render makes, with
|
||||
* the same arguments, so the render reuses it through the per-request memo of the data fetcher
|
||||
* (and of the image size and icon helpers). Failures are left for the render to surface.
|
||||
*/
|
||||
export function runSitePagePlan(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument,
|
||||
deps: Deps = defaultDeps
|
||||
): Promise<void> {
|
||||
const pending: Promise<unknown>[] = [];
|
||||
const start = (fn: () => Promise<unknown>) => {
|
||||
let promise: Promise<unknown>;
|
||||
try {
|
||||
promise = fn();
|
||||
} catch (error) {
|
||||
promise = Promise.reject(error);
|
||||
}
|
||||
pending.push(promise.catch(() => {}));
|
||||
};
|
||||
|
||||
const resolveRef = (document: JSONDocument | null, ref: ContentRef, anchorText: boolean) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(() =>
|
||||
deps.resolveRef(document, ref, context, anchorText ? { resolveAnchorText: true } : {})
|
||||
);
|
||||
};
|
||||
|
||||
// Cross-space refs fetch the space, then its revision; the site structure already knows the
|
||||
// revision, so start both. A stale structure only costs one unused (usually cached) call.
|
||||
const startSpaceRevisionFor = (ref: ContentRef) => {
|
||||
const spaceId = 'space' in ref ? ref.space : undefined;
|
||||
if (!spaceId || spaceId === context.space.id) {
|
||||
return;
|
||||
}
|
||||
const found = findSiteSpaceBy(context.structure, (s) => s.space.id === spaceId);
|
||||
if (found) {
|
||||
start(() =>
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId,
|
||||
revisionId: found.siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const ids = { spaceId: context.space.id, revisionId: context.revisionId, pageId: page.id };
|
||||
|
||||
start(async () => {
|
||||
const links = await getDataOrNull(context.dataFetcher.listRevisionPageMetaLinks(ids));
|
||||
for (const ref of [links?.canonical, ...(links?.alternates ?? [])]) {
|
||||
if (ref) {
|
||||
resolveRef(null, ref, false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
start(async () => {
|
||||
const document = await getPageDocument(context, page);
|
||||
if (!document) {
|
||||
return;
|
||||
}
|
||||
start(() => deps.loadIcons(context, document));
|
||||
visit(document.nodes, (node) => {
|
||||
const data = node.data ?? {};
|
||||
if (node.type === 'embed' && typeof data.url === 'string') {
|
||||
start(() =>
|
||||
context.dataFetcher.getEmbedByUrl({
|
||||
url: data.url as string,
|
||||
spaceId: context.space.id,
|
||||
})
|
||||
);
|
||||
}
|
||||
if (node.type === 'image') {
|
||||
for (const ref of [data.ref, data.refDark]) {
|
||||
if (ref) {
|
||||
planImage(document, ref as ContentRef);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'table') {
|
||||
// Through `start` so a malformed table can't stop the rest of the walk.
|
||||
start(async () =>
|
||||
planTable(document, node.data as unknown as DocumentBlockTable['data'])
|
||||
);
|
||||
}
|
||||
const ref = data.ref as ContentRef | undefined;
|
||||
if (ref) {
|
||||
planRef(document, ref, ANCHOR_TEXT_TYPES.has(node.type ?? ''));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const planRef = (document: JSONDocument, ref: ContentRef, anchorText: boolean) => {
|
||||
if (needsRequest(ref, anchorText, context)) {
|
||||
resolveRef(document, ref, anchorText);
|
||||
}
|
||||
};
|
||||
|
||||
const planImage = (document: JSONDocument, ref: ContentRef) => {
|
||||
startSpaceRevisionFor(ref);
|
||||
start(() => measureImage(document, ref));
|
||||
};
|
||||
|
||||
// Only what the table view renders: its columns, plus covers and target for cards.
|
||||
const planTable = (document: JSONDocument, table: DocumentBlockTable['data']) => {
|
||||
const { view, definition } = table;
|
||||
for (const record of Object.values(table.records ?? {})) {
|
||||
for (const column of view.columns ?? []) {
|
||||
const value = record.values[column];
|
||||
switch (definition[column]?.type) {
|
||||
case 'content-ref':
|
||||
if (value && typeof value === 'object' && 'kind' in value) {
|
||||
planRef(document, value as ContentRef, true);
|
||||
}
|
||||
break;
|
||||
case 'users':
|
||||
if (isStringArray(value)) {
|
||||
for (const user of value) {
|
||||
resolveRef(document, { kind: 'user', user }, false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'image':
|
||||
if (isDocumentTableImageRecord(value)) {
|
||||
planImage(document, 'ref' in value ? value.ref : value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (view.type === 'cards') {
|
||||
const { light, dark } = getRecordCardCovers(record, view);
|
||||
// The dark cover only renders alongside a light one.
|
||||
if (light.contentRef) {
|
||||
planImage(document, light.contentRef);
|
||||
if (dark.contentRef) {
|
||||
planImage(document, dark.contentRef);
|
||||
}
|
||||
}
|
||||
const target = view.targetDefinition
|
||||
? (record.values[view.targetDefinition] as ContentRef | undefined)
|
||||
: undefined;
|
||||
if (target) {
|
||||
planRef(document, target, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Same as the images block: a file without known dimensions is measured by the resizer.
|
||||
const measureImage = async (document: JSONDocument, ref: ContentRef) => {
|
||||
const resolved = (await deps.resolveRef(document, ref, context, {})) as {
|
||||
href: string;
|
||||
file?: { dimensions?: unknown };
|
||||
} | null;
|
||||
if (resolved && !resolved.file?.dimensions) {
|
||||
await context.imageResizer?.getImageSize(resolved.href, { dpr: 2 });
|
||||
}
|
||||
};
|
||||
|
||||
return settle(pending);
|
||||
}
|
||||
|
||||
/** Whether resolving `ref` makes a request; same-space page and file refs resolve in memory. */
|
||||
function needsRequest(ref: ContentRef, anchorText: boolean, context: GitBookSiteContext) {
|
||||
if ('space' in ref && ref.space && ref.space !== context.space.id) {
|
||||
return true;
|
||||
}
|
||||
if (ref.kind === 'user' || ref.kind === 'openapi') {
|
||||
return true;
|
||||
}
|
||||
return ref.kind === 'anchor' && anchorText;
|
||||
}
|
||||
|
||||
function visit(nodes: unknown, fn: (node: Node) => void) {
|
||||
if (!Array.isArray(nodes)) {
|
||||
return;
|
||||
}
|
||||
for (const node of nodes as Node[]) {
|
||||
if (node && (node.object === 'block' || node.object === 'inline')) {
|
||||
fn(node);
|
||||
visit(node.nodes, fn);
|
||||
visit((node as { fragments?: unknown }).fragments, fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits for every started call, including ones started while waiting. */
|
||||
async function settle(pending: Promise<unknown>[]) {
|
||||
let settled = 0;
|
||||
while (settled < pending.length) {
|
||||
const batch = pending.slice(settled);
|
||||
settled = pending.length;
|
||||
await Promise.all(batch);
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,14 @@ import type {
|
||||
CloudflareImageOptions,
|
||||
CloudflareResizeImageOptions,
|
||||
} from './types';
|
||||
import { cache } from '@/lib/cache';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
|
||||
/**
|
||||
* Get the size of an image.
|
||||
* Memoized per request so the site page plan's early call is reused by the render.
|
||||
*/
|
||||
export async function getImageSize(
|
||||
export const getImageSize = cache(async function getImageSize(
|
||||
input: string,
|
||||
defaultSize: Partial<CloudflareImageOptions> = {}
|
||||
): Promise<{ width: number; height: number } | null> {
|
||||
@@ -43,7 +45,7 @@ export async function getImageSize(
|
||||
logger.warn(`Error getting image size for ${input}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Execute a Cloudflare Image Resize operation on an image.
|
||||
|
||||
Reference in New Issue
Block a user