mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-27 10:43:32 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db88aeac4d | |||
| 4cbbda7fab | |||
| 63a4a98384 | |||
| 060f1f63ca | |||
| 7cee30ecb8 | |||
| a035d196f0 | |||
| 1ecd2ca65a | |||
| b0f3822342 | |||
| 7e2658a7a2 | |||
| a10eff9e0a | |||
| 13c0ff0803 | |||
| d2c56e5f0e |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Handle optional emoji and icon values when rendering tags.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Serve the published-docs MCP endpoint independently of the Connect with MCP page action.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Reduce the wait after typing in site search to 100 ms.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published pages available when an integration block needs its connection or settings checked.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published site search results visible while visitors refine a query.
|
||||
@@ -1,6 +0,0 @@
|
||||
---
|
||||
"gitbook": minor
|
||||
"@gitbook/react-openapi": minor
|
||||
---
|
||||
|
||||
Replace the Scalar API client behind "Test it" with a lightweight Try it panel.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep published revision URLs out of search results.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Track the displayed position and search request ID when a visitor opens a search result.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Update the GitBook API SDK for site revision responses.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix wide content in Updates blocks overflowing into the page outline.
|
||||
+2
-1
@@ -48,7 +48,8 @@
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.210.0",
|
||||
"@gitbook/api": "0.213.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"assert-never": "^1.4.0",
|
||||
|
||||
@@ -443,11 +443,6 @@ const testCases: TestsCase[] = [
|
||||
contentBaseURL: 'https://help.openloyalty.io',
|
||||
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
|
||||
},
|
||||
{
|
||||
name: 'retrozia.gitbook.io/retrozia',
|
||||
contentBaseURL: 'https://retrozia.gitbook.io',
|
||||
tests: [{ name: 'Home', url: '/retrozia' }],
|
||||
},
|
||||
{
|
||||
name: 'helpcenter.channable.com',
|
||||
contentBaseURL: 'https://helpcenter.channable.com',
|
||||
|
||||
@@ -442,6 +442,48 @@ const searchTestCases: Test[] = [
|
||||
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter opens the visible result while a new query loads',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
})}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
const searchPopup = page.getByTestId('search-popover');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
const initialSearch = await heldSearch('gitbook');
|
||||
const { siteSpaceId } = initialSearch.request().postDataJSON().scope;
|
||||
const topResult = searchPageResult(
|
||||
initialSearch,
|
||||
siteSpaceId,
|
||||
'Headings',
|
||||
'blocks/headings'
|
||||
);
|
||||
await initialSearch.fulfill({ json: [topResult] });
|
||||
const firstResult = searchPopup.getByTestId('search-page-result').first();
|
||||
await expect(firstResult).toHaveAttribute('href', topResult.href);
|
||||
|
||||
await searchInput.pressSequentially(' docs');
|
||||
const pendingSearch = await heldSearch('gitbook docs');
|
||||
await expect(searchPopup.locator('output[aria-busy="true"]')).toBeVisible();
|
||||
await expect(firstResult).toHaveAttribute('href', topResult.href);
|
||||
await expect(searchPopup.locator('[data-search-placeholder-row]')).toHaveCount(0);
|
||||
|
||||
await searchInput.press('Enter');
|
||||
await expect(searchPopup).toBeHidden();
|
||||
await expect
|
||||
.poll(() => new URL(page.url()).pathname)
|
||||
.toBe(new URL(topResult.href, page.url()).pathname);
|
||||
await pendingSearch.abort().catch(() => {});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter opens the result under the mouse',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@mermaid-js/mermaid-zenuml": "^0.2.2",
|
||||
"@modelcontextprotocol/sdk": "1.17.5",
|
||||
"@opennextjs/aws": "4.1.16",
|
||||
"@opennextjs/cloudflare": "1.20.17",
|
||||
"@opennextjs/aws": "4.2.0",
|
||||
"@opennextjs/cloudflare": "1.20.18",
|
||||
"@panzoom/panzoom": "^4.6.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
@@ -89,6 +89,7 @@
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^7.2.0",
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@scalar/api-client-react": "catalog:",
|
||||
"@tailwindcss/postcss": "^4.1.11",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
@@ -118,9 +119,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "./scripts/generate.sh",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/download-fonts.ts",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
|
||||
"generate:fonts": "bun ./scripts/generate-font-faces.ts",
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/fonts",
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts",
|
||||
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
|
||||
"build": "bun run generate:assets && next build --webpack",
|
||||
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { build } from 'bun';
|
||||
import { mkdir, rename, rm } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { SCALAR_RUNTIME_PATH } from '../src/components/DocumentView/OpenAPI/scalar-runtime-path';
|
||||
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const outputDir = join(scriptDir, '../public/~gitbook/static/scalar');
|
||||
const temporaryDir = join(outputDir, '.build');
|
||||
const scalarPackage = createRequire(import.meta.url)('@scalar/api-client-react/package.json') as {
|
||||
version: string;
|
||||
};
|
||||
|
||||
if (SCALAR_RUNTIME_PATH !== `scalar/scalar-api-client@${scalarPackage.version}.mjs`) {
|
||||
throw new Error(
|
||||
'Update SCALAR_RUNTIME_PATH for the installed @scalar/api-client-react version'
|
||||
);
|
||||
}
|
||||
|
||||
const reactShim = `
|
||||
const react = () => globalThis.__gitbookScalarReact;
|
||||
export const createContext = (...args) => react().createContext(...args);
|
||||
export const useContext = (...args) => react().useContext(...args);
|
||||
export const useEffect = (...args) => react().useEffect(...args);
|
||||
export const useRef = (...args) => react().useRef(...args);
|
||||
export const useSyncExternalStore = (...args) => react().useSyncExternalStore(...args);
|
||||
`;
|
||||
|
||||
const jsxRuntimeShim = `
|
||||
const runtime = () => globalThis.__gitbookScalarJSXRuntime;
|
||||
export const jsx = (...args) => runtime().jsx(...args);
|
||||
export const jsxs = (...args) => runtime().jsxs(...args);
|
||||
`;
|
||||
|
||||
await rm(outputDir, { force: true, recursive: true });
|
||||
await mkdir(temporaryDir, { recursive: true });
|
||||
|
||||
const result = await build({
|
||||
entrypoints: [join(scriptDir, 'scalar-runtime.ts')],
|
||||
format: 'esm',
|
||||
minify: true,
|
||||
outdir: temporaryDir,
|
||||
plugins: [
|
||||
{
|
||||
name: 'scalar-react-shims',
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^react$/ }, () => ({
|
||||
namespace: 'scalar-runtime',
|
||||
path: 'react',
|
||||
}));
|
||||
build.onResolve({ filter: /^react\/jsx-runtime$/ }, () => ({
|
||||
namespace: 'scalar-runtime',
|
||||
path: 'react-jsx-runtime',
|
||||
}));
|
||||
build.onLoad({ filter: /^react$/, namespace: 'scalar-runtime' }, () => ({
|
||||
contents: reactShim,
|
||||
loader: 'js',
|
||||
}));
|
||||
build.onLoad(
|
||||
{ filter: /^react-jsx-runtime$/, namespace: 'scalar-runtime' },
|
||||
() => ({
|
||||
contents: jsxRuntimeShim,
|
||||
loader: 'js',
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
target: 'browser',
|
||||
});
|
||||
|
||||
const [output] = result.outputs;
|
||||
if (!result.success || !output || result.outputs.length !== 1) {
|
||||
throw new Error(`Unable to build Scalar runtime: ${result.logs.join('\n')}`);
|
||||
}
|
||||
|
||||
const outputPath = join(outputDir, SCALAR_RUNTIME_PATH.replace('scalar/', ''));
|
||||
await rename(output.path, outputPath);
|
||||
await rm(temporaryDir, { force: true, recursive: true });
|
||||
@@ -0,0 +1 @@
|
||||
export { ApiClientModalProvider, useApiClientModal } from '@scalar/api-client-react';
|
||||
+3
-1
@@ -14,7 +14,8 @@ const SEARCH_FALLBACK_REASON =
|
||||
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
|
||||
const { asEmbeddable, query, scope, searchId } =
|
||||
(await request.json()) as SearchSiteContentRequest;
|
||||
const [context, siteURLData] = await Promise.all([
|
||||
getServerActionBaseContext({ isEmbeddable: asEmbeddable }),
|
||||
getSiteURLDataFromMiddleware(),
|
||||
@@ -40,6 +41,7 @@ export async function POST(request: NextRequest) {
|
||||
siteId: siteURLData.site,
|
||||
query,
|
||||
scope,
|
||||
searchId,
|
||||
})
|
||||
),
|
||||
throwIfDataError(
|
||||
|
||||
@@ -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
|
||||
]
|
||||
);
|
||||
|
||||
@@ -38,6 +38,7 @@ export type OpenAPIBlockClientContextProps = {
|
||||
/** Rendered on the server: both go through the async document pipeline. */
|
||||
headingNode: React.ReactNode;
|
||||
descriptionNode: React.ReactNode;
|
||||
scalarRuntimeURL: string;
|
||||
};
|
||||
|
||||
type OpenAPIBlockVariant =
|
||||
@@ -69,6 +70,7 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
|
||||
renderDocument: () => descriptionNode,
|
||||
renderHeading: () => headingNode,
|
||||
resolveProxyUrl: proxyUrl ? () => proxyUrl : undefined,
|
||||
scalarRuntimeURL: props.scalarRuntimeURL,
|
||||
};
|
||||
|
||||
switch (props.variant) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type OpenAPISchemasData,
|
||||
type OpenAPIWebhookData,
|
||||
checkIsValidLocale,
|
||||
extractOrigin,
|
||||
getAllServerOrigins,
|
||||
getOperationTitle,
|
||||
getSchemasHeading,
|
||||
@@ -16,7 +17,9 @@ import { PlainCodeBlock } from '../CodeBlock';
|
||||
import { DocumentView } from '../DocumentView';
|
||||
import { Heading } from '../Heading';
|
||||
import type { OpenAPIBlockClientContextProps } from './OpenAPIBlockClient';
|
||||
import { SCALAR_RUNTIME_PATH } from './scalar-runtime-path';
|
||||
import { DEFAULT_LOCALE, getSpaceLocale } from '@/intl/server';
|
||||
import { getAssetURL } from '@/lib/assets';
|
||||
import type { GitBookAnyContext } from '@/lib/context';
|
||||
import { GITBOOK_URL } from '@/lib/env';
|
||||
import { buildSignedProxyUrl } from '@/lib/openapi/proxy-token';
|
||||
@@ -121,6 +124,7 @@ export function getOpenAPIContext(args: {
|
||||
expandAllResponses: expandAllResponses || props.context.mode === 'print',
|
||||
expandAllModelSections: expandAllModelSections || props.context.mode === 'print',
|
||||
headless,
|
||||
scalarRuntimeURL: getAssetURL(SCALAR_RUNTIME_PATH),
|
||||
id: block.meta?.id,
|
||||
blockKey: block.key,
|
||||
locale,
|
||||
@@ -141,7 +145,7 @@ export function getOpenAPIBlockClientProps(args: {
|
||||
expandAllModelSections?: boolean;
|
||||
headless?: boolean;
|
||||
}): OpenAPIBlockClientContextProps {
|
||||
const { props, data, schemas, context } = args;
|
||||
const { props, data, schemas, specUrl, context } = args;
|
||||
const serverContext = getOpenAPIContext(args);
|
||||
const { renderCodeBlock, renderDocument, renderHeading, resolveProxyUrl, ...serializable } =
|
||||
serverContext;
|
||||
@@ -154,6 +158,10 @@ export function getOpenAPIBlockClientProps(args: {
|
||||
const descriptionDocument = data?.operation['x-gitbook-description-document'];
|
||||
|
||||
const origins = data ? getAllServerOrigins(data.servers) : [];
|
||||
const specOrigin = specUrl ? extractOrigin(specUrl) : null;
|
||||
if (specOrigin) {
|
||||
origins.push(specOrigin);
|
||||
}
|
||||
|
||||
return {
|
||||
...serializable,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const SCALAR_RUNTIME_PATH = 'scalar/scalar-api-client@1.3.46.mjs';
|
||||
@@ -0,0 +1,360 @@
|
||||
/* The vendor stylesheet is imported by ScalarApiModal so it ships with the lazy client chunk:
|
||||
its `group-has-*` rules make every DOM change restyle the whole document. */
|
||||
@reference "../../RootLayout/globals.css";
|
||||
|
||||
html,
|
||||
body {
|
||||
/** Override Scalar's overscroll-behavior */
|
||||
@apply !overscroll-auto;
|
||||
}
|
||||
|
||||
.light .scalar-modal-layout,
|
||||
.light .scalar-app,
|
||||
.light .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-300, 180 180 180)),
|
||||
rgb(var(--tint-12, 23 23 23)) 96%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.72)
|
||||
);
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-accent: #007d9c;
|
||||
|
||||
--scalar-background-1: rgb(var(--tint-1, 255 255 255));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 96%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 90%
|
||||
);
|
||||
--scalar-background-accent: #007d9c1f;
|
||||
--scalar-code-language-color-supersede: var(--scalar-color-1);
|
||||
--scalar-code-languages-background-supersede: var(--scalar-background-1);
|
||||
--scalar-border-color: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.08)
|
||||
);
|
||||
|
||||
--scalar-color-green: #0a6355;
|
||||
--scalar-color-red: #dc1b19;
|
||||
--scalar-color-yellow: #ffc90d;
|
||||
--scalar-color-blue: rgb(var(--primary-9, 52 109 219));
|
||||
--scalar-color-orange: #ff8d4d;
|
||||
--scalar-color-purple: #8250df;
|
||||
|
||||
--scalar-scrollbar-color: rgba(255, 255, 255, 0.24);
|
||||
--scalar-scrollbar-color-active: rgba(255, 255, 255, 0.48);
|
||||
|
||||
--scalar-button-1: rgb(49 53 56);
|
||||
--scalar-button-1-color: #fff;
|
||||
--scalar-button-1-hover: rgb(28 31 33);
|
||||
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
|
||||
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
|
||||
#eeeeed 0px 0 0 1px;
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--tint-12, 22 22 22));
|
||||
}
|
||||
.dark .scalar-modal-layout,
|
||||
.dark .scalar-app,
|
||||
.dark .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-700, 70 70 70)),
|
||||
rgb(var(--tint-12, 255 255 255)) 100%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.64)
|
||||
);
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-accent: #50b7e0;
|
||||
|
||||
--scalar-background-1: rgb(var(--tint-1, 22 22 22));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 92%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 88%
|
||||
);
|
||||
--scalar-background-accent: #8ab4f81f;
|
||||
--scalar-code-languages-background-supersede: var(--scalar-background-1);
|
||||
--scalar-border-color: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.08)
|
||||
);
|
||||
|
||||
--scalar-color-green: #56b6c2;
|
||||
--scalar-color-red: rgb(245 124 97);
|
||||
--scalar-color-yellow: #edbe20;
|
||||
--scalar-color-blue: rgb(var(--primary-9, 93 138 226));
|
||||
--scalar-color-orange: #d19a66;
|
||||
--scalar-color-purple: #5203d1;
|
||||
|
||||
--scalar-scrollbar-color: rgba(0, 0, 0, 0.18);
|
||||
--scalar-scrollbar-color-active: rgba(0, 0, 0, 0.36);
|
||||
|
||||
--scalar-button-1: #f6f6f6;
|
||||
--scalar-button-1-color: #000;
|
||||
--scalar-button-1-hover: #e7e7e7;
|
||||
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
|
||||
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px, 0 0 0
|
||||
1px rgba(255, 255, 255, 0.1);
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--tint-12, 255 255 255));
|
||||
}
|
||||
.scalar-modal-layout,
|
||||
.scalar-app,
|
||||
.scalar {
|
||||
--scalar-font: initial;
|
||||
--scalar-font-code: var(--font-mono);
|
||||
|
||||
--scalar-paragraph: 16px;
|
||||
--scalar-small: 14px;
|
||||
--scalar-mini: 13px;
|
||||
--scalar-micro: 12px;
|
||||
|
||||
--scalar-bold: 600;
|
||||
--scalar-semibold: 500;
|
||||
--scalar-regular: 400;
|
||||
|
||||
/* Font sizes for interactive applications (not rendered text content) */
|
||||
--scalar-font-size-1: 24px;
|
||||
--scalar-font-size-2: 16px;
|
||||
--scalar-font-size-3: 14px;
|
||||
--scalar-font-size-4: 13px;
|
||||
--scalar-font-size-5: 12px;
|
||||
|
||||
--scalar-line-height-1: 32px;
|
||||
--scalar-line-height-2: 24px;
|
||||
--scalar-line-height-3: 20px;
|
||||
--scalar-line-height-4: 18px;
|
||||
--scalar-line-height-5: 16px;
|
||||
|
||||
--scalar-app-header-height: 35px;
|
||||
}
|
||||
.scalar input::placeholder {
|
||||
color: var(--scalar-color-3);
|
||||
}
|
||||
.scalar .scalar-app-header {
|
||||
width: 100%;
|
||||
z-index: 1000;
|
||||
padding: 6px 12px 6px 12px;
|
||||
border-radius: 0.25rem 0.25rem 0 0;
|
||||
font-size: 14px;
|
||||
height: var(--scalar-app-header-height);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: 6px;
|
||||
}
|
||||
.scalar .scalar-api-client {
|
||||
max-height: calc(100dvh - (100px + var(--scalar-app-header-height))) !important;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.scalar-api-client__close {
|
||||
appearance: none;
|
||||
border: none;
|
||||
outline: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: transparent;
|
||||
color: var(--scalar-color-1);
|
||||
font-size: var(--scalar-small);
|
||||
font-weight: var(--scalar-semibold);
|
||||
}
|
||||
.scalar-api-client__close:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
.scalar .scalar-app-layout {
|
||||
background: var(--scalar-background-3);
|
||||
height: calc(100dvh - 100px);
|
||||
max-width: 1280px;
|
||||
width: 100%;
|
||||
margin: auto;
|
||||
opacity: 0;
|
||||
animation: scalarapiclientfadein 0.35s forwards;
|
||||
z-index: 1002;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@keyframes scalarapiclientfadein {
|
||||
from {
|
||||
transform: translate3d(0, 20px, 0) scale(0.985);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translate3d(0, 0, 0) scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.scalar .scalar-app-exit {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.62);
|
||||
transition: all 0.3s ease-in-out;
|
||||
z-index: 1000;
|
||||
cursor: pointer;
|
||||
animation: scalardrawerexitfadein 0.35s forwards;
|
||||
}
|
||||
@keyframes scalardrawerexitfadein {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.scalar-container {
|
||||
overflow: hidden;
|
||||
visibility: visible;
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.scalar .url-form-input {
|
||||
min-height: auto !important;
|
||||
}
|
||||
|
||||
.scalar .scalar-container {
|
||||
line-height: normal;
|
||||
}
|
||||
.scalar .scalar-app-header span {
|
||||
color: var(--scalar-color-3);
|
||||
}
|
||||
.scalar .scalar-app-header a {
|
||||
color: var(--scalar-color-1);
|
||||
}
|
||||
.scalar .scalar-app-header a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.scalar-activate {
|
||||
width: fit-content;
|
||||
line-height: 24px;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.scalar-activate-button {
|
||||
@apply flex gap-2 items-center;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
|
||||
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
|
||||
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
|
||||
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
|
||||
@apply grow-0 shrink-0 truncate;
|
||||
@apply text-[13px] px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
|
||||
}
|
||||
|
||||
.scalar-activate-button svg {
|
||||
@apply size-2.5;
|
||||
}
|
||||
|
||||
/* Same size as the play icon it replaces, so the button doesn't shift while loading. */
|
||||
.scalar-activate-button .scalar-activate-spinner {
|
||||
@apply animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
.scalar-app-loading {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.scalar .request-method {
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* Use :where to lower specificity to 0 */
|
||||
.scalar .custom-scroll {
|
||||
overflow-y: auto;
|
||||
scrollbar-color: transparent transparent;
|
||||
scrollbar-width: thin;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.scalar .custom-scroll:hover {
|
||||
scrollbar-color: rgba(0, 0, 0, 0.24) transparent;
|
||||
}
|
||||
.dark .scalar .custom-scroll:hover {
|
||||
scrollbar-color: rgba(255, 255, 255, 0.24) transparent;
|
||||
}
|
||||
.scalar .custom-scroll:hover::-webkit-scrollbar-thumb {
|
||||
background: var(--scalar-scrollbar-color, var(--default-theme-scrollbar-color));
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-thumb:active {
|
||||
background: var(--scalar-scrollbar-color-active, var(--default-theme-scrollbar-color-active));
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar {
|
||||
height: 12px;
|
||||
width: 12px;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.scalar .custom-scroll::-webkit-scrollbar-thumb {
|
||||
border-radius: 20px;
|
||||
background: transparent;
|
||||
background-clip: content-box;
|
||||
border: 3px solid transparent;
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.scalar .custom-scroll {
|
||||
padding-right: 12px;
|
||||
}
|
||||
}
|
||||
.dark .scalar .client-wrapper-bg-color {
|
||||
background: linear-gradient(
|
||||
color-mix(in srgb, var(--tw-bg-base) 6%, transparent) 1%,
|
||||
color-mix(in srgb, var(--scalar-background-1) 30%, black) 9%
|
||||
);
|
||||
}
|
||||
.light .scalar .client-wrapper-bg-color {
|
||||
background-color: var(--scalar-background-2) !important;
|
||||
}
|
||||
.scalar .gitbook-show {
|
||||
display: block !important;
|
||||
}
|
||||
.scalar .gitbook-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
@reference "../../RootLayout/globals.css";
|
||||
@import './tryit.css';
|
||||
@import './scalar.css';
|
||||
|
||||
/* Layout Components */
|
||||
.openapi-operation,
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
@reference "../../RootLayout/globals.css";
|
||||
|
||||
.openapi-tryit-activate {
|
||||
@apply flex items-center w-fit;
|
||||
}
|
||||
|
||||
.openapi-tryit-button {
|
||||
@apply flex gap-2 items-center cursor-pointer;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
|
||||
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
|
||||
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
|
||||
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
|
||||
@apply grow-0 shrink-0 truncate;
|
||||
@apply text-[13px] leading-6 px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
|
||||
}
|
||||
|
||||
.openapi-tryit-button svg {
|
||||
@apply size-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-button-spinner {
|
||||
@apply animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
/* Dialog */
|
||||
.openapi-tryit {
|
||||
@apply m-auto p-0 w-[min(72rem,calc(100vw-2rem))] h-[min(48rem,calc(100dvh-2rem))] max-w-none max-h-none;
|
||||
@apply bg-tint-base text-tint border border-tint-subtle shadow-2xl overflow-hidden;
|
||||
@apply rounded-xl straight-corners:rounded-none circular-corners:rounded-2xl;
|
||||
}
|
||||
|
||||
.openapi-tryit::backdrop {
|
||||
@apply bg-tint-12/40 backdrop-blur-xs;
|
||||
}
|
||||
|
||||
.openapi-tryit-layout {
|
||||
@apply flex flex-col h-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-header {
|
||||
@apply flex items-center gap-3 px-4 py-3 border-b border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-url {
|
||||
@apply flex-1 min-w-0 truncate font-mono text-sm text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-url-server {
|
||||
@apply text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-send {
|
||||
@apply shrink-0 cursor-pointer px-3 py-1 text-sm font-medium;
|
||||
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full transition-colors;
|
||||
}
|
||||
|
||||
.openapi-tryit-close {
|
||||
@apply shrink-0 cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-close svg {
|
||||
@apply size-4;
|
||||
}
|
||||
|
||||
.openapi-tryit-body {
|
||||
@apply flex-1 min-h-0 grid grid-cols-1 md:grid-cols-2 overflow-y-auto md:overflow-hidden;
|
||||
}
|
||||
|
||||
.openapi-tryit-request {
|
||||
@apply flex flex-col gap-5 p-4 md:overflow-y-auto border-b md:border-b-0 md:border-r border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-section {
|
||||
@apply flex flex-col gap-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-section-header {
|
||||
@apply flex items-center justify-between gap-3;
|
||||
}
|
||||
|
||||
.openapi-tryit-section-title {
|
||||
@apply text-xs font-semibold uppercase tracking-wide text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-field {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-label {
|
||||
@apply flex flex-wrap items-baseline gap-x-1.5 text-[0.813rem];
|
||||
}
|
||||
|
||||
.openapi-tryit-field-name {
|
||||
@apply font-mono text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-required {
|
||||
@apply text-danger;
|
||||
}
|
||||
|
||||
.openapi-tryit-field-description {
|
||||
@apply text-xs text-tint line-clamp-2 basis-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-input {
|
||||
@apply w-full min-w-0 px-2.5 py-1.5 text-sm font-mono bg-tint-base text-tint-strong border border-tint-subtle placeholder:text-tint/60;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
@apply outline-none focus:border-primary focus:ring-2 focus:ring-primary/20;
|
||||
}
|
||||
|
||||
.openapi-tryit-input-small {
|
||||
@apply w-auto py-1 text-xs;
|
||||
}
|
||||
|
||||
.openapi-tryit-code {
|
||||
@apply resize-y leading-5 whitespace-pre;
|
||||
}
|
||||
|
||||
.openapi-tryit-invalid {
|
||||
@apply border-danger;
|
||||
}
|
||||
|
||||
.openapi-tryit-file {
|
||||
@apply text-sm text-tint file:mr-3 file:px-2.5 file:py-1 file:border file:border-tint-subtle file:bg-tint file:text-tint-strong file:rounded-md file:cursor-pointer;
|
||||
}
|
||||
|
||||
.openapi-tryit-auth {
|
||||
@apply grid grid-cols-1 sm:grid-cols-2 gap-2.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-hint {
|
||||
@apply text-xs text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-alert {
|
||||
@apply text-sm px-3 py-2 bg-danger text-danger border border-danger-subtle rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-table {
|
||||
@apply flex flex-col border border-tint-subtle divide-y divide-tint-subtle;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-table:empty {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
/* Checkbox · name · value · remove, as a row of a key/value table. */
|
||||
.openapi-tryit-row {
|
||||
@apply grid grid-cols-[auto_minmax(0,1fr)_minmax(0,1.3fr)_1.75rem] gap-x-2 items-center px-2 py-1.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-input {
|
||||
@apply py-1 text-[0.813rem];
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-field-label {
|
||||
@apply min-w-0;
|
||||
}
|
||||
|
||||
.openapi-tryit-row .openapi-tryit-field-name {
|
||||
@apply truncate;
|
||||
}
|
||||
|
||||
.openapi-tryit-check {
|
||||
@apply size-3.5 cursor-pointer disabled:cursor-default disabled:opacity-60;
|
||||
accent-color: rgb(var(--primary-9, 52 109 219));
|
||||
}
|
||||
|
||||
.openapi-tryit-row-remove {
|
||||
@apply cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
.openapi-tryit-row-remove svg {
|
||||
@apply size-3.5;
|
||||
}
|
||||
|
||||
.openapi-tryit-add {
|
||||
@apply self-start cursor-pointer px-2.5 py-1 text-xs text-tint-strong border border-dashed border-tint-subtle hover:bg-tint-hover;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full;
|
||||
}
|
||||
|
||||
/* Response */
|
||||
.openapi-tryit-response {
|
||||
@apply flex flex-col gap-3 p-4 min-h-48 md:overflow-y-auto bg-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-empty {
|
||||
@apply items-center justify-center text-sm text-tint;
|
||||
}
|
||||
|
||||
.openapi-tryit-spinner {
|
||||
@apply size-5 rounded-full border-2 border-tint-subtle border-t-primary animate-spin motion-reduce:animate-none;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-meta {
|
||||
@apply flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-tint font-mono;
|
||||
}
|
||||
|
||||
.openapi-tryit-tabs {
|
||||
@apply ml-auto flex gap-1;
|
||||
}
|
||||
|
||||
.openapi-tryit-tab {
|
||||
@apply cursor-pointer px-2 py-1 text-xs rounded-md straight-corners:rounded-none circular-corners:rounded-full text-tint hover:text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-tab[aria-selected='true'] {
|
||||
@apply bg-tint-active text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-response-body {
|
||||
@apply m-0 p-3 text-xs leading-5 font-mono whitespace-pre-wrap break-all text-tint-strong bg-tint-base border border-tint-subtle;
|
||||
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers {
|
||||
@apply m-0 flex flex-col text-xs font-mono;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers > div {
|
||||
@apply grid grid-cols-[minmax(8rem,auto)_1fr] gap-3 py-1.5 border-b border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers dt {
|
||||
@apply text-tint-strong;
|
||||
}
|
||||
|
||||
.openapi-tryit-headers dd {
|
||||
@apply m-0 text-tint break-all;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary {
|
||||
@apply flex flex-col gap-3 text-sm;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary img {
|
||||
@apply max-w-full max-h-96 self-start border border-tint-subtle;
|
||||
}
|
||||
|
||||
.openapi-tryit-binary a {
|
||||
@apply text-primary underline;
|
||||
}
|
||||
@@ -75,7 +75,7 @@ export function Update(props: BlockProps<DocumentBlockUpdate>) {
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style="flex flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
style="flex min-w-0 flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
|
||||
/>
|
||||
</FilteredUpdate>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { LinkContext } from '../primitives';
|
||||
import { useIsVisible } from '../VisibilityContext';
|
||||
@@ -37,9 +39,10 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
trackEvent({
|
||||
type: 'search_open',
|
||||
});
|
||||
trackEvent(
|
||||
{ type: 'search_open' },
|
||||
{ pageId: null, displayContext: SiteInsightsDisplayContext.Embed }
|
||||
);
|
||||
}, [trackEvent, isVisible]);
|
||||
|
||||
const tabsRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -56,6 +59,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -79,6 +83,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import { PageActionsDropdown } from './PageActionsDropdown';
|
||||
import { getPageActionsURLs } from './pageActionsURLs';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
/**
|
||||
* Menu of the page actions. It loads what it shows from the context and the page alone, so it can be
|
||||
* rendered and cached apart from the page body.
|
||||
*/
|
||||
export async function PageActionsMenu(props: {
|
||||
context: GitBookSiteContext;
|
||||
page: RevisionPageDocument;
|
||||
}) {
|
||||
const { context, page } = props;
|
||||
const { linker, revision } = context;
|
||||
|
||||
return (
|
||||
<PageActionsDropdown
|
||||
siteTitle={context.site.title}
|
||||
urls={await getPageActionsURLs(context, page)}
|
||||
actions={context.customization.pageActions}
|
||||
page={{
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
path: page.path,
|
||||
href: linker.toPathForPage({ pages: revision.pages, page }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { getPageGitMetadata } = await import('./pageActionsData');
|
||||
|
||||
const page = {
|
||||
id: 'page-1',
|
||||
title: 'Introduction',
|
||||
kind: 'sheet',
|
||||
type: 'document',
|
||||
path: 'readme',
|
||||
slug: 'readme',
|
||||
pages: [],
|
||||
} as RevisionPageDocument;
|
||||
|
||||
const git = {
|
||||
oid: 'abc123',
|
||||
path: 'README.md',
|
||||
};
|
||||
|
||||
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
|
||||
const getRevisionPageByPath = mock(async () => ({
|
||||
data: {
|
||||
...page,
|
||||
git,
|
||||
},
|
||||
}));
|
||||
|
||||
const context = {
|
||||
revisionId: 'revision-1',
|
||||
customization: {
|
||||
pageActions: {
|
||||
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
|
||||
},
|
||||
},
|
||||
space: {
|
||||
id: 'space-1',
|
||||
gitSync:
|
||||
options.gitSync === false
|
||||
? undefined
|
||||
: {
|
||||
url: 'https://github.com/gitbook/example/tree/main',
|
||||
},
|
||||
},
|
||||
dataFetcher: { getRevisionPageByPath },
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
return { context, getRevisionPageByPath };
|
||||
}
|
||||
|
||||
describe('getPageGitMetadata', () => {
|
||||
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
|
||||
|
||||
const result = await getPageGitMetadata(context, page);
|
||||
|
||||
expect(getRevisionPageByPath).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
path: 'readme',
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
expect(result).toEqual(git);
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata already on the page', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
|
||||
|
||||
const result = await getPageGitMetadata(context, { ...page, git });
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result).toEqual(git);
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata when the action is disabled', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
|
||||
|
||||
const result = await getPageGitMetadata(context, page);
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata without Git Sync', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({
|
||||
gitEnabled: true,
|
||||
gitSync: false,
|
||||
});
|
||||
|
||||
const result = await getPageGitMetadata(context, page);
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
|
||||
|
||||
const CONFIGURABLE_PAGE_ACTIONS = [
|
||||
CustomizationPageActionType.Assistant,
|
||||
CustomizationPageActionType.ExternalAi,
|
||||
CustomizationPageActionType.Markdown,
|
||||
CustomizationPageActionType.Mcp,
|
||||
CustomizationPageActionType.Pdf,
|
||||
CustomizationPageActionType.Git,
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a given built-in page action is enabled.
|
||||
*/
|
||||
export function isPageActionEnabled(
|
||||
customization: GitBookSiteContext['customization'],
|
||||
type: CustomizationPageActionType
|
||||
): boolean {
|
||||
const { pageActions } = customization;
|
||||
if (pageActions.items) {
|
||||
return pageActions.items.includes(type);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether any of the configured page actions is enabled. The RSS feed is not part of them: it is
|
||||
* only offered on pages with an updates block.
|
||||
*/
|
||||
export function hasConfiguredPageActions(context: Pick<GitBookSiteContext, 'customization'>) {
|
||||
const { customization } = context;
|
||||
return CONFIGURABLE_PAGE_ACTIONS.some((type) => {
|
||||
if (type === CustomizationPageActionType.Mcp && !isSiteMcpEnabled(context)) {
|
||||
return false;
|
||||
}
|
||||
return isPageActionEnabled(customization, type);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Git metadata of a page for the Edit on Git action, or nothing when that action is not shown.
|
||||
*/
|
||||
export async function getPageGitMetadata(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument
|
||||
): Promise<RevisionPageDocument['git']> {
|
||||
if (
|
||||
!context.space.gitSync?.url ||
|
||||
!isPageActionEnabled(context.customization, CustomizationPageActionType.Git)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (page.git) {
|
||||
return page.git;
|
||||
}
|
||||
|
||||
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
|
||||
const response = await context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
path: page.path,
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
const pageWithMetadata = response.data;
|
||||
return pageWithMetadata?.type === 'document' ? pageWithMetadata.git : undefined;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import urlJoin from 'url-join';
|
||||
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import { getPDFURLSearchParams } from '../PDF';
|
||||
import { getPageGitMetadata, isPageActionEnabled } from './pageActionsData';
|
||||
import type { PageActionsDropdownURLs } from './PageActionsDropdown';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { getPageDocument } from '@/lib/data';
|
||||
import { hasTopLevelBlock } from '@/lib/document';
|
||||
import { hasAdaptiveMcpEndpoint, isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { getPageRSSURL } from '@/routes/rss';
|
||||
|
||||
/**
|
||||
* Return the URLs for the page actions. The page's Git path and RSS feed are loaded here, so the
|
||||
* page actions depend on the context and the page alone.
|
||||
*/
|
||||
export async function getPageActionsURLs(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument
|
||||
): Promise<PageActionsDropdownURLs> {
|
||||
const [document, git] = await Promise.all([
|
||||
getPageDocument(context, page),
|
||||
getPageGitMetadata(context, page),
|
||||
]);
|
||||
// Update blocks can only be at the top level of the document, so we optimize the check.
|
||||
const withRSSFeed = document
|
||||
? hasTopLevelBlock(document, (block) => block.type === 'updates')
|
||||
: false;
|
||||
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
|
||||
const { gitSync } = context.space;
|
||||
|
||||
return {
|
||||
html: context.linker.toAbsoluteURL(pagePath),
|
||||
// For the markdown URL, we use the page.path to ensure it works for the default page.
|
||||
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
|
||||
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
|
||||
editOnGit:
|
||||
gitSync?.url && git
|
||||
? {
|
||||
provider: gitSync.installationProvider,
|
||||
url: urlJoin(gitSync.url, git.path),
|
||||
}
|
||||
: undefined,
|
||||
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
|
||||
? context.linker.toPathInSpace(
|
||||
`~gitbook/pdf?${getPDFURLSearchParams({
|
||||
page: page.id,
|
||||
only: true,
|
||||
limit: 100,
|
||||
}).toString()}`
|
||||
)
|
||||
: undefined,
|
||||
mcp: isMcpPageActionEnabled(context) ? getPageActionsMCPURL(context) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the MCP URL to be used in the page actions dropdown.
|
||||
*/
|
||||
function getPageActionsMCPURL(context: GitBookSiteContext) {
|
||||
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
|
||||
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
|
||||
|
||||
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
|
||||
}
|
||||
@@ -1,24 +1,19 @@
|
||||
import assertNever from 'assert-never';
|
||||
import urlJoin from 'url-join';
|
||||
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
type RevisionPage,
|
||||
type RevisionPageDocument,
|
||||
type SiteSection,
|
||||
type SiteSectionGroup,
|
||||
import type {
|
||||
RevisionPage,
|
||||
RevisionPageDocument,
|
||||
SiteSection,
|
||||
SiteSectionGroup,
|
||||
} from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { SpacesDropdownMenuItems, type VariantSpace } from '../Header/SpacesDropdownMenuItem';
|
||||
import { CONTENT_STYLE, CONTENT_STYLE_REDUCED } from '../layout';
|
||||
import {
|
||||
PageActionsDropdown,
|
||||
type PageActionsDropdownURLs,
|
||||
} from '../PageActions/PageActionsDropdown';
|
||||
import { hasConfiguredPageActions } from '../PageActions/pageActionsData';
|
||||
import { PageActionsMenu } from '../PageActions/PageActionsMenu';
|
||||
import { PageAsideToggleButton } from '../PageAside/PageAsideButton';
|
||||
import { PageIcon } from '../PageIcon';
|
||||
import { getPDFURLSearchParams } from '../PDF';
|
||||
import {
|
||||
findBestTargetURL,
|
||||
getTargetURLForSiteSpace,
|
||||
@@ -27,11 +22,9 @@ import { categorizeVariants } from '../SpaceLayout/categorizeVariants';
|
||||
import { BreadcrumbItemDropdown, type BreadcrumbSibling } from './BreadcrumbItemDropdown';
|
||||
import { PageTags } from './PageTags';
|
||||
import type { GitBookSiteContext, SiteStructureNode } from '@/lib/context';
|
||||
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
|
||||
import { type AncestorRevisionPage, resolveFirstDocument } from '@/lib/pages';
|
||||
import { getLocalizedTitle } from '@/lib/sites';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getPageRSSURL } from '@/routes/rss';
|
||||
|
||||
export async function PageHeader(props: {
|
||||
context: GitBookSiteContext;
|
||||
@@ -146,15 +139,7 @@ export async function PageHeader(props: {
|
||||
// Show page actions if *any* of the configured actions are enabled, or if the RSS feed is
|
||||
// available. RSS is contextual (only on update/blog index pages) and is not part of the
|
||||
// configured `items` list, so it is checked separately.
|
||||
const hasConfiguredPageActions = [
|
||||
CustomizationPageActionType.Assistant,
|
||||
CustomizationPageActionType.ExternalAi,
|
||||
CustomizationPageActionType.Markdown,
|
||||
CustomizationPageActionType.Mcp,
|
||||
CustomizationPageActionType.Pdf,
|
||||
CustomizationPageActionType.Git,
|
||||
].some((type) => isPageActionEnabled(context.customization, type));
|
||||
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions || withRSSFeed);
|
||||
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions(context) || withRSSFeed);
|
||||
|
||||
if (!page.layout.title && !page.layout.description && !hasPageActions) {
|
||||
return null;
|
||||
@@ -181,19 +166,7 @@ export async function PageHeader(props: {
|
||||
]
|
||||
)}
|
||||
>
|
||||
{hasPageActions ? (
|
||||
<PageActionsDropdown
|
||||
siteTitle={context.site.title}
|
||||
urls={getPageActionsURLs({ context, page, withRSSFeed })}
|
||||
actions={context.customization.pageActions}
|
||||
page={{
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
path: page.path,
|
||||
href: linker.toPathForPage({ pages: revision.pages, page }),
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{hasPageActions ? <PageActionsMenu context={context} page={page} /> : null}
|
||||
<PageAsideToggleButton />
|
||||
</div>
|
||||
);
|
||||
@@ -520,67 +493,3 @@ function BreadcrumbSeparator() {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the URLs for the page actions.
|
||||
*/
|
||||
function getPageActionsURLs({
|
||||
context,
|
||||
page,
|
||||
withRSSFeed,
|
||||
}: {
|
||||
context: GitBookSiteContext;
|
||||
page: RevisionPageDocument;
|
||||
withRSSFeed: boolean;
|
||||
}): PageActionsDropdownURLs {
|
||||
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
|
||||
return {
|
||||
html: context.linker.toAbsoluteURL(pagePath),
|
||||
// For the markdown URL, we use the page.path to ensure it works for the default page.
|
||||
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
|
||||
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
|
||||
editOnGit:
|
||||
isPageActionEnabled(context.customization, CustomizationPageActionType.Git) &&
|
||||
context.space.gitSync?.url &&
|
||||
page.git
|
||||
? {
|
||||
provider: context.space?.gitSync?.installationProvider,
|
||||
url: urlJoin(context.space.gitSync.url, page.git.path),
|
||||
}
|
||||
: undefined,
|
||||
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
|
||||
? context.linker.toPathInSpace(
|
||||
`~gitbook/pdf?${getPDFURLSearchParams({
|
||||
page: page.id,
|
||||
only: true,
|
||||
limit: 100,
|
||||
}).toString()}`
|
||||
)
|
||||
: undefined,
|
||||
mcp: getPageActionsMCPURL(context),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a given built-in page action is enabled.
|
||||
*/
|
||||
function isPageActionEnabled(
|
||||
customization: GitBookSiteContext['customization'],
|
||||
type: CustomizationPageActionType
|
||||
): boolean {
|
||||
const { pageActions } = customization;
|
||||
if (pageActions.items) {
|
||||
return pageActions.items.includes(type);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the MCP URL to be used in the page actions dropdown.
|
||||
*/
|
||||
function getPageActionsMCPURL(context: GitBookSiteContext) {
|
||||
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
|
||||
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
|
||||
|
||||
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ export function SearchContainer({
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
@@ -178,6 +179,7 @@ export function SearchContainer({
|
||||
query={query}
|
||||
results={results}
|
||||
resultsId={resultsId}
|
||||
resultsQuery={resultsQuery}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
|
||||
@@ -27,6 +27,7 @@ export function SearchFrame(props: {
|
||||
query: string;
|
||||
results: ResultType[];
|
||||
resultsId: string;
|
||||
resultsQuery: string;
|
||||
resultsRef: React.Ref<SearchResultsRef>;
|
||||
onResultSelect?: () => void;
|
||||
/** Select the result under the mouse, so hover and keyboard share one highlight. */
|
||||
@@ -50,6 +51,7 @@ export function SearchFrame(props: {
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
onResultSelect,
|
||||
onResultHover,
|
||||
@@ -78,7 +80,7 @@ export function SearchFrame(props: {
|
||||
fetching ? 'block animate-fade-in' : 'hidden animate-fade-out-slow'
|
||||
)}
|
||||
style={{
|
||||
animationDelay: fetching ? '2s' : undefined,
|
||||
animationDelay: fetching && results.length === 0 ? '2s' : undefined,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -118,7 +120,7 @@ export function SearchFrame(props: {
|
||||
) : (
|
||||
<SearchResults
|
||||
ref={resultsRef}
|
||||
query={query}
|
||||
query={resultsQuery}
|
||||
id={resultsId}
|
||||
fetching={fetching}
|
||||
results={results}
|
||||
|
||||
@@ -135,7 +135,7 @@ export const SearchInput = React.forwardRef<HTMLDivElement, SearchInputProps>(
|
||||
}
|
||||
}
|
||||
trailing={
|
||||
!showAsk && value && resultsCount > 0 ? (
|
||||
!showAsk && !fetching && value && resultsCount > 0 ? (
|
||||
<div className="animate-blur-in mr-2 text-sm text-tint-subtle">
|
||||
{t(language, 'search_results_count', resultsCount.toString())}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useResizeObserver } from '../hooks';
|
||||
import { Tooltip } from '../primitives';
|
||||
import { getPageResultPresentation } from './getPageResultHref';
|
||||
import { HighlightQuery } from './HighlightQuery';
|
||||
import type { ComputedPageResult } from './search-types';
|
||||
import type { ComputedPageResult, SearchResultSource } from './search-types';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -14,13 +14,15 @@ import { tcls } from '@/lib/tailwind';
|
||||
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
|
||||
props: {
|
||||
query: string;
|
||||
item: ComputedPageResult;
|
||||
item: ComputedPageResult & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, style, ...rest } = props;
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const { preview: bestSection, description, href } = getPageResultPresentation(item);
|
||||
@@ -30,7 +32,9 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
|
||||
const insights = {
|
||||
type: 'search_open_result' as const,
|
||||
query,
|
||||
...item.search,
|
||||
position,
|
||||
resultsCount,
|
||||
result: {
|
||||
pageId: item.pageId,
|
||||
spaceId: item.spaceId,
|
||||
|
||||
@@ -4,24 +4,36 @@ import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { Favicon } from '../utils';
|
||||
import { HighlightQuery } from './HighlightQuery';
|
||||
import type { ComputedRecordResult } from './search-types';
|
||||
import type { ComputedRecordResult, SearchResultSource } from './search-types';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
|
||||
export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem(
|
||||
props: {
|
||||
query: string;
|
||||
item: ComputedRecordResult;
|
||||
item: ComputedRecordResult & SearchResultSource;
|
||||
position: number;
|
||||
resultsCount: number;
|
||||
active: boolean;
|
||||
style?: React.CSSProperties;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>
|
||||
) {
|
||||
const { query, item, active, style, ...rest } = props;
|
||||
const { query, item, active, position, resultsCount, style, ...rest } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const domain = getDomain(item.href);
|
||||
|
||||
const insights = {
|
||||
type: 'search_open_result' as const,
|
||||
...item.search,
|
||||
position,
|
||||
resultsCount,
|
||||
result: {
|
||||
recordId: item.id,
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<SearchResultItem
|
||||
ref={ref}
|
||||
@@ -36,13 +48,7 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
|
||||
fallback={<Icon icon="memo" className="size-4" />}
|
||||
/>
|
||||
}
|
||||
insights={{
|
||||
type: 'search_open_result',
|
||||
query,
|
||||
result: {
|
||||
recordId: item.id,
|
||||
},
|
||||
}}
|
||||
insights={insights}
|
||||
aria-label={tString(language, 'search_page_result_title', item.title)}
|
||||
style={{ ...style }}
|
||||
{...rest}
|
||||
|
||||
@@ -72,7 +72,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
|
||||
const language = useLanguage();
|
||||
const { siteSpaceId } = useCurrentContent();
|
||||
const shouldAnimateResults = !query || fetching;
|
||||
const shouldAnimateResults = !query;
|
||||
const previousCursor = React.useRef<number | null>(cursor);
|
||||
const seenResultKeys = React.useRef(new Set<string>());
|
||||
const lastQuery = React.useRef(query);
|
||||
@@ -228,9 +228,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
// users should keep their place in it.
|
||||
if (navigatesCurrentWindow(event)) {
|
||||
event.currentTarget.blur();
|
||||
onResultSelect?.();
|
||||
}
|
||||
|
||||
onResultSelect?.();
|
||||
};
|
||||
const resultItemProps = {
|
||||
'aria-posinset': index + 1,
|
||||
@@ -272,6 +271,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
}}
|
||||
query={query}
|
||||
item={item}
|
||||
position={index + 1}
|
||||
resultsCount={results.length}
|
||||
active={index === cursor}
|
||||
style={{
|
||||
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
|
||||
@@ -341,6 +342,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
key={itemKey}
|
||||
query={query}
|
||||
item={item}
|
||||
position={index + 1}
|
||||
resultsCount={results.length}
|
||||
active={index === cursor}
|
||||
style={{
|
||||
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
|
||||
@@ -359,15 +362,11 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
{!fetching && results.length === 0 ? noResults : null}
|
||||
</>
|
||||
)}
|
||||
{fetching ? (
|
||||
{fetching && results.length === 0 ? (
|
||||
<div
|
||||
role="status"
|
||||
aria-busy="true"
|
||||
className={tcls(
|
||||
results.length > 0 ? 'mt-1' : '',
|
||||
'flex flex-col gap-1',
|
||||
'animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] motion-reduce:animate-none'
|
||||
)}
|
||||
className="flex animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] flex-col gap-1 motion-reduce:animate-none"
|
||||
>
|
||||
<SearchResultsPlaceholder />
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import type { OrderedComputedResult } from './search-types';
|
||||
|
||||
describe('computeFilterSiteSpaceIds', () => {
|
||||
@@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterResultsBySiteSpaces', () => {
|
||||
describe('getDisplayedSearchResults', () => {
|
||||
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
|
||||
type: 'page',
|
||||
id,
|
||||
@@ -52,7 +52,7 @@ describe('filterResultsBySiteSpaces', () => {
|
||||
|
||||
it('keeps the server order and drops pages outside the scope', () => {
|
||||
const results = [page('a', 'current'), page('b', 'other'), page('c', 'current'), page('d')];
|
||||
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
|
||||
expect(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([
|
||||
'a',
|
||||
'c',
|
||||
]);
|
||||
@@ -60,6 +60,24 @@ describe('filterResultsBySiteSpaces', () => {
|
||||
|
||||
it('returns every result when the scope is unrestricted', () => {
|
||||
const results = [page('b', 'other'), page('a', 'current')];
|
||||
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
|
||||
expect(getDisplayedSearchResults(results, undefined)).toBe(results);
|
||||
});
|
||||
|
||||
it('caps the displayed list after applying the site space filter', () => {
|
||||
const pages = Array.from({ length: 10 }, (_, index) => page(`page-${index}`, 'current'));
|
||||
const records = Array.from({ length: 11 }, (_, index): OrderedComputedResult => ({
|
||||
type: 'record',
|
||||
id: `record-${index}`,
|
||||
title: `Record ${index}`,
|
||||
description: undefined,
|
||||
href: `/record-${index}`,
|
||||
score: 1,
|
||||
}));
|
||||
const results = [page('hidden', 'other'), ...pages, ...records];
|
||||
|
||||
expect(getDisplayedSearchResults(results, ['current'])).toEqual([
|
||||
...pages,
|
||||
...records.slice(0, 10),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { OrderedComputedResult } from './search-types';
|
||||
import type { SearchScope } from './useSearch';
|
||||
|
||||
// Keep aligned with SiteInsightsSearchResultNumber in the GitBook API schema.
|
||||
const MAX_DISPLAYED_SEARCH_RESULTS = 20;
|
||||
|
||||
/**
|
||||
* Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction.
|
||||
*
|
||||
@@ -29,20 +32,20 @@ export function computeFilterSiteSpaceIds(
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
|
||||
export function filterResultsBySiteSpaces(
|
||||
results: OrderedComputedResult[],
|
||||
/** Keep the first results in server order within the selected site spaces. */
|
||||
export function getDisplayedSearchResults<Result extends OrderedComputedResult>(
|
||||
results: Result[],
|
||||
allowedSiteSpaceIds: string[] | undefined
|
||||
): OrderedComputedResult[] {
|
||||
if (!allowedSiteSpaceIds) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const allowed = new Set(allowedSiteSpaceIds);
|
||||
|
||||
return results.filter(
|
||||
(result) =>
|
||||
result.type === 'record' ||
|
||||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
|
||||
);
|
||||
): Result[] {
|
||||
const allowed = allowedSiteSpaceIds && new Set(allowedSiteSpaceIds);
|
||||
const matching = allowed
|
||||
? results.filter(
|
||||
(result) =>
|
||||
result.type === 'record' ||
|
||||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
|
||||
)
|
||||
: results;
|
||||
return matching.length > MAX_DISPLAYED_SEARCH_RESULTS
|
||||
? matching.slice(0, MAX_DISPLAYED_SEARCH_RESULTS)
|
||||
: matching;
|
||||
}
|
||||
|
||||
@@ -124,11 +124,12 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
|
||||
const search = async (input: {
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope: SearchSiteContentScope;
|
||||
signal: AbortSignal;
|
||||
asEmbeddable: boolean;
|
||||
}): Promise<DirectSearchOutcome> => {
|
||||
const { query, scope, signal, asEmbeddable } = input;
|
||||
const { query, searchId, scope, signal, asEmbeddable } = input;
|
||||
if (!directSearch) {
|
||||
return { type: 'route' };
|
||||
}
|
||||
@@ -163,7 +164,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope)),
|
||||
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
|
||||
credentials: 'omit',
|
||||
signal: request.signal,
|
||||
});
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { IconName } from '@gitbook/icons';
|
||||
|
||||
export type OrderedComputedResult = ComputedPageResult | ComputedRecordResult;
|
||||
|
||||
export type SearchResultSource = {
|
||||
search: { query: string; searchId: string | undefined };
|
||||
};
|
||||
|
||||
export type BaseComputedResult = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -55,6 +59,7 @@ export type SearchSiteContentScope =
|
||||
|
||||
export interface SearchSiteContentRequest {
|
||||
asEmbeddable?: boolean;
|
||||
searchId?: string;
|
||||
query: string;
|
||||
scope: SearchSiteContentScope;
|
||||
}
|
||||
|
||||
@@ -141,7 +141,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey: string;
|
||||
flush: () => void;
|
||||
resultsRef: React.RefObject<SearchResultsRef | null>;
|
||||
abort: () => void;
|
||||
askCount: number;
|
||||
onAskSelect: (index: number) => void;
|
||||
}) {
|
||||
@@ -154,7 +153,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect,
|
||||
} = props;
|
||||
@@ -190,8 +188,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
|
||||
if (resultsRef.current?.select()) {
|
||||
// Stop any in-flight search request only when activating a result.
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -207,7 +203,6 @@ function useSearchKeyboardNavigation(props: {
|
||||
results.length,
|
||||
onAskSelect,
|
||||
resultsRef,
|
||||
abort,
|
||||
query,
|
||||
fetching,
|
||||
requestKey,
|
||||
@@ -229,13 +224,11 @@ function useSearchKeyboardNavigation(props: {
|
||||
}
|
||||
pendingOpenRef.current = null;
|
||||
if (results.length > 0) {
|
||||
if (resultsRef.current?.selectFirst()) {
|
||||
abort();
|
||||
}
|
||||
resultsRef.current?.selectFirst();
|
||||
} else if (!error && askCount > 0) {
|
||||
onAskSelect(0);
|
||||
}
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
|
||||
}, [isOpen, requestKey, fetching, error, results, resultsRef, askCount, onAskSelect]);
|
||||
|
||||
return {
|
||||
cursor,
|
||||
@@ -379,9 +372,10 @@ export function useSearchController(
|
||||
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
|
||||
|
||||
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
|
||||
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
const { results, resultsQuery, fetching, error, requestKey, flush, abort } = useSearchResults({
|
||||
asEmbeddable,
|
||||
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
|
||||
disabled: options.requestsEnabled === false || showAsk || !(normalizedQuery || withAI),
|
||||
retainPreviousResults: Boolean(state?.open),
|
||||
query: normalizedQuery,
|
||||
siteSpaceId: siteSpace.id,
|
||||
siteSpaceIds,
|
||||
@@ -442,7 +436,6 @@ export function useSearchController(
|
||||
requestKey,
|
||||
flush,
|
||||
resultsRef,
|
||||
abort,
|
||||
askCount,
|
||||
onAskSelect: askInAssistant,
|
||||
});
|
||||
@@ -463,6 +456,7 @@ export function useSearchController(
|
||||
query: normalizedQuery,
|
||||
results,
|
||||
resultsId: searchResultsId,
|
||||
resultsQuery,
|
||||
resultsRef,
|
||||
searchValue,
|
||||
setQuery,
|
||||
|
||||
@@ -8,22 +8,36 @@ import {
|
||||
createRecommendedQuestionResult,
|
||||
getEmptySearchResults,
|
||||
} from './empty-search-results';
|
||||
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
|
||||
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
|
||||
import { useRecentSearchQueries } from './recent-queries';
|
||||
import { computeRemoteSearchScope } from './remote-scope';
|
||||
import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store';
|
||||
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
|
||||
import type {
|
||||
OrderedComputedResult,
|
||||
SearchResultSource,
|
||||
SearchSiteContentScope,
|
||||
} from './search-types';
|
||||
import { streamRecommendedQuestions } from './server-actions';
|
||||
import { type SearchScope, useSearchPass } from './useSearch';
|
||||
import { useAI } from '@/components/AI';
|
||||
|
||||
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
|
||||
export type ResultType = RemoteSearchResult | RecommendedQuestionResult;
|
||||
|
||||
const SEARCH_ID_BYTES = 16;
|
||||
|
||||
type RemoteSearchResult = OrderedComputedResult & SearchResultSource;
|
||||
|
||||
type SearchAnswer = {
|
||||
scopeKey: string;
|
||||
query: string;
|
||||
results: RemoteSearchResult[];
|
||||
};
|
||||
|
||||
type RemoteSearchState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
|
||||
| { status: 'error' };
|
||||
| { status: 'loading'; requestKey: string; answer?: SearchAnswer }
|
||||
| { status: 'ready'; requestKey: string; answer: SearchAnswer }
|
||||
| { status: 'error'; requestKey: string };
|
||||
|
||||
/**
|
||||
* We cache the recommended questions globally to avoid calling the API multiple times
|
||||
@@ -37,6 +51,7 @@ export function useSearchResults(props: {
|
||||
asEmbeddable?: boolean;
|
||||
disabled: boolean;
|
||||
query: string;
|
||||
retainPreviousResults: boolean;
|
||||
siteSpaceId: string;
|
||||
siteSpaceIds: string[];
|
||||
selectedSectionSiteSpaceIds?: string[];
|
||||
@@ -53,6 +68,7 @@ export function useSearchResults(props: {
|
||||
asEmbeddable,
|
||||
disabled,
|
||||
query,
|
||||
retainPreviousResults,
|
||||
siteSpaceId,
|
||||
siteSpaceIds,
|
||||
selectedSectionSiteSpaceIds,
|
||||
@@ -83,8 +99,15 @@ export function useSearchResults(props: {
|
||||
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
|
||||
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
|
||||
);
|
||||
// Identifies the answer the UI needs now; an answer for any other key is never shown as current.
|
||||
const requestKey = JSON.stringify([query, remoteScope]);
|
||||
const scopeKey = JSON.stringify([
|
||||
searchURL,
|
||||
asEmbeddable,
|
||||
siteSpaceId,
|
||||
scope,
|
||||
remoteScope,
|
||||
filterSiteSpaceIds,
|
||||
]);
|
||||
const requestKey = JSON.stringify([scopeKey, query]);
|
||||
|
||||
const [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
|
||||
|
||||
@@ -100,6 +123,7 @@ export function useSearchResults(props: {
|
||||
|
||||
React.useEffect(() => {
|
||||
if (disabled) {
|
||||
setRemoteState({ status: 'idle' });
|
||||
return;
|
||||
}
|
||||
if (!query) {
|
||||
@@ -126,7 +150,7 @@ export function useSearchResults(props: {
|
||||
// We currently have a bug where the same question can be returned multiple times.
|
||||
// This is a workaround to avoid that.
|
||||
const questions = new Set<string>();
|
||||
const recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
let recommendedQuestions: RecommendedQuestionResult[] = [];
|
||||
|
||||
if (suggestions && suggestions.length > 0) {
|
||||
suggestions.forEach((question) => {
|
||||
@@ -153,7 +177,10 @@ export function useSearchResults(props: {
|
||||
}
|
||||
|
||||
questions.add(question);
|
||||
recommendedQuestions.push(createRecommendedQuestionResult(question, question));
|
||||
recommendedQuestions = [
|
||||
...recommendedQuestions,
|
||||
createRecommendedQuestionResult(question, question),
|
||||
];
|
||||
cachedRecommendedQuestions.set(siteSpaceId, recommendedQuestions);
|
||||
|
||||
if (!cancelled) {
|
||||
@@ -168,14 +195,19 @@ export function useSearchResults(props: {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}
|
||||
setRemoteState({ status: 'loading' });
|
||||
setRemoteState((state) => {
|
||||
const answer = 'answer' in state ? state.answer : undefined;
|
||||
return answer?.scopeKey === scopeKey
|
||||
? { status: 'loading', requestKey, answer }
|
||||
: { status: 'loading', requestKey };
|
||||
});
|
||||
let cancelled = false;
|
||||
const abortController = new AbortController();
|
||||
const send = async () => {
|
||||
flushRef.current = null;
|
||||
const fetchSearch = (
|
||||
scope: Parameters<typeof fetchSearchResults>[1]
|
||||
): Promise<OrderedComputedResult[]> =>
|
||||
): Promise<RemoteSearchResult[]> =>
|
||||
fetchSearchResults(
|
||||
searchURL,
|
||||
scope,
|
||||
@@ -188,25 +220,29 @@ export function useSearchResults(props: {
|
||||
try {
|
||||
const resultsPromise = fetchSearch(remoteScope);
|
||||
|
||||
const onResults = (results: OrderedComputedResult[]) => {
|
||||
const onResults = (results: RemoteSearchResult[]) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!results) {
|
||||
// Can happen when the route cannot be found and returns the page's html.
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoteState({ status: 'ready', requestKey, results });
|
||||
setRemoteState({
|
||||
status: 'ready',
|
||||
requestKey,
|
||||
answer: { scopeKey, query, results },
|
||||
});
|
||||
trackEvent({ type: 'search_type_query', query });
|
||||
};
|
||||
const onError = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
};
|
||||
|
||||
await resultsPromise.then(onResults, onError);
|
||||
@@ -215,10 +251,10 @@ export function useSearchResults(props: {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setRemoteState({ status: 'error' });
|
||||
setRemoteState({ status: 'error', requestKey });
|
||||
}
|
||||
};
|
||||
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 150);
|
||||
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
|
||||
flushRef.current = () => {
|
||||
clearTimeout(timeout);
|
||||
void send();
|
||||
@@ -241,6 +277,7 @@ export function useSearchResults(props: {
|
||||
query,
|
||||
remoteScope,
|
||||
requestKey,
|
||||
scopeKey,
|
||||
trackEvent,
|
||||
withAI,
|
||||
siteSpaceId,
|
||||
@@ -252,6 +289,16 @@ export function useSearchResults(props: {
|
||||
searchPass,
|
||||
]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!retainPreviousResults) {
|
||||
setRemoteState((state) =>
|
||||
state.status === 'loading' && state.answer
|
||||
? { status: 'loading', requestKey: state.requestKey }
|
||||
: state
|
||||
);
|
||||
}
|
||||
}, [retainPreviousResults, requestKey]);
|
||||
|
||||
const flush = React.useCallback(() => {
|
||||
flushRef.current?.();
|
||||
}, []);
|
||||
@@ -262,10 +309,20 @@ export function useSearchResults(props: {
|
||||
setRemoteState((prev) => (prev.status === 'loading' ? { status: 'idle' } : prev));
|
||||
}, []);
|
||||
|
||||
const answer = 'answer' in remoteState ? remoteState.answer : undefined;
|
||||
const visibleAnswer =
|
||||
query &&
|
||||
!disabled &&
|
||||
answer?.scopeKey === scopeKey &&
|
||||
(answer.query === query || retainPreviousResults)
|
||||
? answer
|
||||
: undefined;
|
||||
|
||||
const streamedQuestions = cachedRecommendedQuestions.get(siteSpaceId);
|
||||
const results = React.useMemo<ResultType[]>(() => {
|
||||
if (!query) {
|
||||
const recommendedQuestions =
|
||||
cachedRecommendedQuestions.get(siteSpaceId) ??
|
||||
streamedQuestions ??
|
||||
suggestions?.map((question, index) =>
|
||||
createRecommendedQuestionResult(`recommended-question-${index}`, question)
|
||||
) ??
|
||||
@@ -278,27 +335,32 @@ export function useSearchResults(props: {
|
||||
});
|
||||
}
|
||||
|
||||
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
|
||||
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
|
||||
return visibleAnswer
|
||||
? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds)
|
||||
: [];
|
||||
}, [
|
||||
remoteState,
|
||||
requestKey,
|
||||
visibleAnswer,
|
||||
query,
|
||||
filterSiteSpaceIds,
|
||||
withAI,
|
||||
siteSpaceId,
|
||||
streamedQuestions,
|
||||
suggestions,
|
||||
recentQueries,
|
||||
]);
|
||||
|
||||
// Between a query change and its loading state, the previous answer must still read as loading.
|
||||
const isOutdated = remoteState.status === 'ready' && remoteState.requestKey !== requestKey;
|
||||
|
||||
return {
|
||||
results,
|
||||
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
|
||||
error: remoteState.status === 'error',
|
||||
resultsQuery: visibleAnswer?.query ?? query,
|
||||
fetching:
|
||||
Boolean(query) &&
|
||||
!disabled &&
|
||||
(remoteState.status === 'loading' ||
|
||||
(remoteState.status !== 'idle' && remoteState.requestKey !== requestKey)),
|
||||
error:
|
||||
Boolean(query) &&
|
||||
!disabled &&
|
||||
remoteState.status === 'error' &&
|
||||
remoteState.requestKey === requestKey,
|
||||
requestKey,
|
||||
flush,
|
||||
abort,
|
||||
@@ -315,17 +377,21 @@ async function fetchSearchResults(
|
||||
signal: AbortSignal,
|
||||
asEmbeddable: boolean | undefined,
|
||||
searchPass: SearchPassStore | null
|
||||
): Promise<OrderedComputedResult[]> {
|
||||
): Promise<RemoteSearchResult[]> {
|
||||
const directSearchId = generateSearchId();
|
||||
const direct = await searchPass?.search({
|
||||
query,
|
||||
searchId: directSearchId,
|
||||
scope,
|
||||
signal,
|
||||
asEmbeddable: Boolean(asEmbeddable),
|
||||
});
|
||||
if (direct?.type === 'results') {
|
||||
return direct.results;
|
||||
const search = { query, searchId: directSearchId };
|
||||
return direct.results.map((result) => ({ ...result, search }));
|
||||
}
|
||||
|
||||
const searchId = direct ? generateSearchId() : directSearchId;
|
||||
const response = await fetch(searchURL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -335,6 +401,7 @@ async function fetchSearchResults(
|
||||
body: JSON.stringify({
|
||||
asEmbeddable,
|
||||
query,
|
||||
searchId,
|
||||
scope,
|
||||
}),
|
||||
signal,
|
||||
@@ -344,5 +411,12 @@ async function fetchSearchResults(
|
||||
throw new Error(`Search request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<OrderedComputedResult[]>;
|
||||
const results: OrderedComputedResult[] = await response.json();
|
||||
const search = { query, searchId };
|
||||
return results.map((result) => ({ ...result, search }));
|
||||
}
|
||||
|
||||
function generateSearchId() {
|
||||
const bytes = globalThis.crypto?.getRandomValues(new Uint8Array(SEARCH_ID_BYTES));
|
||||
return bytes && Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@ export function useSearchResultsCursor(props: {
|
||||
}, [query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (fetching && resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
if (fetching) {
|
||||
if (resultCount === 0) {
|
||||
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
|
||||
setCursor(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import Script from 'next/script';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
|
||||
import { CustomizationDefaultThemeMode } from '@gitbook/api';
|
||||
|
||||
import { AIContextProvider } from '../AI';
|
||||
import { LLMsTxtDirective } from './LLMsTxtDirective';
|
||||
@@ -20,6 +20,7 @@ import { buildVersion } from '@/lib/build';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@/lib/env';
|
||||
import { getResizedImageURL } from '@/lib/images';
|
||||
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { removeTrailingSlash } from '@/lib/paths';
|
||||
import { isSiteIndexable } from '@/lib/seo';
|
||||
import { getOpenSearchURL } from '@/routes/opensearch';
|
||||
@@ -127,7 +128,7 @@ export async function SiteLayout(props: {
|
||||
</AIContextProvider>
|
||||
|
||||
<LoadIntegrations />
|
||||
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
|
||||
{isMcpPageActionEnabled(context) ? (
|
||||
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
|
||||
) : null}
|
||||
{scripts.map(({ script }) =>
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const {
|
||||
fetchPageData,
|
||||
getLowercasePathnameRedirect,
|
||||
resolveMissingPagePath,
|
||||
resolveSitePageFromURL,
|
||||
} = await import('./fetch');
|
||||
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
|
||||
await import('./fetch');
|
||||
const { normalizeURL } = await import('@/lib/data/urls');
|
||||
const { createLinker } = await import('@/lib/links');
|
||||
|
||||
@@ -25,81 +21,6 @@ const page = {
|
||||
pages: [],
|
||||
} as RevisionPageDocument;
|
||||
|
||||
const git = {
|
||||
oid: 'abc123',
|
||||
path: 'README.md',
|
||||
};
|
||||
|
||||
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
|
||||
const getRevisionPageByPath = mock(async () => ({
|
||||
data: {
|
||||
...page,
|
||||
git,
|
||||
},
|
||||
}));
|
||||
|
||||
const context = {
|
||||
revision: { pages: [page] },
|
||||
revisionId: 'revision-1',
|
||||
customization: {
|
||||
pageActions: {
|
||||
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
|
||||
},
|
||||
},
|
||||
space: {
|
||||
id: 'space-1',
|
||||
gitSync:
|
||||
options.gitSync === false
|
||||
? undefined
|
||||
: {
|
||||
url: 'https://github.com/gitbook/example/tree/main',
|
||||
},
|
||||
},
|
||||
dataFetcher: { getRevisionPageByPath },
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
return { context, getRevisionPageByPath };
|
||||
}
|
||||
|
||||
describe('fetchPageData', () => {
|
||||
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
path: 'readme',
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
expect(result.pageTarget?.page.git).toEqual(git);
|
||||
expect(result.context.page?.git).toEqual(git);
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata when the action is disabled', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result.pageTarget?.page.git).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata without Git Sync', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({
|
||||
gitEnabled: true,
|
||||
gitSync: false,
|
||||
});
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result.pageTarget?.page.git).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveMissingPagePath', () => {
|
||||
function createRedirectContext(options: {
|
||||
siteRedirect?: { source?: string; target: string; permanent?: boolean };
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
type RevisionPageDocument,
|
||||
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
@@ -30,34 +29,7 @@ export type PageParams = PagePathParams | PageIdParams;
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
|
||||
let pageTarget = await resolvePage(context, params);
|
||||
|
||||
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
|
||||
if (
|
||||
pageTarget &&
|
||||
!pageTarget.page.git &&
|
||||
context.space.gitSync?.url &&
|
||||
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
|
||||
) {
|
||||
const response = await context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
path: pageTarget.page.path,
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
const pageWithMetadata = response.data;
|
||||
|
||||
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
|
||||
pageTarget = {
|
||||
...pageTarget,
|
||||
page: {
|
||||
...pageTarget.page,
|
||||
git: pageWithMetadata.git,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const pageTarget = await resolvePage(context, params);
|
||||
|
||||
return {
|
||||
context: {
|
||||
|
||||
@@ -36,11 +36,11 @@ export function Tag(props: { tag: RevisionTag; className?: string }) {
|
||||
export function TagIcon(props: { tag: RevisionTag }) {
|
||||
const { tag } = props;
|
||||
|
||||
if ('emoji' in tag) {
|
||||
if ('emoji' in tag && tag.emoji !== undefined) {
|
||||
return <Emoji code={tag.emoji} style="shrink-0" />;
|
||||
}
|
||||
|
||||
if (tag.icon) {
|
||||
if ('icon' in tag && tag.icon) {
|
||||
return <Icon icon={tag.icon as IconName} className={tcls('size-[1em]', 'shrink-0')} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ function makeContext(
|
||||
siteId?: string;
|
||||
visibility?: SiteVisibility;
|
||||
pageActions?: CustomizationPageActionType[];
|
||||
mcpEnabled?: boolean;
|
||||
} = {}
|
||||
): GitBookSiteContext {
|
||||
const {
|
||||
@@ -32,11 +33,16 @@ function makeContext(
|
||||
siteId = 'site_123',
|
||||
visibility = SiteVisibility.Public,
|
||||
pageActions = [CustomizationPageActionType.Mcp],
|
||||
mcpEnabled,
|
||||
} = options;
|
||||
|
||||
return {
|
||||
site: { id: siteId, title: 'Acme', visibility },
|
||||
customization: { pageActions: { items: pageActions } },
|
||||
customization: {
|
||||
pageActions: { items: pageActions },
|
||||
// DO NOT MERGE - mocking type for development
|
||||
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
|
||||
},
|
||||
linker: createLinker({ host, siteBasePath, spaceBasePath: siteBasePath }),
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
@@ -160,6 +166,14 @@ describe('serveSiteAiCatalog', () => {
|
||||
}
|
||||
);
|
||||
|
||||
it('does not advertise the MCP server when the page action is off', () => {
|
||||
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: true, pageActions: [] }))).toBeNull();
|
||||
});
|
||||
|
||||
it('does not advertise the MCP server when the endpoint is off', () => {
|
||||
expect(buildSiteAiCatalog(makeContext({ mcpEnabled: false }))).toBeNull();
|
||||
});
|
||||
|
||||
it('does not serve a catalog when there is nothing to advertise', async () => {
|
||||
const res = await serveSiteAiCatalog(makeContext({ pageActions: [] }), catalogRequest());
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { serveDiscoveryDocument } from '@/lib/discoveryDocument';
|
||||
import { isSiteMcpEnabled } from '@/lib/mcp/endpoints';
|
||||
import { isMcpPageActionEnabled } from '@/lib/mcp/endpoints';
|
||||
import { MCP_SERVER_CARD_PATH } from '@/lib/mcp/paths';
|
||||
import { SERVER_CARD_MEDIA_TYPE } from '@/lib/mcp/serverCard';
|
||||
|
||||
@@ -45,7 +45,7 @@ export function buildSiteAiCatalog(context: GitBookSiteContext): AiCatalog | nul
|
||||
|
||||
const entries: AiCatalogEntry[] = [];
|
||||
|
||||
if (isSiteMcpEnabled(context)) {
|
||||
if (isMcpPageActionEnabled(context)) {
|
||||
entries.push({
|
||||
identifier: buildCatalogIdentifier(context, 'mcp', site.id),
|
||||
type: SERVER_CARD_MEDIA_TYPE,
|
||||
|
||||
@@ -5,7 +5,6 @@ import { assert } from 'ts-essentials';
|
||||
import type {
|
||||
ChangeRequest,
|
||||
CustomizationDefaultThemeMode,
|
||||
PublishedSiteContent,
|
||||
Revision,
|
||||
RevisionPageDocument,
|
||||
Site,
|
||||
@@ -32,6 +31,7 @@ import { isPublishedPreviewAllowed } from './preview';
|
||||
import type { AskVisitorAgent } from '@/lib/ask-visitor';
|
||||
import {
|
||||
type GitBookDataFetcher,
|
||||
type PublishedSiteContent,
|
||||
createDataFetcher,
|
||||
getDataOrNull,
|
||||
throwIfDataError,
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
GitBookAPI,
|
||||
type HttpResponse,
|
||||
type RenderIntegrationUI,
|
||||
type SiteSearchScope,
|
||||
} from '@gitbook/api';
|
||||
import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags';
|
||||
|
||||
@@ -14,6 +13,7 @@ import { cache } from '../cache';
|
||||
import { DataFetcherError, wrapDataFetcherError } from './errors';
|
||||
import type { GitBookDataFetcher } from './types';
|
||||
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
|
||||
import { toSearchSiteContentBody } from '@/lib/search-results';
|
||||
import { trace } from '@/lib/tracing';
|
||||
|
||||
interface DataFetcherInput {
|
||||
@@ -793,25 +793,12 @@ async function searchSiteContent(
|
||||
return trace(
|
||||
`searchSiteContent(${params.organizationId}, ${params.siteId}, ${params.query})`,
|
||||
async () => {
|
||||
const { organizationId, siteId, query, scope } = params;
|
||||
const { organizationId, siteId, query, scope, searchId } = params;
|
||||
const api = apiClient(input);
|
||||
const res = await api.orgs.searchSiteContent(
|
||||
organizationId,
|
||||
siteId,
|
||||
{
|
||||
query,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
// and the published @gitbook/api types don't include it yet.
|
||||
scope: {
|
||||
mode: 'default',
|
||||
currentSiteSpace: scope.siteSpaceId,
|
||||
restrictTo: scope.restrictTo,
|
||||
} as SiteSearchScope,
|
||||
}
|
||||
: scope),
|
||||
},
|
||||
toSearchSiteContentBody(query, scope, searchId),
|
||||
{},
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
|
||||
|
||||
import type { PublishedSiteContentLookup } from '@gitbook/api';
|
||||
|
||||
import { GITBOOK_PREVIEW_BASE_URL } from '../env';
|
||||
import * as api from './api';
|
||||
import { DataFetcherError } from './errors';
|
||||
@@ -50,64 +48,39 @@ describe('preview auth redirects', () => {
|
||||
expect(redirect.origin + redirect.pathname).toBe(authURL.toString());
|
||||
expect(redirect.searchParams.get('redirect')).toBe(requestURL.toString());
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'non-preview application redirects',
|
||||
requestURL: 'https://docs.example.com/~/changes/66',
|
||||
target: 'application',
|
||||
redirect: 'https://app.gitbook.com/o/org_foo/sites/site_foo',
|
||||
expectedRedirect: 'https://app.gitbook.com/o/org_foo/sites/site_foo',
|
||||
},
|
||||
{
|
||||
name: 'preview content redirects with a remaining page path',
|
||||
requestURL: new URL(
|
||||
'site_foo/~/changes/66/hello%20world',
|
||||
GITBOOK_PREVIEW_BASE_URL
|
||||
).toString(),
|
||||
target: 'content',
|
||||
redirect: 'https://docs.example.com/section?theme=dark',
|
||||
expectedRedirect: 'https://docs.example.com/section/hello%20world?theme=dark',
|
||||
},
|
||||
{
|
||||
name: 'preview external redirects with a remaining page path',
|
||||
requestURL: new URL(
|
||||
'site_foo/~/revisions/revision_123/hello%20world',
|
||||
GITBOOK_PREVIEW_BASE_URL
|
||||
).toString(),
|
||||
target: 'external',
|
||||
redirect: 'https://auth.example.com/login?location=%2Fsection&state=keep',
|
||||
expectedRedirect:
|
||||
'https://auth.example.com/login?location=%2Fsection%2Fhello%2520world&state=keep',
|
||||
},
|
||||
] as const)(
|
||||
'preserves handling of $name',
|
||||
async ({ requestURL, target, redirect, expectedRedirect }) => {
|
||||
const data: PublishedSiteContentLookup =
|
||||
target === 'external'
|
||||
? { target, redirect, site: 'site_foo' }
|
||||
: { target, redirect };
|
||||
apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
|
||||
urls: {
|
||||
async resolvePublishedContentByUrl() {
|
||||
return { data };
|
||||
},
|
||||
describe('lookup URL', () => {
|
||||
it('sends change request URLs in full and keeps the redirect of the API', async () => {
|
||||
const urls: string[] = [];
|
||||
const redirect = new URL(
|
||||
'site_foo/section/~/changes/66/hello%20world',
|
||||
GITBOOK_PREVIEW_BASE_URL
|
||||
).toString();
|
||||
const apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
|
||||
urls: {
|
||||
async resolvePublishedContentByUrl({ url }: { url: string }) {
|
||||
urls.push(url);
|
||||
return { data: { target: 'content', redirect } };
|
||||
},
|
||||
} as unknown as ReturnType<typeof api.apiClient>);
|
||||
},
|
||||
} as unknown as ReturnType<typeof api.apiClient>);
|
||||
|
||||
try {
|
||||
const result = await lookupPublishedContentByUrl({
|
||||
url: requestURL,
|
||||
url: 'https://docs.example.com/section/~/changes/66/hello%20world?jwt_token=abc',
|
||||
apiToken: null,
|
||||
redirectOnError: false,
|
||||
visitorPayload: {},
|
||||
});
|
||||
|
||||
expect(result).toEqual({ data: { ...data, redirect: expectedRedirect } });
|
||||
expect(result).toEqual({ data: { target: 'content', redirect } });
|
||||
} finally {
|
||||
apiClientSpy.mockRestore();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('lookup URL', () => {
|
||||
expect(urls).toEqual(['https://docs.example.com/section/~/changes/66/hello%20world']);
|
||||
});
|
||||
|
||||
it('resolves the full URL without search params in a single call', async () => {
|
||||
const urls: string[] = [];
|
||||
const apiClientSpy = spyOn(api, 'apiClient').mockReturnValue({
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import type { GitBookAPI, PublishedSiteContentLookup, SiteVisitorPayload } from '@gitbook/api';
|
||||
import type * as API from '@gitbook/api';
|
||||
|
||||
import { apiClient } from './api';
|
||||
import { getExposableError } from './errors';
|
||||
import type { DataFetcherResponse } from './types';
|
||||
import { getURLLookup, getURLLookupPathname, stripURLSearch } from './urls';
|
||||
import { getURLLookup, stripURLSearch } from './urls';
|
||||
import { tryCatch } from '@/lib/async';
|
||||
import { joinPath, joinPathWithBaseURL } from '@/lib/paths';
|
||||
import { isPreviewRequest } from '@/lib/preview';
|
||||
import { trace } from '@/lib/tracing';
|
||||
|
||||
type ResolveBody = Parameters<GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
type ResolveBody = Parameters<API.GitBookAPI['urls']['resolvePublishedContentByUrl']>[0];
|
||||
|
||||
export type PublishedSiteContent = API.PublishedSiteContent &
|
||||
Partial<API.PublishedSiteContentAtRevision & API.PublishedSiteContentInChangeRequest>;
|
||||
|
||||
interface LookupPublishedContentByUrlInput {
|
||||
url: string;
|
||||
redirectOnError: boolean;
|
||||
apiToken: string | null;
|
||||
visitorPayload: SiteVisitorPayload;
|
||||
visitorPayload: API.SiteVisitorPayload;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,7 +25,7 @@ interface LookupPublishedContentByUrlInput {
|
||||
*/
|
||||
export async function lookupPublishedContentByUrl(
|
||||
input: LookupPublishedContentByUrlInput
|
||||
): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
|
||||
): Promise<DataFetcherResponse<PublishedSiteContent | API.PublishedContentRedirect>> {
|
||||
const lookupURL = new URL(input.url);
|
||||
const lookup = getURLLookup(stripURLSearch(lookupURL));
|
||||
|
||||
@@ -40,12 +42,12 @@ export async function lookupPublishedContentByUrl(
|
||||
const callResult = await trace(
|
||||
{
|
||||
operation: 'resolvePublishedContentByUrl',
|
||||
name: lookup.url,
|
||||
name: lookup,
|
||||
},
|
||||
() =>
|
||||
tryCatch(
|
||||
api.urls.resolvePublishedContentByUrl({
|
||||
url: lookup.url,
|
||||
url: lookup,
|
||||
...(input.visitorPayload ? { visitor: input.visitorPayload } : {}),
|
||||
redirectOnError: input.redirectOnError,
|
||||
} as ResolveBody) //TODO: remove cast when we are sure that everything is good
|
||||
@@ -62,47 +64,16 @@ export async function lookupPublishedContentByUrl(
|
||||
data: { data },
|
||||
} = callResult;
|
||||
|
||||
if ('redirect' in data) {
|
||||
if (data.target === 'application' && isPreviewRequest(lookupURL)) {
|
||||
// The cached lookup omits content selectors and query params needed after login.
|
||||
const redirect = new URL(data.redirect);
|
||||
redirect.searchParams.set('redirect', lookupURL.toString());
|
||||
return { data: { ...data, redirect: redirect.toString() } };
|
||||
}
|
||||
|
||||
// Append the path to the redirect URL
|
||||
// because we resolved a shorter path and the redirect is relative to it
|
||||
if (lookup.extraPath) {
|
||||
if (data.target === 'content') {
|
||||
const redirect = new URL(data.redirect);
|
||||
redirect.pathname = joinPath(redirect.pathname, lookup.extraPath);
|
||||
data.redirect = redirect.toString();
|
||||
} else {
|
||||
const redirect = new URL(data.redirect);
|
||||
if (redirect.searchParams.has('location')) {
|
||||
redirect.searchParams.set(
|
||||
'location',
|
||||
joinPath(redirect.searchParams.get('location') ?? '', lookup.extraPath)
|
||||
);
|
||||
data.redirect = redirect.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!('redirect' in data)) {
|
||||
return { data };
|
||||
}
|
||||
|
||||
const changeRequest = data.changeRequest ?? lookup.changeRequest;
|
||||
const revision = data.revision ?? lookup.revision;
|
||||
if (data.target === 'application' && isPreviewRequest(lookupURL)) {
|
||||
// The cached lookup omits the query params needed after login.
|
||||
const redirect = new URL(data.redirect);
|
||||
redirect.searchParams.set('redirect', lookupURL.toString());
|
||||
return { data: { ...data, redirect: redirect.toString() } };
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
...data,
|
||||
canonicalUrl: joinPathWithBaseURL(data.canonicalUrl, lookup.extraPath),
|
||||
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
|
||||
pathname: getURLLookupPathname(lookup, data),
|
||||
...(changeRequest ? { changeRequest } : {}),
|
||||
...(revision ? { revision } : {}),
|
||||
},
|
||||
};
|
||||
return { data };
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ export interface GitBookDataFetcher {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope:
|
||||
| { mode: 'all' }
|
||||
| {
|
||||
|
||||
@@ -1,88 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { getURLLookup, getURLLookupPathname, normalizeRequestURL, normalizeURL } from './urls';
|
||||
|
||||
describe('getURLLookupPathname', () => {
|
||||
const previewRoot = 'https://sites.gitbook.com/preview/site_example/section';
|
||||
const pagePath = 'guides/access/setup';
|
||||
const homepagePath = '/welcome/overview';
|
||||
|
||||
it.each(['revisions', 'changes'])(
|
||||
'resolves a page in a %s preview from the site-space root',
|
||||
(kind) => {
|
||||
const lookup = getURLLookup(
|
||||
new URL(`${previewRoot}/~/${kind}/revision-id/${pagePath}`)
|
||||
)!;
|
||||
|
||||
expect(
|
||||
getURLLookupPathname(lookup, {
|
||||
basePath: '/preview/site_example/section/',
|
||||
pathname: homepagePath,
|
||||
})
|
||||
).toBe(`/${pagePath}`);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['revisions', 'changes'])(
|
||||
'preserves the custom homepage at a %s preview root',
|
||||
(kind) => {
|
||||
const lookup = getURLLookup(new URL(`${previewRoot}/~/${kind}/revision-id/`))!;
|
||||
|
||||
expect(
|
||||
getURLLookupPathname(lookup, {
|
||||
basePath: '/preview/site_example/section/',
|
||||
pathname: homepagePath,
|
||||
})
|
||||
).toBe(`${homepagePath}/`);
|
||||
}
|
||||
);
|
||||
|
||||
it('uses the resolved pathname for a full URL lookup', () => {
|
||||
const lookup = getURLLookup(new URL(`https://docs.example.com/section/${pagePath}`))!;
|
||||
|
||||
expect(
|
||||
getURLLookupPathname(lookup, {
|
||||
basePath: '/section/',
|
||||
pathname: `/${pagePath}`,
|
||||
})
|
||||
).toBe(`/${pagePath}/`);
|
||||
});
|
||||
|
||||
it('preserves page resolution without a custom homepage', () => {
|
||||
const lookup = getURLLookup(new URL(`${previewRoot}/~/revisions/revision-id/${pagePath}`))!;
|
||||
|
||||
expect(
|
||||
getURLLookupPathname(lookup, {
|
||||
basePath: '/preview/site_example/section/',
|
||||
pathname: '/',
|
||||
})
|
||||
).toBe(`/${pagePath}`);
|
||||
});
|
||||
|
||||
it.each(['/section/variant', '/section/variant/'])(
|
||||
'recognizes a root lookup with base path %s',
|
||||
(basePath) => {
|
||||
expect(
|
||||
getURLLookupPathname(
|
||||
{
|
||||
url: 'https://docs.example.com/section/variant/',
|
||||
extraPath: 'guide/page',
|
||||
},
|
||||
{ basePath, pathname: homepagePath }
|
||||
)
|
||||
).toBe('/guide/page');
|
||||
}
|
||||
);
|
||||
|
||||
it('preserves a legitimate page prefix for a non-root lookup', () => {
|
||||
expect(
|
||||
getURLLookupPathname(
|
||||
{ url: 'https://docs.example.com/section/guide', extraPath: 'page' },
|
||||
{ basePath: '/section/', pathname: '/guide' }
|
||||
)
|
||||
).toBe('/guide/page');
|
||||
});
|
||||
});
|
||||
import { getURLLookup, normalizeRequestURL, normalizeURL } from './urls';
|
||||
|
||||
describe('getURLLookup', () => {
|
||||
it.each([
|
||||
@@ -98,68 +16,26 @@ describe('getURLLookup', () => {
|
||||
'https://docs.mycompany.com/section/blog/rss.xml',
|
||||
'https://docs.mycompany.com/a/b/intro.md',
|
||||
'https://proxy.gitbook.site/sites/site_foo/hello/world',
|
||||
'https://docs.mycompany.com/~/revisions/id/a/b/c',
|
||||
'https://docs.mycompany.com/~/changes/id/hello',
|
||||
'https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c',
|
||||
'https://docs.mycompany.com/~/revisions/id/a/~gitbook/ogimage/pageId',
|
||||
])('looks up the full URL %s', (url) => {
|
||||
expect(getURLLookup(new URL(url))).toEqual({ url, extraPath: '' });
|
||||
expect(getURLLookup(new URL(url))).toBe(url);
|
||||
});
|
||||
|
||||
it('looks up the normalized URL', () => {
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toEqual({
|
||||
url: 'https://docs.mycompany.com/hello',
|
||||
extraPath: '',
|
||||
});
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com//hello/'))).toBe(
|
||||
'https://docs.mycompany.com/hello'
|
||||
);
|
||||
});
|
||||
|
||||
it('should not match before a revision ID', () => {
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c'))).toEqual({
|
||||
url: 'https://docs.mycompany.com/',
|
||||
extraPath: 'a/b/c',
|
||||
basePath: '~/revisions/id',
|
||||
revision: 'id',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not match before a change request ID', () => {
|
||||
expect(getURLLookup(new URL('https://docs.mycompany.com/~/changes/id/hello'))).toEqual({
|
||||
url: 'https://docs.mycompany.com/',
|
||||
extraPath: 'hello',
|
||||
basePath: '~/changes/id',
|
||||
changeRequest: 'id',
|
||||
});
|
||||
});
|
||||
|
||||
it('should match a revision in a variant in a share-link', () => {
|
||||
expect(
|
||||
getURLLookup(
|
||||
new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c')
|
||||
)
|
||||
).toEqual({
|
||||
url: 'https://test.gitbook.io/sharelink/v/variant',
|
||||
extraPath: 'a/b/c',
|
||||
basePath: '~/revisions/id',
|
||||
revision: 'id',
|
||||
});
|
||||
});
|
||||
|
||||
it('should keep the revision base path for an internal path', () => {
|
||||
expect(
|
||||
getURLLookup(
|
||||
new URL('https://docs.mycompany.com/~/revisions/id/a/~gitbook/ogimage/pageId')
|
||||
)
|
||||
).toEqual({
|
||||
url: 'https://docs.mycompany.com/',
|
||||
extraPath: 'a/~gitbook/ogimage/pageId',
|
||||
basePath: '~/revisions/id',
|
||||
revision: 'id',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
'https://proxy.gitbook.site/',
|
||||
'https://proxy.gitbook.site/sites',
|
||||
'https://proxy.gitbook.site/sites/~/changes/id/hello',
|
||||
])('should skip the proxy root URL %s', (url) => {
|
||||
expect(getURLLookup(new URL(url))).toBeNull();
|
||||
});
|
||||
it.each(['https://proxy.gitbook.site/', 'https://proxy.gitbook.site/sites'])(
|
||||
'should skip the proxy root URL %s',
|
||||
(url) => {
|
||||
expect(getURLLookup(new URL(url))).toBeNull();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('normalizeRequestURL', () => {
|
||||
|
||||
@@ -1,107 +1,13 @@
|
||||
import { joinPath, removeTrailingSlash } from '../paths';
|
||||
import { isProxyRequest, isProxyRootRequest } from '../proxy';
|
||||
import { DataFetcherError, getExposableError } from './errors';
|
||||
|
||||
/**
|
||||
* Paths served by our own routes rather than by site content. They can never be part of a
|
||||
* site URL, so a revision or change marker is never searched for inside them.
|
||||
* Kept in sync with the site route handlers and `encodePathInSiteContent` in the middleware.
|
||||
*/
|
||||
const INTERNAL_PATHS = [
|
||||
// Simple `~gitbook` endpoints. `image`, `__evt` and `visitor` are served by the middleware
|
||||
// before the lookup, but are listed so this stays a complete registry.
|
||||
/^~gitbook\/(pdf|search|search-prewarm|icon|site-index|image|__evt|visitor)$/,
|
||||
/^~gitbook\/ogimage\/[^/]+$/,
|
||||
/^~gitbook\/auth\/(login|logout)$/,
|
||||
/^~gitbook\/oauth2\/v1\/[^/]+\/authorize$/,
|
||||
/^~gitbook\/embed(\/(assistant|search|demo|script\.js|page(\/.*)?))?$/,
|
||||
/^~gitbook\/markdown\/.+$/,
|
||||
/^~gitbook\/markdown-ask\/[^/]+(\/[^/]+)?$/,
|
||||
/^~gitbook\/rss\/.+$/,
|
||||
// Site root files, including the `llms.txt` aliases from `PATH_ALIASES`.
|
||||
/^llms\.txt$/,
|
||||
/^llms-full\.txt(\/\d+)?$/,
|
||||
/^(\.well-known\/)?sitemap\.md$/,
|
||||
/^robots\.txt$/,
|
||||
/^sitemap(-pages)?\.xml$/,
|
||||
/^rss\.xml$/,
|
||||
];
|
||||
|
||||
/**
|
||||
* Return the leading segments that can be part of the site URL, dropping the internal path
|
||||
* (if any) that follows them.
|
||||
*/
|
||||
function getContentPathSegments(pathSegments: string[]): string[] {
|
||||
for (let index = 0; index < pathSegments.length; index++) {
|
||||
const remaining = pathSegments.slice(index).join('/');
|
||||
if (INTERNAL_PATHS.some((regex) => regex.test(remaining))) {
|
||||
return pathSegments.slice(0, index);
|
||||
}
|
||||
}
|
||||
|
||||
return pathSegments;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a given GitBook URL, return the URL to resolve with the API.
|
||||
*
|
||||
* The full URL is resolved as-is, except for revisions and changes in the path
|
||||
* (`~/revisions/<id>/` or `~/changes/<id>/`): these are resolved up to the tilde,
|
||||
* and the rest of the path goes in the extraPath.
|
||||
*
|
||||
* Returns `null` for the root proxy URLs, which can never resolve to a site.
|
||||
*/
|
||||
export function getURLLookup(input: URL): {
|
||||
url: string;
|
||||
extraPath: string;
|
||||
basePath?: string;
|
||||
changeRequest?: string;
|
||||
revision?: string;
|
||||
} | null {
|
||||
export function getURLLookup(input: URL): string | null {
|
||||
const url = normalizeURL(input);
|
||||
|
||||
const pathSegments = url.pathname.slice(1).split('/');
|
||||
// A `~` in an internal path (like `~gitbook/...`) is not a revision or change marker.
|
||||
const contentSegments = getContentPathSegments(pathSegments);
|
||||
const tildeIndex = contentSegments.indexOf('~');
|
||||
const kind = tildeIndex >= 0 ? contentSegments[tildeIndex + 1] : undefined;
|
||||
|
||||
if (kind !== 'revisions' && kind !== 'changes') {
|
||||
return isProxyRootRequest(url) ? null : { url: url.toString(), extraPath: '' };
|
||||
}
|
||||
|
||||
const idIndex = tildeIndex + 2;
|
||||
const id = contentSegments[idIndex];
|
||||
const contentURL = new URL(url);
|
||||
contentURL.pathname = contentSegments.slice(0, tildeIndex).join('/');
|
||||
|
||||
if (isProxyRootRequest(contentURL)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
url: contentURL.toString(),
|
||||
extraPath: pathSegments.slice(idIndex + 1).join('/'),
|
||||
basePath: contentSegments.slice(tildeIndex, idIndex + 1).join('/'),
|
||||
...(kind === 'revisions' ? { revision: id } : { changeRequest: id }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Combine a resolved lookup with the remaining requested page path. */
|
||||
export function getURLLookupPathname(
|
||||
alternative: { url: string; extraPath: string },
|
||||
resolved: { basePath: string; pathname: string }
|
||||
) {
|
||||
if (
|
||||
alternative.extraPath &&
|
||||
removeTrailingSlash(new URL(alternative.url).pathname) ===
|
||||
removeTrailingSlash(resolved.basePath)
|
||||
) {
|
||||
// A root lookup can resolve to a custom homepage, which is not a prefix for other pages.
|
||||
return joinPath('/', alternative.extraPath);
|
||||
}
|
||||
|
||||
return joinPath(resolved.pathname, alternative.extraPath);
|
||||
return isProxyRootRequest(url) ? null : url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,12 +3,31 @@ import { CustomizationPageActionType, SiteVisibility } from '@gitbook/api';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
/**
|
||||
* Whether the site publishes an MCP server at all. Gates the endpoint and everything describing it.
|
||||
* Whether the site serves its MCP endpoint. Falls back to the `mcp` page action for cached
|
||||
* customizations that predate the setting.
|
||||
*/
|
||||
export function isSiteMcpEnabled(context: GitBookSiteContext): boolean {
|
||||
export function isSiteMcpEnabled(context: Pick<GitBookSiteContext, 'customization'>): boolean {
|
||||
// DO NOT MERGE - mocking type for development
|
||||
const mcp = (context.customization as { mcp?: { enabled: boolean } }).mcp;
|
||||
if (mcp) {
|
||||
return mcp.enabled;
|
||||
}
|
||||
return context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the site advertises its MCP server to visitors: the endpoint is served and the
|
||||
* "Connect with MCP server" page action is enabled for this visitor.
|
||||
*/
|
||||
export function isMcpPageActionEnabled(
|
||||
context: Pick<GitBookSiteContext, 'customization'>
|
||||
): boolean {
|
||||
return (
|
||||
isSiteMcpEnabled(context) &&
|
||||
context.customization.pageActions.items.includes(CustomizationPageActionType.Mcp)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `~gitbook/mcp` endpoint requires auth for the site (i.e VA site).
|
||||
*/
|
||||
|
||||
@@ -31,6 +31,7 @@ function makeContext(
|
||||
adaptiveContent?: boolean;
|
||||
aiMode?: CustomizationAIMode;
|
||||
pageActions?: CustomizationPageActionType[];
|
||||
mcpEnabled?: boolean;
|
||||
} = {}
|
||||
): GitBookSiteContext {
|
||||
const {
|
||||
@@ -43,6 +44,7 @@ function makeContext(
|
||||
adaptiveContent = true,
|
||||
aiMode = CustomizationAIMode.Search,
|
||||
pageActions = [CustomizationPageActionType.Mcp],
|
||||
mcpEnabled,
|
||||
} = options;
|
||||
|
||||
return {
|
||||
@@ -59,6 +61,8 @@ function makeContext(
|
||||
customization: {
|
||||
ai: { mode: aiMode },
|
||||
pageActions: { items: pageActions },
|
||||
// DO NOT MERGE - mocking type for development
|
||||
...(mcpEnabled === undefined ? {} : { mcp: { enabled: mcpEnabled } }),
|
||||
},
|
||||
linker: createLinker({ host, siteBasePath, spaceBasePath }),
|
||||
} as unknown as GitBookSiteContext;
|
||||
@@ -384,6 +388,29 @@ describe('serveSiteMcpServerCard', () => {
|
||||
expect(card.$schema).toBe(SERVER_CARD_SCHEMA_URL);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
scenario: 'the endpoint is on and the page action is off',
|
||||
options: { mcpEnabled: true, pageActions: [] },
|
||||
status: 200,
|
||||
},
|
||||
{
|
||||
scenario: 'the endpoint is off and the page action is on',
|
||||
options: { mcpEnabled: false },
|
||||
status: 404,
|
||||
},
|
||||
{ scenario: 'the setting is missing and the page action is on', options: {}, status: 200 },
|
||||
{
|
||||
scenario: 'the setting is missing and the page action is off',
|
||||
options: { pageActions: [] },
|
||||
status: 404,
|
||||
},
|
||||
])('answers $status when $scenario', async ({ options, status }) => {
|
||||
const res = await serveSiteMcpServerCard(makeContext(options), cardRequest());
|
||||
|
||||
expect(res.status).toBe(status);
|
||||
});
|
||||
|
||||
it('answers a preflight with a 204', async () => {
|
||||
const res = await serveSiteMcpServerCard(makeContext(), cardRequest({ method: 'OPTIONS' }));
|
||||
|
||||
|
||||
@@ -76,3 +76,7 @@ export function getExtension(path: string): string {
|
||||
export function isGitBookInternalPath(path: string): boolean {
|
||||
return /(^|\/)~gitbook(\/|$)/.test(path);
|
||||
}
|
||||
|
||||
export function hasRevisionSelector(path: string): boolean {
|
||||
return /(?:^|\/)~\/revisions\/[^/]+/.test(path);
|
||||
}
|
||||
|
||||
@@ -52,10 +52,12 @@ export type DirectSearchProps = {
|
||||
*/
|
||||
export function toSearchSiteContentBody(
|
||||
query: string,
|
||||
scope: SearchSiteContentScope
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] {
|
||||
scope: SearchSiteContentScope,
|
||||
searchId?: string
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] & { searchId?: string } {
|
||||
return {
|
||||
query,
|
||||
searchId,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type RevisionPageDocument, type RevisionPageGroup, SiteVisibility } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { hasRevisionSelector } from '@/lib/paths';
|
||||
|
||||
/**
|
||||
* Return true if a page is indexable in search.
|
||||
@@ -29,8 +30,11 @@ export function isSiteIndexable(context: GitBookSiteContext) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prevent indexation of preview of revisions / change-requests
|
||||
if (context.changeRequest || context.revisionId !== context.space.revision) {
|
||||
if (
|
||||
context.changeRequest ||
|
||||
context.revisionId !== context.space.revision ||
|
||||
hasRevisionSelector(context.linker.spaceBasePath)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
ContentType,
|
||||
CustomizationDefaultThemeMode,
|
||||
CustomizationThemeMode,
|
||||
type PublishedSiteContent,
|
||||
SiteInsightsDisplayContext,
|
||||
type SiteInsightsEventLocation,
|
||||
SiteInsightsLLMSVariant,
|
||||
@@ -31,6 +30,7 @@ import { getContentSecurityPolicy } from '@/lib/csp';
|
||||
import { validateSerializedCustomization } from '@/lib/customization';
|
||||
import {
|
||||
DataFetcherError,
|
||||
type PublishedSiteContent,
|
||||
apiClient,
|
||||
getVisitorAuthBasePath,
|
||||
lookupPublishedContentByUrl,
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
import { GITBOOK_DISABLE_INSIGHTS, isGitBookAssetsHostURL, isGitBookHostURL } from '@/lib/env';
|
||||
import { getImageResizingContextId } from '@/lib/images';
|
||||
import { isAITrainingOrIndexingRequest } from '@/lib/indexing-crawlers';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { MCP_SERVER_CARD_PATH, MCP_SERVER_CARD_WELL_KNOWN_PATH } from '@/lib/mcp/paths';
|
||||
import { MiddlewareHeaders } from '@/lib/middleware';
|
||||
import {
|
||||
@@ -50,7 +51,7 @@ import {
|
||||
isOAuthProtectedResourceMetadataRequestForAuthEndpoint,
|
||||
isOAuthProtectedResourceRequest,
|
||||
} from '@/lib/oauth-protected';
|
||||
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
|
||||
import { hasRevisionSelector, removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
|
||||
import {
|
||||
getPreviewCookieResponse,
|
||||
getPreviewRequestIdentifier,
|
||||
@@ -84,6 +85,8 @@ export const config = {
|
||||
|
||||
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
|
||||
|
||||
const REVISION_ROBOTS_TAG = 'noindex, nofollow';
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
try {
|
||||
const requestURL = new URL(request.url);
|
||||
@@ -167,6 +170,20 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = await serveSiteRequest(requestURL, request, match);
|
||||
if (
|
||||
response &&
|
||||
hasRevisionSelector(match.url.pathname) &&
|
||||
!response.headers.has('x-robots-tag')
|
||||
) {
|
||||
const revisionResponse = new Response(response.body, response);
|
||||
revisionResponse.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
|
||||
return revisionResponse;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
|
||||
const { url: siteRequestURL, mode } = match;
|
||||
|
||||
if (isAITrainingOrIndexingRequest(request)) {
|
||||
@@ -179,6 +196,13 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
// Normalize URL after extracting the URL from the request to make sure the client is redirected to the proper one
|
||||
const normalization = normalizeRequestURL(siteRequestURL, mode);
|
||||
if (normalization instanceof Response) {
|
||||
const location = normalization.headers.get('location');
|
||||
if (location && hasRevisionSelector(new URL(location).pathname)) {
|
||||
return NextResponse.redirect(location, {
|
||||
status: normalization.status,
|
||||
headers: { 'x-robots-tag': REVISION_ROBOTS_TAG },
|
||||
});
|
||||
}
|
||||
return normalization;
|
||||
}
|
||||
const isNormalizedURL = normalization.isNormalized;
|
||||
@@ -316,21 +340,25 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
// oxlint-disable-next-line no-console
|
||||
console.log('redirect', siteURLData.redirect);
|
||||
if (siteURLData.target === 'content') {
|
||||
let contentRedirect = new URL(siteURLData.redirect, request.url);
|
||||
const redirectURL = new URL(siteURLData.redirect, request.url);
|
||||
let contentRedirect = new URL(redirectURL);
|
||||
|
||||
// For content redirects, we redirect using the /url/:url format
|
||||
// during development and testing in 'url' mode.
|
||||
if (mode === 'url') {
|
||||
const urlObject = new URL(siteURLData.redirect);
|
||||
contentRedirect = new URL(
|
||||
`/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`,
|
||||
`/url/${redirectURL.host}${redirectURL.pathname}${redirectURL.search}`,
|
||||
request.url
|
||||
);
|
||||
}
|
||||
|
||||
// Keep the same search params as the original request
|
||||
// as it might contain a VA token
|
||||
contentRedirect.search = request.nextUrl.search;
|
||||
if (!isPreviewRequest(siteRequestURL) && isPreviewRequest(redirectURL)) {
|
||||
getLogger().info('Redirected disabled published preview to the preview domain');
|
||||
} else {
|
||||
// Keep the same search params as the original request
|
||||
// as it might contain a VA token
|
||||
contentRedirect.search = request.nextUrl.search;
|
||||
}
|
||||
|
||||
return createRedirectResponse(contentRedirect.toString());
|
||||
}
|
||||
@@ -617,6 +645,8 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
// noindex search/assistant deep links, kept crawlable so Google sees the directive.
|
||||
if (rewrittenURL.searchParams.has('ask') || rewrittenURL.searchParams.has('q')) {
|
||||
response.headers.set('x-robots-tag', 'none');
|
||||
} else if (hasRevisionSelector(siteURLData.basePath)) {
|
||||
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
|
||||
}
|
||||
|
||||
// Allow cross-origin requests from the same parent domain as the site.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import { type RevisionPageDocument, SiteVisibility } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { createLinker } from '@/lib/links';
|
||||
@@ -26,7 +26,7 @@ function createContext(options: {
|
||||
return {
|
||||
displayAgentInstructions: false,
|
||||
organizationId: 'org-1',
|
||||
site: { id: 'site-1' },
|
||||
site: { id: 'site-1', visibility: SiteVisibility.Public },
|
||||
siteSpace: { id: 'site-space-1' },
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
revisionId: 'revision-1',
|
||||
@@ -66,6 +66,23 @@ describe('servePageMarkdown', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('serves the current revision by selector with a noindex header for AI agents', async () => {
|
||||
const context = createContext({});
|
||||
const response = await servePageMarkdown(
|
||||
{
|
||||
...context,
|
||||
isAiAgent: true,
|
||||
linker: context.linker.fork({
|
||||
spaceBasePath: `/docs/~/revisions/${context.revisionId}/`,
|
||||
}),
|
||||
},
|
||||
'new-page'
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('X-Robots-Tag')).toBe('noindex, nofollow');
|
||||
});
|
||||
|
||||
it('redirects to the markdown version of a site redirect target', async () => {
|
||||
const context = createContext({
|
||||
siteRedirect: { target: 'https://docs.example.com/docs/new-page', permanent: true },
|
||||
|
||||
@@ -47,7 +47,7 @@ const CORS_HEADERS = {
|
||||
} as const;
|
||||
|
||||
// Neutralize active HTML: a navigated proxy response must never execute script, on any origin.
|
||||
// The fetch-based "Test it" panel is unaffected (the sandbox applies to documents, not fetch).
|
||||
// Scalar's fetch-based "Test it" is unaffected (the sandbox applies to documents, not fetch).
|
||||
const PROXY_SECURITY_HEADERS = {
|
||||
'content-security-policy': 'sandbox',
|
||||
'x-content-type-options': 'nosniff',
|
||||
@@ -201,13 +201,13 @@ export async function handleOpenAPIProxyRequest(request: NextRequest): Promise<R
|
||||
}
|
||||
}
|
||||
|
||||
// Browsers can't set Cookie on fetch, so Test it sends cookies via X-Scalar-Cookie
|
||||
// Scalar sends cookies via X-Scalar-Cookie when using a proxy
|
||||
const scalarCookie = request.headers.get('x-scalar-cookie');
|
||||
if (scalarCookie) {
|
||||
forwardedHeaders.set('cookie', scalarCookie);
|
||||
}
|
||||
|
||||
// Kept for clients that override the user-agent this way
|
||||
// Scalar sends user-agent via X-Scalar-User-Agent in some environments
|
||||
const scalarUserAgent = request.headers.get('x-scalar-user-agent');
|
||||
if (scalarUserAgent) {
|
||||
forwardedHeaders.set('user-agent', scalarUserAgent);
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
"@base-ui/react": "catalog:",
|
||||
"@gitbook/expr": "workspace:*",
|
||||
"@gitbook/openapi-parser": "workspace:*",
|
||||
"@scalar/api-client-react": "catalog:",
|
||||
"@scalar/oas-utils": "^0.6.3",
|
||||
"@scalar/types": "^0.4.0",
|
||||
"classnames": "catalog:",
|
||||
"flatted": "^3.2.9",
|
||||
"js-yaml": "^4.1.0",
|
||||
|
||||
@@ -8,12 +8,16 @@ import {
|
||||
OpenAPIMediaTypeExamplesSelector,
|
||||
} from './OpenAPICodeSampleInteractive';
|
||||
import { OpenAPICodeSampleBody } from './OpenAPICodeSampleSelector';
|
||||
import { OpenAPITryItButton } from './OpenAPITryItButton';
|
||||
import { ScalarApiButton } from './ScalarApiButton';
|
||||
import { stringifyOpenAPI } from './stringifyOpenAPI';
|
||||
import { buildTryItOperation } from './tryit/buildTryItOperation';
|
||||
import type { OpenAPIOperationData } from './types';
|
||||
import { mergeHeaders } from './util/headers';
|
||||
import { getAllServerOrigins, getDefaultServerURL, hasValidServerHost } from './util/server';
|
||||
import {
|
||||
extractOrigin,
|
||||
getAllServerOrigins,
|
||||
getDefaultServerURL,
|
||||
hasValidServerHost,
|
||||
} from './util/server';
|
||||
import {
|
||||
resolvePrefillCodePlaceholderFromSecurityScheme,
|
||||
resolveURLWithPrefillCodePlaceholdersFromServer,
|
||||
@@ -206,7 +210,7 @@ function OpenAPICodeSampleFooter(props: {
|
||||
context: OpenAPIContext;
|
||||
}) {
|
||||
const { data, context, renderers } = props;
|
||||
const { method, securities, servers } = data;
|
||||
const { method, path, securities, servers } = data;
|
||||
const { specUrl } = context;
|
||||
const hideTryItPanel = data['x-hideTryItPanel'] || data.operation['x-hideTryItPanel'];
|
||||
const hasMultipleMediaTypes =
|
||||
@@ -237,12 +241,14 @@ function OpenAPICodeSampleFooter(props: {
|
||||
<span />
|
||||
)}
|
||||
{!hideTryItPanel && hasValidHost && specUrl && (
|
||||
<OpenAPITryItButton
|
||||
context={resolveTryItClientContext(context, servers)}
|
||||
<ScalarApiButton
|
||||
context={resolveScalarClientContext(context, servers, specUrl)}
|
||||
withProxy={Boolean(data.operation['x-enable-proxy'] ?? data['x-enable-proxy'])}
|
||||
operation={buildTryItOperation(data)}
|
||||
method={method}
|
||||
path={path}
|
||||
securities={securities}
|
||||
servers={servers}
|
||||
specUrl={specUrl}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -250,17 +256,27 @@ function OpenAPICodeSampleFooter(props: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the client context for the Try it button, resolving the signed proxy URL
|
||||
* Build the client context for ScalarApiButton, resolving the signed proxy URL
|
||||
* with the allowed server hosts for SSRF protection.
|
||||
*/
|
||||
function resolveTryItClientContext(
|
||||
function resolveScalarClientContext(
|
||||
context: OpenAPIContext,
|
||||
servers: OpenAPIOperationData['servers']
|
||||
servers: OpenAPIOperationData['servers'],
|
||||
specUrl: string
|
||||
) {
|
||||
const clientContext = getOpenAPIClientContext(context);
|
||||
|
||||
if (context.resolveProxyUrl) {
|
||||
clientContext.proxyUrl = context.resolveProxyUrl(getAllServerOrigins(servers)) ?? undefined;
|
||||
// Collect all possible host+path entries from spec servers
|
||||
const origins = getAllServerOrigins(servers);
|
||||
|
||||
// Add the spec URL so the proxy can resolve it
|
||||
const specOrigin = extractOrigin(specUrl);
|
||||
if (specOrigin) {
|
||||
origins.push(specOrigin);
|
||||
}
|
||||
|
||||
clientContext.proxyUrl = context.resolveProxyUrl(origins) ?? undefined;
|
||||
}
|
||||
|
||||
return clientContext;
|
||||
|
||||
@@ -21,6 +21,7 @@ const context: OpenAPIClientContext = {
|
||||
hashtag: null,
|
||||
},
|
||||
expandAllModelSections: true,
|
||||
scalarRuntimeURL: '',
|
||||
$$isClientContext$$: true,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { type ComponentType, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import type { OpenAPIClientContext } from './context';
|
||||
import { useOpenAPIOperationContext } from './OpenAPIOperationContext';
|
||||
import { t } from './translate';
|
||||
import type { OpenAPITryItDialogProps } from './tryit/OpenAPITryItDialog';
|
||||
import type { TryItOperation } from './tryit/types';
|
||||
import type { OpenAPIOperationData } from './types';
|
||||
|
||||
let dialogPromise: Promise<ComponentType<OpenAPITryItDialogProps>> | null = null;
|
||||
|
||||
function loadDialog() {
|
||||
if (!dialogPromise) {
|
||||
dialogPromise = import('./tryit/OpenAPITryItDialog')
|
||||
.then((mod) => mod.OpenAPITryItDialog)
|
||||
.catch((error) => {
|
||||
dialogPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return dialogPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Button which opens the Try it panel for an operation.
|
||||
*/
|
||||
export function OpenAPITryItButton(props: {
|
||||
operation: TryItOperation;
|
||||
securities: OpenAPIOperationData['securities'];
|
||||
servers: OpenAPIOperationData['servers'];
|
||||
withProxy: boolean;
|
||||
context: OpenAPIClientContext;
|
||||
}) {
|
||||
const { operation, securities, servers, withProxy, context } = props;
|
||||
const { onOpenClient } = useOpenAPIOperationContext();
|
||||
const [Dialog, setDialog] = useState<ComponentType<OpenAPITryItDialogProps> | null>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const open = () => {
|
||||
onOpenClient({ method: operation.method, path: operation.path });
|
||||
if (Dialog) {
|
||||
setIsOpen(true);
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
loadDialog()
|
||||
.then((component) => {
|
||||
setDialog(() => component);
|
||||
setIsOpen(true);
|
||||
})
|
||||
.catch((error) => console.error('Unable to load the Try it panel', error))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="openapi-tryit-activate">
|
||||
<button
|
||||
type="button"
|
||||
className="openapi-tryit-button"
|
||||
aria-busy={isLoading}
|
||||
// Warm the chunk so the click usually opens instantly.
|
||||
onPointerEnter={() => void loadDialog().catch(() => {})}
|
||||
onFocus={() => void loadDialog().catch(() => {})}
|
||||
onClick={open}
|
||||
>
|
||||
{t(context.translation, 'test_it')}
|
||||
{isLoading ? (
|
||||
<svg
|
||||
className="openapi-tryit-button-spinner"
|
||||
aria-hidden="true"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeOpacity="0.3"
|
||||
strokeWidth="3"
|
||||
/>
|
||||
<path
|
||||
d="M12 2a10 10 0 0 1 10 10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="3"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg aria-hidden="true" viewBox="0 0 10 12" fill="currentColor">
|
||||
<path
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
d="M1 10.05V1.43c0-.2.2-.31.37-.22l7.26 4.08c.17.1.17.33.01.43l-7.26 4.54a.25.25 0 0 1-.38-.21Z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isOpen && Dialog
|
||||
? createPortal(
|
||||
<Dialog
|
||||
operation={operation}
|
||||
securities={securities}
|
||||
servers={servers}
|
||||
withProxy={withProxy}
|
||||
context={context}
|
||||
onClose={() => setIsOpen(false)}
|
||||
/>,
|
||||
document.body
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { type ComponentType, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import * as ReactJSXRuntime from 'react/jsx-runtime';
|
||||
|
||||
import type { OpenAPIV3_1 } from '@gitbook/openapi-parser';
|
||||
|
||||
import type { OpenAPIClientContext } from './context';
|
||||
import type {
|
||||
ScalarApiModalProps,
|
||||
ScalarModalControllerRef,
|
||||
ScalarRuntime,
|
||||
} from './ScalarApiModal';
|
||||
import { t } from './translate';
|
||||
import type { OpenAPIOperationData } from './types';
|
||||
|
||||
let scalarRuntimePromise: Promise<ScalarRuntime> | null = null;
|
||||
|
||||
/** Everything needed to render the client, none of it in the initial bundle. */
|
||||
type ScalarClient = {
|
||||
runtime: ScalarRuntime;
|
||||
Modal: ComponentType<ScalarApiModalProps>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Button which launches the Scalar API Client
|
||||
*/
|
||||
export function ScalarApiButton(props: {
|
||||
method: OpenAPIV3_1.HttpMethods;
|
||||
path: string;
|
||||
securities: OpenAPIOperationData['securities'];
|
||||
servers: OpenAPIOperationData['servers'];
|
||||
specUrl: string;
|
||||
withProxy: boolean;
|
||||
context: OpenAPIClientContext;
|
||||
}) {
|
||||
const { method, path, securities, servers, specUrl, withProxy, context } = props;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [client, setClient] = useState<ScalarClient | null>(null);
|
||||
const controllerRef = useRef<ScalarModalControllerRef>(null);
|
||||
|
||||
return (
|
||||
<div className="scalar scalar-activate">
|
||||
<button
|
||||
type="button"
|
||||
className="scalar-activate-button button"
|
||||
aria-busy={isLoading}
|
||||
onClick={() => {
|
||||
controllerRef.current?.openClient?.();
|
||||
setIsOpen(true);
|
||||
if (!client) {
|
||||
setIsLoading(true);
|
||||
loadScalarClient(context.scalarRuntimeURL)
|
||||
.then(setClient)
|
||||
.catch((error) => {
|
||||
console.error('Unable to load the Scalar API client', error);
|
||||
setIsOpen(false);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t(context.translation, 'test_it')}
|
||||
{isLoading ? (
|
||||
<svg
|
||||
className="scalar-activate-spinner"
|
||||
aria-hidden="true"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeOpacity="0.3"
|
||||
strokeWidth="3"
|
||||
/>
|
||||
<path
|
||||
d="M12 2a10 10 0 0 1 10 10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="3"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 10 12"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
d="M1 10.05V1.43c0-.2.2-.31.37-.22l7.26 4.08c.17.1.17.33.01.43l-7.26 4.54a.25.25 0 0 1-.38-.21Z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isOpen &&
|
||||
client &&
|
||||
createPortal(
|
||||
<client.Modal
|
||||
controllerRef={controllerRef}
|
||||
method={method}
|
||||
path={path}
|
||||
securities={securities}
|
||||
servers={servers}
|
||||
specUrl={specUrl}
|
||||
withProxy={withProxy}
|
||||
context={context}
|
||||
runtime={client.runtime}
|
||||
onReady={() => setIsLoading(false)}
|
||||
/>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Fetch the modal chunk and the Scalar runtime in parallel. */
|
||||
async function loadScalarClient(runtimeURL: string): Promise<ScalarClient> {
|
||||
const [runtime, mod] = await Promise.all([
|
||||
loadScalarRuntime(runtimeURL),
|
||||
import('./ScalarApiModal'),
|
||||
]);
|
||||
|
||||
return { runtime, Modal: mod.ScalarApiModal };
|
||||
}
|
||||
|
||||
async function loadScalarRuntime(runtimeURL: string): Promise<ScalarRuntime> {
|
||||
if (!scalarRuntimePromise) {
|
||||
Object.assign(globalThis, {
|
||||
__gitbookScalarReact: React,
|
||||
__gitbookScalarJSXRuntime: ReactJSXRuntime,
|
||||
});
|
||||
scalarRuntimePromise = import(/* webpackIgnore: true */ runtimeURL).catch((error) => {
|
||||
scalarRuntimePromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
return scalarRuntimePromise;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
'use client';
|
||||
|
||||
import '@scalar/api-client-react/style.css';
|
||||
import {
|
||||
type ComponentType,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from 'react';
|
||||
|
||||
import type { OpenAPIV3_1 } from '@gitbook/openapi-parser';
|
||||
|
||||
import type { OpenAPIClientContext } from './context';
|
||||
import { useOpenAPIOperationContext } from './OpenAPIOperationContext';
|
||||
import { useOpenAPIPrefillContext } from './OpenAPIPrefillContextProvider';
|
||||
import type { OpenAPIOperationData } from './types';
|
||||
import { resolveTryItPrefillForOperation } from './util/tryit-prefill';
|
||||
|
||||
export type ScalarModalControllerRef = {
|
||||
openClient: (() => void) | undefined;
|
||||
};
|
||||
|
||||
export type ScalarRuntime = {
|
||||
ApiClientModalProvider: ComponentType<{
|
||||
configuration: object;
|
||||
initialRequest: { method: string; path: string };
|
||||
children: ReactNode;
|
||||
}>;
|
||||
useApiClientModal: () => {
|
||||
open?: (request: { method: string; path: string; _source?: string }) => void;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type ScalarApiModalProps = {
|
||||
method: OpenAPIV3_1.HttpMethods;
|
||||
path: string;
|
||||
securities: OpenAPIOperationData['securities'];
|
||||
servers: OpenAPIOperationData['servers'];
|
||||
specUrl: string;
|
||||
withProxy: boolean;
|
||||
context: OpenAPIClientContext;
|
||||
runtime: ScalarRuntime;
|
||||
controllerRef: Ref<ScalarModalControllerRef>;
|
||||
/** Called once the client is initialized and the modal is opening. */
|
||||
onReady: () => void;
|
||||
};
|
||||
|
||||
/** Loaded only after a reader opens the Try it client. */
|
||||
export function ScalarApiModal(props: ScalarApiModalProps) {
|
||||
const {
|
||||
method,
|
||||
path,
|
||||
securities,
|
||||
servers,
|
||||
specUrl,
|
||||
withProxy,
|
||||
context,
|
||||
controllerRef,
|
||||
runtime,
|
||||
onReady,
|
||||
} = props;
|
||||
const getPrefillInputContextData = useOpenAPIPrefillContext();
|
||||
const prefillInputContext = getPrefillInputContextData();
|
||||
|
||||
const prefillConfig = resolveTryItPrefillForOperation({
|
||||
operation: { securities, servers },
|
||||
prefillInputContext,
|
||||
});
|
||||
|
||||
return (
|
||||
<runtime.ApiClientModalProvider
|
||||
configuration={{
|
||||
url: specUrl,
|
||||
...prefillConfig,
|
||||
proxyUrl: withProxy ? context.proxyUrl : undefined,
|
||||
}}
|
||||
initialRequest={{ method: toScalarHttpMethod(method), path }}
|
||||
>
|
||||
<ScalarModalController
|
||||
method={method}
|
||||
path={path}
|
||||
controllerRef={controllerRef}
|
||||
runtime={runtime}
|
||||
onReady={onReady}
|
||||
/>
|
||||
</runtime.ApiClientModalProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ScalarModalController(props: {
|
||||
method: OpenAPIV3_1.HttpMethods;
|
||||
path: string;
|
||||
controllerRef: Ref<ScalarModalControllerRef>;
|
||||
runtime: ScalarRuntime;
|
||||
onReady: () => void;
|
||||
}) {
|
||||
const { method, path, controllerRef, runtime, onReady } = props;
|
||||
const client = runtime.useApiClientModal();
|
||||
const openScalarClient = client?.open;
|
||||
const { onOpenClient: trackClientOpening } = useOpenAPIOperationContext();
|
||||
const openClient = useMemo(() => {
|
||||
if (openScalarClient) {
|
||||
return () => {
|
||||
openScalarClient({
|
||||
method: toScalarHttpMethod(method),
|
||||
path,
|
||||
_source: 'gitbook',
|
||||
});
|
||||
trackClientOpening({ method, path });
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}, [openScalarClient, method, path, trackClientOpening]);
|
||||
useImperativeHandle(
|
||||
controllerRef,
|
||||
() => ({ openClient: openClient ? () => openClient() : undefined }),
|
||||
[openClient]
|
||||
);
|
||||
|
||||
// Through a ref, so an unstable callback doesn't re-open the client on every render.
|
||||
const onReadyRef = useRef(onReady);
|
||||
onReadyRef.current = onReady;
|
||||
|
||||
useEffect(() => {
|
||||
if (openClient) {
|
||||
openClient();
|
||||
onReadyRef.current();
|
||||
}
|
||||
}, [openClient]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function toScalarHttpMethod<T extends OpenAPIV3_1.HttpMethods>(method: T): Uppercase<T> {
|
||||
return method.toUpperCase() as Uppercase<T>;
|
||||
}
|
||||
@@ -43,10 +43,13 @@ export interface OpenAPIClientContext {
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* The URL of the proxy used by Try it for APIs that don't allow CORS.
|
||||
* The URL for the Scalar proxy endpoint.
|
||||
*/
|
||||
proxyUrl?: string;
|
||||
|
||||
/** URL of the lazily loaded Scalar browser runtime. */
|
||||
scalarRuntimeURL: string;
|
||||
|
||||
/**
|
||||
* Mark the context as a client context.
|
||||
*/
|
||||
@@ -55,7 +58,7 @@ export interface OpenAPIClientContext {
|
||||
|
||||
export interface OpenAPIContext extends Omit<
|
||||
OpenAPIClientContext,
|
||||
'$$isClientContext$$' | 'proxyUrl'
|
||||
'$$isClientContext$$' | 'proxyUrl' | 'scalarRuntimeURL'
|
||||
> {
|
||||
/**
|
||||
* Render a code block.
|
||||
@@ -82,7 +85,8 @@ export interface OpenAPIContext extends Omit<
|
||||
headless?: boolean;
|
||||
|
||||
/**
|
||||
* Public specification URL. When null, the "Test it" button is hidden.
|
||||
* Public specification URL, used by Scalar's "Test it" modal.
|
||||
* When null, the "Test it" button is hidden.
|
||||
*/
|
||||
specUrl: string | null;
|
||||
|
||||
@@ -91,6 +95,9 @@ export interface OpenAPIContext extends Omit<
|
||||
* Called at render time (server-side) with the server origins for an operation.
|
||||
*/
|
||||
resolveProxyUrl?: (allowedOrigins: string[]) => string | null;
|
||||
|
||||
/** URL of the lazily loaded Scalar browser runtime. */
|
||||
scalarRuntimeURL: string;
|
||||
}
|
||||
|
||||
export type OpenAPIUniversalContext = OpenAPIClientContext | OpenAPIContext;
|
||||
@@ -126,6 +133,7 @@ export function getOpenAPIClientContext(context: OpenAPIUniversalContext): OpenA
|
||||
blockKey: context.blockKey,
|
||||
id: context.id,
|
||||
proxyUrl: '$$isClientContext$$' in context ? context.proxyUrl : undefined,
|
||||
scalarRuntimeURL: context.scalarRuntimeURL,
|
||||
$$isClientContext$$: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -46,26 +46,4 @@ export const de = {
|
||||
and: 'und',
|
||||
possible_values: 'Mögliche Werte',
|
||||
direct_link_to_model: 'Direktlink zu ${1}',
|
||||
server: 'Server',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Senden',
|
||||
cancel: 'Abbrechen',
|
||||
close: 'Schließen',
|
||||
username: 'Benutzername',
|
||||
password: 'Passwort',
|
||||
tryit_no_auth: 'Keine Autorisierung',
|
||||
tryit_no_response: 'Senden Sie die Anfrage, um die Antwort zu sehen.',
|
||||
tryit_request_failed:
|
||||
'Die Anfrage konnte nicht gesendet werden. Die API ist möglicherweise nicht erreichbar oder akzeptiert keine Anfragen von dieser Website.',
|
||||
tryit_missing_required: 'Füllen Sie die Pflichtfelder aus: ${1}',
|
||||
tryit_binary_response: 'Binäre Antwort, ${1}',
|
||||
tryit_truncated: 'Es werden die ersten ${1} der Antwort angezeigt.',
|
||||
tryit_download: 'Herunterladen',
|
||||
tryit_cookies_need_proxy:
|
||||
'Cookies werden nur gesendet, wenn Anfragen über den GitBook-Proxy laufen.',
|
||||
name: 'Name',
|
||||
value: 'Wert',
|
||||
tryit_add_header: 'Header',
|
||||
tryit_add_query_parameter: 'Query-Parameter',
|
||||
tryit_remove: 'Entfernen',
|
||||
};
|
||||
|
||||
@@ -46,25 +46,4 @@ export const en = {
|
||||
or: 'or',
|
||||
and: 'and',
|
||||
direct_link_to_model: 'Direct link to ${1}',
|
||||
server: 'Server',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Send',
|
||||
cancel: 'Cancel',
|
||||
close: 'Close',
|
||||
username: 'Username',
|
||||
password: 'Password',
|
||||
tryit_no_auth: 'No authorization',
|
||||
tryit_no_response: 'Send the request to see the response.',
|
||||
tryit_request_failed:
|
||||
'The request could not be sent. The API may be unreachable, or may not accept requests from this site.',
|
||||
tryit_missing_required: 'Fill in the required fields: ${1}',
|
||||
tryit_binary_response: 'Binary response, ${1}',
|
||||
tryit_truncated: 'Showing the first ${1} of the response.',
|
||||
tryit_download: 'Download',
|
||||
tryit_cookies_need_proxy: 'Cookies are only sent when requests go through the GitBook proxy.',
|
||||
name: 'Name',
|
||||
value: 'Value',
|
||||
tryit_add_header: 'Header',
|
||||
tryit_add_query_parameter: 'Query parameter',
|
||||
tryit_remove: 'Remove',
|
||||
};
|
||||
|
||||
@@ -46,26 +46,4 @@ export const es = {
|
||||
and: 'y',
|
||||
possible_values: 'Valores posibles',
|
||||
direct_link_to_model: 'Enlace directo a ${1}',
|
||||
server: 'Servidor',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Enviar',
|
||||
cancel: 'Cancelar',
|
||||
close: 'Cerrar',
|
||||
username: 'Usuario',
|
||||
password: 'Contraseña',
|
||||
tryit_no_auth: 'Sin autorización',
|
||||
tryit_no_response: 'Envía la solicitud para ver la respuesta.',
|
||||
tryit_request_failed:
|
||||
'No se pudo enviar la solicitud. Es posible que la API no esté disponible o que no acepte solicitudes desde este sitio.',
|
||||
tryit_missing_required: 'Completa los campos obligatorios: ${1}',
|
||||
tryit_binary_response: 'Respuesta binaria, ${1}',
|
||||
tryit_truncated: 'Mostrando los primeros ${1} de la respuesta.',
|
||||
tryit_download: 'Descargar',
|
||||
tryit_cookies_need_proxy:
|
||||
'Las cookies solo se envían cuando las solicitudes pasan por el proxy de GitBook.',
|
||||
name: 'Nombre',
|
||||
value: 'Valor',
|
||||
tryit_add_header: 'Encabezado',
|
||||
tryit_add_query_parameter: 'Parámetro de consulta',
|
||||
tryit_remove: 'Eliminar',
|
||||
};
|
||||
|
||||
@@ -46,26 +46,4 @@ export const fr = {
|
||||
and: 'et',
|
||||
possible_values: 'Valeurs possibles',
|
||||
direct_link_to_model: 'Lien direct vers ${1}',
|
||||
server: 'Serveur',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Envoyer',
|
||||
cancel: 'Annuler',
|
||||
close: 'Fermer',
|
||||
username: 'Nom d’utilisateur',
|
||||
password: 'Mot de passe',
|
||||
tryit_no_auth: 'Aucune autorisation',
|
||||
tryit_no_response: 'Envoyez la requête pour voir la réponse.',
|
||||
tryit_request_failed:
|
||||
'La requête n’a pas pu être envoyée. L’API est peut-être injoignable, ou n’accepte pas les requêtes depuis ce site.',
|
||||
tryit_missing_required: 'Renseignez les champs obligatoires : ${1}',
|
||||
tryit_binary_response: 'Réponse binaire, ${1}',
|
||||
tryit_truncated: 'Affichage des premiers ${1} de la réponse.',
|
||||
tryit_download: 'Télécharger',
|
||||
tryit_cookies_need_proxy:
|
||||
'Les cookies ne sont envoyés que lorsque les requêtes passent par le proxy GitBook.',
|
||||
name: 'Nom',
|
||||
value: 'Valeur',
|
||||
tryit_add_header: 'En-tête',
|
||||
tryit_add_query_parameter: 'Paramètre de requête',
|
||||
tryit_remove: 'Supprimer',
|
||||
};
|
||||
|
||||
@@ -46,25 +46,4 @@ export const ja = {
|
||||
and: 'および',
|
||||
possible_values: '可能な値',
|
||||
direct_link_to_model: '${1} への直接リンク',
|
||||
server: 'サーバー',
|
||||
cookie_parameters: 'Cookie',
|
||||
send: '送信',
|
||||
cancel: 'キャンセル',
|
||||
close: '閉じる',
|
||||
username: 'ユーザー名',
|
||||
password: 'パスワード',
|
||||
tryit_no_auth: '認証なし',
|
||||
tryit_no_response: 'リクエストを送信するとレスポンスが表示されます。',
|
||||
tryit_request_failed:
|
||||
'リクエストを送信できませんでした。API に到達できないか、このサイトからのリクエストを受け付けていない可能性があります。',
|
||||
tryit_missing_required: '必須項目を入力してください: ${1}',
|
||||
tryit_binary_response: 'バイナリレスポンス、${1}',
|
||||
tryit_truncated: 'レスポンスの最初の ${1} を表示しています。',
|
||||
tryit_download: 'ダウンロード',
|
||||
tryit_cookies_need_proxy: 'Cookie は GitBook プロキシ経由のリクエストでのみ送信されます。',
|
||||
name: '名前',
|
||||
value: '値',
|
||||
tryit_add_header: 'ヘッダー',
|
||||
tryit_add_query_parameter: 'クエリパラメーター',
|
||||
tryit_remove: '削除',
|
||||
};
|
||||
|
||||
@@ -46,26 +46,4 @@ export const nl = {
|
||||
and: 'en',
|
||||
possible_values: 'Mogelijke waarden',
|
||||
direct_link_to_model: 'Directe link naar ${1}',
|
||||
server: 'Server',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Verzenden',
|
||||
cancel: 'Annuleren',
|
||||
close: 'Sluiten',
|
||||
username: 'Gebruikersnaam',
|
||||
password: 'Wachtwoord',
|
||||
tryit_no_auth: 'Geen autorisatie',
|
||||
tryit_no_response: 'Verzend het verzoek om het antwoord te zien.',
|
||||
tryit_request_failed:
|
||||
'Het verzoek kon niet worden verzonden. De API is mogelijk onbereikbaar of accepteert geen verzoeken van deze site.',
|
||||
tryit_missing_required: 'Vul de verplichte velden in: ${1}',
|
||||
tryit_binary_response: 'Binair antwoord, ${1}',
|
||||
tryit_truncated: 'De eerste ${1} van het antwoord worden getoond.',
|
||||
tryit_download: 'Downloaden',
|
||||
tryit_cookies_need_proxy:
|
||||
'Cookies worden alleen verzonden als verzoeken via de GitBook-proxy gaan.',
|
||||
name: 'Naam',
|
||||
value: 'Waarde',
|
||||
tryit_add_header: 'Header',
|
||||
tryit_add_query_parameter: 'Queryparameter',
|
||||
tryit_remove: 'Verwijderen',
|
||||
};
|
||||
|
||||
@@ -46,26 +46,4 @@ export const no = {
|
||||
and: 'og',
|
||||
possible_values: 'Mulige verdier',
|
||||
direct_link_to_model: 'Direktelenke til ${1}',
|
||||
server: 'Server',
|
||||
cookie_parameters: 'Informasjonskapsler',
|
||||
send: 'Send',
|
||||
cancel: 'Avbryt',
|
||||
close: 'Lukk',
|
||||
username: 'Brukernavn',
|
||||
password: 'Passord',
|
||||
tryit_no_auth: 'Ingen autorisasjon',
|
||||
tryit_no_response: 'Send forespørselen for å se svaret.',
|
||||
tryit_request_failed:
|
||||
'Forespørselen kunne ikke sendes. API-et er kanskje utilgjengelig, eller godtar ikke forespørsler fra dette nettstedet.',
|
||||
tryit_missing_required: 'Fyll ut de obligatoriske feltene: ${1}',
|
||||
tryit_binary_response: 'Binært svar, ${1}',
|
||||
tryit_truncated: 'Viser de første ${1} av svaret.',
|
||||
tryit_download: 'Last ned',
|
||||
tryit_cookies_need_proxy:
|
||||
'Informasjonskapsler sendes bare når forespørsler går gjennom GitBook-proxyen.',
|
||||
name: 'Navn',
|
||||
value: 'Verdi',
|
||||
tryit_add_header: 'Header',
|
||||
tryit_add_query_parameter: 'Spørringsparameter',
|
||||
tryit_remove: 'Fjern',
|
||||
};
|
||||
|
||||
@@ -46,26 +46,4 @@ export const pt_br = {
|
||||
and: 'e',
|
||||
possible_values: 'Valores possíveis',
|
||||
direct_link_to_model: 'Link direto para ${1}',
|
||||
server: 'Servidor',
|
||||
cookie_parameters: 'Cookies',
|
||||
send: 'Enviar',
|
||||
cancel: 'Cancelar',
|
||||
close: 'Fechar',
|
||||
username: 'Usuário',
|
||||
password: 'Senha',
|
||||
tryit_no_auth: 'Sem autorização',
|
||||
tryit_no_response: 'Envie a requisição para ver a resposta.',
|
||||
tryit_request_failed:
|
||||
'Não foi possível enviar a requisição. A API pode estar inacessível ou não aceitar requisições deste site.',
|
||||
tryit_missing_required: 'Preencha os campos obrigatórios: ${1}',
|
||||
tryit_binary_response: 'Resposta binária, ${1}',
|
||||
tryit_truncated: 'Mostrando os primeiros ${1} da resposta.',
|
||||
tryit_download: 'Baixar',
|
||||
tryit_cookies_need_proxy:
|
||||
'Os cookies só são enviados quando as requisições passam pelo proxy do GitBook.',
|
||||
name: 'Nome',
|
||||
value: 'Valor',
|
||||
tryit_add_header: 'Cabeçalho',
|
||||
tryit_add_query_parameter: 'Parâmetro de consulta',
|
||||
tryit_remove: 'Remover',
|
||||
};
|
||||
|
||||
@@ -46,24 +46,4 @@ export const zh = {
|
||||
and: '和',
|
||||
possible_values: '可能的值',
|
||||
direct_link_to_model: '${1} 的直接链接',
|
||||
server: '服务器',
|
||||
cookie_parameters: 'Cookie',
|
||||
send: '发送',
|
||||
cancel: '取消',
|
||||
close: '关闭',
|
||||
username: '用户名',
|
||||
password: '密码',
|
||||
tryit_no_auth: '无授权',
|
||||
tryit_no_response: '发送请求以查看响应。',
|
||||
tryit_request_failed: '无法发送请求。API 可能无法访问,或不接受来自此站点的请求。',
|
||||
tryit_missing_required: '请填写必填字段:${1}',
|
||||
tryit_binary_response: '二进制响应,${1}',
|
||||
tryit_truncated: '显示响应的前 ${1}。',
|
||||
tryit_download: '下载',
|
||||
tryit_cookies_need_proxy: '仅当请求通过 GitBook 代理时才会发送 Cookie。',
|
||||
name: '名称',
|
||||
value: '值',
|
||||
tryit_add_header: '请求头',
|
||||
tryit_add_query_parameter: '查询参数',
|
||||
tryit_remove: '删除',
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,254 +0,0 @@
|
||||
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
|
||||
|
||||
import {
|
||||
isFormData,
|
||||
isFormUrlEncoded,
|
||||
isJSON,
|
||||
isPlainObject,
|
||||
isText,
|
||||
isXML,
|
||||
isYAML,
|
||||
} from '../contentTypeChecks';
|
||||
import { generateMediaTypeExamples, generateSchemaExample } from '../generateSchemaExample';
|
||||
import { json2xml } from '../json2xml';
|
||||
import { stringifyOpenAPI } from '../stringifyOpenAPI';
|
||||
import type { OpenAPIOperationData } from '../types';
|
||||
import { checkIsReference } from '../utils';
|
||||
import type {
|
||||
TryItBodyField,
|
||||
TryItMediaType,
|
||||
TryItOperation,
|
||||
TryItParameter,
|
||||
TryItParameterLocation,
|
||||
TryItSecurityOption,
|
||||
} from './types';
|
||||
|
||||
const PARAMETER_LOCATIONS = new Set<string>(['path', 'query', 'header', 'cookie']);
|
||||
|
||||
/**
|
||||
* Reduce an operation to what the Try it panel needs, so the client never receives the full
|
||||
* (possibly huge, possibly circular) dereferenced operation.
|
||||
*/
|
||||
export function buildTryItOperation(data: OpenAPIOperationData): TryItOperation {
|
||||
return {
|
||||
method: data.method,
|
||||
path: data.path,
|
||||
parameters: buildParameters(data.operation.parameters),
|
||||
body: buildBody(data.operation.requestBody),
|
||||
securityOptions: buildSecurityOptions(data),
|
||||
};
|
||||
}
|
||||
|
||||
function buildParameters(parameters: OpenAPIV3.OperationObject['parameters']): TryItParameter[] {
|
||||
// The parser can return an object instead of an array for invalid specs.
|
||||
if (!Array.isArray(parameters)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: TryItParameter[] = [];
|
||||
const seen = new Set<string>();
|
||||
// Operation-level parameters come last and override path-level ones with the same key.
|
||||
for (const parameter of [...parameters].reverse()) {
|
||||
if (!parameter || checkIsReference(parameter) || !parameter.name) {
|
||||
continue;
|
||||
}
|
||||
if (!parameter.in || !PARAMETER_LOCATIONS.has(parameter.in)) {
|
||||
continue;
|
||||
}
|
||||
const key = `${parameter.in}:${parameter.name}`;
|
||||
if (seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(key);
|
||||
|
||||
const schema = checkIsReference(parameter.schema) ? undefined : parameter.schema;
|
||||
result.unshift({
|
||||
name: parameter.name,
|
||||
in: parameter.in as TryItParameterLocation,
|
||||
required: parameter.in === 'path' || Boolean(parameter.required),
|
||||
description: parameter.description,
|
||||
...(parameter.in === 'query' &&
|
||||
schema?.type === 'array' &&
|
||||
(parameter.style ?? 'form') === 'form' &&
|
||||
parameter.explode !== false
|
||||
? { explode: true }
|
||||
: {}),
|
||||
...describeField(schema, parameter.example ?? firstExampleValue(parameter.examples)),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildBody(requestBody: OpenAPIV3.OperationObject['requestBody']): TryItOperation['body'] {
|
||||
if (!requestBody || checkIsReference(requestBody) || !requestBody.content) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mediaTypes = Object.entries(requestBody.content).map(([mediaType, mediaTypeObject]) =>
|
||||
buildMediaType(mediaType, mediaTypeObject)
|
||||
);
|
||||
if (mediaTypes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { required: Boolean(requestBody.required), mediaTypes };
|
||||
}
|
||||
|
||||
function buildMediaType(
|
||||
mediaType: string,
|
||||
mediaTypeObject: OpenAPIV3.MediaTypeObject
|
||||
): TryItMediaType {
|
||||
const schema = checkIsReference(mediaTypeObject.schema) ? undefined : mediaTypeObject.schema;
|
||||
const formLike = isFormData(mediaType) || isFormUrlEncoded(mediaType);
|
||||
const fields = formLike ? buildBodyFields(schema) : [];
|
||||
|
||||
if (formLike && fields.length > 0) {
|
||||
return {
|
||||
mediaType,
|
||||
kind: isFormData(mediaType) ? 'multipart' : 'form',
|
||||
examples: [],
|
||||
fields,
|
||||
};
|
||||
}
|
||||
|
||||
if (isBinaryMediaType(mediaType, schema)) {
|
||||
return { mediaType, kind: 'binary', examples: [], fields: [] };
|
||||
}
|
||||
|
||||
const examples = generateMediaTypeExamples(mediaTypeObject, { mode: 'write' })
|
||||
.filter((example) => example.value !== undefined)
|
||||
.map((example, index) => ({
|
||||
label: example.summary || `Example ${index + 1}`,
|
||||
value: formatBodyExample(mediaType, example.value),
|
||||
}));
|
||||
|
||||
return { mediaType, kind: 'raw', examples, fields: [] };
|
||||
}
|
||||
|
||||
function buildBodyFields(schema: OpenAPIV3.SchemaObject | undefined): TryItBodyField[] {
|
||||
if (!schema?.properties) {
|
||||
return [];
|
||||
}
|
||||
const required = new Set(schema.required ?? []);
|
||||
|
||||
return Object.entries(schema.properties).flatMap(([name, property]) => {
|
||||
if (checkIsReference(property) || property.readOnly) {
|
||||
return [];
|
||||
}
|
||||
const binary = isBinarySchema(property);
|
||||
return [
|
||||
{
|
||||
name,
|
||||
required: required.has(name),
|
||||
description: property.description,
|
||||
binary,
|
||||
...(binary ? {} : describeField(property, undefined)),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function buildSecurityOptions(data: OpenAPIOperationData): TryItSecurityOption[] {
|
||||
const known = new Set(data.securities.map(([name]) => name));
|
||||
const requirements = data.operation.security;
|
||||
|
||||
if (!requirements || requirements.length === 0) {
|
||||
return data.securities.map(([name]) => ({ label: name, schemes: [name] }));
|
||||
}
|
||||
|
||||
const options = new Map<string, TryItSecurityOption>();
|
||||
for (const requirement of requirements) {
|
||||
const schemes = Object.keys(requirement)
|
||||
.filter((name) => known.has(name))
|
||||
.sort();
|
||||
// An empty requirement (`{}`) means the operation can be called anonymously.
|
||||
const label = schemes.length ? schemes.join(' & ') : '';
|
||||
if (!options.has(label)) {
|
||||
options.set(label, { label, schemes });
|
||||
}
|
||||
}
|
||||
return Array.from(options.values());
|
||||
}
|
||||
|
||||
function describeField(
|
||||
schema: OpenAPIV3.SchemaObject | undefined,
|
||||
explicitExample: unknown
|
||||
): Pick<TryItParameter, 'enum' | 'placeholder' | 'defaultValue'> {
|
||||
const values =
|
||||
schema?.enum ??
|
||||
(isPlainObject(schema?.items) ? schema.items.enum : undefined) ??
|
||||
(schema?.type === 'boolean' ? [true, false] : undefined);
|
||||
const enumValues = Array.isArray(values)
|
||||
? values.filter((value) => value !== null).map((value) => toInputValue(value))
|
||||
: undefined;
|
||||
|
||||
const explicit = schema?.default ?? explicitExample ?? schema?.example;
|
||||
let generated =
|
||||
explicit === undefined && schema
|
||||
? generateSchemaExample(schema, { mode: 'write' })
|
||||
: explicit;
|
||||
// The generator's stand-in for a plain string; the type tells the reader more.
|
||||
if (explicit === undefined && generated === 'text' && schema) {
|
||||
generated = schema.format ?? 'string';
|
||||
}
|
||||
|
||||
return {
|
||||
...(enumValues?.length ? { enum: enumValues } : {}),
|
||||
...(generated !== undefined && generated !== null
|
||||
? { placeholder: toInputValue(generated) }
|
||||
: {}),
|
||||
...(explicit !== undefined && explicit !== null
|
||||
? { defaultValue: toInputValue(explicit) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function firstExampleValue(examples: OpenAPIV3.ParameterObject['examples']): unknown {
|
||||
const first = examples ? Object.values(examples)[0] : undefined;
|
||||
return first && !checkIsReference(first) ? first.value : undefined;
|
||||
}
|
||||
|
||||
function toInputValue(value: unknown): string {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
// Arrays of scalars are typed comma-separated, the way most APIs accept them in a query.
|
||||
if (Array.isArray(value) && value.every((item) => typeof item !== 'object')) {
|
||||
return value.join(',');
|
||||
}
|
||||
return stringifyOpenAPI(value);
|
||||
}
|
||||
|
||||
function formatBodyExample(mediaType: string, value: unknown): string {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (isXML(mediaType) && isPlainObject(value)) {
|
||||
return json2xml(value);
|
||||
}
|
||||
if (isJSON(mediaType) || isYAML(mediaType) || isText(mediaType) || isPlainObject(value)) {
|
||||
return stringifyOpenAPI(value, null, 2);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function isBinarySchema(schema: OpenAPIV3.SchemaObject): boolean {
|
||||
const items = isPlainObject(schema.items) ? (schema.items as OpenAPIV3.SchemaObject) : null;
|
||||
return (
|
||||
schema.format === 'binary' ||
|
||||
'contentMediaType' in schema ||
|
||||
(schema.type === 'array' && items !== null && isBinarySchema(items))
|
||||
);
|
||||
}
|
||||
|
||||
function isBinaryMediaType(mediaType: string, schema: OpenAPIV3.SchemaObject | undefined) {
|
||||
const lower = mediaType.toLowerCase();
|
||||
return (
|
||||
lower === 'application/octet-stream' ||
|
||||
lower.startsWith('image/') ||
|
||||
lower.startsWith('audio/') ||
|
||||
lower.startsWith('video/') ||
|
||||
lower === 'application/pdf' ||
|
||||
(schema !== undefined && schema.format === 'binary')
|
||||
);
|
||||
}
|
||||
@@ -1,333 +0,0 @@
|
||||
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
|
||||
|
||||
import { isFormData } from '../contentTypeChecks';
|
||||
import type { OpenAPICustomSecurityScheme } from '../types';
|
||||
import type { TryItPrefillAuthValue } from '../util/tryit-prefill';
|
||||
import type { TryItMediaType, TryItOperation, TryItParameter } from './types';
|
||||
|
||||
/** Values typed by the reader, keyed by `fieldKey`/`authKey`. */
|
||||
export interface TryItValues {
|
||||
server: OpenAPIV3.ServerObject | undefined;
|
||||
serverVariables: Record<string, string>;
|
||||
/** Schemes of the selected security option. */
|
||||
schemes: [string, OpenAPICustomSecurityScheme][];
|
||||
auth: Record<string, string>;
|
||||
parameters: Record<string, string>;
|
||||
/** Checkbox state of optional parameters, by `fieldKey`; unset means checked. */
|
||||
enabledParameters?: Record<string, boolean>;
|
||||
mediaType: TryItMediaType | undefined;
|
||||
bodyText: string;
|
||||
bodyFields: Record<string, string>;
|
||||
bodyFiles: Record<string, File[]>;
|
||||
/** Headers and query parameters the spec doesn't declare, added by the reader. */
|
||||
extraParameters?: TryItExtraParameter[];
|
||||
}
|
||||
|
||||
export interface TryItExtraParameter {
|
||||
/** Stable React key for the row. */
|
||||
id?: number;
|
||||
in: 'header' | 'query';
|
||||
name: string;
|
||||
value: string;
|
||||
/** Unset means checked. */
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface TryItRequest {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
body: string | FormData | URLSearchParams | File | undefined;
|
||||
/** Cookies can't be set from the browser; only the proxy can forward them. */
|
||||
cookies: string;
|
||||
/** Labels of the required fields left empty. */
|
||||
missing: string[];
|
||||
}
|
||||
|
||||
export function fieldKey(parameter: Pick<TryItParameter, 'in' | 'name'>) {
|
||||
return `${parameter.in}:${parameter.name}`;
|
||||
}
|
||||
|
||||
export function authKey(scheme: string, part: 'value' | 'username' | 'password' = 'value') {
|
||||
return `${scheme}:${part}`;
|
||||
}
|
||||
|
||||
/** Turn prefilled auth into initial input values. */
|
||||
export function prefillAuthValues(
|
||||
securitySchemes: Record<string, TryItPrefillAuthValue> | undefined
|
||||
): Record<string, string> {
|
||||
const values: Record<string, string> = {};
|
||||
for (const [scheme, value] of Object.entries(securitySchemes ?? {})) {
|
||||
if ('token' in value) {
|
||||
values[authKey(scheme)] = value.token;
|
||||
} else if ('username' in value) {
|
||||
values[authKey(scheme, 'username')] = value.username ?? '';
|
||||
values[authKey(scheme, 'password')] = value.password ?? '';
|
||||
} else {
|
||||
values[authKey(scheme)] = value.value;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
export function resolveServerURL(
|
||||
server: OpenAPIV3.ServerObject | undefined,
|
||||
variables: Record<string, string>
|
||||
): string {
|
||||
if (!server?.url) {
|
||||
return '';
|
||||
}
|
||||
const url = server.url.replace(/{([^}]+)}/g, (match, name: string) => {
|
||||
return variables[name] ?? server.variables?.[name]?.default?.toString() ?? match;
|
||||
});
|
||||
// `hasValidServerHost` also accepts a bare host (`api.example.com`); default those to HTTPS.
|
||||
const absolute = /^https?:\/\//i.test(url) ? url : `https://${url}`;
|
||||
return absolute.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the HTTP request from the operation and what the reader typed.
|
||||
*/
|
||||
export function buildTryItRequest(operation: TryItOperation, values: TryItValues): TryItRequest {
|
||||
const missing: string[] = [];
|
||||
const headers: Record<string, string> = {};
|
||||
const query = new URLSearchParams();
|
||||
const cookies: string[] = [];
|
||||
|
||||
let path = operation.path;
|
||||
for (const parameter of operation.parameters) {
|
||||
const key = fieldKey(parameter);
|
||||
if (!parameter.required && values.enabledParameters?.[key] === false) {
|
||||
continue;
|
||||
}
|
||||
const value = values.parameters[key] ?? '';
|
||||
if (value === '') {
|
||||
if (parameter.required) {
|
||||
missing.push(parameter.name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
switch (parameter.in) {
|
||||
case 'path':
|
||||
path = path.replaceAll(`{${parameter.name}}`, encodeURIComponent(value));
|
||||
break;
|
||||
case 'query':
|
||||
if (parameter.explode) {
|
||||
for (const item of value.split(',')) {
|
||||
query.append(parameter.name, item.trim());
|
||||
}
|
||||
} else {
|
||||
query.append(parameter.name, value);
|
||||
}
|
||||
break;
|
||||
case 'header':
|
||||
setHeader(headers, parameter.name, value);
|
||||
break;
|
||||
case 'cookie':
|
||||
cookies.push(`${parameter.name}=${encodeURIComponent(value)}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (const extra of values.extraParameters ?? []) {
|
||||
const name = extra.name.trim();
|
||||
if (!name || extra.enabled === false) {
|
||||
continue;
|
||||
}
|
||||
if (extra.in === 'header') {
|
||||
setHeader(headers, name, extra.value);
|
||||
} else {
|
||||
query.append(name, extra.value);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, scheme] of values.schemes) {
|
||||
applyAuth(name, scheme, values.auth, { headers, query, cookies });
|
||||
}
|
||||
|
||||
const { body, contentType } = buildBody(values, missing, operation.body?.required ?? false);
|
||||
if (contentType && !hasHeader(headers, 'content-type')) {
|
||||
headers['Content-Type'] = contentType;
|
||||
}
|
||||
|
||||
const search = query.toString();
|
||||
return {
|
||||
url: `${resolveServerURL(values.server, values.serverVariables)}${path}${search ? `?${search}` : ''}`,
|
||||
method: operation.method.toUpperCase(),
|
||||
headers,
|
||||
body,
|
||||
cookies: cookies.join('; '),
|
||||
missing,
|
||||
};
|
||||
}
|
||||
|
||||
function applyAuth(
|
||||
name: string,
|
||||
scheme: OpenAPICustomSecurityScheme,
|
||||
auth: Record<string, string>,
|
||||
target: { headers: Record<string, string>; query: URLSearchParams; cookies: string[] }
|
||||
) {
|
||||
switch (scheme.type) {
|
||||
case 'http': {
|
||||
const httpScheme = scheme.scheme?.toLowerCase() ?? '';
|
||||
if (httpScheme.includes('basic')) {
|
||||
const username = auth[authKey(name, 'username')] ?? '';
|
||||
const password = auth[authKey(name, 'password')] ?? '';
|
||||
if (username || password) {
|
||||
setHeader(
|
||||
target.headers,
|
||||
'Authorization',
|
||||
`Basic ${encodeBase64(`${username}:${password}`)}`
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const token = auth[authKey(name)];
|
||||
if (token) {
|
||||
const prefix = httpScheme.includes('bearer')
|
||||
? 'Bearer'
|
||||
: (scheme.scheme ?? 'Bearer');
|
||||
setHeader(target.headers, 'Authorization', `${prefix} ${token}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'apiKey': {
|
||||
const value = auth[authKey(name)];
|
||||
if (!value || !scheme.name) {
|
||||
return;
|
||||
}
|
||||
const prefix = scheme['x-gitbook-prefix'];
|
||||
const full = prefix ? `${prefix} ${value}` : value;
|
||||
if (scheme.in === 'query') {
|
||||
target.query.append(scheme.name, full);
|
||||
} else if (scheme.in === 'cookie') {
|
||||
target.cookies.push(`${scheme.name}=${encodeURIComponent(full)}`);
|
||||
} else {
|
||||
setHeader(target.headers, scheme.name, full);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'oauth2':
|
||||
case 'openIdConnect': {
|
||||
const token = auth[authKey(name)];
|
||||
if (token) {
|
||||
setHeader(
|
||||
target.headers,
|
||||
'Authorization',
|
||||
`${scheme['x-gitbook-prefix'] ?? 'Bearer'} ${token}`
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildBody(
|
||||
values: TryItValues,
|
||||
missing: string[],
|
||||
required: boolean
|
||||
): { body: TryItRequest['body']; contentType?: string } {
|
||||
const { mediaType } = values;
|
||||
if (!mediaType) {
|
||||
return { body: undefined };
|
||||
}
|
||||
|
||||
switch (mediaType.kind) {
|
||||
case 'raw': {
|
||||
if (values.bodyText.trim() === '') {
|
||||
if (required) {
|
||||
missing.push('body');
|
||||
}
|
||||
return { body: undefined };
|
||||
}
|
||||
return {
|
||||
body: values.bodyText,
|
||||
// A multipart Content-Type without its boundary would make the body unparseable.
|
||||
contentType: isFormData(mediaType.mediaType) ? undefined : mediaType.mediaType,
|
||||
};
|
||||
}
|
||||
case 'binary': {
|
||||
const file = values.bodyFiles['']?.[0];
|
||||
if (!file) {
|
||||
if (required) {
|
||||
missing.push('body');
|
||||
}
|
||||
return { body: undefined };
|
||||
}
|
||||
return { body: file, contentType: mediaType.mediaType };
|
||||
}
|
||||
case 'form': {
|
||||
const form = new URLSearchParams();
|
||||
for (const field of mediaType.fields) {
|
||||
const value = values.bodyFields[field.name] ?? '';
|
||||
if (value === '') {
|
||||
if (field.required) {
|
||||
missing.push(field.name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
form.append(field.name, value);
|
||||
}
|
||||
return { body: form, contentType: mediaType.mediaType };
|
||||
}
|
||||
case 'multipart': {
|
||||
const form = new FormData();
|
||||
for (const field of mediaType.fields) {
|
||||
if (field.binary) {
|
||||
const files = values.bodyFiles[field.name] ?? [];
|
||||
if (files.length === 0 && field.required) {
|
||||
missing.push(field.name);
|
||||
}
|
||||
for (const file of files) {
|
||||
form.append(field.name, file);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const value = values.bodyFields[field.name] ?? '';
|
||||
if (value === '') {
|
||||
if (field.required) {
|
||||
missing.push(field.name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
form.append(field.name, value);
|
||||
}
|
||||
// No Content-Type: the browser has to add the multipart boundary itself.
|
||||
return { body: form };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Route the request through GitBook's proxy, for APIs that don't allow CORS. */
|
||||
export function toProxyRequest(request: TryItRequest, proxyUrl: string): TryItRequest {
|
||||
const url = new URL(proxyUrl);
|
||||
url.searchParams.set('scalar_url', request.url);
|
||||
const headers = { ...request.headers };
|
||||
if (request.cookies) {
|
||||
headers['X-Scalar-Cookie'] = request.cookies;
|
||||
}
|
||||
return { ...request, url: url.toString(), headers };
|
||||
}
|
||||
|
||||
function hasHeader(headers: Record<string, string>, name: string) {
|
||||
return Object.keys(headers).some((key) => key.toLowerCase() === name);
|
||||
}
|
||||
|
||||
/** Header names are case-insensitive; a later value (auth) replaces an earlier one. */
|
||||
function setHeader(headers: Record<string, string>, name: string, value: string) {
|
||||
for (const key of Object.keys(headers)) {
|
||||
if (key.toLowerCase() === name.toLowerCase()) {
|
||||
delete headers[key];
|
||||
}
|
||||
}
|
||||
headers[name] = value;
|
||||
}
|
||||
|
||||
function encodeBase64(value: string) {
|
||||
const bytes = new TextEncoder().encode(value);
|
||||
let binary = '';
|
||||
for (let index = 0; index < bytes.length; index++) {
|
||||
binary += String.fromCharCode(bytes[index] ?? 0);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
const MAX_DISPLAYED_BYTES = 512 * 1024;
|
||||
const TEXT_CONTENT_TYPE = /json|xml|text\/|javascript|yaml|csv|html|x-www-form-urlencoded|graphql/i;
|
||||
const PREVIEWABLE_IMAGE = /^image\/(png|jpeg|gif|webp|avif|bmp)\b/i;
|
||||
|
||||
export interface TryItResponse {
|
||||
status: number;
|
||||
statusText: string;
|
||||
durationMs: number;
|
||||
headers: [string, string][];
|
||||
size: number;
|
||||
contentType: string;
|
||||
/** Set for textual responses, pretty-printed when JSON. */
|
||||
text: string | null;
|
||||
truncated: boolean;
|
||||
/** Object URL of the raw body, for binary responses; the caller revokes it. */
|
||||
blobUrl: string | null;
|
||||
/** Whether `blobUrl` is a raster image safe to show in an `<img>`. */
|
||||
isImage: boolean;
|
||||
}
|
||||
|
||||
export async function readTryItResponse(
|
||||
response: Response,
|
||||
startedAt: number
|
||||
): Promise<TryItResponse> {
|
||||
const buffer = await response.arrayBuffer();
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
const headers = Array.from(response.headers.entries());
|
||||
const base = {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
durationMs,
|
||||
headers,
|
||||
size: buffer.byteLength,
|
||||
contentType,
|
||||
};
|
||||
|
||||
const isBinary = contentType
|
||||
? !TEXT_CONTENT_TYPE.test(contentType)
|
||||
: looksBinary(new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 1024)));
|
||||
if (buffer.byteLength > 0 && isBinary) {
|
||||
const isImage = PREVIEWABLE_IMAGE.test(contentType);
|
||||
// The blob lives on the docs site's origin: never let the API pick a type a browser
|
||||
// could render as a document if the reader opens the link.
|
||||
const blobType = isImage ? contentType : 'application/octet-stream';
|
||||
return {
|
||||
...base,
|
||||
text: null,
|
||||
truncated: false,
|
||||
blobUrl: URL.createObjectURL(new Blob([buffer], { type: blobType })),
|
||||
isImage,
|
||||
};
|
||||
}
|
||||
|
||||
const truncated = buffer.byteLength > MAX_DISPLAYED_BYTES;
|
||||
const text = new TextDecoder().decode(
|
||||
truncated ? buffer.slice(0, MAX_DISPLAYED_BYTES) : buffer
|
||||
);
|
||||
return {
|
||||
...base,
|
||||
text: truncated ? text : prettyPrint(text, contentType),
|
||||
truncated,
|
||||
blobUrl: null,
|
||||
isImage: false,
|
||||
};
|
||||
}
|
||||
|
||||
function looksBinary(bytes: Uint8Array): boolean {
|
||||
if (bytes.includes(0)) {
|
||||
return true;
|
||||
}
|
||||
// `stream` holds back a multibyte character cut at the end of the sample instead of flagging it.
|
||||
return new TextDecoder().decode(bytes, { stream: true }).includes('\uFFFD');
|
||||
}
|
||||
|
||||
function prettyPrint(text: string, contentType: string): string {
|
||||
if (!/json/i.test(contentType)) {
|
||||
return text;
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(text), null, 2);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) {
|
||||
return `${bytes} B`;
|
||||
}
|
||||
if (bytes < 1024 * 1024) {
|
||||
return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from 'bun:test';
|
||||
|
||||
import {
|
||||
getTryItApiScope,
|
||||
getTryItApiSession,
|
||||
getTryItOperationSession,
|
||||
resetTryItSession,
|
||||
saveTryItOperationSession,
|
||||
} from './session';
|
||||
|
||||
const operation = { method: 'post', path: '/pets' };
|
||||
const values = {
|
||||
parameters: { 'query:limit': '5' },
|
||||
enabledParameters: {},
|
||||
mediaType: 'application/json',
|
||||
bodyText: '{}',
|
||||
bodyFields: {},
|
||||
extraParameters: [],
|
||||
};
|
||||
|
||||
describe('Try it session', () => {
|
||||
beforeEach(() => resetTryItSession());
|
||||
|
||||
it('identifies an API by its server origins, whatever the paths or order', () => {
|
||||
expect(
|
||||
getTryItApiScope([
|
||||
{ url: 'https://b.example.com/v2' },
|
||||
{ url: 'https://A.example.com/v1/' },
|
||||
])
|
||||
).toBe(getTryItApiScope([{ url: 'https://a.example.com' }, { url: 'b.example.com' }]));
|
||||
});
|
||||
|
||||
it('resolves templated servers before comparing them', () => {
|
||||
const withHost = (host: string) =>
|
||||
getTryItApiScope([{ url: '{host}/v1', variables: { host: { default: host } } }]);
|
||||
expect(withHost('https://api.gitbook.com')).toBe('api.gitbook.com');
|
||||
expect(withHost('https://api.a.com')).not.toBe(withHost('https://api.b.com'));
|
||||
});
|
||||
|
||||
it('has no scope when no server resolves to a concrete host', () => {
|
||||
expect(getTryItApiScope([{ url: '/relative' }])).toBeNull();
|
||||
expect(getTryItApiScope([{ url: 'https://{region}.example.com' }])).toBeNull();
|
||||
expect(getTryItApiScope([])).toBeNull();
|
||||
});
|
||||
|
||||
it('never shares credentials between two APIs', () => {
|
||||
const a = getTryItApiScope([{ url: 'https://a.example.com' }]) ?? '';
|
||||
const b = getTryItApiScope([{ url: 'https://b.example.com' }]) ?? '';
|
||||
getTryItApiSession(a).auth['bearerAuth:value'] = 'token-for-a';
|
||||
|
||||
expect(getTryItApiSession(a).auth).toEqual({ 'bearerAuth:value': 'token-for-a' });
|
||||
expect(getTryItApiSession(b).auth).toEqual({});
|
||||
});
|
||||
|
||||
it('keeps operations with the same method and path apart across APIs', () => {
|
||||
const a = getTryItApiScope([{ url: 'https://a.example.com' }]) ?? '';
|
||||
const b = getTryItApiScope([{ url: 'https://b.example.com' }]) ?? '';
|
||||
saveTryItOperationSession(a, operation, values);
|
||||
|
||||
expect(getTryItOperationSession(a, { method: 'POST', path: '/pets' })).toEqual(values);
|
||||
expect(getTryItOperationSession(b, operation)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
|
||||
|
||||
import { interpolateServerURL, isValidServerHost } from '../util/server';
|
||||
import type { TryItExtraParameter } from './request';
|
||||
|
||||
export interface TryItOperationSession {
|
||||
parameters: Record<string, string>;
|
||||
enabledParameters: Record<string, boolean>;
|
||||
/** Stored by name: the index alone can't tell whether it still points at the same type. */
|
||||
mediaType: string | null;
|
||||
bodyText: string;
|
||||
bodyFields: Record<string, string>;
|
||||
extraParameters: TryItExtraParameter[];
|
||||
}
|
||||
|
||||
/** Values shared by every operation of one API, like a token entered once. */
|
||||
export interface TryItApiSession {
|
||||
/** Only values the reader typed, so fresh prefill still applies to the rest. */
|
||||
auth: Record<string, string>;
|
||||
serverURL: string | null;
|
||||
serverVariables: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the reader typed, kept for the page's lifetime so reopening Try it doesn't start over.
|
||||
* Scoped per API (its server origins) so a token typed for one API is never sent to another
|
||||
* that happens to reuse a scheme name. Memory only: credentials must never reach web storage.
|
||||
*/
|
||||
let apis = new Map<string, TryItApiSession>();
|
||||
let operations = new Map<string, TryItOperationSession>();
|
||||
|
||||
/**
|
||||
* Identify the API an operation belongs to by the hosts its servers resolve to, with their
|
||||
* variables' defaults. Raw templates such as `{host}/v1` would make unrelated APIs collide.
|
||||
* Returns null when no server resolves to a concrete host: nothing may be shared then.
|
||||
*/
|
||||
export function getTryItApiScope(servers: OpenAPIV3.ServerObject[]): string | null {
|
||||
const hosts = new Set<string>();
|
||||
for (const server of servers) {
|
||||
const host = resolveHost(interpolateServerURL(server));
|
||||
if (host) {
|
||||
hosts.add(host);
|
||||
}
|
||||
}
|
||||
return hosts.size > 0 ? Array.from(hosts).sort().join(' ') : null;
|
||||
}
|
||||
|
||||
function resolveHost(url: string): string | null {
|
||||
if (!isValidServerHost(url)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const { host } = new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`);
|
||||
return host && !host.includes('{') ? host : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getTryItApiSession(scope: string): TryItApiSession {
|
||||
let api = apis.get(scope);
|
||||
if (!api) {
|
||||
api = { auth: {}, serverURL: null, serverVariables: {} };
|
||||
apis.set(scope, api);
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
export function getTryItOperationSession(
|
||||
scope: string,
|
||||
operation: { method: string; path: string }
|
||||
) {
|
||||
return operations.get(operationKey(scope, operation));
|
||||
}
|
||||
|
||||
export function saveTryItOperationSession(
|
||||
scope: string,
|
||||
operation: { method: string; path: string },
|
||||
value: TryItOperationSession
|
||||
) {
|
||||
operations.set(operationKey(scope, operation), value);
|
||||
}
|
||||
|
||||
function operationKey(scope: string, operation: { method: string; path: string }) {
|
||||
return `${scope}\n${operation.method.toUpperCase()} ${operation.path}`;
|
||||
}
|
||||
|
||||
/** For tests. */
|
||||
export function resetTryItSession() {
|
||||
apis = new Map();
|
||||
operations = new Map();
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type { OpenAPIOperationData } from '../types';
|
||||
import { buildTryItOperation } from './buildTryItOperation';
|
||||
import { type TryItValues, authKey, buildTryItRequest, toProxyRequest } from './request';
|
||||
|
||||
function operationData(overrides: Partial<OpenAPIOperationData> = {}): OpenAPIOperationData {
|
||||
return {
|
||||
path: '/pets/{petId}',
|
||||
method: 'post',
|
||||
servers: [
|
||||
{ url: 'https://{region}.example.com/v1/', variables: { region: { default: 'eu' } } },
|
||||
],
|
||||
securities: [
|
||||
['bearer', { type: 'http', scheme: 'bearer' }],
|
||||
['key', { type: 'apiKey', name: 'api_key', in: 'query' }],
|
||||
],
|
||||
operation: {
|
||||
security: [{ bearer: [] }, { key: [] }],
|
||||
parameters: [
|
||||
{ name: 'petId', in: 'path', schema: { type: 'string' }, example: '42' },
|
||||
{ name: 'limit', in: 'query', schema: { type: 'integer', default: 10 } },
|
||||
{
|
||||
name: 'sort',
|
||||
in: 'query',
|
||||
required: true,
|
||||
schema: { type: 'string', enum: ['asc', 'desc'] },
|
||||
},
|
||||
{ name: 'X-Trace', in: 'header', schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string', example: 'Rex' } },
|
||||
},
|
||||
},
|
||||
'multipart/form-data': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['photo'],
|
||||
properties: {
|
||||
caption: { type: 'string' },
|
||||
photo: { type: 'string', format: 'binary' },
|
||||
id: { type: 'string', readOnly: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {},
|
||||
},
|
||||
...overrides,
|
||||
} as OpenAPIOperationData;
|
||||
}
|
||||
|
||||
function values(data: OpenAPIOperationData, overrides: Partial<TryItValues> = {}): TryItValues {
|
||||
const operation = buildTryItOperation(data);
|
||||
return {
|
||||
server: data.servers[0],
|
||||
serverVariables: {},
|
||||
schemes: [],
|
||||
auth: {},
|
||||
parameters: {},
|
||||
mediaType: operation.body?.mediaTypes[0],
|
||||
bodyText: '',
|
||||
bodyFields: {},
|
||||
bodyFiles: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildTryItOperation', () => {
|
||||
it('describes parameters with their defaults, placeholders and enums', () => {
|
||||
const operation = buildTryItOperation(operationData());
|
||||
expect(operation.parameters).toEqual([
|
||||
{
|
||||
name: 'petId',
|
||||
in: 'path',
|
||||
required: true,
|
||||
description: undefined,
|
||||
placeholder: '42',
|
||||
defaultValue: '42',
|
||||
},
|
||||
{
|
||||
name: 'limit',
|
||||
in: 'query',
|
||||
required: false,
|
||||
description: undefined,
|
||||
placeholder: '10',
|
||||
defaultValue: '10',
|
||||
},
|
||||
{
|
||||
name: 'sort',
|
||||
in: 'query',
|
||||
required: true,
|
||||
description: undefined,
|
||||
enum: ['asc', 'desc'],
|
||||
placeholder: 'asc',
|
||||
},
|
||||
{
|
||||
name: 'X-Trace',
|
||||
in: 'header',
|
||||
required: false,
|
||||
description: undefined,
|
||||
placeholder: 'string',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('turns JSON bodies into editable text and multipart bodies into fields', () => {
|
||||
const { body } = buildTryItOperation(operationData());
|
||||
expect(body?.required).toBe(true);
|
||||
|
||||
const [json, multipart] = body?.mediaTypes ?? [];
|
||||
expect(json?.kind).toBe('raw');
|
||||
expect(JSON.parse(json?.examples[0]?.value ?? '')).toEqual({ name: 'Rex' });
|
||||
|
||||
expect(multipart?.kind).toBe('multipart');
|
||||
expect(
|
||||
multipart?.fields.map((field) => [field.name, field.required, field.binary])
|
||||
).toEqual([
|
||||
['caption', false, false],
|
||||
['photo', true, true],
|
||||
]);
|
||||
});
|
||||
|
||||
it('lists each security requirement as an option', () => {
|
||||
const { securityOptions } = buildTryItOperation(operationData());
|
||||
expect(securityOptions).toEqual([
|
||||
{ label: 'bearer', schemes: ['bearer'] },
|
||||
{ label: 'key', schemes: ['key'] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers true and false for boolean parameters', () => {
|
||||
const data = operationData();
|
||||
data.operation.parameters = [
|
||||
{ name: 'nested', in: 'query', schema: { type: 'boolean', default: true } },
|
||||
];
|
||||
expect(buildTryItOperation(data).parameters[0]).toMatchObject({
|
||||
enum: ['true', 'false'],
|
||||
defaultValue: 'true',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the operation-level parameter when the path item defines the same one', () => {
|
||||
const data = operationData();
|
||||
data.operation.parameters = [
|
||||
{ name: 'petId', in: 'path', description: 'path item' },
|
||||
{ name: 'petId', in: 'path', description: 'operation' },
|
||||
];
|
||||
const { parameters } = buildTryItOperation(data);
|
||||
expect(parameters).toHaveLength(1);
|
||||
expect(parameters[0]?.description).toBe('operation');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildTryItRequest', () => {
|
||||
const data = operationData();
|
||||
const operation = buildTryItOperation(data);
|
||||
const [bearer, key] = data.securities;
|
||||
|
||||
it('builds the URL, headers and JSON body', () => {
|
||||
const request = buildTryItRequest(
|
||||
operation,
|
||||
values(data, {
|
||||
serverVariables: { region: 'us' },
|
||||
schemes: bearer ? [bearer] : [],
|
||||
auth: { [authKey('bearer')]: 'secret' },
|
||||
parameters: {
|
||||
'path:petId': 'a b',
|
||||
'query:sort': 'desc',
|
||||
'header:X-Trace': 'abc',
|
||||
},
|
||||
bodyText: '{"name":"Rex"}',
|
||||
})
|
||||
);
|
||||
|
||||
expect(request).toEqual({
|
||||
url: 'https://us.example.com/v1/pets/a%20b?sort=desc',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Trace': 'abc',
|
||||
Authorization: 'Bearer secret',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{"name":"Rex"}',
|
||||
cookies: '',
|
||||
missing: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('reports empty required fields', () => {
|
||||
const request = buildTryItRequest(operation, values(data));
|
||||
expect(request.missing).toEqual(['petId', 'sort', 'body']);
|
||||
});
|
||||
|
||||
it('puts query API keys in the query string', () => {
|
||||
const request = buildTryItRequest(
|
||||
operation,
|
||||
values(data, {
|
||||
schemes: key ? [key] : [],
|
||||
auth: { [authKey('key')]: 'k' },
|
||||
parameters: { 'path:petId': '1', 'query:sort': 'asc' },
|
||||
bodyText: '{}',
|
||||
})
|
||||
);
|
||||
expect(request.url).toBe('https://eu.example.com/v1/pets/1?sort=asc&api_key=k');
|
||||
});
|
||||
|
||||
it('encodes basic auth as UTF-8', () => {
|
||||
const request = buildTryItRequest(
|
||||
operation,
|
||||
values(data, {
|
||||
schemes: [['basic', { type: 'http', scheme: 'basic' }]],
|
||||
auth: { [authKey('basic', 'username')]: 'é', [authKey('basic', 'password')]: 'p' },
|
||||
})
|
||||
);
|
||||
expect(request.headers.Authorization).toBe(`Basic ${btoa('é:p')}`);
|
||||
});
|
||||
|
||||
it('sends multipart bodies without a Content-Type so the browser adds the boundary', () => {
|
||||
const multipart = operation.body?.mediaTypes[1];
|
||||
const photo = new File(['x'], 'photo.png');
|
||||
const request = buildTryItRequest(
|
||||
operation,
|
||||
values(data, {
|
||||
mediaType: multipart,
|
||||
parameters: { 'path:petId': '1', 'query:sort': 'asc' },
|
||||
bodyFields: { caption: 'hi' },
|
||||
bodyFiles: { photo: [photo] },
|
||||
})
|
||||
);
|
||||
expect(request.headers['Content-Type']).toBeUndefined();
|
||||
expect(request.body).toBeInstanceOf(FormData);
|
||||
const form = request.body as FormData;
|
||||
expect(form.get('caption')).toBe('hi');
|
||||
expect(form.get('photo')).toBeInstanceOf(File);
|
||||
});
|
||||
|
||||
it('routes through the proxy and forwards cookies in a header', () => {
|
||||
const proxied = toProxyRequest(
|
||||
{
|
||||
url: 'https://api.example.com/x?a=1',
|
||||
method: 'GET',
|
||||
headers: {},
|
||||
body: undefined,
|
||||
cookies: 'session=1',
|
||||
missing: [],
|
||||
},
|
||||
'https://app.gitbook.com/~scalar/proxy?token=t&site_id=s'
|
||||
);
|
||||
const url = new URL(proxied.url);
|
||||
expect(url.searchParams.get('scalar_url')).toBe('https://api.example.com/x?a=1');
|
||||
expect(url.searchParams.get('token')).toBe('t');
|
||||
expect(proxied.headers['X-Scalar-Cookie']).toBe('session=1');
|
||||
});
|
||||
|
||||
it('repeats exploded array query parameters', () => {
|
||||
const arrays = operationData();
|
||||
arrays.operation.parameters = [
|
||||
{ name: 'id', in: 'query', schema: { type: 'array', items: { type: 'string' } } },
|
||||
{
|
||||
name: 'tag',
|
||||
in: 'query',
|
||||
explode: false,
|
||||
schema: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
];
|
||||
arrays.operation.requestBody = undefined;
|
||||
const request = buildTryItRequest(
|
||||
buildTryItOperation(arrays),
|
||||
values(arrays, { parameters: { 'query:id': '1, 2', 'query:tag': 'a,b' } })
|
||||
);
|
||||
expect(request.url).toBe('https://eu.example.com/v1/pets/{petId}?id=1&id=2&tag=a%2Cb');
|
||||
});
|
||||
|
||||
it('lets auth replace a header parameter of the same name, whatever its case', () => {
|
||||
const withHeader = operationData();
|
||||
withHeader.operation.parameters = [{ name: 'authorization', in: 'header' }];
|
||||
withHeader.operation.requestBody = undefined;
|
||||
const request = buildTryItRequest(
|
||||
buildTryItOperation(withHeader),
|
||||
values(withHeader, {
|
||||
schemes: bearer ? [bearer] : [],
|
||||
auth: { [authKey('bearer')]: 'secret' },
|
||||
parameters: { 'header:authorization': 'manual' },
|
||||
})
|
||||
);
|
||||
expect(request.headers).toEqual({ Authorization: 'Bearer secret' });
|
||||
});
|
||||
|
||||
it('never sends a multipart Content-Type without a boundary', () => {
|
||||
const opaque = operationData();
|
||||
opaque.operation.requestBody = {
|
||||
content: { 'multipart/form-data': { schema: { type: 'object' } } },
|
||||
};
|
||||
const operation = buildTryItOperation(opaque);
|
||||
expect(operation.body?.mediaTypes[0]?.kind).toBe('raw');
|
||||
const request = buildTryItRequest(
|
||||
operation,
|
||||
values(opaque, { parameters: { 'path:petId': '1' }, bodyText: 'x' })
|
||||
);
|
||||
expect(request.headers['Content-Type']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('adds reader-defined headers and query parameters, with auth taking precedence', () => {
|
||||
const extra = operationData();
|
||||
extra.operation.parameters = [];
|
||||
extra.operation.requestBody = undefined;
|
||||
const request = buildTryItRequest(
|
||||
buildTryItOperation(extra),
|
||||
values(extra, {
|
||||
schemes: bearer ? [bearer] : [],
|
||||
auth: { [authKey('bearer')]: 'secret' },
|
||||
extraParameters: [
|
||||
{ in: 'header', name: 'X-Api-Version', value: '2' },
|
||||
{ in: 'header', name: 'authorization', value: 'manual' },
|
||||
{ in: 'query', name: 'filter', value: 'a b' },
|
||||
{ in: 'query', name: '', value: 'ignored' },
|
||||
],
|
||||
})
|
||||
);
|
||||
expect(request.url).toBe('https://eu.example.com/v1/pets/{petId}?filter=a+b');
|
||||
expect(request.headers).toEqual({ 'X-Api-Version': '2', Authorization: 'Bearer secret' });
|
||||
});
|
||||
|
||||
it('skips unchecked optional parameters and extra rows, but never required ones', () => {
|
||||
const checks = operationData();
|
||||
checks.operation.requestBody = undefined;
|
||||
const request = buildTryItRequest(
|
||||
buildTryItOperation(checks),
|
||||
values(checks, {
|
||||
parameters: {
|
||||
'path:petId': '1',
|
||||
'query:limit': '10',
|
||||
'query:sort': 'asc',
|
||||
'header:X-Trace': 'abc',
|
||||
},
|
||||
enabledParameters: {
|
||||
'query:limit': false,
|
||||
'query:sort': false,
|
||||
'header:X-Trace': true,
|
||||
},
|
||||
extraParameters: [
|
||||
{ in: 'header', name: 'Accept', value: '*/*' },
|
||||
{ in: 'query', name: 'debug', value: '1', enabled: false },
|
||||
],
|
||||
})
|
||||
);
|
||||
expect(request.url).toBe('https://eu.example.com/v1/pets/1?sort=asc');
|
||||
expect(request.headers).toEqual({ 'X-Trace': 'abc', Accept: '*/*' });
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
export type TryItParameterLocation = 'path' | 'query' | 'header' | 'cookie';
|
||||
|
||||
export interface TryItField {
|
||||
name: string;
|
||||
required: boolean;
|
||||
description?: string;
|
||||
enum?: string[];
|
||||
/** Shown as the input placeholder, generated from the schema. */
|
||||
placeholder?: string;
|
||||
/** Initial value, from an explicit `default` or `example`. */
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
export interface TryItParameter extends TryItField {
|
||||
in: TryItParameterLocation;
|
||||
/** Array query parameter sent as `?id=1&id=2`; the reader types it comma-separated. */
|
||||
explode?: boolean;
|
||||
}
|
||||
|
||||
export interface TryItBodyField extends TryItField {
|
||||
binary: boolean;
|
||||
}
|
||||
|
||||
export interface TryItMediaType {
|
||||
mediaType: string;
|
||||
/** `raw` is edited as text, `form` and `multipart` field by field, `binary` as a file. */
|
||||
kind: 'raw' | 'form' | 'multipart' | 'binary';
|
||||
examples: { label: string; value: string }[];
|
||||
fields: TryItBodyField[];
|
||||
}
|
||||
|
||||
export interface TryItSecurityOption {
|
||||
label: string;
|
||||
/** Scheme names; all of them apply together. */
|
||||
schemes: string[];
|
||||
}
|
||||
|
||||
/** Everything the Try it panel needs about an operation, small and serializable. */
|
||||
export interface TryItOperation {
|
||||
method: string;
|
||||
path: string;
|
||||
parameters: TryItParameter[];
|
||||
body: { required: boolean; mediaTypes: TryItMediaType[] } | null;
|
||||
securityOptions: TryItSecurityOption[];
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ApiClientConfiguration } from '@scalar/types';
|
||||
|
||||
import { ExpressionRuntime, type TemplatePart, parseTemplate } from '@gitbook/expr';
|
||||
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
|
||||
|
||||
@@ -8,20 +10,15 @@ import type {
|
||||
OpenAPIServerWithCustomProperties,
|
||||
} from '../types';
|
||||
|
||||
export type TryItPrefillAuthValue =
|
||||
| { token: string }
|
||||
| { username: string | undefined; password: string | undefined }
|
||||
| { name: string | undefined; in: string | undefined; value: string };
|
||||
|
||||
export interface TryItPrefillConfiguration {
|
||||
authentication?: { securitySchemes: Record<string, TryItPrefillAuthValue> };
|
||||
servers?: OpenAPIV3.ServerObject[];
|
||||
authentication?: ApiClientConfiguration['authentication'];
|
||||
servers?: ApiClientConfiguration['servers'];
|
||||
}
|
||||
|
||||
export const PREFILL_CUSTOM_PROPERTY = 'x-gitbook-prefill';
|
||||
|
||||
/**
|
||||
* Resolve the Try it prefill configuration for a given OpenAPI operation.
|
||||
* Resolve the Scalar API client prefill configuration for a given OpenAPI operation.
|
||||
*/
|
||||
export function resolveTryItPrefillForOperation(args: {
|
||||
/**
|
||||
@@ -38,7 +35,18 @@ export function resolveTryItPrefillForOperation(args: {
|
||||
prefillInputContext,
|
||||
} = args;
|
||||
|
||||
const resolveTryItPrefillExpression = createPrefillExpressionResolver(prefillInputContext);
|
||||
const resolveTryItPrefillExpression = prefillInputContext
|
||||
? (() => {
|
||||
const runtime = new ExpressionRuntime();
|
||||
return (expr: string) => {
|
||||
const parts = parseTemplate(expr);
|
||||
if (!parts.length) {
|
||||
return undefined;
|
||||
}
|
||||
return runtime.evaluateTemplate(expr, prefillInputContext);
|
||||
};
|
||||
})()
|
||||
: undefined;
|
||||
|
||||
const prefillAuth = securities
|
||||
? resolveTryItPrefillAuthForOperationSecurities({
|
||||
@@ -60,31 +68,15 @@ export function resolveTryItPrefillForOperation(args: {
|
||||
};
|
||||
}
|
||||
|
||||
function createPrefillExpressionResolver(
|
||||
prefillInputContext: PrefillInputContextData | null
|
||||
): ((expr: string) => string | undefined) | undefined {
|
||||
if (!prefillInputContext) {
|
||||
return undefined;
|
||||
}
|
||||
const runtime = new ExpressionRuntime();
|
||||
return (expr: string) => {
|
||||
const parts = parseTemplate(expr);
|
||||
if (!parts.length) {
|
||||
return undefined;
|
||||
}
|
||||
return runtime.evaluateTemplate(expr, prefillInputContext);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve prefill authentication configuration for the security schemes defined for an operation.
|
||||
*/
|
||||
function resolveTryItPrefillAuthForOperationSecurities(args: {
|
||||
securities: OpenAPIOperationData['securities'];
|
||||
resolveTryItPrefillExpression?: (expr: string) => string | undefined;
|
||||
}): TryItPrefillConfiguration['authentication'] | undefined {
|
||||
}): ApiClientConfiguration['authentication'] | undefined {
|
||||
const { securities, resolveTryItPrefillExpression } = args;
|
||||
const prefillAuthConfig: Record<string, TryItPrefillAuthValue> = {};
|
||||
const prefillAuthConfig: ApiClientConfiguration['authentication']['securitySchemes'] = {};
|
||||
|
||||
for (const [schemeName, security] of Object.values(securities)) {
|
||||
const resolvedPrefill = security[PREFILL_CUSTOM_PROPERTY]
|
||||
@@ -136,63 +128,50 @@ function resolveTryItPrefillAuthForOperationSecurities(args: {
|
||||
function resolveTryItPrefillServersForOperationServers(args: {
|
||||
servers: OpenAPIOperationData['servers'];
|
||||
resolveTryItPrefillExpression?: (expr: string) => string | undefined;
|
||||
}): TryItPrefillConfiguration['servers'] | undefined {
|
||||
const resolvedServers = args.servers
|
||||
.map((server) => resolveTryItPrefillServer(server, args.resolveTryItPrefillExpression))
|
||||
.filter((resolved) => resolved.prefilled)
|
||||
.map((resolved) => resolved.server);
|
||||
}): ApiClientConfiguration['servers'] | undefined {
|
||||
const { servers, resolveTryItPrefillExpression } = args;
|
||||
const resolvedServers: ApiClientConfiguration['servers'] = [];
|
||||
|
||||
return resolvedServers.length > 0 ? resolvedServers : undefined;
|
||||
}
|
||||
for (const server of servers) {
|
||||
// Url-level prefill
|
||||
const tryItPrefillServerUrlExpr = server[PREFILL_CUSTOM_PROPERTY];
|
||||
const tryItPrefillServerUrlValue =
|
||||
tryItPrefillServerUrlExpr && resolveTryItPrefillExpression
|
||||
? resolveTryItPrefillExpression(tryItPrefillServerUrlExpr)
|
||||
: undefined;
|
||||
|
||||
/**
|
||||
* Resolve every server of an operation with its prefilled URL and variable defaults applied.
|
||||
*/
|
||||
export function resolveTryItServers(args: {
|
||||
servers: OpenAPIOperationData['servers'];
|
||||
prefillInputContext: PrefillInputContextData | null;
|
||||
}): OpenAPIV3.ServerObject[] {
|
||||
const resolveExpression = createPrefillExpressionResolver(args.prefillInputContext);
|
||||
return args.servers.map(
|
||||
(server) => resolveTryItPrefillServer(server, resolveExpression).server
|
||||
);
|
||||
}
|
||||
const variables: { [variable: string]: OpenAPIV3.ServerVariableObject } = server.variables
|
||||
? { ...server.variables }
|
||||
: {};
|
||||
|
||||
function resolveTryItPrefillServer(
|
||||
server: OpenAPIOperationData['servers'][number],
|
||||
resolveTryItPrefillExpression: ((expr: string) => string | undefined) | undefined
|
||||
): { server: OpenAPIV3.ServerObject; prefilled: boolean } {
|
||||
// Url-level prefill
|
||||
const tryItPrefillServerUrlExpr = server[PREFILL_CUSTOM_PROPERTY];
|
||||
const tryItPrefillServerUrlValue =
|
||||
tryItPrefillServerUrlExpr && resolveTryItPrefillExpression
|
||||
? resolveTryItPrefillExpression(tryItPrefillServerUrlExpr)
|
||||
: undefined;
|
||||
// Variable-level prefill
|
||||
if (server.variables) {
|
||||
for (const [varName, variable] of Object.entries(server.variables)) {
|
||||
const { [PREFILL_CUSTOM_PROPERTY]: tryItPrefillVarExpr, ...variableProps } =
|
||||
variable;
|
||||
|
||||
const variables: { [variable: string]: OpenAPIV3.ServerVariableObject } = {};
|
||||
const tryItPrefillVarValue = tryItPrefillVarExpr
|
||||
? resolveTryItPrefillExpression?.(tryItPrefillVarExpr)
|
||||
: undefined;
|
||||
variables[varName] = {
|
||||
...variableProps,
|
||||
...(tryItPrefillVarValue ? { default: String(tryItPrefillVarValue) } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Variable-level prefill
|
||||
for (const [varName, variable] of Object.entries(server.variables ?? {})) {
|
||||
const { [PREFILL_CUSTOM_PROPERTY]: tryItPrefillVarExpr, ...variableProps } = variable;
|
||||
|
||||
const tryItPrefillVarValue = tryItPrefillVarExpr
|
||||
? resolveTryItPrefillExpression?.(tryItPrefillVarExpr)
|
||||
: undefined;
|
||||
variables[varName] = {
|
||||
...variableProps,
|
||||
...(tryItPrefillVarValue ? { default: String(tryItPrefillVarValue) } : {}),
|
||||
};
|
||||
const hasServerVariables = Object.keys(variables).length > 0;
|
||||
if (server.url && (tryItPrefillServerUrlValue || hasServerVariables)) {
|
||||
const resolvedServer: OpenAPIV3.ServerObject = {
|
||||
url: tryItPrefillServerUrlValue ?? server.url,
|
||||
...(server.description ? { description: server.description } : {}),
|
||||
...(hasServerVariables ? { variables } : {}),
|
||||
};
|
||||
resolvedServers.push(resolvedServer);
|
||||
}
|
||||
}
|
||||
|
||||
const hasServerVariables = Object.keys(variables).length > 0;
|
||||
return {
|
||||
server: {
|
||||
url: tryItPrefillServerUrlValue ?? server.url ?? '',
|
||||
...(server.description ? { description: server.description } : {}),
|
||||
...(hasServerVariables ? { variables } : {}),
|
||||
},
|
||||
prefilled: Boolean(server.url && (tryItPrefillServerUrlValue || hasServerVariables)),
|
||||
};
|
||||
return resolvedServers.length > 0 ? resolvedServers : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user