Compare commits

..

26 Commits

Author SHA1 Message Date
Samy Pessé 725952a106 Version Packages (#2881)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-02-28 17:22:32 +00:00
Greg Bergé 3319375e9a Support OpenAPI operation block (#2902) 2025-02-28 18:12:08 +01:00
spastorelli c5a4619020 Fix multi-id/preview mode not using context id for api cache calls (#2905) 2025-02-28 18:04:16 +01:00
Greg Bergé 989fc69abe Format package.json after running changeset (#2904) 2025-02-28 15:56:44 +00:00
Greg Bergé 0924259217 Expose OpenAPI helper shouldIgnoreEntity (#2903) 2025-02-28 16:22:20 +01:00
Taran Vohra 05affac34f Add support for proxy sites using x-gitbook-url in v2 (#2901) 2025-02-28 20:03:05 +05:30
Samy Pessé 453a459566 Fix content ref resolution for pages of other spaces (#2900) 2025-02-28 13:00:54 +01:00
Nolann B. 722f02ea09 Fix recursion in OpenAPISchemaAlternative (#2892) 2025-02-28 10:07:56 +00:00
Samy Pessé 5bcea2fe3b Fix signature verification with image resizing on v1 (#2899) 2025-02-28 10:36:10 +01:00
Samy Pessé 73afd1f5d0 Improve error message for image resizing (#2898) 2025-02-28 10:23:17 +01:00
Greg Bergé 9b8a0d3e54 Fix CI tests (#2897) 2025-02-28 10:14:09 +01:00
Samy Pessé 75bd98d66c V2: robots.txt, sitemap.xml, image resizing, etc (#2895) 2025-02-28 09:52:56 +01:00
Taran Vohra 9b914d10bd Fix getProxyModeBasePath (#2896) 2025-02-28 12:27:25 +05:30
Brett Jephson 3e11678d8d fix: section groups went missing (#2891) 2025-02-28 00:00:39 +01:00
Samy Pessé 6e03638130 Remove loading.tsx for static rendering in v2 (#2894) 2025-02-27 18:23:06 +01:00
Greg Bergé 23f884efb7 Fix the fonts display on the site (#2893) 2025-02-27 17:27:17 +01:00
Taran Vohra 2ae76f999b Change how a site in proxy mode is resolved (#2890) 2025-02-27 21:43:29 +05:30
Samy Pessé 685325cdc7 Deploy v2 to staging from main using a composite action (#2888) 2025-02-27 11:12:02 +01:00
Samy Pessé ab132eadb7 Cache OpenAPI using next "use cache" for v2 (#2887) 2025-02-27 09:39:08 +01:00
Samy Pessé 14504e43b5 V2: embeds and CSP (#2885) 2025-02-27 08:44:32 +01:00
Taran Vohra 4ed79574e8 change proxy mode site lookup url (#2886) 2025-02-27 12:38:55 +05:30
Samy Pessé 31bcd1a386 Improve detection of code path not supported in v2, add visual tests (#2884) 2025-02-26 20:18:38 +01:00
Samy Pessé 270e5ef7ad Improve linking to other sections/variants in development (#2883) 2025-02-26 19:14:27 +01:00
Samy Pessé 1f4733355e Remove eslint/prettier and switch to biome (#2880) 2025-02-26 17:59:34 +01:00
Zeno Kapitein 027a859ef4 Add link styles (#2861) 2025-02-26 13:03:14 +00:00
Samy Pessé 59f50eaee7 Fix production deployments to Vercel (#2879) 2025-02-26 13:47:24 +01:00
387 changed files with 4438 additions and 4254 deletions
-1
View File
@@ -1 +0,0 @@
1.2.1
@@ -0,0 +1,58 @@
name: 'Deploy vercel'
description: 'Deploy GitBook to Vercel'
inputs:
vercel-org:
description: 'Vercel organization'
required: true
vercel-project:
description: 'Vercel project'
required: true
vercel-token:
description: 'Vercel token'
required: true
environment:
description: 'Environment to deploy to'
required: true
outputs:
deployment-url:
description: "Deployment URL"
value: ${{ steps.deploy.outputs.deployment-url }}
runs:
using: 'composite'
steps:
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
shell: bash
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Sets env vars for environment
shell: bash
run: |
echo "VERCEL_ENVIRONMENT=${{ inputs.environment }}" >> $GITHUB_ENV
- name: Pull Vercel Environment Information
run: bun run vercel pull --yes --environment=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Build Project Artifacts
run: bun run vercel build --target=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Deploy Project Artifacts to Vercel
id: deploy
shell: bash
run: |
DEPLOYMENT_URL=$(bun run vercel deploy --prebuilt --target=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }})
echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT"
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
- name: Outputs
shell: bash
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+1 -1
View File
@@ -15,4 +15,4 @@ runs:
- name: Setup bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: '.bun-version'
bun-version-file: 'package.json'
+79 -69
View File
@@ -87,49 +87,41 @@ jobs:
statuses: write
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Sets env vars for production
run: |
echo "VERCEL_ENVIRONMENT=production" >> $GITHUB_ENV
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
echo "GITBOOK_URL=https://open-2v.gitbook.com" >> $GITHUB_ENV
echo "GITBOOK_ASSETS_PREFIX=https://static-2v.gitbook.com" >> $GITHUB_ENV
if: startsWith(github.ref, 'refs/heads/main')
- name: Sets env vars for preview
run: |
echo "VERCEL_ENVIRONMENT=preview" >> $GITHUB_ENV
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
if: 1 && !startsWith(github.ref, 'refs/heads/main')
- name: Pull Vercel Environment Information
run: bun run vercel pull --yes --environment=$VERCEL_ENVIRONMENT --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
run: bun run vercel build --token=${{ secrets.VERCEL_TOKEN }}
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
SENTRY_RELEASE: ${{ github.sha }}
- name: Deploy Project Artifacts to Vercel
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
id: deploy
run: |
DEPLOYMENT_URL=$(bun run vercel deploy --prebuilt --target=$VERCEL_ENVIRONMENT $([ "$VERCEL_ENVIRONMENT" = "production" ] && echo "--prod") --token=${{ secrets.VERCEL_TOKEN }})
echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT"
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
uses: ./.github/composite/deploy-vercel
with:
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
deploy-v2-vercel-staging:
name: Deploy v2 to Vercel (staging)
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
issues: write
pull-requests: write
checks: write
statuses: write
if: startsWith(github.ref, 'refs/heads/main')
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy staging
id: deploy
uses: ./.github/composite/deploy-vercel
with:
environment: staging
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker
runs-on: ubuntu-latest
@@ -142,9 +134,6 @@ jobs:
statuses: write
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -235,6 +224,7 @@ jobs:
runs-on: ubuntu-latest
name: Visual Testing
needs: deploy
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -247,18 +237,33 @@ jobs:
- name: Run Playwright tests
run: bun e2e
env:
BASE_URL: ${{needs.deploy.outputs.deployment-url}}
BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-test-results
path: packages/gitbook/test-results/
retention-days: 3
visual-testing-v2:
runs-on: ubuntu-latest
name: Visual Testing v2
needs: deploy-v2-vercel
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Setup Playwright
uses: ./.github/actions/setup-playwright
- name: Run Playwright tests
run: bun e2e
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'v2'
visual-testing-customers:
runs-on: ubuntu-latest
name: Visual Testing Customers
needs: deploy
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -271,15 +276,29 @@ jobs:
- name: Run Playwright tests
run: bun e2e-customers
env:
BASE_URL: ${{needs.deploy.outputs.deployment-url}}
BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers'
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-test-results-customers
path: packages/gitbook/test-results/
retention-days: 3
visual-testing-customers-v2:
runs-on: ubuntu-latest
name: Visual Testing Customers v2
needs: deploy-v2-vercel
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Setup Playwright
uses: ./.github/actions/setup-playwright
- name: Run Playwright tests
run: bun e2e-customers
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers-v2'
pagespeed-testing:
runs-on: ubuntu-latest
name: PageSpeed Testing
@@ -301,6 +320,7 @@ jobs:
format:
runs-on: ubuntu-latest
name: Format
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -311,22 +331,10 @@ jobs:
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- run: bun format:check
lint:
runs-on: ubuntu-latest
name: Lint
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: ./.github/composite/setup-bun
- name: Install dependencies
run: bun install --frozen-lockfile
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- run: bun lint --no-cache
test:
runs-on: ubuntu-latest
name: Test
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -341,6 +349,7 @@ jobs:
# CI to check that the repository builds correctly on a machine without the credentials
runs-on: ubuntu-latest
name: Build (Open Source)
timeout-minutes: 6
env:
NPM_TOKEN_READONLY: ''
steps:
@@ -356,6 +365,7 @@ jobs:
typecheck:
runs-on: ubuntu-latest
name: Typecheck
timeout-minutes: 6
steps:
- name: Checkout
uses: actions/checkout@v4
+1
View File
@@ -28,6 +28,7 @@ jobs:
uses: changesets/action@v1
with:
publish: npm run release
version: npm run changeset-version
env:
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["biomejs.biome"]
}
+6 -1
View File
@@ -7,5 +7,10 @@
["style \\=([^;]*);", "\"([^\"]*)\""],
["style \\=([^;]*);", "\\`([^\\`]*)\\`"]
],
"tailwindCSS.classAttributes": ["class", "className", "style", ".*Style"]
"tailwindCSS.classAttributes": ["class", "className", "style", ".*Style"],
"prettier.enable": false,
"editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
}
+168
View File
@@ -0,0 +1,168 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false,
"ignore": [
"**/node_modules/**/*",
"**/dist/**/*",
"**/build/**/*",
"**/public/**/*",
"**/.next/**/*",
"**/.open-next/**/*",
"**/.turbo/**/*",
"**/.vercel/**/*",
"**/.cache/**/*",
"**/.wrangler/**/*",
"packages/openapi-parser/src/fixtures/**/*"
]
},
"formatter": {
"enabled": true,
"useEditorconfig": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 4,
"lineEnding": "lf",
"lineWidth": 100,
"attributePosition": "auto",
"bracketSpacing": true
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"performance": {
"noDelete": "warn"
},
"security": {
"noDangerouslySetInnerHtml": "off"
},
"complexity": {
"noForEach": "off",
"noUselessFragments": "warn",
"noBannedTypes": "warn"
},
"correctness": {
"noUndeclaredVariables": "error",
"noUnusedVariables": "error",
"useArrayLiterals": "error",
"useHookAtTopLevel": "error",
"noUnusedImports": "error",
"noVoidElementsWithChildren": "warn",
"useJsxKeyInIterable": "warn",
"useExhaustiveDependencies": "warn",
"noUnknownFunction": "warn"
},
"style": {
"noNonNullAssertion": "warn",
"noParameterAssign": "off",
"useThrowOnlyError": "error"
},
"suspicious": {
"noConsole": "warn",
"noExplicitAny": "warn",
"noImplicitAnyLet": "warn",
"noConfusingVoidType": "warn",
"noControlCharactersInRegex": "warn",
"noPrototypeBuiltins": "warn",
"noAssignInExpressions": "warn",
"noArrayIndexKey": "warn"
},
"a11y": {
"useSemanticElements": "warn",
"useKeyWithClickEvents": "warn",
"noSvgWithoutTitle": "warn",
"useButtonType": "warn",
"useIframeTitle": "warn",
"useAltText": "warn",
"noPositiveTabindex": "warn",
"useFocusableInteractive": "warn",
"useAriaPropsForRole": "warn",
"useValidAnchor": "warn",
"noLabelWithoutControl": "warn",
"noNoninteractiveTabindex": "warn"
},
"nursery": {
"useSortedClasses": {
"level": "error",
"fix": "safe",
"options": {
"attributes": ["class", "className", "style"],
"functions": ["clsx", "tw"]
}
}
}
}
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "es5",
"semicolons": "always",
"arrowParentheses": "always",
"bracketSameLine": false,
"quoteStyle": "single",
"attributePosition": "auto",
"bracketSpacing": true
}
},
"overrides": [
{
"include": [
"packages/gitbook/**/*",
"packages/gitbook-v2/**/*",
"packages/react-openapi/**/*",
"packages/react-math/**/*",
"packages/react-contentkit/**/*",
"packages/icons/**/*"
],
"javascript": {
"globals": ["React"]
}
},
{
"include": ["packages/gitbook/**/*"],
"javascript": {
"globals": ["React", "GitBookIntegrationEvent"]
}
},
{
"include": ["*.css"],
"javascript": {
"globals": ["theme"]
}
},
{
"include": ["*.test.ts", "packages/gitbook/tests/**/*"],
"javascript": {
"globals": ["Bun"]
}
},
{
"include": [
"packages/cache-do/**/*",
"packages/gitbook/cf-env.d.ts",
"packages/gitbook/src/cloudflare-entrypoint.ts"
],
"javascript": {
"globals": [
"DurableObjectLocationHint",
"DurableObjectNamespace",
"DurableObjectStub",
"ContinentCode",
"Fetcher",
"ExportedHandler"
]
}
}
]
}
+81 -513
View File
File diff suppressed because it is too large Load Diff
-22
View File
@@ -1,22 +0,0 @@
# Caching
## Revalidating the cache
Invalidate cache can be done at two levels using tags:
- Data fetching cache
- Rendering cache
To invalidate and refetch the data cache, you can execute a POST request to `/~/gitbook/revalidate`:
```bash
curl --location --request POST 'https://gitbook/mycompany.com/~gitbook/revalidate' \
--header 'Content-Type: application/json' \
--data-raw '{"tags": ["space.id"]}'
```
To invalidate the rendering cache, the implementation mainly depends on the infrastructure serving the content, GitBook outputs a `Cache-Tag` header on every requests. The value of the header is a comma separated list of tags.
## Purging the cache
Purging the cache, without revalidating, is done by passing `"purge": true` in the request body.
+7 -10
View File
@@ -2,12 +2,12 @@
"name": "gitbook",
"version": "0.1.0",
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@changesets/cli": "^2.27.12",
"prettier": "^3.0.3",
"turbo": "^2.4.1-canary.2",
"turbo": "^2.4.4",
"vercel": "^39.3.0"
},
"packageManager": "bun@1.1.18",
"packageManager": "bun@1.2.4",
"overrides": {
"@codemirror/state": "6.4.1",
"react": "18.3.1",
@@ -20,23 +20,20 @@
"build": "turbo run build",
"build:v2": "turbo run build:v2",
"clean-deps": "rm -rf node_modules && rm -rf packages/*/node_modules",
"lint": "turbo run lint",
"lint:fix": "turbo run lint -- --fix",
"typecheck": "turbo run typecheck",
"format": "prettier ./ --ignore-unknown --write",
"format:check": "prettier ./ --ignore-unknown --list-different",
"format": "biome check --write ./",
"format:check": "biome check --diagnostic-level=error ./",
"unit": "turbo run unit",
"e2e": "turbo run e2e",
"e2e-customers": "turbo run e2e-customers",
"changeset": "changeset",
"changeset-version": "changeset version && bun run format",
"release": "turbo run release && changeset publish",
"release:preview": "turbo run release:preview",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
"clean": "turbo run clean"
},
"workspaces": [
"packages/*"
],
"workspaces": ["packages/*"],
"patchedDependencies": {
"decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch",
"@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch"
+1 -8
View File
@@ -31,12 +31,5 @@
"release": "wrangler deploy",
"release:preview": "wrangler deploy && wrangler deploy --env preview"
},
"files": [
"dist",
"src",
"bin",
"data",
"README.md",
"CHANGELOG.md"
]
"files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"]
}
+8 -15
View File
@@ -1,5 +1,5 @@
import { encode, decode } from '@msgpack/msgpack';
import { DurableObject } from 'cloudflare:workers';
import { decode, encode } from '@msgpack/msgpack';
import { LRUMap } from 'lru_map';
export interface CacheObjectDescriptor {
@@ -137,7 +137,7 @@ export class CacheObject extends DurableObject {
*/
public async purge() {
return this.logOperation({ operation: 'purge' }, async (setLog) => {
let result = new Set<string>();
const result = new Set<string>();
try {
// List all the keys in the cache object.
@@ -149,11 +149,7 @@ export class CacheObject extends DurableObject {
entries.forEach((exp) => {
result.add(exp.k);
});
} catch (error) {
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during purge, resetting the cache object', error);
}
} catch (_error) {}
await this.reset();
return Array.from(result);
@@ -174,7 +170,7 @@ export class CacheObject extends DurableObject {
const toDeleteSet = new Set<string>();
for (const [key, exp] of entries) {
const timestamp = parseInt(key.split('.')[1]);
const timestamp = Number.parseInt(key.split('.')[1]);
if (timestamp < Date.now()) {
toDeleteSet.add(key);
for (let i = 0; i < exp.c; i++) {
@@ -194,10 +190,7 @@ export class CacheObject extends DurableObject {
if (toDelete.length) {
await this.ctx.storage.setAlarm(Date.now() + 12 * 60 * 60 * 1000);
}
} catch (error) {
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during alarm, reset the cache object', error);
} catch (_error) {
await this.reset();
}
});
@@ -218,10 +211,10 @@ export class CacheObject extends DurableObject {
*/
async logOperation<T>(
log: Record<string, unknown>,
fn: (update: (log: Record<string, unknown>) => void) => Promise<T>,
fn: (update: (log: Record<string, unknown>) => void) => Promise<T>
): Promise<T> {
const objectId = this.ctx.id.name ?? this.ctx.id.toString();
let update: Record<string, unknown> = {};
const update: Record<string, unknown> = {};
const start = performance.now();
try {
return await fn((arg) => {
@@ -265,7 +258,7 @@ function encodeChunks<T>(key: string, value: T): Record<string, Uint8Array> {
function decodeChunks<T>(entries: Map<string, Uint8Array>): { value: T; size: number } | undefined {
const chunks = Array.from(entries.entries())
.map(([key, value]) => {
const index = parseInt(key.split('.').pop()!);
const index = Number.parseInt(key.split('.').pop()!);
return [index, value] as const;
})
.sort(([a], [b]) => a - b)
+3 -3
View File
@@ -1,4 +1,4 @@
import type { CacheObject, CacheObjectDescriptor } from './CacheObject';
import type { CacheObject } from './CacheObject';
export type CacheLocationId = ContinentCode;
const allLocations: CacheLocationId[] = ['AF', 'AS', 'NA', 'SA', 'AN', 'EU', 'OC'];
@@ -30,7 +30,7 @@ export class CacheObjectStub {
/** ID of the location to target */
private locationId: CacheLocationId,
/** Name of the tag */
private tag: string,
private tag: string
) {
const groupId = getCacheObjectIdName(this.locationId, this.tag);
this.stub = this.doNamespace.get(this.doNamespace.idFromName(groupId), {
@@ -85,7 +85,7 @@ export class CacheObjectStub {
});
const locationkeys = await cacheGroup.purge();
locationkeys.forEach((key) => keys.add(key));
}),
})
);
return keys;
+1 -6
View File
@@ -17,10 +17,5 @@
"typecheck": "tsc --noEmit",
"dev": "tsc -w"
},
"files": [
"dist",
"src",
"README.md",
"CHANGELOG.md"
]
"files": ["dist", "src", "README.md", "CHANGELOG.md"]
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { DARK_BASE, LIGHT_BASE, DEFAULT_TINT_COLOR } from './colors';
import { DARK_BASE, DEFAULT_TINT_COLOR, LIGHT_BASE } from './colors';
type ColorShades = {
[key: string]: string;
@@ -178,7 +178,7 @@ export function colorScale(
background = darkMode ? DARK_BASE : LIGHT_BASE,
foreground = darkMode ? LIGHT_BASE : DARK_BASE,
mix,
}: ColorScaleOptions = {},
}: ColorScaleOptions = {}
) {
const baseColor = rgbToOklch(hexToRgbArray(hex));
const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null;
+1 -1
View File
@@ -13,7 +13,7 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react",
"jsx": "react-jsx",
"incremental": true,
"types": [
"bun-types" // add Bun global
+1 -2
View File
@@ -17,12 +17,11 @@ Object.entries(emojis).forEach(([key, value]) => {
if (emoji && key !== emoji) {
output[key] = emoji;
} else if (!emoji) {
console.log('No emoji for', key);
}
});
fs.mkdirSync(path.resolve(__dirname, 'dist'), { recursive: true });
fs.writeFileSync(
path.resolve(__dirname, 'dist/index.ts'),
`export const emojiCodepoints: Record<string, string> = ${JSON.stringify(output, null, 4)};`,
`export const emojiCodepoints: Record<string, string> = ${JSON.stringify(output, null, 4)};`
);
+6
View File
@@ -1,5 +1,11 @@
# gitbook-v2
## 0.1.1
### Patch Changes
- 3e11678: fix: lost section groups
## 0.1.0
### Minor Changes
+3
View File
@@ -15,6 +15,9 @@ const nextConfig = {
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
// Used to detect if the app is running in V2 mode
GITBOOK_V2: 'true',
},
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "gitbook-v2",
"version": "0.1.0",
"version": "0.1.1",
"private": true,
"dependencies": {
"next": "canary",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"@gitbook/api": "^0.96.0",
"@gitbook/api": "0.96.1",
"@sindresorhus/fnv1a": "^3.1.0",
"server-only": "^0.0.1"
},
@@ -18,7 +18,7 @@
},
"scripts": {
"generate": "rm -rf ./public && cp -r ../gitbook/public ./public",
"dev:v2": "env-cmd --silent -f ../../.env.local next",
"dev:v2": "env-cmd --silent -f ../../.env.local next --turbopack",
"build": "next build",
"build:v2": "next build",
"start": "next start",
@@ -1,10 +1,10 @@
import { getDynamicSiteContext, getPagePathFromParams, RouteParams } from '@v2/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
SitePage,
} from '@/components/SitePage';
import { Metadata, Viewport } from 'next';
import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@v2/app/utils';
import type { Metadata, Viewport } from 'next';
type PageProps = {
params: Promise<RouteParams>;
@@ -1,16 +1,21 @@
import { CustomizationRootLayout } from '@/components/RootLayout';
import { SiteLayout } from '@/components/SiteLayout';
import { getDynamicSiteContext, RouteLayoutParams } from '@v2/app/utils';
import {
SiteLayout,
generateSiteLayoutMetadata,
generateSiteLayoutViewport,
} from '@/components/SiteLayout';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
import { getThemeFromMiddleware } from '@v2/lib/middleware';
interface SiteDynamicLayoutProps {
params: Promise<RouteLayoutParams>;
}
export default async function SiteDynamicLayout({
params,
children,
}: {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
}: React.PropsWithChildren<SiteDynamicLayoutProps>) {
const context = await getDynamicSiteContext(await params);
const forcedTheme = await getThemeFromMiddleware();
@@ -26,3 +31,13 @@ export default async function SiteDynamicLayout({
</CustomizationRootLayout>
);
}
export async function generateViewport({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params);
return generateSiteLayoutViewport(context);
}
export async function generateMetadata({ params }: SiteDynamicLayoutProps) {
const context = await getDynamicSiteContext(await params);
return generateSiteLayoutMetadata(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveLLMsTxt } from '@/routes/llms';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveLLMsTxt(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveRobotsTxt } from '@/routes/robots';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveRobotsTxt(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { servePagesSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return servePagesSitemap(context);
}
@@ -0,0 +1,12 @@
import type { NextRequest } from 'next/server';
import { serveRootSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveRootSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveIcon } from '@/routes/icon';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveIcon(context, request);
}
@@ -0,0 +1,13 @@
import type { NextRequest } from 'next/server';
import type { PageIdParams } from '@/components/SitePage';
import { serveOGImage } from '@/routes/ogimage';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) {
const context = await getDynamicSiteContext(await params);
return serveOGImage(context, await params);
}
@@ -1,5 +0,0 @@
import { SitePageSkeleton } from '@/components/SitePage';
export default function Loading() {
return <SitePageSkeleton />;
}
@@ -1,12 +1,12 @@
import { unstable_cacheTag as cacheTag } from 'next/cache';
import { getSiteCacheTag } from '@v2/lib/cache';
import { getPagePathFromParams, getStaticSiteContext, RouteParams } from '@v2/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
SitePage,
} from '@/components/SitePage';
import { Metadata, Viewport } from 'next';
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@v2/app/utils';
import { getSiteCacheTag } from '@v2/lib/cache';
import type { Metadata, Viewport } from 'next';
import { unstable_cacheTag as cacheTag } from 'next/cache';
export const dynamic = 'force-static';
@@ -1,17 +1,22 @@
import { unstable_cacheTag as cacheTag } from 'next/cache';
import { getSiteCacheTag } from '@v2/lib/cache';
import { getStaticSiteContext, RouteLayoutParams } from '@v2/app/utils';
import { CustomizationRootLayout } from '@/components/RootLayout';
import { SiteLayout } from '@/components/SiteLayout';
import {
SiteLayout,
generateSiteLayoutMetadata,
generateSiteLayoutViewport,
} from '@/components/SiteLayout';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
import { getSiteCacheTag } from '@v2/lib/cache';
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
import { unstable_cacheTag as cacheTag } from 'next/cache';
interface SiteStaticLayoutProps {
params: Promise<RouteLayoutParams>;
}
export default async function SiteStaticLayout({
params,
children,
}: {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
}: React.PropsWithChildren<SiteStaticLayoutProps>) {
'use cache';
const context = await getStaticSiteContext(await params);
@@ -26,3 +31,13 @@ export default async function SiteStaticLayout({
</CustomizationRootLayout>
);
}
export async function generateViewport({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params);
return generateSiteLayoutViewport(context);
}
export async function generateMetadata({ params }: SiteStaticLayoutProps) {
const context = await getStaticSiteContext(await params);
return generateSiteLayoutMetadata(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveLLMsTxt } from '@/routes/llms';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveLLMsTxt(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveRobotsTxt } from '@/routes/robots';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveRobotsTxt(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { servePagesSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return servePagesSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveRootSitemap } from '@/routes/sitemap';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveRootSitemap(context);
}
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';
import { serveIcon } from '@/routes/icon';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const context = await getStaticSiteContext(await params);
return serveIcon(context, request);
}
@@ -0,0 +1,15 @@
import type { NextRequest } from 'next/server';
import type { PageIdParams } from '@/components/SitePage';
import { serveOGImage } from '@/routes/ogimage';
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
) {
const context = await getStaticSiteContext(await params);
return serveOGImage(context, await params);
}
+41 -18
View File
@@ -1,7 +1,7 @@
import { fetchSiteContextByURL } from '@v2/lib/context';
import { createDataFetcher } from '@v2/lib/data';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_URL } from '@v2/lib/env';
import { createNoopImageResizer } from '@v2/lib/images';
import { createImageResizer } from '@v2/lib/images';
import { createLinker } from '@v2/lib/links';
import { headers } from 'next/headers';
@@ -21,25 +21,29 @@ export type RouteParams = RouteLayoutParams & {
/**
* Get the static context when rendering statically a site.
*/
export function getStaticSiteContext(params: RouteLayoutParams) {
export async function getStaticSiteContext(params: RouteLayoutParams) {
const url = getSiteURLFromParams(params);
const dataFetcher = createDataFetcher();
const linker = createLinkerFromParams(params);
const imageResizer = createNoopImageResizer();
return fetchSiteContextByURL(
const { linker, host } = createLinkerFromParams(params);
const context = await fetchSiteContextByURL(
{
dataFetcher,
linker,
imageResizer,
},
{
url: url.toString(),
visitorAuthToken: null,
redirectOnError: false,
},
}
);
context.imageResizer = createImageResizer({
host,
linker: context.linker,
});
return context;
}
/**
@@ -55,14 +59,12 @@ export async function getDynamicSiteContext(params: RouteLayoutParams) {
apiEndpoint: headersSet.get('x-gitbook-api') ?? GITBOOK_API_URL,
});
const linker = createLinkerFromParams(params);
const imageResizer = createNoopImageResizer();
const { linker, host } = createLinkerFromParams(params);
return fetchSiteContextByURL(
const context = await fetchSiteContextByURL(
{
dataFetcher,
linker,
imageResizer,
},
{
url: url.toString(),
@@ -70,8 +72,15 @@ export async function getDynamicSiteContext(params: RouteLayoutParams) {
// TODO: set it only when the token comes from the cookies.
redirectOnError: true,
},
}
);
context.imageResizer = createImageResizer({
host,
linker: context.linker,
});
return context;
}
/**
@@ -87,23 +96,37 @@ function createLinkerFromParams(params: RouteLayoutParams) {
const mode = getModeFromParams(params.mode);
if (mode === 'url-host') {
return createLinker({
return {
linker: createLinker({
host: url.host,
pathname: '/',
}),
host: url.host,
pathname: '/',
});
};
}
const gitbookURL = new URL(GITBOOK_URL);
return createLinker({
const linker = createLinker({
protocol: gitbookURL.protocol,
host: gitbookURL.host,
pathname: `/url/${url.host}`,
});
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}`;
};
return {
linker,
host: gitbookURL.host,
};
}
function getSiteURLFromParams(params: RouteLayoutParams) {
const decoded = decodeURIComponent(params.siteURL);
const url = new URL('https://' + decoded);
const url = new URL(`https://${decoded}`);
return url;
}
+51 -17
View File
@@ -1,4 +1,5 @@
import {
import { getSiteStructureSections } from '@/lib/sites';
import type {
ChangeRequest,
RevisionPage,
RevisionPageDocument,
@@ -11,12 +12,11 @@ import {
SiteStructure,
Space,
} from '@gitbook/api';
import { type GitBookDataFetcher, createDataFetcher } from '@v2/lib/data';
import { redirect } from 'next/navigation';
import { assert } from 'ts-essentials';
import { getSiteStructureSections } from '@/lib/sites';
import { createDataFetcher, GitBookDataFetcher } from '@v2/lib/data';
import { GitBookSpaceLinker, appendPrefixToLinker } from './links';
import { ImageResizer } from './images';
import type { ImageResizer } from './images';
import { type GitBookSpaceLinker, appendBasePathToLinker } from './links';
/**
* Generic context when rendering content.
@@ -35,7 +35,7 @@ export type GitBookBaseContext = {
/**
* Image resizer to resize images.
*/
imageResizer: ImageResizer;
imageResizer?: ImageResizer;
};
/**
@@ -111,7 +111,7 @@ export async function fetchSiteContextByURL(
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
},
}
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
const data = await dataFetcher.getPublishedContentByUrl({
@@ -142,12 +142,12 @@ export async function fetchSiteContextByURL(
changeRequest: data.changeRequest,
revision: data.revision,
visitorAuthToken: input.visitorAuthToken,
},
}
);
const siteContext = {
...context,
linker: appendPrefixToLinker(context.linker, data.basePath),
linker: appendBasePathToLinker(context.linker, data.basePath),
};
return siteContext;
@@ -168,7 +168,7 @@ export async function fetchSiteContextByIds(
changeRequest: string | undefined;
revision: string | undefined;
visitorAuthToken: string | null;
},
}
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
@@ -189,7 +189,9 @@ export async function fetchSiteContextByIds(
...(customizations.site?.title ? { title: customizations.site.title } : {}),
};
const sections = ids.siteSection ? parseSiteSectionsList(siteStructure, ids.siteSection) : null;
const sections = ids.siteSection
? parseSiteSectionsAndGroups(siteStructure, ids.siteSection)
: null;
const siteSpace = (
siteStructure.type === 'siteSpaces' && siteStructure.structure
@@ -211,11 +213,13 @@ export async function fetchSiteContextByIds(
if (siteSpaceSettings) {
return siteSpaceSettings;
}
// We got the pointer from an API and customizations from another.
// It's possible that the two are unsynced leading to not found customizations for the space.
// It's better to fallback on customization of the site that displaying an error.
console.warn('Customization not found for site space', ids.siteSpace);
}
return customizations.site;
})();
@@ -243,7 +247,7 @@ export async function fetchSpaceContextByIds(
shareKey: string | undefined;
changeRequest: string | undefined;
revision: string | undefined;
},
}
): Promise<GitBookSpaceContext> {
const { dataFetcher } = baseContext;
@@ -281,9 +285,39 @@ export async function fetchSpaceContextByIds(
};
}
function parseSiteSectionsList(structure: SiteStructure, siteSectionId: string) {
const sections = getSiteStructureSections(structure);
const section = sections.find((section) => section.id === siteSectionId);
assert(section, 'A section must be defined when there are multiple sections');
return { list: sections, current: section } satisfies SiteSections;
/**
* Check if the context is the root one for a site.
* Meaning we are on the default section / space.
*/
export function checkIsRootSiteContext(context: GitBookSiteContext): boolean {
const { structure } = context;
switch (structure.type) {
case 'sections': {
return getSiteStructureSections(structure, { ignoreGroups: true }).some(
(structure) =>
structure.default &&
structure.id === context.sections?.current.id &&
structure.siteSpaces.some(
(siteSpace) => siteSpace.default && siteSpace.id === context.siteSpace.id
)
);
}
case 'siteSpaces': {
return structure.structure.some(
(siteSpace) => siteSpace.default && siteSpace.id === context.siteSpace.id
);
}
}
}
function parseSiteSectionsAndGroups(structure: SiteStructure, siteSectionId: string) {
const sectionsAndGroups = getSiteStructureSections(structure, { ignoreGroups: false });
const section = parseCurrentSection(structure, siteSectionId);
assert(section, 'A section must be defined when there are multiple sections');
return { list: sectionsAndGroups, current: section } satisfies SiteSections;
}
function parseCurrentSection(structure: SiteStructure, siteSectionId: string) {
const sections = getSiteStructureSections(structure, { ignoreGroups: true });
return sections.find((section) => section.id === siteSectionId);
}
+74 -25
View File
@@ -1,7 +1,6 @@
import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache';
import { ComputedContentSource, GitBookAPI } from '@gitbook/api';
import { type ComputedContentSource, GitBookAPI } from '@gitbook/api';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env';
import { GitBookDataFetcher } from './types';
import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache';
import {
getChangeRequestCacheTag,
getHostnameCacheTag,
@@ -9,6 +8,7 @@ import {
getSiteCacheTag,
getSpaceCacheTag,
} from '../cache';
import type { GitBookDataFetcher } from './types';
interface DataFetcherInput {
/**
@@ -118,6 +118,12 @@ export function createDataFetcher(input: DataFetcherInput = commonInput): GitBoo
source: params.source,
});
},
getEmbedByUrl(params) {
return getEmbedByUrl(input, {
url: params.url,
spaceId: params.spaceId,
});
},
//
// API that are not tied to the token
@@ -139,6 +145,8 @@ export function createDataFetcher(input: DataFetcherInput = commonInput): GitBoo
async function getUserById(input: DataFetcherInput, userId: string) {
'use cache';
cacheLife('days');
try {
const res = await getAPI(input).users.getUserById(userId);
return res.data;
@@ -156,10 +164,11 @@ async function getSpace(
params: {
spaceId: string;
shareKey: string | undefined;
},
}
) {
'use cache';
cacheLife('days');
cacheTag(getSpaceCacheTag(params.spaceId));
const res = await getAPI(input).spaces.getSpaceById(params.spaceId, {
@@ -173,14 +182,16 @@ async function getChangeRequest(
params: {
spaceId: string;
changeRequestId: string;
},
}
) {
'use cache';
cacheLife('minutes');
try {
const res = await getAPI(input).spaces.getChangeRequestById(
params.spaceId,
params.changeRequestId,
params.changeRequestId
);
cacheTag(getChangeRequestCacheTag(params.spaceId, res.data.id));
return res.data;
@@ -199,10 +210,12 @@ async function getRevision(
spaceId: string;
revisionId: string;
metadata: boolean;
},
}
) {
'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.getRevisionById(params.spaceId, params.revisionId, {
metadata: params.metadata,
});
@@ -215,16 +228,18 @@ async function getRevisionPages(
spaceId: string;
revisionId: string;
metadata: boolean;
},
}
) {
'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.listPagesInRevisionById(
params.spaceId,
params.revisionId,
{
metadata: params.metadata,
},
}
);
return res.data.pages;
}
@@ -235,15 +250,17 @@ async function getRevisionFile(
spaceId: string;
revisionId: string;
fileId: string;
},
}
) {
'use cache';
cacheLife('max');
try {
const res = await getAPI(input).spaces.getFileInRevisionById(
params.spaceId,
params.revisionId,
params.fileId,
params.fileId
);
return res.data;
} catch (error) {
@@ -261,17 +278,18 @@ async function getRevisionPageByPath(
spaceId: string;
revisionId: string;
path: string;
},
}
) {
'use cache';
const encodedPath = encodeURIComponent(params.path);
cacheLife('max');
const encodedPath = encodeURIComponent(params.path);
try {
const res = await getAPI(input).spaces.getPageInRevisionByPath(
params.spaceId,
params.revisionId,
encodedPath,
encodedPath
);
return res.data;
@@ -289,10 +307,12 @@ async function getDocument(
params: {
spaceId: string;
documentId: string;
},
}
) {
'use cache';
cacheLife('max');
const res = await getAPI(input).spaces.getDocumentById(params.spaceId, params.documentId);
return res.data;
}
@@ -302,10 +322,13 @@ async function getComputedDocument(
params: {
spaceId: string;
source: ComputedContentSource;
},
}
) {
'use cache';
// TODO: we need to resolve dependencies and pass them in the cache key
cacheLife('days');
const res = await getAPI(input).spaces.getComputedDocument(params.spaceId, {
source: params.source,
});
@@ -318,15 +341,17 @@ async function getReusableContent(
spaceId: string;
revisionId: string;
reusableContentId: string;
},
}
) {
'use cache';
cacheLife('max');
try {
const res = await getAPI(input).spaces.getReusableContentInRevisionById(
params.spaceId,
params.revisionId,
params.reusableContentId,
params.reusableContentId
);
return res.data;
} catch (error) {
@@ -343,16 +368,17 @@ async function getLatestOpenAPISpecVersionContent(
params: {
organizationId: string;
slug: string;
},
}
) {
'use cache';
cacheTag(getOpenAPISpecCacheTag(params.organizationId, params.slug));
cacheLife('days');
try {
const res = await getAPI(input).orgs.getLatestOpenApiSpecVersionContent(
params.organizationId,
params.slug,
params.slug
);
return res.data;
} catch (error) {
@@ -370,7 +396,7 @@ async function getPublishedContentByUrl(
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
},
}
) {
'use cache';
@@ -378,6 +404,7 @@ async function getPublishedContentByUrl(
const hostname = new URL(url).hostname;
cacheTag(getHostnameCacheTag(hostname));
cacheLife('days');
const res = await getAPI(input).urls.getPublishedContentByUrl({
url,
@@ -398,16 +425,19 @@ async function getPublishedContentSite(
organizationId: string;
siteId: string;
siteShareKey: string | undefined;
},
}
) {
'use cache';
cacheTag(getSiteCacheTag(params.siteId));
cacheLife('days');
const res = await getAPI(input).orgs.getPublishedContentSite(
params.organizationId,
params.siteId,
{
shareKey: params.siteShareKey,
},
}
);
return res.data;
}
@@ -419,10 +449,13 @@ async function getSiteRedirectBySource(
siteId: string;
siteShareKey: string | undefined;
source: string;
},
}
) {
'use cache';
cacheTag(getSiteCacheTag(params.siteId));
cacheLife('days');
try {
const res = await getAPI(input).orgs.getSiteRedirectBySource(
params.organizationId,
@@ -430,7 +463,7 @@ async function getSiteRedirectBySource(
{
shareKey: params.siteShareKey,
source: params.source,
},
}
);
return res.data;
@@ -449,6 +482,22 @@ async function getSiteRedirectBySource(
}
}
async function getEmbedByUrl(
input: DataFetcherInput,
params: {
url: string;
spaceId: string;
}
) {
'use cache';
cacheLife('weeks');
const api = getAPI(input);
const res = await api.spaces.getEmbedByUrlInSpace(params.spaceId, { url: params.url });
return res.data;
}
function getAPI(input: DataFetcherInput) {
const { apiEndpoint, apiToken } = input;
const api = new GitBookAPI({
@@ -121,4 +121,9 @@ export interface GitBookDataFetcher {
siteShareKey: string | undefined;
source: string;
}): Promise<{ redirect: api.SiteRedirect | null; target: string } | null>;
/**
* Get an embed by its URL.
*/
getEmbedByUrl(params: { url: string; spaceId: string }): Promise<api.Embed>;
}
+14 -14
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'bun:test';
import { describe, expect, it } from 'bun:test';
import { getURLLookupAlternatives, normalizeURL } from './urls';
@@ -68,7 +68,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before the variant for a variant url', () => {
expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/v/variant/space')),
getURLLookupAlternatives(new URL('https://test.gitbook.io/v/variant/space'))
).toEqual({
revision: undefined,
changeRequest: undefined,
@@ -85,7 +85,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before the variant for a variant in a share link', () => {
expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space')),
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space'))
).toEqual({
revision: undefined,
changeRequest: undefined,
@@ -103,8 +103,8 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a revision in a variant', () => {
expect(
getURLLookupAlternatives(
new URL('https://test.gitbook.io/v/variant/~/revisions/id/rest'),
),
new URL('https://test.gitbook.io/v/variant/~/revisions/id/rest')
)
).toEqual({
revision: 'id',
changeRequest: undefined,
@@ -121,7 +121,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a revision ID', () => {
expect(
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c')),
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/revisions/id/a/b/c'))
).toEqual({
revision: 'id',
changeRequest: undefined,
@@ -138,7 +138,7 @@ describe('getURLLookupAlternatives', () => {
it('should not match before a change request ID', () => {
expect(
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/changes/id/hello')),
getURLLookupAlternatives(new URL('https://docs.mycompany.com/~/changes/id/hello'))
).toEqual({
revision: undefined,
changeRequest: 'id',
@@ -195,7 +195,7 @@ describe('getURLLookupAlternatives', () => {
it('should match a variant in a share-link', () => {
expect(
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space')),
getURLLookupAlternatives(new URL('https://test.gitbook.io/sharelink/v/variant/space'))
).toEqual({
revision: undefined,
changeRequest: undefined,
@@ -213,8 +213,8 @@ describe('getURLLookupAlternatives', () => {
it('should match a revision in a variant in a share-link', () => {
expect(
getURLLookupAlternatives(
new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c'),
),
new URL('https://test.gitbook.io/sharelink/v/variant/~/revisions/id/a/b/c')
)
).toEqual({
revision: 'id',
changeRequest: undefined,
@@ -232,8 +232,8 @@ describe('getURLLookupAlternatives', () => {
it('should match a change request in a variant in a share-link', () => {
expect(
getURLLookupAlternatives(
new URL('https://test.gitbook.io/sharelink/v/variant/~/changes/id/a/b/c'),
),
new URL('https://test.gitbook.io/sharelink/v/variant/~/changes/id/a/b/c')
)
).toEqual({
revision: undefined,
changeRequest: 'id',
@@ -367,13 +367,13 @@ describe('getURLLookupAlternatives', () => {
describe('normalizeURL', () => {
it('should remove trailing slashes', () => {
expect(normalizeURL(new URL('https://docs.mycompany.com/hello/'))).toEqual(
new URL('https://docs.mycompany.com/hello'),
new URL('https://docs.mycompany.com/hello')
);
});
it('should remove duplicate slashes', () => {
expect(normalizeURL(new URL('https://docs.mycompany.com//hello//there'))).toEqual(
new URL('https://docs.mycompany.com/hello/there'),
new URL('https://docs.mycompany.com/hello/there')
);
});
});
+5 -9
View File
@@ -19,10 +19,6 @@ export async function getPublishedContentByURL(input: {
const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url);
console.log(
`lookup content for url "${url.toString()}", with ${lookup.urls.length} alternatives`,
);
const result = await race(lookup.urls, async (alternative, { signal }) => {
const api = new GitBookAPI({
authToken: GITBOOK_API_TOKEN ?? undefined,
@@ -43,8 +39,8 @@ export async function getPublishedContentByURL(input: {
headers: {
'x-gitbook-force-cache': 'true',
},
},
),
}
)
);
if (callResult.error) {
@@ -76,8 +72,8 @@ export async function getPublishedContentByURL(input: {
'location',
joinPath(
redirect.searchParams.get('location') ?? '',
alternative.extraPath,
),
alternative.extraPath
)
);
data.redirect = redirect.toString();
}
@@ -155,7 +151,7 @@ export function getURLLookupAlternatives(input: URL) {
throw new Error(
`Invalid extraPath ${extraPath} for url ${adding.toString()}, already set to ${
existing.extraPath
}`,
}`
);
}
return;
+5 -4
View File
@@ -1,5 +1,5 @@
import { RevisionPageDocument } from '@gitbook/api';
import { GitBookDataFetcher } from './types';
import type { RevisionPageDocument } from '@gitbook/api';
import type { GitBookDataFetcher } from './types';
/**
* Get the document for a page.
@@ -7,11 +7,12 @@ import { GitBookDataFetcher } from './types';
export async function getPageDocument(
dataFetcher: GitBookDataFetcher,
spaceId: string,
page: RevisionPageDocument,
page: RevisionPageDocument
) {
if (page.documentId) {
return dataFetcher.getDocument({ spaceId, documentId: page.documentId });
} else if (page.computed) {
}
if (page.computed) {
return dataFetcher.getComputedDocument({ spaceId, source: page.computed });
}
+24 -2
View File
@@ -8,10 +8,18 @@ export const GITBOOK_URL =
process.env.GITBOOK_URL ??
'');
/**
* URL at which static assets are served.
*/
export const GITBOOK_ASSETS_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: (process.env.GITBOOK_ASSETS_PREFIX ?? GITBOOK_URL);
/**
* GitBook app URL.
*/
export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? `https://app.gitbook.com`;
export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? 'https://app.gitbook.com';
/**
* Default GitBook API URL endpoint.
@@ -34,5 +42,19 @@ export const GITBOOK_USER_AGENT = process.env.GITBOOK_USER_AGENT ?? 'GitBook-Ope
* This is used to disable tracking in development mode.
*/
export const GITBOOK_DISABLE_TRACKING = Boolean(
!!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production',
!!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production'
);
/**
* Hostname serving the integrations.
*/
export const GITBOOK_INTEGRATIONS_HOST =
process.env.GITBOOK_INTEGRATIONS_HOST ?? 'integrations.gitbook.com';
/**
* Endpoint to use for resizing images.
* It should be a Cloudflare domain with image resizing enabled.
*/
export const GITBOOK_IMAGE_RESIZE_URL = process.env.GITBOOK_IMAGE_RESIZE_URL ?? null;
export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null;
@@ -1,8 +1,9 @@
import 'server-only';
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env';
import type { GitBookSpaceLinker } from '../links';
import { type SignatureVersion, generateImageSignature } from './signatures';
import type { ImageResizer } from './types';
import { generateImageSignature, SignatureVersion } from './signatures';
import { GitBookSpaceLinker } from '../links';
interface CloudflareImageJsonFormat {
width: number;
@@ -40,8 +41,12 @@ export function createImageResizer({
/** The host name of the current site. */
host: string;
}): ImageResizer {
if (!GITBOOK_IMAGE_RESIZE_URL || !GITBOOK_IMAGE_RESIZE_SIGNING_KEY) {
return createNoopImageResizer();
}
return {
resize: (urlInput) => {
getResizedImageURL: (urlInput) => {
if (!checkIsSizableImageURL(urlInput)) {
return null;
}
@@ -57,7 +62,9 @@ export function createImageResizer({
url: urlInput,
});
const url = new URL(linker.toAbsoluteURL('/~gitbook/image'));
const url = new URL(
linker.toAbsoluteURL(linker.toPathInContent('/~gitbook/image'))
);
url.searchParams.set('url', getImageAPIUrl(urlInput));
if (options.width) {
@@ -95,18 +102,11 @@ export function createImageResizer({
*/
export function createNoopImageResizer(): ImageResizer {
return {
resize: () => null,
getImageSize: async (input) => null,
getResizedImageURL: () => null,
getImageSize: async (_input) => null,
};
}
/**
* Return true if images resizing is enabled.
*/
export function isImageResizingEnabled(): boolean {
return !!process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY;
}
/**
* Check if a URL is an HTTP URL.
*/
@@ -149,9 +149,9 @@ export function checkIsSizableImageURL(input: string): boolean {
*/
export async function getImageSize(
input: string,
defaultSize: Partial<CloudflareImageOptions> = {},
defaultSize: Partial<CloudflareImageOptions> = {}
): Promise<{ width: number; height: number } | null> {
if (!isImageResizingEnabled() || !checkIsSizableImageURL(input)) {
if (!checkIsSizableImageURL(input)) {
return null;
}
@@ -171,12 +171,7 @@ export async function getImageSize(
width: json.original.width,
height: json.original.height,
};
} catch (error) {
console.error(
`failed to fetch image size for ${input}: ${
(error as Error).stack ?? (error as Error).message ?? error
}`,
);
} catch (_error) {
return null;
}
}
@@ -188,7 +183,7 @@ export async function resizeImage(
input: string,
options: CloudflareImageOptions & {
signal?: AbortSignal;
},
}
): Promise<Response> {
const { signal, ...resizeOptions } = options;
@@ -203,33 +198,25 @@ export async function resizeImage(
// Since Cloudflare Images options on fetch are not supported on Cloudflare Pages,
// we need to use the Cloudflare Image Resize API directly.
if (process.env.GITBOOK_IMAGE_RESIZE_URL) {
const response = await fetch(
`${process.env.GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions(
resizeOptions,
)}/${encodeURIComponent(input)}`,
{
headers: {
// Pass the `Accept` header, as Cloudflare uses this to validate the format.
Accept:
resizeOptions.format === 'json'
? 'application/json'
: `image/${resizeOptions.format || 'jpeg'}`,
},
signal,
},
);
return response;
if (!GITBOOK_IMAGE_RESIZE_URL) {
throw new Error('GITBOOK_IMAGE_RESIZE_URL is not set');
}
return fetch(parsed, {
// @ts-ignore
cf: {
image: resizeOptions,
},
signal,
});
return await fetch(
`${GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions(
resizeOptions
)}/${encodeURIComponent(input)}`,
{
headers: {
// Pass the `Accept` header, as Cloudflare uses this to validate the format.
Accept:
resizeOptions.format === 'json'
? 'application/json'
: `image/${resizeOptions.format || 'jpeg'}`,
},
signal,
}
);
}
function stringifyOptions(options: CloudflareImageOptions): string {
@@ -2,6 +2,8 @@ import 'server-only';
import fnv1a from '@sindresorhus/fnv1a';
import type { MaybePromise } from 'p-map';
import { assert } from 'ts-essentials';
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY } from '../env';
/**
* GitBook has supported different version of image signing in the past. To maintain backwards
@@ -26,7 +28,7 @@ type SignFn = (input: SignFnInput) => MaybePromise<string>;
*/
export async function verifyImageSignature(
input: SignFnInput,
{ signature, version }: { signature: string; version: SignatureVersion },
{ signature, version }: { signature: string; version: SignatureVersion }
): Promise<boolean> {
const generator = IMAGE_SIGNATURE_FUNCTIONS[version];
const generated = await generator(input);
@@ -55,10 +57,11 @@ const fnv1aUtf8Buffer = new Uint8Array(512);
* The signature is relative to the current site being rendered to avoid serving images from other sites on the same domain.
*/
const generateSignatureV2: SignFn = async (input) => {
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [
input.url,
input.host, // The hostname is used to avoid serving images from other sites on the same domain
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
]
.filter(Boolean)
.join(':');
@@ -74,7 +77,8 @@ const fnv1aUtf8BufferV1 = new Uint8Array(512);
* to know that it was the algorithm that was used.
*/
const generateSignatureV1: SignFn = async (input) => {
const all = [input.url, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [input.url, GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
return fnv1a(all, { utf8Buffer: fnv1aUtf8BufferV1 }).toString(16);
};
@@ -84,7 +88,8 @@ const generateSignatureV1: SignFn = async (input) => {
* but still exist in previously generated and cached content.
*/
const generateSignatureV0: SignFn = async (input) => {
const all = [input.url, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
const all = [input.url, GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(all));
// Convert ArrayBuffer to hex string
+2 -2
View File
@@ -20,10 +20,10 @@ export type ImageResizer = {
* @param input - The image URL to resize.
* @param options - The options to resize the image.
*/
resize(input: string): null | ((options: ResizeImageOptions) => Promise<string>);
getResizedImageURL(imageURL: string): null | ((options: ResizeImageOptions) => Promise<string>);
/**
* Get the size of an image.
*/
getImageSize(input: string, options: GetImageSizeOptions): Promise<ImageSize | null>;
getImageSize(imageURL: string, options: GetImageSizeOptions): Promise<ImageSize | null>;
};
+4 -4
View File
@@ -1,14 +1,14 @@
import { ImageResizer, ResizeImageOptions } from './types';
import type { ImageResizer, ResizeImageOptions } from './types';
/**
* Quick utility to get a resized image URL.
*/
export async function getResizedImageURL(
resizer: ImageResizer,
resizer: ImageResizer | undefined,
url: string,
options: ResizeImageOptions,
options: ResizeImageOptions
) {
const getURL = resizer.resize(url);
const getURL = resizer?.getResizedImageURL(url);
if (!getURL) {
return url;
}
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'bun:test';
import { appendBasePathToLinker, createLinker } from './links';
const root = createLinker({
host: 'docs.company.com',
pathname: '/',
});
const variantInSection = createLinker({
host: 'docs.company.com',
pathname: '/section/variant',
});
describe('toPathInContent', () => {
it('should return the correct path', () => {
expect(root.toPathInContent('some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('some/path')).toBe('/section/variant/some/path');
});
it('should handle leading slash', () => {
expect(root.toPathInContent('/some/path')).toBe('/some/path');
expect(variantInSection.toPathInContent('/some/path')).toBe('/section/variant/some/path');
});
});
describe('toAbsoluteURL', () => {
it('should return the correct path', () => {
expect(root.toAbsoluteURL('some/path')).toBe('https://docs.company.com/some/path');
expect(variantInSection.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
});
});
describe('appendBasePathToLinker', () => {
const prefixedRoot = appendBasePathToLinker(root, '/section/variant');
const prefixedVariantInSection = appendBasePathToLinker(variantInSection, '/base');
describe('toPathInContent', () => {
it('should return the correct path', () => {
expect(prefixedRoot.toPathInContent('some/path')).toBe('/section/variant/some/path');
expect(prefixedVariantInSection.toPathInContent('some/path')).toBe(
'/section/variant/base/some/path'
);
});
});
describe('toAbsoluteURL', () => {
it('should return the correct path', () => {
expect(prefixedRoot.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
expect(prefixedVariantInSection.toAbsoluteURL('some/path')).toBe(
'https://docs.company.com/some/path'
);
});
});
});
+38 -16
View File
@@ -1,17 +1,26 @@
import { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import { getPagePath } from '@/lib/pages';
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
/**
* Generic interface to generate links based on a given context.
*
* URL levels:
*
* https://docs.company.com/section/variant/page
*
* toPathInContent('some/path') => /section/variant/some/path
* toPathForPage({ pages, page }) => /section/variant/some/path
* toAbsoluteURL('some/path') => https://docs.company.com/some/path
*/
export interface GitBookSpaceLinker {
/**
* Generate an absolute path for a relative path in the current space content.
* Generate an absolute path for a relative path to the current content.
*/
toPathInSpace(relativePath: string): string;
toPathInContent(relativePath: string): string;
/**
* Generate an absolute path for a page in the current space.
* Generate an absolute path for a page in the current content.
* The result should NOT be passed to `toPathInContent`.
*/
toPathForPage(input: {
pages: RevisionPage[];
@@ -20,9 +29,14 @@ export interface GitBookSpaceLinker {
}): string;
/**
* Generate an absolute URL for a given path.
* Generate an absolute URL for a given path relative to the host of the current content.
*/
toAbsoluteURL(absolutePath: string): string;
/**
* Generate a link (URL or path) for a GitBook content URL (url of another site)
*/
toLinkForContent(url: string): string;
}
/**
@@ -34,14 +48,14 @@ export function createLinker(
protocol?: string;
host: string;
pathname: string;
},
}
): GitBookSpaceLinker {
if (servedOn.host.includes('/')) {
throw new Error('Host cannot include a slash');
}
const linker: GitBookSpaceLinker = {
toPathInSpace(relativePath: string): string {
toPathInContent(relativePath: string): string {
return joinPaths(servedOn.pathname, relativePath);
},
@@ -50,7 +64,11 @@ export function createLinker(
},
toPathForPage({ pages, page, anchor }) {
return linker.toPathInSpace(getPagePath(pages, page)) + (anchor ? '#' + anchor : '');
return linker.toPathInContent(getPagePath(pages, page)) + (anchor ? `#${anchor}` : '');
},
toLinkForContent(url: string): string {
return url;
},
};
@@ -60,32 +78,36 @@ export function createLinker(
/**
* Append a prefix to a linker.
*/
export function appendPrefixToLinker(
export function appendBasePathToLinker(
linker: GitBookSpaceLinker,
prefix: string,
basePath: string
): GitBookSpaceLinker {
const linkerWithPrefix: GitBookSpaceLinker = {
toPathInSpace(relativePath: string): string {
return linker.toPathInSpace(joinPaths(prefix, relativePath));
toPathInContent(relativePath: string): string {
return linker.toPathInContent(joinPaths(basePath, relativePath));
},
toAbsoluteURL(absolutePath: string): string {
return linker.toAbsoluteURL(joinPaths(prefix, absolutePath));
return linker.toAbsoluteURL(absolutePath);
},
toPathForPage({ pages, page, anchor }) {
return (
linkerWithPrefix.toPathInSpace(getPagePath(pages, page)) +
(anchor ? '#' + anchor : '')
linkerWithPrefix.toPathInContent(getPagePath(pages, page)) +
(anchor ? `#${anchor}` : '')
);
},
toLinkForContent(url: string): string {
return linker.toLinkForContent(url);
},
};
return linkerWithPrefix;
}
function joinPaths(prefix: string, path: string): string {
const prefixPath = prefix.endsWith('/') ? prefix : prefix + '/';
const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`;
const suffixPath = path.startsWith('/') ? path.slice(1) : path;
return prefixPath + suffixPath;
}
+87 -23
View File
@@ -1,10 +1,12 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { GitBookAPIError } from '@gitbook/api';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { removeTrailingSlash } from '@/lib/paths';
import { MiddlewareHeaders } from '@v2/lib/middleware';
import { getContentSecurityPolicy } from '@/lib/csp';
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import { serveResizedImage } from '@/routes/image';
import { getPublishedContentByURL } from '@v2/lib/data';
import { MiddlewareHeaders } from '@v2/lib/middleware';
export const config = {
matcher: ['/((?!_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)'],
@@ -13,12 +15,30 @@ export const config = {
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
export async function middleware(request: NextRequest) {
const extracted = extractURL(request);
if (extracted) {
return serveSiteByURL(request, extracted);
}
try {
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (request.nextUrl.pathname.endsWith('/~gitbook/image')) {
return serveResizedImage(request);
}
return NextResponse.next();
// Route all requests to a site
const extracted = extractURL(request);
if (extracted) {
return serveSiteByURL(request, extracted);
}
// Handle the rest with the router default logic
return NextResponse.next();
} catch (error) {
return serveErrorResponse(error as Error);
}
}
/**
@@ -35,16 +55,7 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
});
if (result.error) {
if (result.error instanceof GitBookAPIError) {
return NextResponse.json(
{
error: result.error.message,
},
{ status: result.error.code },
);
} else {
throw result.error;
}
throw result.error;
}
const { data } = result;
@@ -66,20 +77,50 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
dynamicHeaders ? 'dynamic' : 'static',
mode,
encodeURIComponent(url.host + data.basePath),
encodeURIComponent(removeTrailingSlash(data.pathname) || '/'),
encodePathInSiteContent(data.pathname),
].join('/');
return NextResponse.rewrite(new URL('/' + route, request.url), {
console.log('route', route);
const response = NextResponse.rewrite(new URL(`/${route}`, request.url), {
headers: requestHeaders,
});
// Add Content Security Policy header
response.headers.set('content-security-policy', getContentSecurityPolicy());
return response;
}
/**
* The URL of the GitBook content can be passed in 2 different ways:
* Serve an error response.
*/
function serveErrorResponse(error: Error) {
if (error instanceof GitBookAPIError) {
return NextResponse.json(
{ error: error.message },
{ status: 500, headers: { 'content-type': 'application/json' } }
);
}
throw error;
}
/**
* The URL of the GitBook content can be passed in 3 different ways:
* - The request URL is in the `X-GitBook-URL` header.
* - Hostname is in the `X-GitBook-Host` header and the pathname is the path in the request URL.
* - The request URL is matching `/url/:url`
*/
function extractURL(request: NextRequest): URLWithMode | null {
const xGitbookUrl = request.headers.get('x-gitbook-url');
if (xGitbookUrl) {
return {
url: new URL(xGitbookUrl),
mode: 'url-host',
};
}
const xGitbookHost = request.headers.get('x-gitbook-host');
if (xGitbookHost) {
return {
@@ -102,10 +143,33 @@ function extractURL(request: NextRequest): URLWithMode | null {
/**
* Evaluate if a request is dynamic or static.
*/
function getDynamicHeaders(request: NextRequest): null | Record<string, string> {
function getDynamicHeaders(_request: NextRequest): null | Record<string, string> {
// TODO:
// - check token in query string
// - check token in cookies
// - check special headers or query string
return null;
}
/**
* Encode path in a site content.
* Special paths are not encoded and passed to be handled by the route handlers.
*/
function encodePathInSiteContent(rawPathname: string) {
const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname));
if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) {
return pathname;
}
switch (pathname) {
case '~gitbook/icon':
case '~gitbook/image':
case 'llms.txt':
case 'sitemap.xml':
case 'robots.txt':
return pathname;
default:
return encodeURIComponent(pathname || '/');
}
}
-31
View File
@@ -1,31 +0,0 @@
{
"extends": "next/core-web-vitals",
"plugins": ["import"],
"rules": {
"import/order": [
"error",
{
"groups": ["builtin", "external", ["internal", "parent", "sibling", "index"]],
"newlines-between": "always",
"distinctGroup": true,
"pathGroups": [
{
"pattern": "@/**",
"group": "external",
"position": "after"
},
{
"pattern": "@gitbook/**",
"group": "external",
"position": "after"
}
],
"alphabetize": {
"order": "asc",
"caseInsensitive": true
}
}
],
"@next/next/no-img-element": ["off"]
}
}
+14
View File
@@ -1,5 +1,19 @@
# gitbook
## 0.6.4
### Patch Changes
- 9b914d1: Fix getProxyModeBasePath that was computing incorrect base path in some scenarios
- 2ae76f9: Change how a site in proxy mode is resolved
- 027a859: Add support for links style customization option
- 3e11678: fix: lost section groups
- 3319375: Support OpenAPI operation block
- Updated dependencies [722f02e]
- Updated dependencies [0924259]
- @gitbook/react-openapi@1.0.4
- @gitbook/openapi-parser@2.0.1
## 0.6.3
### Patch Changes
+1 -1
View File
@@ -1,4 +1,4 @@
import { runTestCases, TestsCase, waitForCookiesDialog } from './util';
import { type TestsCase, runTestCases } from './util';
/** A list of test cases to run on the customers' docs sites. */
const testCases: TestsCase[] = [
+118 -99
View File
@@ -9,12 +9,13 @@ import { expect } from '@playwright/test';
import jwt from 'jsonwebtoken';
import {
VISITOR_TOKEN_COOKIE,
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
VISITOR_TOKEN_COOKIE,
} from '@/lib/visitor-token';
import {
type TestsCase,
allDeprecatedThemePresets,
allLocales,
allSidebarBackgroundStyles,
@@ -24,7 +25,6 @@ import {
getCustomizationURL,
headerLinks,
runTestCases,
TestsCase,
waitForCookiesDialog,
} from './util';
@@ -43,7 +43,7 @@ const testCases: TestsCase[] = [
url: '',
run: async (page) => {
await expect(page.locator('[data-testid="space-dropdown-button"]')).toHaveCount(
0,
0
);
},
},
@@ -114,20 +114,20 @@ const testCases: TestsCase[] = [
await spaceDrowpdown.click();
const variantSelectionDropdown = page.locator(
'css=[data-testid="space-dropdown-button"] + div',
'css=[data-testid="space-dropdown-button"] + div'
);
// the customized space title
await expect(
variantSelectionDropdown.getByRole('link', {
name: 'Multi-Variants',
}),
})
).toBeVisible();
// the NON-customized space title
await expect(
variantSelectionDropdown.getByRole('link', {
name: 'RFCs',
}),
})
).toBeVisible();
},
},
@@ -156,7 +156,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true'
);
},
},
@@ -179,7 +179,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true'
);
},
},
@@ -195,7 +195,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
})(),
@@ -214,7 +214,38 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true'
);
},
},
],
},
{
name: 'GitBook Site (Sections and Section Groups)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
tests: [
{
name: 'Site with sections and section groups',
url: '',
},
{
name: 'Section group dropdown',
url: '',
run: async (page) => {
await page.getByRole('button', { name: 'Test Section Group 1' }).hover();
await expect(page.getByRole('link', { name: /Section B/ })).toBeVisible();
},
},
{
name: 'Section group link',
url: '',
screenshot: false,
run: async (page) => {
const sectionGroupDropdown = await page.getByText('Test Section Group 1');
await sectionGroupDropdown.hover();
await page.getByText('Section B').click();
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/sections/sections-4'
);
},
},
@@ -331,7 +362,7 @@ const testCases: TestsCase[] = [
for (const p of document.querySelectorAll('p')) {
if (
p.textContent?.includes(
'This image has intrinsic 400px width, but renders as 300px:',
'This image has intrinsic 400px width, but renders as 300px:'
)
) {
p.style.color = 'transparent';
@@ -413,7 +444,7 @@ const testCases: TestsCase[] = [
await page.waitForFunction(() => {
const fonts = Array.from(document.fonts.values());
const mjxFonts = fonts.filter(
(font) => font.family === 'MJXZERO' || font.family === 'MJXTEX',
(font) => font.family === 'MJXZERO' || font.family === 'MJXTEX'
);
return (
mjxFonts.length === 2 &&
@@ -505,17 +536,15 @@ const testCases: TestsCase[] = [
},
{
name: `With duotone icons - Theme mode ${themeMode}`,
url:
'page-options/page-with-icon' +
getCustomizationURL({
styling: {
icons: CustomizationIconsStyle.Duotone,
},
themes: {
default: themeMode,
toggeable: false,
},
}),
url: `page-options/page-with-icon${getCustomizationURL({
styling: {
icons: CustomizationIconsStyle.Duotone,
},
themes: {
default: themeMode,
toggeable: false,
},
})}`,
run: waitForCookiesDialog,
},
{
@@ -643,7 +672,7 @@ const testCases: TestsCase[] = [
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
await expect(
page.getByRole('heading', { level: 1, name: 'shared' }),
page.getByRole('heading', { level: 1, name: 'shared' })
).toBeVisible();
const url = page.url();
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
@@ -663,7 +692,7 @@ const testCases: TestsCase[] = [
run: async (page) => {
await page.locator('a.underline').click();
await expect(
page.getByRole('heading', { level: 1, name: 'shared' }),
page.getByRole('heading', { level: 1, name: 'shared' })
).toBeVisible();
const url = page.url();
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
@@ -700,7 +729,7 @@ const testCases: TestsCase[] = [
url: 'invalid/',
run: async (page) => {
await expect(
page.getByText('Authentication missing to access this content'),
page.getByText('Authentication missing to access this content')
).toBeVisible();
},
screenshot: false,
@@ -709,7 +738,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Space',
baseUrl: `https://gitbook.gitbook.io/gbo-va-space/`,
baseUrl: 'https://gitbook.gitbook.io/gbo-va-space/',
tests: [
{
name: 'First',
@@ -722,13 +751,13 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `first?jwt_token=${token}`;
})(),
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' }),
page.getByRole('heading', { level: 1, name: 'first' })
).toBeVisible();
},
screenshot: false,
@@ -744,13 +773,13 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `second?jwt_token=${token}`;
})(),
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'second' }),
page.getByRole('heading', { level: 1, name: 'second' })
).toBeVisible();
},
screenshot: false,
@@ -759,7 +788,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Collection',
baseUrl: `https://gitbook.gitbook.io/gbo-va-collection/`,
baseUrl: 'https://gitbook.gitbook.io/gbo-va-collection/',
tests: [
{
name: 'Root',
@@ -772,7 +801,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
@@ -789,7 +818,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `spacea?jwt_token=${token}`;
})(),
@@ -806,7 +835,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `spaceb?jwt_token=${token}`;
})(),
@@ -823,7 +852,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `spacec?jwt_token=${token}`;
})(),
@@ -833,7 +862,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Space (custom domain)',
baseUrl: `https://test.gitbook.community/`,
baseUrl: 'https://test.gitbook.community/',
tests: [
{
name: 'Root',
@@ -846,7 +875,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
@@ -863,13 +892,13 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `first?jwt_token=${token}`;
})(),
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' }),
page.getByRole('heading', { level: 1, name: 'first' })
).toBeVisible();
},
screenshot: false,
@@ -885,7 +914,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `custom-page?jwt_token=${token}`;
})(),
@@ -902,7 +931,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `custom-page/inner-page?jwt_token=${token}`;
})(),
@@ -912,7 +941,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/`,
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/',
tests: [
{
name: 'Redirect to fallback on invalid token pulled from cookie',
@@ -927,7 +956,7 @@ const testCases: TestsCase[] = [
'invalidKey',
{
expiresIn: '24h',
},
}
);
return [
{
@@ -952,13 +981,13 @@ const testCases: TestsCase[] = [
'invalidKey',
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
run: async (page) => {
await expect(page.locator('pre')).toContainText(
'Error while validating the JWT token. Reason: The token signature is invalid.',
'Error while validating the JWT token. Reason: The token signature is invalid.'
);
},
},
@@ -985,7 +1014,7 @@ const testCases: TestsCase[] = [
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: `Index by default`,
name: 'Index by default',
url: '?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
@@ -1033,7 +1062,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Adaptive Content - VA',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/`,
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/',
tests: [
{
name: 'isAlphaUser',
@@ -1047,7 +1076,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
@@ -1074,7 +1103,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
@@ -1102,7 +1131,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return `?jwt_token=${token}`;
})(),
@@ -1121,7 +1150,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Adaptive Content - Public',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/`,
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/',
tests: [
{
name: 'No custom cookie',
@@ -1154,7 +1183,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return [
{
@@ -1193,7 +1222,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return [
{
@@ -1233,7 +1262,7 @@ const testCases: TestsCase[] = [
privateKey,
{
expiresIn: '24h',
},
}
);
return [
{
@@ -1274,25 +1303,21 @@ const testCases: TestsCase[] = [
},
{
name: 'Table with straight corners',
url:
'blocks/tables' +
getCustomizationURL({
styling: {
corners: CustomizationCorners.Straight,
},
}),
url: `blocks/tables${getCustomizationURL({
styling: {
corners: CustomizationCorners.Straight,
},
})}`,
run: waitForCookiesDialog,
fullPage: true,
},
{
name: 'Table with primary color',
url:
'blocks/tables' +
getCustomizationURL({
styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
},
}),
url: `blocks/tables${getCustomizationURL({
styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
},
})}`,
run: waitForCookiesDialog,
fullPage: true,
},
@@ -1300,46 +1325,40 @@ const testCases: TestsCase[] = [
...allThemeModes.flatMap((theme) => [
{
name: `Table in ${theme} mode`,
url:
'blocks/tables' +
getCustomizationURL({
themes: {
default: theme,
toggeable: false,
},
}),
url: `blocks/tables${getCustomizationURL({
themes: {
default: theme,
toggeable: false,
},
})}`,
run: waitForCookiesDialog,
fullPage: true,
},
{
name: `Table with straight corners in ${theme} mode`,
url:
'blocks/tables' +
getCustomizationURL({
styling: {
corners: CustomizationCorners.Straight,
},
themes: {
default: theme,
toggeable: false,
},
}),
url: `blocks/tables${getCustomizationURL({
styling: {
corners: CustomizationCorners.Straight,
},
themes: {
default: theme,
toggeable: false,
},
})}`,
run: waitForCookiesDialog,
fullPage: true,
},
{
name: `Table with primary color in ${theme} mode`,
url:
'blocks/tables' +
getCustomizationURL({
styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
},
themes: {
default: theme,
toggeable: false,
},
}),
url: `blocks/tables${getCustomizationURL({
styling: {
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
},
themes: {
default: theme,
toggeable: false,
},
})}`,
run: waitForCookiesDialog,
fullPage: true,
},
+11 -10
View File
@@ -3,7 +3,7 @@ import {
CustomizationBackground,
CustomizationCorners,
CustomizationFont,
CustomizationHeaderItem,
type CustomizationHeaderItem,
CustomizationHeaderPreset,
CustomizationIconsStyle,
CustomizationLinksStyle,
@@ -11,14 +11,14 @@ import {
CustomizationSidebarBackgroundStyle,
CustomizationSidebarListStyle,
CustomizationTheme,
CustomizationThemedColor,
CustomizationThemeMode,
SiteCustomizationSettings,
type CustomizationThemedColor,
type SiteCustomizationSettings,
} from '@gitbook/api';
import { BrowserContext, expect, Page, test } from '@playwright/test';
import { type BrowserContext, type Page, expect, test } from '@playwright/test';
import deepMerge from 'deepmerge';
import rison from 'rison';
import { DeepPartial } from 'ts-essentials';
import type { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils';
@@ -151,9 +151,10 @@ export function runTestCases(testCases: TestsCase[]) {
...cookie,
domain: new URL(url).host,
path: '/',
})),
}))
);
}
await page.goto(url);
if (testEntry.run) {
await testEntry.run(page);
@@ -231,11 +232,11 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
font: CustomizationFont.Inter,
background: CustomizationBackground.Plain,
icons: CustomizationIconsStyle.Regular,
links: CustomizationLinksStyle.Default,
sidebar: {
background: CustomizationSidebarBackgroundStyle.Default,
list: CustomizationSidebarListStyle.Default,
},
links: CustomizationLinksStyle.Default,
},
internationalization: {
locale: CustomizationLocale.En,
@@ -296,7 +297,7 @@ async function waitForIcons(page: Page) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = (error) => reject(new Error(`Failed to load image: ${src}`));
img.onerror = (_error) => reject(new Error(`Failed to load image: ${src}`));
img.src = src;
});
}
@@ -312,7 +313,7 @@ async function waitForIcons(page: Page) {
throw new Error('No mask-image');
}
await loadImage(url);
}),
})
);
});
}
@@ -327,7 +328,7 @@ async function waitForTOCScrolling(page: Page) {
await expect(toc).toBeVisible();
await page.evaluate(() => {
const tocScrollContainer = document.querySelector(
'[data-testid="table-of-contents"] [data-testid="toc-scroll-container"]',
'[data-testid="table-of-contents"] [data-testid="toc-scroll-container"]'
);
if (!tocScrollContainer) {
throw new Error('TOC scroll container not found');
+2 -2
View File
@@ -34,7 +34,7 @@ module.exports = withSentryConfig(
__RRWEB_EXCLUDE_IFRAME__: true,
__RRWEB_EXCLUDE_SHADOW_DOM__: true,
__SENTRY_EXCLUDE_REPLAY_WORKER__: true,
}),
})
);
}
@@ -79,5 +79,5 @@ module.exports = withSentryConfig(
// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
tunnelRoute: '/~gitbook/monitoring',
disableLogger: true,
},
}
);
+2 -7
View File
@@ -1,13 +1,12 @@
{
"name": "gitbook",
"version": "0.6.3",
"version": "0.6.4",
"private": true,
"scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev",
"build": "next build",
"build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit",
"e2e": "playwright test e2e/internal.spec.ts",
"e2e-customers": "playwright test e2e/customers.spec.ts",
@@ -17,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math"
},
"dependencies": {
"@gitbook/api": "^0.96.0",
"@gitbook/api": "0.96.1",
"@gitbook/cache-do": "workspace:*",
"@gitbook/colors": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
@@ -38,7 +37,6 @@
"assert-never": "^1.2.1",
"bun-types": "^1.1.20",
"classnames": "^2.5.1",
"content-security-policy-merger": "^1.0.0",
"framer-motion": "^10.16.14",
"js-cookie": "^3.0.5",
"jsontoxml": "^1.0.1",
@@ -86,9 +84,6 @@
"autoprefixer": "^10",
"deepmerge": "^4.3.1",
"env-cmd": "^10.1.0",
"eslint": "^8",
"eslint-config-next": "^14.2.5",
"eslint-plugin-import": "^2.29.1",
"jsonwebtoken": "^9.0.2",
"postcss": "^8",
"psi": "^4.1.0",
@@ -1,124 +1,9 @@
import {
resizeImage,
checkIsSizableImageURL,
CloudflareImageOptions,
CURRENT_SIGNATURE_VERSION,
isSignatureVersion,
SignatureVersion,
verifyImageSignature,
parseImageAPIURL,
} from '@v2/lib/images';
import { NextRequest, NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getHost } from '@/lib/links';
import { serveResizedImage } from '@/routes/image';
export const runtime = 'edge';
/**
* Only on Cloudflare Workers:
*
* Fetch and resize an image.
*/
export async function GET(request: NextRequest) {
let urlParam = request.nextUrl.searchParams.get('url');
const signature = request.nextUrl.searchParams.get('sign');
if (!urlParam || !signature) {
return new Response('Missing url/sign parameters', { status: 400 });
}
const signatureVersion = parseSignatureVersion(request.nextUrl.searchParams.get('sv'));
if (!signatureVersion) {
return new Response(`Invalid sv parameter`, { status: 400 });
}
const url = parseImageAPIURL(urlParam);
// Check again if the image can be sized, even though we checked when rendering the Image component
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
// Also prevent infinite redirects.
if (!checkIsSizableImageURL(url)) {
return new Response('Invalid url parameter', { status: 400 });
}
// Verify the signature
const verified = await verifyImageSignature(
{
url,
host: await getHost(),
},
{ signature, version: signatureVersion },
);
if (!verified) {
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
}
if (signatureVersion !== CURRENT_SIGNATURE_VERSION) {
return NextResponse.redirect(url, 302);
}
// Cloudflare-specific options are in the cf object.
const options: CloudflareImageOptions = {
fit: 'scale-down',
format: 'jpeg',
quality: 100,
};
const width = request.nextUrl.searchParams.get('width');
if (width) {
options.width = Number(width);
}
const height = request.nextUrl.searchParams.get('height');
if (height) {
options.height = Number(height);
}
const dpr = request.nextUrl.searchParams.get('dpr');
if (dpr) {
options.dpr = Number(dpr);
}
const quality = request.nextUrl.searchParams.get('quality');
if (quality) {
options.quality = Number(quality);
}
// Check the Accept header to handle content negotiation
const accept = request.headers.get('accept');
if (accept && /image\/avif/.test(accept)) {
options.format = 'avif';
} else if (accept && /image\/webp/.test(accept)) {
options.format = 'webp';
}
try {
const response = await resizeImage(url, options);
if (!response.ok) {
throw new Error('Failed to resize image');
}
return response;
} catch (error) {
// Redirect to the original image if resizing fails
return NextResponse.redirect(url, 302);
}
}
/**
* Parse the image signature version from a query param. Returns null if the version is invalid.
*/
function parseSignatureVersion(input: string | null): SignatureVersion | null {
// Before introducing the sv parameter, all signatures were generated with version 0.
if (!input) {
return '0';
}
// If the query param explicitly asks for a signature version.
if (isSignatureVersion(input)) {
return input;
}
// Otherwise the version is invalid.
return null;
return serveResizedImage(request);
}
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server';
import { type NextRequest, NextResponse } from 'next/server';
import { revalidateTags } from '@/lib/cache';
@@ -21,7 +21,7 @@ export async function POST(req: NextRequest) {
{
error: 'tags must be an array',
},
{ status: 400 },
{ status: 400 }
);
}
+3 -3
View File
@@ -1,7 +1,7 @@
'use client';
import { captureException } from '@sentry/nextjs';
import Error from 'next/error';
import NextError from 'next/error';
import { useEffect } from 'react';
export default function GlobalError({ error }: { error: Error }) {
@@ -10,9 +10,9 @@ export default function GlobalError({ error }: { error: Error }) {
}, [error]);
return (
<html>
<html lang="en">
<body>
<Error statusCode={undefined as any} />
<NextError statusCode={undefined as any} />
</body>
</html>
);
@@ -1,11 +1,10 @@
import { Metadata, Viewport } from 'next';
import React from 'react';
import type { Metadata, Viewport } from 'next';
import {
type PagePathParams,
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
SitePage,
PagePathParams,
} from '@/components/SitePage';
import { getSiteContentPointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
@@ -1,13 +1,12 @@
import { getThemeFromMiddleware } from '@v2/lib/middleware';
import { Metadata, Viewport } from 'next';
import React from 'react';
import type { Metadata, Viewport } from 'next';
import type React from 'react';
import {
SiteLayout,
generateSiteLayoutMetadata,
generateSiteLayoutViewport,
SiteLayout,
} from '@/components/SiteLayout';
import { getContentSecurityPolicyNonce } from '@/lib/csp';
import { getSiteContentPointer } from '@/lib/pointer';
import { shouldTrackEvents } from '@/lib/tracking';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
@@ -21,14 +20,12 @@ export const dynamic = 'force-dynamic';
export default async function ContentLayout(props: { children: React.ReactNode }) {
const { children } = props;
const nonce = await getContentSecurityPolicyNonce();
const context = await fetchLayoutData();
const queryStringTheme = await getThemeFromMiddleware();
return (
<SiteLayout
context={context}
nonce={nonce}
forcedTheme={queryStringTheme}
withTracking={await shouldTrackEvents()}
>
@@ -1,154 +1,14 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api';
import assertNever from 'assert-never';
import { ListItem, Paragraph, Root, RootContent } from 'mdast';
import { toMarkdown } from 'mdast-util-to-markdown';
import { NextRequest } from 'next/server';
import type { NextRequest } from 'next/server';
import { getPublishedContentSite, getRevisionPages } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap';
import { getSiteStructureSections } from '@/lib/sites';
import { getSiteContentPointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveLLMsTxt } from '@/routes/llms';
export const runtime = 'edge';
/**
* Generate a llms.txt file for the site.
*/
export async function GET(req: NextRequest) {
export async function GET(_req: NextRequest) {
const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { structure: siteStructure, site } = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('llms.txt is only served from the root of the site', { status: 404 });
}
const tree: Root = {
type: 'root',
children: [
{
type: 'heading',
depth: 1,
children: [{ type: 'text', value: site.title }],
},
...(await getNodesFromSiteStructure(siteStructure)),
],
};
return new Response(
toMarkdown(tree, {
bullet: '-',
}),
{
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
},
);
}
/**
* Get MDAST nodes from site structure.
*/
async function getNodesFromSiteStructure(siteStructure: SiteStructure): Promise<RootContent[]> {
switch (siteStructure.type) {
case 'sections':
return getNodesFromSections(getSiteStructureSections(siteStructure));
case 'siteSpaces':
return getNodesFromSiteSpaces(siteStructure.structure, { heading: true });
default:
assertNever(siteStructure);
}
}
/**
* Get MDAST nodes from site sections.
*/
async function getNodesFromSections(siteSections: SiteSection[]): Promise<RootContent[]> {
const all = await Promise.all(
siteSections.map(async (siteSection): Promise<RootContent[]> => {
const siteSpaceNodes = await getNodesFromSiteSpaces(siteSection.siteSpaces, {
heading: false,
});
return [
{
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSection.title }],
},
...siteSpaceNodes,
];
}),
);
return all.flat();
}
/**
* Get MDAST nodes from site spaces.
*/
async function getNodesFromSiteSpaces(
siteSpaces: SiteSpace[],
options: {
/**
* Includes a heading for each site space.
*/
heading?: boolean;
},
): Promise<RootContent[]> {
const all = await Promise.all(
siteSpaces.map(async (siteSpace): Promise<RootContent[]> => {
const siteSpaceUrl = siteSpace.urls.published;
if (!siteSpaceUrl) {
return [];
}
const rootPages = await getRevisionPages(siteSpace.space.id, siteSpace.space.revision, {
metadata: false,
});
const pages = getIndexablePages(rootPages);
const listChildren = await Promise.all(
pages.map(async ({ page }): Promise<ListItem> => {
const url = await getAbsoluteHref(
joinPath(new URL(siteSpaceUrl).pathname, getPagePath(rootPages, page)),
true,
);
const children: Paragraph['children'] = [
{
type: 'link',
url,
children: [{ type: 'text', value: page.title }],
},
];
if (page.description) {
children.push({ type: 'text', value: `: ${page.description}` });
}
return {
type: 'listItem',
children: [{ type: 'paragraph', children }],
};
}),
);
const nodes: RootContent[] = [];
if (options.heading) {
nodes.push({
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSpace.title }],
});
}
nodes.push({
type: 'list',
spread: false,
children: listChildren,
});
return nodes;
}),
);
return all.flat();
return serveLLMsTxt(context);
}
@@ -1,31 +1,14 @@
import { NextRequest } from 'next/server';
import type { NextRequest } from 'next/server';
import { getSite } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getSiteContentPointer } from '@/lib/pointer';
import { isSiteIndexable } from '@/lib/seo';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveRobotsTxt } from '@/routes/robots';
export const runtime = 'edge';
/**
* Generate a robots.txt for the current space.
*/
export async function GET(req: NextRequest) {
export async function GET(_request: NextRequest) {
const pointer = await getSiteContentPointer();
const site = await getSite(pointer.organizationId, pointer.siteId);
const context = await fetchV1ContextForSitePointer(pointer);
const lines = [
`User-agent: *`,
'Disallow: /~gitbook/',
...((await isSiteIndexable(site))
? [`Allow: /`, `Sitemap: ${await getAbsoluteHref(`/sitemap.xml`, true)}`]
: [`Disallow: /`]),
];
const content = lines.join('\n');
return new Response(content, {
headers: {
'Content-Type': 'text/plain',
},
});
return serveRobotsTxt(context);
}
@@ -1,66 +1,12 @@
import jsontoxml from 'jsontoxml';
import { getRevisionPages, getSpace } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { servePagesSitemap } from '@/routes/sitemap';
export const runtime = 'edge';
/**
* Generate a sitemap.xml for the current section / space.
*/
export async function GET() {
const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const revisionId =
pointer.revisionId ?? (await getSpace(pointer.spaceId, pointer.siteShareKey)).revision;
const rootPages = await getRevisionPages(pointer.spaceId, revisionId, { metadata: false });
const pages = getIndexablePages(rootPages);
const urls = await Promise.all(
pages.map(async ({ page, depth }) => {
// Decay priority with depth
const priority = Math.pow(2, -0.25 * depth);
// Normalize to keep 2 decimals
const normalizedPriority = Math.floor(100 * priority) / 100;
const lastModified = page.updatedAt || page.createdAt;
const url: { loc: string; priority: number; lastmod?: string } = {
priority: normalizedPriority,
loc: await getAbsoluteHref(getPagePath(rootPages, page), true),
};
if (lastModified) {
url.lastmod = new Date(lastModified).toISOString();
}
return { url };
}),
);
const xml = jsontoxml(
[
{
name: 'urlset',
children: urls,
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
return servePagesSitemap(context);
}
@@ -1,98 +1,12 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api';
import assertNever from 'assert-never';
import jsontoxml from 'jsontoxml';
import { getPublishedContentSite } from '@/lib/api';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { getSiteStructureSections } from '@/lib/sites';
import { filterOutNullable } from '@/lib/typescript';
import { getSiteContentPointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveRootSitemap } from '@/routes/sitemap';
export const runtime = 'edge';
/**
* Generate a root sitemap that point to all sitemap-pages.xml.
*/
export async function GET() {
const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { structure: siteStructure } = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('Root sitemap is only served from the root of the site', {
status: 404,
});
}
const urls = await getUrlsFromSiteStructure(siteStructure);
const xml = jsontoxml(
[
{
name: 'sitemapindex',
children: urls.map((url) => ({
name: 'sitemap',
children: [{ name: 'loc', text: url }],
})),
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}
/**
* Get Sitemap URLs from site structure.
*/
async function getUrlsFromSiteStructure(siteStructure: SiteStructure): Promise<string[]> {
switch (siteStructure.type) {
case 'sections':
return getUrlsFromSiteSections(getSiteStructureSections(siteStructure));
case 'siteSpaces':
return getUrlsFromSiteSpaces(siteStructure.structure);
default:
assertNever(siteStructure);
}
}
/**
* Get Sitemap URLs from site sections.
*/
async function getUrlsFromSiteSections(siteSections: SiteSection[]): Promise<string[]> {
const urls = await Promise.all(
siteSections.map(async (siteSection) => getUrlsFromSiteSpaces(siteSection.siteSpaces), []),
);
return urls.flat();
}
/**
* Get Sitemap URLs from site spaces.
*/
async function getUrlsFromSiteSpaces(siteSpaces: SiteSpace[]): Promise<string[]> {
const urls = await Promise.all(
siteSpaces.map(async (siteSpace) => {
if (!siteSpace.urls.published) {
return null;
}
const url = new URL(siteSpace.urls.published);
url.pathname = joinPath(url.pathname, 'sitemap-pages.xml');
return url.toString();
}, []),
);
return urls.filter(filterOutNullable);
return serveRootSitemap(context);
}
@@ -1,93 +1,14 @@
import { notFound } from 'next/navigation';
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import type { NextRequest } from 'next/server';
import { getEmojiForCode } from '@/lib/emojis';
import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveIcon } from '@/routes/icon';
export const runtime = 'edge';
const SIZES = {
/** Size for a favicon */
small: {
width: 48,
height: 48,
textSize: 'text-[32px]',
boxStyle: 'rounded-[8px]',
},
/** Size for display as an app icon or in the header */
medium: {
width: 256,
height: 256,
textSize: 'text-[164px]',
boxStyle: 'rounded-[32px]',
},
};
/**
* Render an icon for the space.
*/
export async function GET(req: NextRequest) {
const options = getOptions(req.url);
const size = SIZES[options.size];
const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
const { site, customization } = await fetchV1ContextForSitePointer(pointer);
const contentTitle = site.title;
return new ImageResponse(
(
<div
tw={tcls(options.theme === 'light' ? 'bg-white' : 'bg-black', size.boxStyle)}
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<h2
tw={tcls(
size.textSize,
'font-bold',
'tracking-tight',
options.theme === 'light' ? 'text-black' : 'text-white',
)}
>
{'emoji' in customization.favicon
? getEmojiForCode(customization.favicon.emoji)
: contentTitle.slice(0, 1).toUpperCase()}
</h2>
</div>
),
{
width: size.width,
height: size.height,
},
);
}
function getOptions(inputUrl: string): {
size: keyof typeof SIZES;
theme: 'light' | 'dark';
} {
const url = new URL(inputUrl);
const sizeParam = (url.searchParams.get('size') ?? 'small') as keyof typeof SIZES;
const themeParam = url.searchParams.get('theme') ?? 'light';
if (!SIZES[sizeParam] || !['light', 'dark'].includes(themeParam)) {
notFound();
}
return {
// @ts-ignore
size: sizeParam,
// @ts-ignore
theme: themeParam,
};
return serveIcon(context, req);
}
@@ -1,232 +1,15 @@
import { CustomizationHeaderPreset } from '@gitbook/api';
import { colorContrast } from '@gitbook/colors';
import { redirect } from 'next/navigation';
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import type { NextRequest } from 'next/server';
import { PageIdParams, fetchPageData } from '@/components/SitePage';
import { googleFontsMap } from '@/fonts';
import { getAbsoluteHref } from '@/lib/links';
import type { PageIdParams } from '@/components/SitePage';
import { getSiteContentPointer } from '@/lib/pointer';
import { filterOutNullable } from '@/lib/typescript';
import { fetchV1ContextForSitePointer } from '@/lib/v1';
import { serveOGImage } from '@/routes/ogimage';
export const runtime = 'edge';
async function loadGoogleFont(input: { fontFamily: string; text: string; weight: 400 | 700 }) {
const { fontFamily, text, weight } = input;
if (!text.trim()) {
return null;
}
const url = new URL('https://fonts.googleapis.com/css2');
url.searchParams.set('family', `${fontFamily}:wght@${weight}`);
url.searchParams.set('text', text);
const result = await fetch(url.href);
if (!result.ok) {
return null;
}
const css = await result.text();
const resource = css.match(/src: url\((.+)\) format\('(opentype|truetype)'\)/);
const resourceUrl = resource ? resource[1] : null;
if (resourceUrl) {
const response = await fetch(resourceUrl);
if (response.ok) {
const data = await response.arrayBuffer();
return {
name: fontFamily,
data,
style: 'normal' as const,
weight,
};
}
}
// If for some reason we can't load the font, we'll just use the default one
return null;
}
/**
* Render the OpenGraph image for a space.
*/
export async function GET(req: NextRequest, { params }: { params: Promise<PageIdParams> }) {
export async function GET(_req: NextRequest, { params }: { params: Promise<PageIdParams> }) {
const pointer = await getSiteContentPointer();
const baseContext = await fetchV1ContextForSitePointer(pointer);
const { context, pageTarget } = await fetchPageData(baseContext, await params);
const { customization, site } = context;
const page = pageTarget?.page;
// If user configured a custom social preview, we redirect to it.
if (customization.socialPreview.url) {
redirect(customization.socialPreview.url);
}
// Compute all text to load only the necessary fonts
const contentTitle = customization.header.logo ? '' : site.title;
const pageTitle = page
? page.title.length > 64
? page.title.slice(0, 64) + '...'
: page.title
: 'Not found';
const pageDescription =
page?.description && page?.title.length <= 64
? page.description.length > 164
? page.description.slice(0, 164) + '...'
: page.description
: '';
const fontFamily = googleFontsMap[customization.styling.font] ?? 'Inter';
const regularText = pageDescription;
const boldText = `${contentTitle}${pageTitle}`;
const fonts = (
await Promise.all([
loadGoogleFont({ fontFamily, text: regularText, weight: 400 }),
loadGoogleFont({ fontFamily, text: boldText, weight: 700 }),
])
).filter(filterOutNullable);
const theme = customization.themes.default;
const useLightTheme = theme === 'light';
// We have no access to CSS variables, so we'll have to hardcode some values
const baseColors = { light: '#ffffff', dark: '#111827' };
let colors = {
background: baseColors[theme],
gradient: customization.styling.primaryColor[theme],
title: customization.styling.primaryColor[theme],
body: baseColors[useLightTheme ? 'dark' : 'light'], // Invert text on background
};
const [gridWhite, gridBlack] = await Promise.all([
getAbsoluteHref('~gitbook/static/images/ogimage-grid-white.png', true),
getAbsoluteHref('~gitbook/static/images/ogimage-grid-black.png', true),
]);
let gridAsset = useLightTheme ? gridBlack : gridWhite;
switch (customization.header.preset) {
case CustomizationHeaderPreset.Custom:
colors = {
background: customization.header.backgroundColor?.[theme] || colors.background,
gradient: customization.header.linkColor?.[theme] || colors.gradient,
title: customization.header.linkColor?.[theme] || colors.title,
body: colorContrast(
customization.header.backgroundColor?.[theme] || colors.background,
[baseColors.light, baseColors.dark],
),
};
gridAsset = colors.body == baseColors.light ? gridWhite : gridBlack;
break;
case CustomizationHeaderPreset.Bold:
colors = {
background: customization.styling.primaryColor[theme],
gradient: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
title: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
body: colorContrast(customization.styling.primaryColor[theme], [
baseColors.light,
baseColors.dark,
]),
};
gridAsset = colors.body == baseColors.light ? gridWhite : gridBlack;
break;
}
const favicon = await (async () => {
if ('icon' in customization.favicon)
return (
<img
src={customization.favicon.icon[theme]}
width={40}
height={40}
tw="mr-4"
alt="Icon"
/>
);
if ('emoji' in customization.favicon)
return (
<span tw="text-4xl mr-4">
{String.fromCodePoint(parseInt('0x' + customization.favicon.emoji))}
</span>
);
const src = await getAbsoluteHref(
`~gitbook/icon?size=medium&theme=${customization.themes.default}`,
true,
);
return <img src={src} alt="Icon" width={40} height={40} tw="mr-4" />;
})();
return new ImageResponse(
(
<div
tw={`justify-between p-20 relative w-full h-full flex flex-col bg-[${colors.background}] text-[${colors.body}]`}
style={{
fontFamily,
}}
>
{/* Gradient */}
<div
tw="absolute inset-0"
style={{
backgroundImage: `radial-gradient(ellipse 100% 100% at top right , ${colors.gradient}, ${colors.gradient}00)`,
opacity: 0.5,
}}
></div>
{/* Grid */}
<img tw="absolute inset-0 w-[100vw] h-[100vh]" src={gridAsset} alt="Grid" />
{/* Logo */}
{customization.header.logo ? (
<img
alt="Logo"
height={60}
src={
useLightTheme
? customization.header.logo.light
: customization.header.logo.dark
}
/>
) : (
<div tw="flex">
{favicon}
<h3 tw="text-4xl my-0 font-bold">{contentTitle}</h3>
</div>
)}
{/* Title and description */}
<div tw="flex flex-col">
<h1
tw={`text-8xl my-0 tracking-tight leading-none text-left text-[${colors.title}] font-bold`}
>
{pageTitle}
</h1>
{pageDescription ? (
<h2 tw="text-4xl mb-0 mt-8 w-[75%] font-normal">{pageDescription}</h2>
) : null}
</div>
</div>
),
{
width: 1200,
height: 630,
fonts: fonts.length ? fonts : undefined,
},
);
return serveOGImage(baseContext, await params);
}
@@ -32,7 +32,7 @@ export default function ErrorPage(props: {
'flex',
'items-center',
'justify-center',
'p-7',
'p-7'
)}
>
<div>
@@ -50,7 +50,7 @@ export function PageControlButtons(props: {
'flex-col',
'gap-2',
'print:hidden',
'z-50',
'z-50'
)}
>
{singlePageMode ? null : (
@@ -84,7 +84,7 @@ export function PageControlButtons(props: {
'items-end',
'gap-2',
'print:hidden',
'z-50',
'z-50'
)}
>
{total !== pageIds.length ? (
@@ -102,7 +102,7 @@ export function PageControlButtons(props: {
'border',
'rounded-md',
'p-4',
'max-w-sm',
'max-w-sm'
)}
>
<Icon
@@ -140,7 +140,7 @@ export function PageControlButtons(props: {
'rounded-full',
'shadow-sm',
'border-slate-300',
'border',
'border'
)}
>
{t(language, 'pdf_page_of', activeIndex, pageIds.length)}
@@ -2,7 +2,7 @@
import * as React from 'react';
import { PolymorphicComponentProp } from '@/components/utils/types';
import type { PolymorphicComponentProp } from '@/components/utils/types';
export function PrintButton(props: PolymorphicComponentProp<'button'>) {
const { className, children, ...rest } = props;
@@ -1,36 +1,36 @@
import {
CustomizationSettings,
Revision,
RevisionPageDocument,
RevisionPageGroup,
type CustomizationSettings,
type Revision,
type RevisionPageDocument,
type RevisionPageGroup,
RevisionPageType,
SiteCustomizationSettings,
type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
Space,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { GitBookSpaceContext } from '@v2/lib/context';
import type { GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data';
import { GitBookSpaceLinker } from '@v2/lib/links';
import { Metadata } from 'next';
import type { GitBookSpaceLinker } from '@v2/lib/links';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import { PolymorphicComponentProp } from '@/components/utils/types';
import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate';
import { getPagePDFContainerId, getAbsoluteHref } from '@/lib/links';
import { getAbsoluteHref, getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
import { type PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
import { defaultCustomizationForSpace } from '@/lib/utils';
import './pdf.css';
import { PageControlButtons } from './PageControlButtons';
import { getV1ContextForPDF } from './pointer';
import { PrintButton } from './PrintButton';
import './pdf.css';
import { getV1ContextForPDF } from './pointer';
const DEFAULT_LIMIT = 100;
@@ -57,7 +57,7 @@ export default async function PDFHTMLOutput(props: {
// Build current PDF URL and preserve all search params
let currentPDFUrl = await getAbsoluteHref('~gitbook/pdf', true);
currentPDFUrl += '?' + searchParams.toString();
currentPDFUrl += `?${searchParams.toString()}`;
// Fetch the context
const baseContext = await getV1ContextForPDF();
@@ -69,7 +69,7 @@ export default async function PDFHTMLOutput(props: {
// Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string],
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
);
// Build a linker that create anchor links for the pages rendered in the PDF page.
@@ -77,15 +77,14 @@ export default async function PDFHTMLOutput(props: {
...baseContext.linker,
toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) {
return '#' + getPagePDFContainerId(input.page, input.anchor);
} else {
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
return `#${getPagePDFContainerId(input.page, input.anchor)}`;
}
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
},
};
@@ -100,7 +99,7 @@ export default async function PDFHTMLOutput(props: {
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a
title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? context.linker.toAbsoluteURL('')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls(
'flex',
'flex-row',
@@ -115,7 +114,7 @@ export default async function PDFHTMLOutput(props: {
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border',
'border'
)}
>
<Icon icon="arrow-left" className={tcls('size-6')} />
@@ -140,7 +139,7 @@ export default async function PDFHTMLOutput(props: {
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border',
'border'
)}
>
<Icon icon="print" className={tcls('size-6')} />
@@ -181,7 +180,7 @@ export default async function PDFHTMLOutput(props: {
>
<PDFPageDocument page={page} context={context} />
</React.Suspense>
),
)
)}
</div>
);
@@ -217,7 +216,7 @@ async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
'flex',
'items-center',
'justify-center',
'py-12',
'py-12'
)}
>
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
@@ -266,7 +265,7 @@ function PrintPage(
{
isFirst?: boolean;
}
>,
>
) {
const { children, isFirst, className, ...rest } = props;
@@ -289,7 +288,7 @@ function PrintPage(
'min-h-[29.7cm]',
'print:min-h-0',
isFirst ? null : 'break-before-page',
'break-anywhere',
'break-anywhere'
)}
>
{children}
@@ -304,11 +303,11 @@ type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: nu
*/
function selectPages(
rootPages: Revision['pages'],
params: PDFSearchParams,
params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number,
depth: number
): FlatPageEntry[] => {
return [
{ page, depth },
@@ -1,6 +1,6 @@
import { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import type { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1';
@@ -16,7 +16,7 @@ export async function getSiteOrSpacePointerForPDF(): Promise<
> {
try {
return await getSiteContentPointer();
} catch (error) {
} catch (_error) {
return getSpacePointer();
}
}
@@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server';
import { type NextRequest, NextResponse } from 'next/server';
type ProxyRequest = {
url: string;
@@ -67,11 +67,7 @@ export async function POST(req: NextRequest) {
// TODO: transform cookie data
cookies: response.headers.get('cookies'),
});
} catch (error) {
console.error(
'Scalar API Client Proxy Error',
(error as Error).stack ?? (error as Error).message ?? error,
);
} catch (_error) {
return NextResponse.json({
data: 'Scalar API Client Proxy Error',
});
@@ -10,7 +10,7 @@ import { withMiddlewareHeadersStorage } from './lib/middleware';
export default {
async fetch(request, env, ctx) {
const response = await withMiddlewareHeadersStorage(() =>
nextOnPagesHandler.fetch(request, env, ctx),
nextOnPagesHandler.fetch(request, env, ctx)
);
return response;
@@ -1,13 +1,13 @@
import { Icon } from '@gitbook/icons';
import { GitBookSiteContext } from '@v2/lib/context';
import type { GitBookSiteContext } from '@v2/lib/context';
import { headers } from 'next/headers';
import React from 'react';
import { tcls } from '@/lib/tailwind';
import { DateRelative } from '../primitives';
import { RefreshChangeRequestButton } from './RefreshChangeRequestButton';
import { Toolbar, ToolbarBody, ToolbarButton, ToolbarButtonGroups } from './Toolbar';
import { DateRelative } from '../primitives';
interface AdminToolbarProps {
context: GitBookSiteContext;
@@ -34,7 +34,7 @@ function ToolbarLayout(props: { children: React.ReactNode }) {
'p-2',
'max-w-md',
'border-tint-12/1',
'backdrop-blur-md',
'backdrop-blur-md'
)}
>
<React.Suspense fallback={null}>{props.children}</React.Suspense>
@@ -83,7 +83,7 @@ async function ChangeRequestToolbar(props: { context: GitBookSiteContext }) {
<p>
#{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
</p>
<p className="text-xs text-tint-2 dark:text-tint-11">
<p className="text-tint-2 text-xs dark:text-tint-11">
Change request updated <DateRelative value={changeRequest.updatedAt} />
</p>
</ToolbarBody>
@@ -124,7 +124,7 @@ async function RevisionToolbar(props: { context: GitBookSiteContext }) {
Revision created <DateRelative value={revision.createdAt} />
</p>
{revision.git ? (
<p className="text-xs text-tint-2 dark:text-tint-11">
<p className="text-tint-2 text-xs dark:text-tint-11">
{revision.git.message}
</p>
) : null}
@@ -1,6 +1,6 @@
'use client';
import * as React from 'react';
import type * as React from 'react';
import { tcls } from '@/lib/tailwind';
@@ -20,7 +20,7 @@ export function Toolbar(props: { children: React.ReactNode }) {
'rounded-full',
'truncate',
'text-tint-1',
'dark:text-tint-12',
'dark:text-tint-12'
)}
>
{children}
@@ -56,7 +56,7 @@ export function ToolbarButton(props: React.HTMLProps<HTMLAnchorElement>) {
'hover:bg-tint-12',
'dark:hover:bg-tint-1',
'hover:shadow-lg',
'cursor-pointer',
'cursor-pointer'
)}
>
{children}
+6 -7
View File
@@ -1,21 +1,21 @@
'use client';
import {
SiteAds,
type SiteAds,
SiteAdsStatus,
SiteInsightsAdPlacement,
SiteInsightsAd,
type SiteInsightsAd,
type SiteInsightsAdPlacement,
SiteInsightsTrademarkPlacement,
} from '@gitbook/api';
import * as React from 'react';
import { t, useLanguage } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { renderAd } from './renderAd';
import { useHasBeenInViewport } from '../hooks/useHasBeenInViewport';
import { useTrackEvent } from '../Insights';
import { useHasBeenInViewport } from '../hooks/useHasBeenInViewport';
import { Link } from '../primitives';
import { renderAd } from './renderAd';
/**
* Zone ID provided by BuySellAds for the preview.
@@ -125,7 +125,6 @@ export function Ad({
function AdSponsoredLink(props: { spaceId: string }) {
const { spaceId } = props;
const language = useLanguage();
const trackEvent = useTrackEvent();
const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content');
@@ -1,12 +1,11 @@
import { SiteInsightsAd } from '@gitbook/api';
import { GitBookBaseContext } from '@v2/lib/context';
import type { SiteInsightsAd } from '@gitbook/api';
import type { GitBookBaseContext } from '@v2/lib/context';
import { getResizedImageURL } from '@v2/lib/images';
import * as React from 'react';
import { tcls } from '@/lib/tailwind';
import { AdItem } from './types';
import { Link } from '../primitives';
import type { AdItem } from './types';
/**
* Classic rendering for an ad.
@@ -48,7 +47,7 @@ export async function AdClassicRendering({
'text-tint',
'hover:text-tint-strong',
'rounded-lg',
'p-4',
'p-4'
)}
href={ad.statlink}
>
@@ -1,13 +1,12 @@
import { SiteInsightsAd } from '@gitbook/api';
import type { SiteInsightsAd } from '@gitbook/api';
import { hexToRgba } from '@gitbook/colors';
import { GitBookBaseContext } from '@v2/lib/context';
import type { GitBookBaseContext } from '@v2/lib/context';
import { getResizedImageURL } from '@v2/lib/images';
import * as React from 'react';
import { tcls } from '@/lib/tailwind';
import { AdCover } from './types';
import { Link } from '../primitives';
import type { AdCover } from './types';
/**
* Cover rendering for an ad.
@@ -50,7 +49,7 @@ export async function AdCoverRendering({
'rounded-lg',
'p-4',
'overflow-hidden',
'shadow-sm',
'shadow-sm'
)}
style={{ backgroundColor: ad.backgroundColor, color: ad.textColor ?? '#ffffff' }}
href={ad.statlink}
@@ -62,7 +61,7 @@ export async function AdCoverRendering({
'bg-center',
'bg-cover',
'bg-no-repeat',
'z-0',
'z-0'
)}
style={{
backgroundImage: `url(${largeImage})`,
@@ -71,14 +70,14 @@ export async function AdCoverRendering({
<div className={tcls('z-[2]')}>
<img
alt="Large image"
alt="Large cover"
src={largeImage}
className={tcls(
'rounded-md',
'shadow-md',
'max-h-32',
'group-hover/ad:max-h-16',
'transition-all',
'transition-all'
)}
/>
</div>
@@ -94,7 +93,7 @@ export async function AdCoverRendering({
'opacity-0',
'group-hover/ad:h-16',
'group-hover/ad:opacity-10',
'transition-all',
'transition-all'
)}
>
{ad.description}
@@ -109,7 +108,7 @@ export async function AdCoverRendering({
'rounded-md',
'bg-white',
'py-2',
'px-4',
'px-4'
)}
style={{
backgroundColor: ad.ctaBackgroundColor,
@@ -1,5 +1,3 @@
import * as React from 'react';
import { tcls } from '@/lib/tailwind';
/**
@@ -1,6 +1,6 @@
'use server';
import { SiteInsightsAd, SiteInsightsAdPlacement } from '@gitbook/api';
import type { SiteInsightsAd, SiteInsightsAdPlacement } from '@gitbook/api';
import { headers } from 'next/headers';
import { getV1BaseContext } from '@/lib/v1';
@@ -9,7 +9,7 @@ import { AdClassicRendering } from './AdClassicRendering';
import { AdCoverRendering } from './AdCoverRendering';
import { AdPixels } from './AdPixels';
import adRainbow from './assets/ad-rainbow.svg';
import { AdItem, AdsResponse } from './types';
import type { AdItem, AdsResponse } from './types';
type FetchAdOptions = FetchLiveAdOptions | FetchPlaceholderAdOptions;
@@ -3,7 +3,7 @@
import { Icon } from '@gitbook/icons';
import * as React from 'react';
import { Button } from '@/components/primitives';
import { Button, StyledLink } from '@/components/primitives';
import { useLanguage } from '@/intl/client';
import { t, tString } from '@/intl/translate';
import { tcls } from '@/lib/tailwind';
@@ -57,25 +57,16 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
'left-16',
'max-w-md',
'text-balance',
'sm:left-auto',
'sm:left-auto'
)}
>
<p id={describedById} className={tcls('text-sm')}>
{t(
language,
'cookies_prompt',
<a
href={privacyPolicy}
className={tcls(
'text-primary-subtle',
'hover:text-primary',
'contrast-more:text-primary',
'contrast-more:hover:text-primary-strong',
'underline',
)}
>
<StyledLink href={privacyPolicy}>
{t(language, 'cookies_prompt_privacy')}
</a>,
</StyledLink>
)}
</p>
<button
@@ -92,7 +83,7 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
'justify-center',
'items-center',
'rounded-sm',
'hover:bg-tint-hover',
'hover:bg-tint-hover'
)}
title={tString(language, 'cookies_close')}
>
@@ -1,11 +1,11 @@
import { DocumentInlineAnnotation } from '@gitbook/api';
import type { DocumentInlineAnnotation } from '@gitbook/api';
import { getNodeFragmentByType } from '@/lib/document';
import { AnnotationPopover } from './AnnotationPopover';
import { Blocks } from '../Blocks';
import { InlineProps } from '../Inline';
import type { InlineProps } from '../Inline';
import { Inlines } from '../Inlines';
import { AnnotationPopover } from './AnnotationPopover';
export function Annotation(props: InlineProps<DocumentInlineAnnotation>) {
const { inline, context, document, children } = props;
@@ -1,9 +1,9 @@
'use client';
import * as Popover from '@radix-ui/react-popover';
import React from 'react';
import type React from 'react';
import { useLanguage, tString } from '@/intl/client';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
export function AnnotationPopover(props: { children: React.ReactNode; body: React.ReactNode }) {
@@ -20,7 +20,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'decoration-dotted',
'decoration-1',
'underline',
'underline-offset-2',
'underline-offset-2'
)}
>
{children}
@@ -43,7 +43,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'-outline-offset-2',
'outline-2',
'outline-primary/8',
'z-20',
'z-20'
)}
sideOffset={4}
>
@@ -56,7 +56,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
'z-[2]',
'fill-tint-3', // Same as bg-tint
'stroke-tint-7', // Same as ring-tint
'[paint-order:stroke_fill]',
'[paint-order:stroke_fill]'
)}
fill="none"
xmlns="http://www.w3.org/2000/svg"
@@ -1,19 +1,19 @@
import { DocumentBlock, JSONDocument } from '@gitbook/api';
import type { DocumentBlock, JSONDocument } from '@gitbook/api';
import React from 'react';
import {
SkeletonParagraph,
SkeletonHeading,
SkeletonCard,
SkeletonHeading,
SkeletonImage,
SkeletonParagraph,
SkeletonSmall,
} from '@/components/primitives';
import { ClassValue } from '@/lib/tailwind';
import type { ClassValue } from '@/lib/tailwind';
import { BlockContentRef } from './BlockContentRef';
import { CodeBlock } from './CodeBlock';
import { Divider } from './Divider';
import { DocumentContextProps } from './DocumentView';
import type { DocumentContextProps } from './DocumentView';
import { Drawing } from './Drawing';
import { Embed } from './Embed';
import { Expandable } from './Expandable';
@@ -47,7 +47,7 @@ export interface BlockProps<Block extends DocumentBlock> extends DocumentContext
/**
* Alternative to `assertNever` that returns `null` instead of throwing an error.
*/
function nullIfNever(value: never): null {
function nullIfNever(_value: never): null {
return null;
}
@@ -81,6 +81,7 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
case 'table':
return <Table {...props} block={block} />;
case 'swagger':
case 'openapi-operation':
return <OpenAPI {...props} block={block} />;
case 'embed':
return <Embed {...props} block={block} />;
@@ -154,6 +155,7 @@ export function BlockSkeleton(props: { block: DocumentBlock; style: ClassValue }
case 'expandable':
case 'table':
case 'swagger':
case 'openapi-operation':
case 'math':
case 'divider':
case 'content-ref':
@@ -1,9 +1,9 @@
import { DocumentBlockContentRef, SiteInsightsLinkPosition } from '@gitbook/api';
import { type DocumentBlockContentRef, SiteInsightsLinkPosition } from '@gitbook/api';
import { Card } from '@/components/primitives';
import { resolveContentRef, ResolvedContentRef } from '@/lib/references';
import { type ResolvedContentRef, resolveContentRef } from '@/lib/references';
import { BlockProps } from './Block';
import type { BlockProps } from './Block';
export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>) {
const { block, context, style } = props;
@@ -46,7 +46,7 @@ export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>
}
async function SpaceRefCard(
props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>,
props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>
) {
const { context, style, resolved } = props;
const spaceId = context.contentContext?.space.id;
@@ -1,9 +1,9 @@
import { DocumentBlock, JSONDocument } from '@gitbook/api';
import type { DocumentBlock, JSONDocument } from '@gitbook/api';
import { tcls, ClassValue } from '@/lib/tailwind';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { Block } from './Block';
import { DocumentContextProps } from './DocumentView';
import type { DocumentContextProps } from './DocumentView';
import { isBlockOffscreen } from './utils';
/**
@@ -19,7 +19,7 @@ export function Blocks<TBlock extends DocumentBlock, Tag extends React.ElementTy
/** Props to pass to the wrapper element */
wrapperProps?: React.ComponentProps<Tag>;
},
}
) {
const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props;
@@ -68,7 +68,7 @@ export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBl
key={node.key}
block={node}
style={[
'w-full mx-auto decoration-primary/6',
'mx-auto w-full decoration-primary/6',
node.data && 'fullWidth' in node.data && node.data.fullWidth
? 'max-w-screen-xl'
: 'max-w-3xl',
@@ -1,4 +1,4 @@
import {
import type {
DocumentBlockDrawing,
DocumentBlockEmbed,
DocumentBlockFile,
@@ -7,9 +7,9 @@ import {
} from '@gitbook/api';
import { getNodeFragmentByName, isNodeEmpty } from '@/lib/document';
import { ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { DocumentContextProps } from './DocumentView';
import type { DocumentContextProps } from './DocumentView';
import { Inlines } from './Inlines';
/**
@@ -24,7 +24,7 @@ export function Caption(
wrapperStyle?: ClassValue;
block: DocumentBlockImage | DocumentBlockDrawing | DocumentBlockEmbed | DocumentBlockFile;
withBorder?: boolean;
} & DocumentContextProps,
} & DocumentContextProps
) {
const {
children,
@@ -5,9 +5,9 @@ import { useEffect, useRef, useState } from 'react';
import { useHasBeenInViewport } from '@/components/hooks/useHasBeenInViewport';
import type { HighlightLine, RenderedInline } from './highlight';
import type { BlockProps } from '../Block';
import { CodeBlockRenderer } from './CodeBlockRenderer';
import type { HighlightLine, RenderedInline } from './highlight';
import { plainHighlight } from './plain-highlight';
type ClientBlockProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'style'> & {
@@ -41,9 +41,19 @@ export function ClientCodeBlock(props: ClientBlockProps) {
// We use requestIdleCallback to avoid blocking the main thread
// when scrolling.
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(() => highlight(block, inlines).then(setLines));
requestIdleCallback(() =>
highlight(block, inlines).then((result) => {
if (!canceled) {
setLines(result);
}
})
);
} else {
highlight(block, inlines).then(setLines);
highlight(block, inlines).then((result) => {
if (!canceled) {
setLines(result);
}
});
}
});
return () => {
@@ -2,10 +2,10 @@ import type { DocumentBlockCode } from '@gitbook/api';
import { getNodeFragmentByType } from '@/lib/document';
import { BlockProps } from '../Block';
import { ClientCodeBlock } from './ClientCodeBlock';
import { getInlines, RenderedInline } from './highlight';
import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { ClientCodeBlock } from './ClientCodeBlock';
import { type RenderedInline, getInlines } from './highlight';
/**
* Render a code block, can be client-side or server-side.
@@ -4,10 +4,10 @@ import { forwardRef, useId } from 'react';
import { tcls } from '@/lib/tailwind';
import { CopyCodeButton } from './CopyCodeButton';
import type { HighlightLine, HighlightToken } from './highlight';
import { AnnotationPopover } from '../Annotation/AnnotationPopover';
import type { BlockProps } from '../Block';
import { CopyCodeButton } from './CopyCodeButton';
import type { HighlightLine, HighlightToken } from './highlight';
import './theme.css';
import './CodeBlockRenderer.css';
@@ -21,7 +21,7 @@ type CodeBlockRendererProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'sty
*/
export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
props: CodeBlockRendererProps,
ref: React.ForwardedRef<HTMLDivElement>,
ref: React.ForwardedRef<HTMLDivElement>
) {
const { block, style, lines } = props;
@@ -32,29 +32,29 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
return (
<div ref={ref} className={tcls('group/codeblock grid grid-flow-col', style)}>
<div className="flex items-center justify-start [grid-area:1/1] text-sm gap-2">
<div className="flex items-center justify-start gap-2 text-sm [grid-area:1/1]">
{title ? (
<div className="text-xs tracking-wide text-tint leading-none inline-flex items-center justify-center bg-tint rounded-t straight-corners:rounded-t-s px-3 py-2">
<div className="inline-flex items-center justify-center rounded-t straight-corners:rounded-t-s bg-tint px-3 py-2 text-tint text-xs leading-none tracking-wide">
{title}
</div>
) : null}
</div>
<CopyCodeButton
codeId={id}
style="group-hover/codeblock:opacity-[1] transition-opacity duration-75 opacity-0 text-xs [grid-area:2/1] z-[2] justify-self-end backdrop-blur-md leading-none self-start ring-1 ring-tint text-tint bg-transparent rounded-md mr-2 mt-2 p-1 hover:ring-tint-hover"
style="z-[2] mt-2 mr-2 self-start justify-self-end rounded-md bg-transparent p-1 text-tint text-xs leading-none opacity-0 ring-1 ring-tint backdrop-blur-md transition-opacity duration-75 [grid-area:2/1] hover:ring-tint-hover group-hover/codeblock:opacity-[1]"
/>
<pre
className={tcls(
'[grid-area:2/1] relative overflow-auto bg-tint theme-gradient:bg-tint-12/1 ring-tint-subtle hide-scroll',
'hide-scroll relative overflow-auto bg-tint theme-gradient:bg-tint-12/1 ring-tint-subtle [grid-area:2/1]',
'rounded-md straight-corners:rounded-sm',
title && 'rounded-ss-none',
title && 'rounded-ss-none'
)}
>
<code
id={id}
className={tcls(
'min-w-full inline-grid grid-cols-[auto_1fr] p-2 [count-reset:line]',
withWrap && 'whitespace-pre-wrap',
'inline-grid min-w-full grid-cols-[auto_1fr] p-2 [count-reset:line]',
withWrap && 'whitespace-pre-wrap'
)}
>
{lines.map((line, index) => (
@@ -3,7 +3,7 @@
import React from 'react';
import { t, useLanguage } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, tcls } from '@/lib/tailwind';
/**
* Client component to copy the code of a code block.
@@ -52,7 +52,7 @@ export function CopyCodeButton(props: { codeId: string; style: ClassValue }) {
* ignoring the empty white space we use for empty lines (represented with a class "ew").
*/
function getCodeText(code: HTMLElement): string {
let text: string = '';
let text = '';
const iterate = (node: Node) => {
if (node instanceof HTMLBRElement) {
@@ -1,4 +1,4 @@
import { DocumentBlockCode, JSONDocument } from '@gitbook/api';
import type { DocumentBlockCode, JSONDocument } from '@gitbook/api';
import { useId } from 'react';
import { CodeBlock } from './CodeBlock';
@@ -1,7 +1,7 @@
import { expect, it } from 'bun:test';
import type { DocumentBlockCode } from '@gitbook/api';
import { it, expect } from 'bun:test';
import { getInlines, highlight, RenderedInline } from './highlight';
import { type RenderedInline, getInlines, highlight } from './highlight';
async function highlightWithInlines(block: DocumentBlockCode) {
const inlines: RenderedInline[] = getInlines(block).map((inline) => ({
@@ -68,9 +68,9 @@ it('should parse different code in parallel', async () => {
},
],
},
[],
),
),
[]
)
)
);
});
@@ -1,12 +1,16 @@
import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api';
import type {
DocumentBlockCode,
DocumentBlockCodeLine,
DocumentInlineAnnotation,
} from '@gitbook/api';
import {
createdBundledHighlighter,
ThemedToken,
type ThemedToken,
createCssVariablesTheme,
createSingletonShorthands,
createdBundledHighlighter,
} from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import { BundledLanguage, bundledLanguages } from 'shiki/langs';
import { type BundledLanguage, bundledLanguages } from 'shiki/langs';
import { plainHighlight } from './plain-highlight';
@@ -39,7 +43,7 @@ const highlighter = createSingletonShorthands(
createJavaScriptRegexEngine({
forgiving: true,
}),
}),
})
);
/**
@@ -60,7 +64,7 @@ export async function preloadHighlight(block: DocumentBlockCode) {
*/
export async function highlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
inlines: RenderedInline[]
): Promise<HighlightLine[]> {
const langName = getBlockLang(block);
if (!langName) {
@@ -159,7 +163,7 @@ export function getInlines(block: DocumentBlockCode) {
function matchTokenAndInlines(
eat: () => PositionedToken | null,
allInlines: RenderedInline[],
allInlines: RenderedInline[]
): HighlightToken[] {
const initialToken = eat();
if (!initialToken) {
@@ -167,7 +171,7 @@ function matchTokenAndInlines(
}
const inlines = allInlines.filter(
({ inline }) => inline.start >= initialToken.start && inline.start < initialToken.end,
({ inline }) => inline.start >= initialToken.start && inline.start < initialToken.end
);
let token = initialToken;
const result: HighlightToken[] = [];
@@ -191,7 +195,7 @@ function matchTokenAndInlines(
});
}
if (!afterBefore) {
throw new Error(`expect afterBefore to not be empty`);
throw new Error('expect afterBefore to not be empty');
}
token = afterBefore;
@@ -206,14 +210,14 @@ function matchTokenAndInlines(
const next = eat();
if (!next) {
throw new Error(`expect token to not be empty`);
throw new Error('expect token to not be empty');
}
token = next;
}
const [inside, after] = splitPositionedTokenAt(token, inline.inline.end);
if (!inside) {
throw new Error(`expect inside to not be empty`);
throw new Error('expect inside to not be empty');
}
children.push({
@@ -255,7 +259,7 @@ function getPlainCodeBlock(code: DocumentBlockCode, inlines?: InlineIndexed[]):
function getPlainCodeBlockLine(
parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
index: number,
inlines?: InlineIndexed[],
inlines?: InlineIndexed[]
): string {
let content = '';
@@ -283,7 +287,7 @@ function getPlainCodeBlockLine(
function slicePositionedToken(
token: PositionedToken,
relativeStart: number,
relativeLength: number,
relativeLength: number
): PositionedToken {
return {
...token,
@@ -295,7 +299,7 @@ function slicePositionedToken(
function splitPositionedTokenAt(
token: PositionedToken,
absoluteIndex: number,
absoluteIndex: number
): [PositionedToken | null, PositionedToken | null] {
if (absoluteIndex < token.start || absoluteIndex > token.end) {
throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
@@ -305,7 +309,7 @@ function splitPositionedTokenAt(
const after = slicePositionedToken(
token,
absoluteIndex - token.start,
token.end - absoluteIndex,
token.end - absoluteIndex
);
return [
@@ -1,4 +1,4 @@
import { DocumentBlockCode } from '@gitbook/api';
import type { DocumentBlockCode } from '@gitbook/api';
import { getNodeText } from '@/lib/document';
@@ -9,7 +9,7 @@ import type { HighlightLine, HighlightToken, RenderedInline } from './highlight'
*/
export function plainHighlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
inlines: RenderedInline[]
): HighlightLine[] {
const inlinesCopy = Array.from(inlines);
return block.nodes.map((lineBlock) => {

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