mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-21 15:52:36 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ecd2ca65a |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published pages available when an integration block needs its connection or settings checked.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { ContentKitOutput } from '@gitbook/react-contentkit';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
@@ -53,6 +54,7 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
|
||||
{
|
||||
integrationName: block.data.integration,
|
||||
request: initialInput,
|
||||
allowFailedDependency: true,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -66,12 +68,29 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
|
||||
// Integration output can render blocks with generated keys.
|
||||
{...getCommentAnchorProps(context, block.key)}
|
||||
{...getCommentMarkerProps(context, 'data-comment-block')}
|
||||
className={tcls(style)}
|
||||
role="note"
|
||||
className={tcls(
|
||||
'flex items-start gap-3 p-4 text-sm',
|
||||
'rounded-corners:rounded-md circular-corners:rounded-xl',
|
||||
'bg-warning border-warning text-neutral-strong',
|
||||
style
|
||||
)}
|
||||
>
|
||||
<pre>
|
||||
Unexpected error with integration {block.data.integration}:{' '}
|
||||
{initialResponse.error.message}
|
||||
</pre>
|
||||
<Icon
|
||||
icon="circle-exclamation"
|
||||
className="mt-0.5 size-4 shrink-0 text-warning-subtle contrast-more:text-warning"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="wrap-anywhere min-w-0">
|
||||
<p className="font-medium">
|
||||
Could not load the {block.data.integration} integration
|
||||
</p>
|
||||
<p>
|
||||
{initialResponse.error.code === 424
|
||||
? 'Ask an administrator to check its connection and settings.'
|
||||
: initialResponse.error.message}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ export async function fetchSafeIntegrationUI(
|
||||
{
|
||||
integrationName,
|
||||
request,
|
||||
allowFailedDependency = false,
|
||||
}: {
|
||||
integrationName: string;
|
||||
request: RenderIntegrationUI;
|
||||
allowFailedDependency?: boolean;
|
||||
}
|
||||
) {
|
||||
const output = await ignoreDataFetcherErrors(
|
||||
@@ -27,6 +29,7 @@ export async function fetchSafeIntegrationUI(
|
||||
404, // Integration has been uninstalled
|
||||
400, // Integration is rejecting its own request
|
||||
422, // Integration is triggering an invalid request, failing at the validation step
|
||||
...(allowFailedDependency ? [424] : []),
|
||||
502, // Integration is failing in an unexpected way
|
||||
]
|
||||
);
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from '@gitbook/openapi-parser';
|
||||
|
||||
import { enrichFilesystem } from './enrich';
|
||||
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
|
||||
import type {
|
||||
AnyOpenAPIOperationsBlock,
|
||||
OpenAPISchemasBlock,
|
||||
@@ -42,9 +41,7 @@ export async function fetchOpenAPIFilesystem(
|
||||
// If the reference is a new OpenAPI reference, we return it.
|
||||
if (ref.kind === 'openapi') {
|
||||
assert(resolved.openapi?.filesystem);
|
||||
return resolveOpenAPIDescriptionLinks(resolved.openapi.filesystem, (contentRef) =>
|
||||
resolveContentRef(contentRef, context)
|
||||
);
|
||||
return resolved.openapi.filesystem;
|
||||
}
|
||||
// For legacy blocks ("swagger"), we need to fetch the file system.
|
||||
return fetchFilesystem(resolved.href, context.space.id);
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { parseOpenAPI } from '@gitbook/openapi-parser';
|
||||
|
||||
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
|
||||
|
||||
const APP_URL = 'https://app.gitbook.com/s/space-1/tables';
|
||||
|
||||
describe('resolveOpenAPIDescriptionLinks', () => {
|
||||
it('points tagged links at their resolved URL without mutating the input', async () => {
|
||||
const original =
|
||||
`<p><a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>` +
|
||||
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
|
||||
' <a href="https://example.com">Docs</a></p>';
|
||||
const { filesystem } = await parseOpenAPI({
|
||||
value: JSON.stringify({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 'Test', version: '1.0.0' },
|
||||
paths: {},
|
||||
components: {
|
||||
schemas: {
|
||||
Condition: { type: 'object', 'x-gitbook-description-html': original },
|
||||
},
|
||||
},
|
||||
}),
|
||||
rootURL: null,
|
||||
});
|
||||
|
||||
const resolved = await resolveOpenAPIDescriptionLinks(filesystem, async (ref) =>
|
||||
ref.kind === 'page' && ref.page === 'page-1' ? { href: '/docs/tables' } : null
|
||||
);
|
||||
|
||||
expect(resolved[0]?.specification.components?.schemas?.Condition).toMatchObject({
|
||||
'x-gitbook-description-html':
|
||||
'<p><a href="/docs/tables" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>' +
|
||||
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
|
||||
' <a href="https://example.com">Docs</a></p>',
|
||||
});
|
||||
// The spec content comes from the data cache, shared across sites.
|
||||
expect(filesystem[0]?.specification.components?.schemas?.Condition).toMatchObject({
|
||||
'x-gitbook-description-html': original,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,165 +0,0 @@
|
||||
import { type DefaultTreeAdapterMap, parseFragment } from 'parse5';
|
||||
import * as React from 'react';
|
||||
|
||||
import type { ContentRef } from '@gitbook/api';
|
||||
import type { Filesystem, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
|
||||
|
||||
import { escapeHTML } from '@/lib/html';
|
||||
import { resolveStringContentRef } from '@/lib/references';
|
||||
|
||||
const DESCRIPTION_HTML_KEY = 'x-gitbook-description-html';
|
||||
// Set by spec processing on links to GitBook content, e.g. `/spaces/{space}/pages/{page}`.
|
||||
const CONTENT_REF_ATTRIBUTE = 'data-gitbook-ref';
|
||||
|
||||
type OpenAPIFilesystem = Filesystem<OpenAPIV3xDocument>;
|
||||
type HTMLElement = DefaultTreeAdapterMap['element'];
|
||||
type HTMLNode = DefaultTreeAdapterMap['parentNode'] | DefaultTreeAdapterMap['childNode'];
|
||||
|
||||
// Per request: resolved hrefs depend on the site being rendered.
|
||||
const getResolvedFilesystems = React.cache(
|
||||
() => new WeakMap<OpenAPIFilesystem, Promise<OpenAPIFilesystem>>()
|
||||
);
|
||||
|
||||
/**
|
||||
* Point description links that spec processing tagged with a content ref at their URL in the
|
||||
* current site. Links whose ref doesn't resolve keep the href written in the spec.
|
||||
* Returns a copy when something changed: the input may be shared through the data cache.
|
||||
*/
|
||||
export function resolveOpenAPIDescriptionLinks(
|
||||
filesystem: OpenAPIFilesystem,
|
||||
resolveContentRef: (ref: ContentRef) => Promise<{ href: string } | null>
|
||||
): Promise<OpenAPIFilesystem> {
|
||||
const resolvedFilesystems = getResolvedFilesystems();
|
||||
let promise = resolvedFilesystems.get(filesystem);
|
||||
if (!promise) {
|
||||
promise = baseResolveOpenAPIDescriptionLinks(filesystem, resolveContentRef);
|
||||
resolvedFilesystems.set(filesystem, promise);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function baseResolveOpenAPIDescriptionLinks(
|
||||
filesystem: OpenAPIFilesystem,
|
||||
resolveContentRef: (ref: ContentRef) => Promise<{ href: string } | null>
|
||||
): Promise<OpenAPIFilesystem> {
|
||||
const taggedHTML = new Set<string>();
|
||||
mapDescriptionHTML(filesystem, (html) => {
|
||||
if (html.includes(CONTENT_REF_ATTRIBUTE)) {
|
||||
taggedHTML.add(html);
|
||||
}
|
||||
return html;
|
||||
});
|
||||
|
||||
if (taggedHTML.size === 0) {
|
||||
return filesystem;
|
||||
}
|
||||
|
||||
const hrefs = new Map<string, Promise<string | null>>();
|
||||
const resolveHref = (source: string) => {
|
||||
let href = hrefs.get(source);
|
||||
if (!href) {
|
||||
const ref = resolveStringContentRef(source);
|
||||
href = ref
|
||||
? resolveContentRef(ref).then((resolved) => resolved?.href ?? null)
|
||||
: Promise.resolve(null);
|
||||
hrefs.set(source, href);
|
||||
}
|
||||
return href;
|
||||
};
|
||||
|
||||
const rewritten = new Map<string, string>();
|
||||
await Promise.all(
|
||||
Array.from(taggedHTML, async (html) => {
|
||||
rewritten.set(html, await rewriteLinks(html, resolveHref));
|
||||
})
|
||||
);
|
||||
|
||||
return mapDescriptionHTML(filesystem, (html) => rewritten.get(html) ?? html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the href of each tagged link with its resolved URL.
|
||||
*/
|
||||
async function rewriteLinks(
|
||||
html: string,
|
||||
resolveHref: (source: string) => Promise<string | null>
|
||||
): Promise<string> {
|
||||
const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
|
||||
const replacements: { start: number; end: number; value: string }[] = [];
|
||||
|
||||
await Promise.all(
|
||||
collectLinks(fragment).map(async (link) => {
|
||||
const source = link.attrs.find((attr) => attr.name === CONTENT_REF_ATTRIBUTE)?.value;
|
||||
const location = link.sourceCodeLocation?.attrs?.href;
|
||||
if (!source || !location) {
|
||||
return;
|
||||
}
|
||||
|
||||
const href = await resolveHref(source);
|
||||
if (href) {
|
||||
replacements.push({
|
||||
start: location.startOffset,
|
||||
end: location.endOffset,
|
||||
value: `href="${escapeHTML(href)}"`,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Apply from the end so earlier offsets stay valid.
|
||||
replacements.sort((a, b) => b.start - a.start);
|
||||
let result = html;
|
||||
for (const { start, end, value } of replacements) {
|
||||
result = result.slice(0, start) + value + result.slice(end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectLinks(node: HTMLNode, links: HTMLElement[] = []): HTMLElement[] {
|
||||
if ('tagName' in node && node.tagName === 'a') {
|
||||
links.push(node);
|
||||
}
|
||||
if ('childNodes' in node) {
|
||||
for (const child of node.childNodes) {
|
||||
collectLinks(child, links);
|
||||
}
|
||||
}
|
||||
return links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map every description HTML in a JSON value, copying only the objects on a changed path.
|
||||
*/
|
||||
function mapDescriptionHTML<T>(value: T, transform: (html: string) => string): T {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
let result: unknown[] | null = null;
|
||||
value.forEach((item, index) => {
|
||||
const next = mapDescriptionHTML(item, transform);
|
||||
if (next !== item) {
|
||||
result ??= [...value];
|
||||
result[index] = next;
|
||||
}
|
||||
});
|
||||
return (result ?? value) as T;
|
||||
}
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
let result: Record<string, unknown> | null = null;
|
||||
// `for...in` over plain JSON objects: several times faster than `Object.entries` on large specs.
|
||||
for (const key in record) {
|
||||
const child = record[key];
|
||||
const next =
|
||||
key === DESCRIPTION_HTML_KEY && typeof child === 'string'
|
||||
? transform(child)
|
||||
: mapDescriptionHTML(child, transform);
|
||||
if (next !== child) {
|
||||
result ??= { ...record };
|
||||
result[key] = next;
|
||||
}
|
||||
}
|
||||
return (result ?? record) as T;
|
||||
}
|
||||
Reference in New Issue
Block a user