Compare commits

..

14 Commits

Author SHA1 Message Date
Samy Pessé a92cb49445 Version Packages (#2958)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-03-11 09:38:39 +00:00
Greg Bergé 88f64b0d63 Support Node.js v20 with @gitbook/icons (#2960) 2025-03-11 09:27:26 +00:00
Nolann B. 844059f9a5 Fix spacing in OpenAPISecurities (#2954) 2025-03-11 09:37:34 +01:00
Nolann B. eaf2d68308 OpenAPI operation title fallback in sections (#2955) 2025-03-11 09:37:00 +01:00
Nolann B. 12bdbf988d Fix react-openapi tests (#2956) 2025-03-11 09:20:24 +01:00
Samy Pessé 29bab79005 v2: PDF export for sites and spaces (#2949) 2025-03-10 00:08:33 +01:00
Samy Pessé 8d5de97ddf v2: fix fallback and VA redirects (#2948) 2025-03-08 11:21:49 +01:00
Samy Pessé d9b5a898ab Version Packages (#2947)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-03-08 00:29:16 +01:00
Nolann B. f127d28675 Rename OpenAPIModels to OpenAPISchemas (#2946) 2025-03-07 22:28:37 +01:00
Samy Pessé 65c1bdc455 Version Packages (#2945)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-03-07 19:37:41 +01:00
Samy Pessé 0711a171d4 Fix deployment of 2c to production 2025-03-07 18:26:51 +01:00
Samy Pessé c58c551f9e Simplify envs management for deployments (#2943) 2025-03-07 18:17:44 +01:00
Greg Bergé f574858b9b Fix OpenAPI example (#2944) 2025-03-07 17:54:35 +01:00
Samy Pessé 3e1592e16b Fix configuration for v2 staging (#2940) 2025-03-07 14:46:45 +01:00
88 changed files with 1669 additions and 1102 deletions
+24 -47
View File
@@ -1,6 +1,12 @@
name: 'Deploy cloudflare'
description: 'Deploy GitBook to Cloudflare'
inputs:
opItem:
description: '1Password item to load secrets from'
required: true
opServiceAccount:
description: '1Password service account token'
required: true
apiToken:
description: 'Cloudflare API token'
required: true
@@ -8,44 +14,11 @@ inputs:
description: 'Cloudflare account ID'
required: true
environment:
description: 'Environment to deploy to'
description: 'Cloudflare environment to deploy to (staging, production, preview)'
required: true
deploy:
description: 'Deploy as main version for all traffic instead of uploading versions'
required: true
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY:
description: 'Next server actions encryption key'
required: true
GITBOOK_URL:
description: 'GitBook URL'
required: true
GITBOOK_SECRET:
description: 'GitBook secret'
required: true
GITBOOK_APP_URL:
description: 'GitBook app URL'
required: false
GITBOOK_API_URL:
description: 'GitBook API URL'
required: false
GITBOOK_INTEGRATIONS_HOST:
description: 'GitBook integrations host'
required: false
GITBOOK_IMAGE_RESIZE_SIGNING_KEY:
description: 'GitBook image resize signing key'
required: true
GITBOOK_IMAGE_RESIZE_URL:
description: 'GitBook image resize URL'
required: true
GITBOOK_ICONS_URL:
description: 'GitBook icons URL'
required: true
GITBOOK_ICONS_TOKEN:
description: 'GitBook icons token'
required: true
GITBOOK_ASSETS_PREFIX:
description: 'GitBook assets prefix'
required: false
outputs:
deployment-url:
description: "Deployment URL"
@@ -60,21 +33,25 @@ runs:
shell: bash
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Load secret
uses: 1password/load-secrets-action@v2
env:
OP_SERVICE_ACCOUNT_TOKEN: ${{ inputs.opServiceAccount }}
GITBOOK_URL: ${{ inputs.opItem }}/GITBOOK_URL
GITBOOK_ICONS_URL: ${{ inputs.opItem }}/GITBOOK_ICONS_URL
GITBOOK_ICONS_TOKEN: ${{ inputs.opItem }}/GITBOOK_ICONS_TOKEN
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ inputs.opItem }}/NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
GITBOOK_SECRET: ${{ inputs.opItem }}/GITBOOK_SECRET
GITBOOK_APP_URL: ${{ inputs.opItem }}/GITBOOK_APP_URL
GITBOOK_API_URL: ${{ inputs.opItem }}/GITBOOK_API_URL
GITBOOK_API_TOKEN: ${{ inputs.opItem }}/GITBOOK_API_TOKEN
GITBOOK_INTEGRATIONS_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_HOST
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY
GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
- name: Build worker
run: bun run turbo build:v2:cloudflare
shell: bash
env:
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ inputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
GITBOOK_URL: ${{ inputs.GITBOOK_URL }}
GITBOOK_SECRET: ${{ inputs.GITBOOK_SECRET }}
GITBOOK_APP_URL: ${{ inputs.GITBOOK_APP_URL }}
GITBOOK_API_URL: ${{ inputs.GITBOOK_API_URL }}
GITBOOK_INTEGRATIONS_HOST: ${{ inputs.GITBOOK_INTEGRATIONS_HOST }}
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.GITBOOK_IMAGE_RESIZE_SIGNING_KEY }}
GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.GITBOOK_IMAGE_RESIZE_URL }}
GITBOOK_ICONS_URL: ${{ inputs.GITBOOK_ICONS_URL }}
GITBOOK_ICONS_TOKEN: ${{ inputs.GITBOOK_ICONS_TOKEN }}
GITBOOK_ASSETS_PREFIX: ${{ inputs.GITBOOK_ASSETS_PREFIX }}
- id: deploy
name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3.14.0
@@ -84,7 +61,7 @@ runs:
workingDirectory: ./
wranglerVersion: '3.112.0'
environment: ${{ inputs.environment }}
command: ${{ inputs.deploy && 'deploy' || 'versions upload' }} --config ./packages/gitbook-v2/wrangler.toml
command: ${{ fromJSON(inputs.deploy) == true && 'deploy' || 'versions upload' }} --config ./packages/gitbook-v2/wrangler.toml
- name: Outputs
shell: bash
env:
+33 -16
View File
@@ -1,15 +1,21 @@
name: 'Deploy vercel'
description: 'Deploy GitBook to Vercel'
inputs:
vercel-org:
vercelOrg:
description: 'Vercel organization'
required: true
vercel-project:
vercelProject:
description: 'Vercel project'
required: true
vercel-token:
vercelToken:
description: 'Vercel token'
required: true
opItem:
description: '1Password item to load secrets from'
required: true
opServiceAccount:
description: '1Password service account token'
required: true
environment:
description: 'Environment to deploy to'
required: true
@@ -27,31 +33,42 @@ runs:
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 }}
run: bun run vercel pull --yes --environment=${{ inputs.environment }} --token=${{ inputs.vercelToken }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercelProject }}
- name: Load secret
uses: 1password/load-secrets-action@v2
env:
OP_SERVICE_ACCOUNT_TOKEN: ${{ inputs.opServiceAccount }}
GITBOOK_URL: ${{ inputs.opItem }}/GITBOOK_URL
GITBOOK_ICONS_URL: ${{ inputs.opItem }}/GITBOOK_ICONS_URL
GITBOOK_ICONS_TOKEN: ${{ inputs.opItem }}/GITBOOK_ICONS_TOKEN
GITBOOK_SECRET: ${{ inputs.opItem }}/GITBOOK_SECRET
GITBOOK_APP_URL: ${{ inputs.opItem }}/GITBOOK_APP_URL
GITBOOK_API_URL: ${{ inputs.opItem }}/GITBOOK_API_URL
GITBOOK_API_TOKEN: ${{ inputs.opItem }}/GITBOOK_API_TOKEN
GITBOOK_INTEGRATIONS_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_HOST
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SIGNING_KEY
GITBOOK_IMAGE_RESIZE_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
- name: Build Project Artifacts
run: bun run vercel build --target=$VERCEL_ENVIRONMENT --token=${{ inputs.vercel-token }}
run: bun run vercel build --target=${{ inputs.environment }} --token=${{ inputs.vercelToken }}
shell: bash
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercelProject }}
- 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 }})
DEPLOYMENT_URL=$(bun run vercel deploy --prebuilt --target=${{ inputs.environment }} --token=${{ inputs.vercelToken }})
echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT"
env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }}
VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercelProject }}
- name: Outputs
shell: bash
run: |
+26 -32
View File
@@ -10,6 +10,9 @@ jobs:
deploy-v1-cloudflare:
name: Deploy v1 to Cloudflare Pages
runs-on: ubuntu-latest
environment:
name: ${{ github.ref == 'refs/heads/main' && '1c-production' || '1c-preview' }}
url: ${{ steps.deploy.outputs.deployment-url }}
permissions:
contents: read
deployments: write
@@ -63,56 +66,45 @@ jobs:
deploy-v2-vercel:
name: Deploy v2 to Vercel (preview)
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
issues: write
pull-requests: write
checks: write
statuses: write
environment:
name: 2v-preview
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
- name: Deploy to Vercel
id: deploy
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 }}
environment: preview
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-preview
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (preview)
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
issues: write
pull-requests: write
checks: write
statuses: write
environment:
name: 2c-preview
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
- name: Deploy to Cloudflare
id: deploy
uses: ./.github/composite/deploy-cloudflare
with:
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
environment: preview
deploy: ${{ github.ref == 'refs/heads/main' }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
GITBOOK_URL: ${{ github.ref == 'refs/heads/main' && vars.PRODUCTION_2C_GITBOOK_URL || vars.PREVIEW_2C_GITBOOK_URL }}
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ secrets.PREVIEW_GITBOOK_IMAGE_RESIZE_SIGNING_KEY }}
GITBOOK_IMAGE_RESIZE_URL: ${{ vars.GITBOOK_IMAGE_RESIZE_URL }}
GITBOOK_ICONS_URL: ${{ vars.GITBOOK_ICONS_URL }}
GITBOOK_ICONS_TOKEN: ${{ vars.GITBOOK_ICONS_TOKEN }}
GITBOOK_SECRET: ${{ github.ref == 'refs/heads/main' && secrets.PRODUCTION_GITBOOK_SECRET|| '' }}
opItem: op://gitbook-open/2c-preview
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
@@ -198,7 +190,8 @@ jobs:
- name: Run Playwright tests
run: bun e2e
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'v2-vercel'
visual-testing-customers-v1:
@@ -238,7 +231,8 @@ jobs:
- name: Run Playwright tests
run: bun e2e-customers
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers-v2'
pagespeed-testing-v1:
@@ -255,7 +249,7 @@ jobs:
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Run pagespeed tests
run: bun ./packages/gitbook/tests/pagespeed-testing.ts $DEPLOYMENT_URL
run: bun ./packages/gitbook/tests/pagespeed-testing.ts
env:
DEPLOYMENT_URL: ${{needs.deploy-v1-cloudflare.outputs.deployment-url}}
BASE_URL: ${{needs.deploy-v1-cloudflare.outputs.deployment-url}}
PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
+16 -12
View File
@@ -9,6 +9,9 @@ jobs:
deploy-v2-vercel:
name: Deploy v2 to Vercel (production)
runs-on: ubuntu-latest
environment:
name: 2v-production
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
@@ -18,13 +21,18 @@ jobs:
id: deploy
uses: ./.github/composite/deploy-vercel
with:
environment: production
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
environment: production
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-production
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (production)
runs-on: ubuntu-latest
environment:
name: 2c-production
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
@@ -34,16 +42,12 @@ jobs:
id: deploy
uses: ./.github/composite/deploy-cloudflare
with:
environment: staging
environment: production
deploy: true
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
GITBOOK_URL: ${{ vars.STAGING_2C_GITBOOK_URL }}
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ secrets.STAGING_GITBOOK_IMAGE_RESIZE_SIGNING_KEY }}
GITBOOK_IMAGE_RESIZE_URL: ${{ vars.GITBOOK_IMAGE_RESIZE_URL }}
GITBOOK_ICONS_URL: ${{ vars.GITBOOK_ICONS_URL }}
GITBOOK_ICONS_TOKEN: ${{ vars.GITBOOK_ICONS_TOKEN }}
GITBOOK_ASSETS_PREFIX: ${{ vars.STAGING_2C_GITBOOK_ASSETS_PREFIX }}
opItem: op://gitbook-open/2c-production
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+14 -15
View File
@@ -9,6 +9,9 @@ jobs:
deploy-v2-vercel:
name: Deploy v2 to Vercel (staging)
runs-on: ubuntu-latest
environment:
name: 2v-staging
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
@@ -18,13 +21,18 @@ jobs:
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 }}
environment: staging
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-staging
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (staging)
runs-on: ubuntu-latest
environment:
name: 2c-staging
url: ${{ steps.deploy.outputs.deployment-url }}
outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps:
@@ -38,17 +46,8 @@ jobs:
deploy: true
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
GITBOOK_URL: ${{ vars.STAGING_2C_GITBOOK_URL }}
GITBOOK_SECRET: ${{ secrets.STAGING_GITBOOK_SECRET }}
GITBOOK_APP_URL: https://app.gitbook-staging.com
GITBOOK_API_URL: https://api.gitbook-staging.com
GITBOOK_INTEGRATIONS_HOST: https://integrations.gitbook-staging.com
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: ${{ secrets.STAGING_GITBOOK_IMAGE_RESIZE_SIGNING_KEY }}
GITBOOK_IMAGE_RESIZE_URL: ${{ vars.GITBOOK_IMAGE_RESIZE_URL }}
GITBOOK_ICONS_URL: ${{ vars.GITBOOK_ICONS_URL }}
GITBOOK_ICONS_TOKEN: ${{ vars.GITBOOK_ICONS_TOKEN }}
GITBOOK_ASSETS_PREFIX: ${{ vars.STAGING_2C_GITBOOK_ASSETS_PREFIX }}
opItem: op://gitbook-open/2c-staging
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+6 -7
View File
@@ -49,7 +49,7 @@
},
"packages/gitbook": {
"name": "gitbook",
"version": "0.6.5",
"version": "0.7.2",
"dependencies": {
"@gitbook/api": "0.96.1",
"@gitbook/cache-do": "workspace:*",
@@ -132,7 +132,7 @@
},
"packages/gitbook-v2": {
"name": "gitbook-v2",
"version": "0.1.2",
"version": "0.2.0",
"dependencies": {
"@gitbook/api": "0.96.1",
"@gitbook/cache-tags": "workspace:*",
@@ -144,7 +144,7 @@
"warn-once": "^0.1.1",
},
"devDependencies": {
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d",
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d",
"gitbook": "*",
"postcss": "^8",
"tailwindcss": "^3.4.0",
@@ -172,7 +172,7 @@
},
"packages/openapi-parser": {
"name": "@gitbook/openapi-parser",
"version": "2.0.2",
"version": "2.1.0",
"dependencies": {
"@scalar/openapi-parser": "^0.10.9",
"@scalar/openapi-types": "^0.1.9",
@@ -198,7 +198,6 @@
"dependencies": {
"@gitbook/api": "0.96.1",
"@gitbook/icons": "workspace:*",
"assert-never": "^1.2.1",
"classnames": "^2.5.1",
},
"devDependencies": {
@@ -227,7 +226,7 @@
},
"packages/react-openapi": {
"name": "@gitbook/react-openapi",
"version": "1.0.5",
"version": "1.1.2",
"dependencies": {
"@gitbook/openapi-parser": "workspace:*",
"@scalar/api-client-react": "^1.1.36",
@@ -793,7 +792,7 @@
"@opennextjs/aws": ["@opennextjs/aws@https://pkg.pr.new/@opennextjs/aws@756", { "dependencies": { "@aws-sdk/client-cloudfront": "3.398.0", "@aws-sdk/client-dynamodb": "^3.398.0", "@aws-sdk/client-lambda": "^3.398.0", "@aws-sdk/client-s3": "^3.398.0", "@aws-sdk/client-sqs": "^3.398.0", "@node-minify/core": "^8.0.6", "@node-minify/terser": "^8.0.6", "@tsconfig/node18": "^1.0.1", "aws4fetch": "^1.0.18", "chalk": "^5.3.0", "esbuild": "0.19.2", "express": "5.0.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.0.0" }, "bin": { "open-next": "./dist/index.js" } }],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d", { "dependencies": { "@ast-grep/napi": "^0.34.1", "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "https://pkg.pr.new/@opennextjs/aws@756", "enquirer": "^2.4.1", "glob": "^11.0.0", "yaml": "^2.7.0" }, "peerDependencies": { "wrangler": "^3.111.0" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d", { "dependencies": { "@ast-grep/napi": "^0.34.1", "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "https://pkg.pr.new/@opennextjs/aws@756", "enquirer": "^2.4.1", "glob": "^11.0.0", "yaml": "^2.7.0" }, "peerDependencies": { "wrangler": "^3.111.0" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }],
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+9 -4
View File
@@ -10,16 +10,21 @@ const nextConfig = {
env: {
BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7),
GITBOOK_URL: process.env.GITBOOK_URL,
GITBOOK_SECRET: process.env.GITBOOK_SECRET,
// GitBook envs
GITBOOK_API_URL: process.env.GITBOOK_API_URL,
GITBOOK_APP_URL: process.env.GITBOOK_APP_URL,
GITBOOK_INTEGRATIONS_HOST: process.env.GITBOOK_INTEGRATIONS_HOST,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_IMAGE_RESIZE_URL: process.env.GITBOOK_IMAGE_RESIZE_URL,
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
GITBOOK_URL: process.env.GITBOOK_URL,
GITBOOK_API_TOKEN: process.env.GITBOOK_API_TOKEN,
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
GITBOOK_SECRET: process.env.GITBOOK_SECRET,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
// Next.js envs
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
// Used to detect if the app is running in V2 mode
+1 -1
View File
@@ -14,7 +14,7 @@
},
"devDependencies": {
"gitbook": "*",
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@40fec7d",
"@opennextjs/cloudflare": "https://pkg.pr.new/opennextjs/opennextjs-cloudflare/@opennextjs/cloudflare@236c84d",
"tailwindcss": "^3.4.0",
"postcss": "^8"
},
@@ -16,7 +16,7 @@ export default async function Page(props: PageProps) {
const context = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />;
return <SitePage context={context} pageParams={{ pathname }} />;
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
@@ -25,14 +25,12 @@ export async function generateViewport(props: PageProps): Promise<Viewport> {
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const [params, searchParams] = await Promise.all([props.params, props.searchParams]);
const params = await props.params;
const context = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({
context,
pageParams: { pathname },
redirectOnFallback: true,
fallback: !!searchParams.fallback,
});
}
@@ -0,0 +1,12 @@
import { PDFRootLayout } from '@/components/PDF';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export default async function RootLayout(props: {
params: Promise<RouteLayoutParams>;
children: React.ReactNode;
}) {
const { params, children } = props;
const context = await getDynamicSiteContext(await params);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
}
@@ -0,0 +1,20 @@
import { PDFPage, generatePDFMetadata } from '@/components/PDF';
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
export async function generateMetadata({
params,
}: {
params: Promise<RouteLayoutParams>;
}) {
const context = await getDynamicSiteContext(await params);
return generatePDFMetadata(context);
}
export default async function Page(props: {
params: Promise<RouteLayoutParams>;
searchParams: Promise<{ [key: string]: string }>;
}) {
const { params, searchParams } = props;
const context = await getDynamicSiteContext(await params);
return <PDFPage context={context} searchParams={await searchParams} />;
}
@@ -28,7 +28,7 @@ export default async function Page(props: PageProps) {
})
);
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />;
return <SitePage context={context} pageParams={{ pathname }} />;
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
@@ -44,6 +44,5 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
return generateSitePageMetadata({
context,
pageParams: { pathname },
redirectOnFallback: true,
});
}
+10
View File
@@ -1,11 +1,15 @@
import { type NextRequest, NextResponse } from 'next/server';
import {
GITBOOK_API_TOKEN,
GITBOOK_API_URL,
GITBOOK_APP_URL,
GITBOOK_ASSETS_URL,
GITBOOK_DISABLE_TRACKING,
GITBOOK_ICONS_URL,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_INTEGRATIONS_HOST,
GITBOOK_SECRET,
GITBOOK_URL,
GITBOOK_USER_AGENT,
} from '@v2/lib/env';
@@ -19,8 +23,14 @@ export async function GET(_req: NextRequest) {
GITBOOK_APP_URL,
GITBOOK_API_URL,
GITBOOK_ASSETS_URL,
GITBOOK_ICONS_URL,
GITBOOK_USER_AGENT,
GITBOOK_INTEGRATIONS_HOST,
GITBOOK_DISABLE_TRACKING,
// Secret envs
GITBOOK_SECRET: !!GITBOOK_SECRET,
GITBOOK_API_TOKEN: !!GITBOOK_API_TOKEN,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: !!GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
});
}
@@ -0,0 +1,59 @@
import {
type GitBookBaseContext,
type GitBookSpaceContext,
fetchSpaceContextByIds,
} from '@v2/lib/context';
import { createDataFetcher } from '@v2/lib/data';
import { GITBOOK_API_URL } from '@v2/lib/env';
import { createLinker } from '@v2/lib/links';
import { getAPITokenFromMiddleware } from '@v2/lib/middleware';
export type SpacePDFRouteParams = {
spaceId: string;
changeRequestId?: string;
revisionId?: string;
};
export async function getSpacePDFContext(
params: SpacePDFRouteParams
): Promise<GitBookSpaceContext> {
const { spaceId } = params;
const apiToken = await getAPITokenFromMiddleware();
const linker = createLinker({
pathname: getPDFRoutePath(params),
});
const dataFetcher = createDataFetcher({
apiToken: apiToken,
apiEndpoint: GITBOOK_API_URL,
});
const baseContext: GitBookBaseContext = {
linker,
dataFetcher,
};
return await fetchSpaceContextByIds(baseContext, {
space: spaceId,
shareKey: undefined,
changeRequest: params.changeRequestId,
revision: params.revisionId,
});
}
function getPDFRoutePath(params: SpacePDFRouteParams) {
let path = `/~space/${params.spaceId}`;
if (params.changeRequestId) {
path += `/~/changes/${params.changeRequestId}`;
}
if (params.revisionId) {
path += `/~/revisions/${params.revisionId}`;
}
path += '~gitbook/pdf';
return path;
}
@@ -0,0 +1,2 @@
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
export default RootLayout;
@@ -0,0 +1,4 @@
import PDFPage, { generateMetadata } from '@v2/app/~space/[spaceId]/~gitbook/pdf/page';
export default PDFPage;
export { generateMetadata };
@@ -0,0 +1,2 @@
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
export default RootLayout;
@@ -0,0 +1,4 @@
import PDFPage, { generateMetadata } from '@v2/app/~space/[spaceId]/~gitbook/pdf/page';
export default PDFPage;
export { generateMetadata };
@@ -0,0 +1,12 @@
import { PDFRootLayout } from '@/components/PDF';
import { type SpacePDFRouteParams, getSpacePDFContext } from '@v2/app/~space/[spaceId]/pdf';
export default async function RootLayout(props: {
params: Promise<SpacePDFRouteParams>;
children: React.ReactNode;
}) {
const { params, children } = props;
const context = await getSpacePDFContext(await params);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
}
@@ -0,0 +1,20 @@
import { PDFPage, generatePDFMetadata } from '@/components/PDF';
import { type SpacePDFRouteParams, getSpacePDFContext } from '@v2/app/~space/[spaceId]/pdf';
export async function generateMetadata({
params,
}: {
params: Promise<SpacePDFRouteParams>;
}) {
const context = await getSpacePDFContext(await params);
return generatePDFMetadata(context);
}
export default async function Page(props: {
params: Promise<SpacePDFRouteParams>;
searchParams: Promise<{ [key: string]: string }>;
}) {
const { params, searchParams } = props;
const context = await getSpacePDFContext(await params);
return <PDFPage context={context} searchParams={await searchParams} />;
}
+37 -20
View File
@@ -116,27 +116,11 @@ export function getBaseContext(input: {
apiToken: input.apiToken ?? GITBOOK_API_TOKEN,
apiEndpoint: GITBOOK_API_URL,
});
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
const linker =
urlMode === 'url-host'
? createLinker({
host: url.host,
pathname: url.pathname,
})
: createLinker({
protocol: gitbookURL?.protocol,
host: gitbookURL?.host,
pathname: `/url/${url.host}${url.pathname}`,
});
if (urlMode === 'url') {
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}`;
};
}
const linker = getLinkerForSiteURL({
siteURL: url,
urlMode,
});
const imageResizer = createImageResizer({
host: url.host,
@@ -152,6 +136,39 @@ export function getBaseContext(input: {
};
}
/**
* Get the linker for a given site URL.
*/
export function getLinkerForSiteURL(input: {
siteURL: URL;
urlMode: 'url' | 'url-host';
}) {
const { siteURL, urlMode } = input;
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
const linker =
urlMode === 'url-host'
? createLinker({
host: siteURL.host,
pathname: siteURL.pathname,
})
: createLinker({
protocol: gitbookURL?.protocol,
host: gitbookURL?.host,
pathname: `/url/${siteURL.host}${siteURL.pathname}`,
});
if (urlMode === 'url') {
// Create link in the same format for links to other sites/sections.
linker.toLinkForContent = (rawURL: string) => {
const urlObject = new URL(rawURL);
return `/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`;
};
}
return linker;
}
/**
* Fetch the context of a site for a given URL and a base context.
*/
+4 -1
View File
@@ -93,7 +93,10 @@ export async function wrapDataFetcherError<T>(
}
}
function getExposableError(error: Error): DataFetcherErrorData {
/**
* Get a data fetcher exposable error from a JS error.
*/
export function getExposableError(error: Error): DataFetcherErrorData {
if (error instanceof GitBookAPIError) {
return {
code: error.code,
@@ -3,3 +3,4 @@ export * from './types';
export * from './pages';
export * from './urls';
export * from './errors';
export * from './lookup';
+135
View File
@@ -0,0 +1,135 @@
import { race, tryCatch } from '@/lib/async';
import { joinPath } from '@/lib/paths';
import { GitBookAPI, type PublishedSiteContentLookup } from '@gitbook/api';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env';
import { getExposableError } from './errors';
import type { DataFetcherResponse } from './types';
import { getURLLookupAlternatives, stripURLSearch } from './urls';
/**
* Lookup a content by its URL using the GitBook API.
* To optimize caching, we try multiple lookup alternatives and return the first one that matches.
*/
export async function getPublishedContentByURL(input: {
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
}): Promise<DataFetcherResponse<PublishedSiteContentLookup>> {
const lookupURL = new URL(input.url);
const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url);
const result = await race(lookup.urls, async (alternative, { signal }) => {
const api = new GitBookAPI({
authToken: GITBOOK_API_TOKEN ?? undefined,
endpoint: GITBOOK_API_URL,
userAgent: GITBOOK_USER_AGENT,
});
const startTime = performance.now();
const callResult = await tryCatch(
api.urls.getPublishedContentByUrl(
{
url: alternative.url,
visitorAuthToken: input.visitorAuthToken ?? undefined,
redirectOnError: input.redirectOnError,
cache: true,
},
{
signal,
headers: {
'x-gitbook-force-cache': 'true',
},
}
)
);
const endTime = performance.now();
// biome-ignore lint/suspicious/noConsole: we want to log performance data
console.log(
`getPublishedContentByURL(${alternative.url}) Time taken: ${endTime - startTime}ms`
);
if (callResult.error) {
if (alternative.primary) {
// We only return an error for the primary alternative (full URL),
// as other parts could result in errors due to the URL being incomplete (share links, etc).
return { error: callResult.error };
}
return null;
}
const {
data: { data },
} = callResult;
if ('redirect' in data) {
if (alternative.primary) {
// Append the path to the redirect URL
// because we might have matched a shorter path and the redirect is relative to it
if (alternative.extraPath) {
if (data.target === 'content') {
const redirect = new URL(data.redirect);
redirect.pathname = joinPath(redirect.pathname, alternative.extraPath);
data.redirect = redirect.toString();
} else {
const redirect = new URL(data.redirect);
if (redirect.searchParams.has('location')) {
redirect.searchParams.set(
'location',
joinPath(
redirect.searchParams.get('location') ?? '',
alternative.extraPath
)
);
data.redirect = redirect.toString();
}
}
}
return { data };
}
return null;
}
/**
* We use the following criteria to determine if the lookup result is the right one:
* - the primary alternative was resolved (because that's the longest or most inclusive path)
* - the resolution of the site URL is complete (because we want to resolve the deepest path possible)
*
* In both cases, the idea is to use the deepest/longest/most inclusive path to resolve the content.
*/
if (alternative.primary || ('site' in data && data.complete)) {
const siteResult: PublishedSiteContentLookup = {
...data,
changeRequest: data.changeRequest ?? lookup.changeRequest,
revision: data.revision ?? lookup.revision,
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
pathname: joinPath(data.pathname, alternative.extraPath),
};
return { data: siteResult };
}
return null;
});
if (!result) {
return {
error: {
code: 404,
message: 'No content found',
},
};
}
if (result.error) {
return {
error: getExposableError(result.error),
};
}
return {
data: result.data,
};
}
-118
View File
@@ -1,121 +1,3 @@
import { race, tryCatch } from '@/lib/async';
import { joinPath } from '@/lib/paths';
import { GitBookAPI, type GitBookAPIError, type PublishedSiteContentLookup } from '@gitbook/api';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@v2/lib/env';
/**
* Lookup a content by its URL using the GitBook API.
* To optimize caching, we try multiple lookup alternatives and return the first one that matches.
*/
export async function getPublishedContentByURL(input: {
url: string;
visitorAuthToken: string | null;
redirectOnError: boolean;
}): Promise<
| { data: PublishedSiteContentLookup; error?: undefined }
| { data?: undefined; error: Error | GitBookAPIError }
> {
const lookupURL = new URL(input.url);
const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url);
const result = await race(lookup.urls, async (alternative, { signal }) => {
const api = new GitBookAPI({
authToken: GITBOOK_API_TOKEN ?? undefined,
endpoint: GITBOOK_API_URL,
userAgent: GITBOOK_USER_AGENT,
});
const callResult = await tryCatch(
api.urls.getPublishedContentByUrl(
{
url: alternative.url,
visitorAuthToken: input.visitorAuthToken ?? undefined,
redirectOnError: input.redirectOnError,
cache: true,
},
{
signal,
headers: {
'x-gitbook-force-cache': 'true',
},
}
)
);
if (callResult.error) {
if (alternative.primary) {
// We only return an error for the primary alternative (full URL),
// as other parts could result in errors due to the URL being incomplete (share links, etc).
return { error: callResult.error };
}
return null;
}
const {
data: { data },
} = callResult;
if ('redirect' in data) {
if (alternative.primary) {
// Append the path to the redirect URL
// because we might have matched a shorter path and the redirect is relative to it
if (alternative.extraPath) {
if (data.target === 'content') {
const redirect = new URL(data.redirect);
redirect.pathname = joinPath(redirect.pathname, alternative.extraPath);
data.redirect = redirect.toString();
} else {
const redirect = new URL(data.redirect);
if (redirect.searchParams.has('location')) {
redirect.searchParams.set(
'location',
joinPath(
redirect.searchParams.get('location') ?? '',
alternative.extraPath
)
);
data.redirect = redirect.toString();
}
}
}
return { data };
}
return null;
}
/**
* We use the following criteria to determine if the lookup result is the right one:
* - the primary alternative was resolved (because that's the longest or most inclusive path)
* - the resolution of the site URL is complete (because we want to resolve the deepest path possible)
*
* In both cases, the idea is to use the deepest/longest/most inclusive path to resolve the content.
*/
if (alternative.primary || ('site' in data && data.complete)) {
const siteResult: PublishedSiteContentLookup = {
...data,
changeRequest: data.changeRequest ?? lookup.changeRequest,
revision: data.revision ?? lookup.revision,
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
pathname: joinPath(data.pathname, alternative.extraPath),
};
return { data: siteResult };
}
return null;
});
if (!result) {
return {
error: new Error('No content found'),
};
}
return result;
}
/**
* For a given GitBook URL, return a list of alternative URLs that could be matched against to lookup the content.
* The approach is optimized to aim at reusing cached lookup results as much as possible.
+22 -3
View File
@@ -1,3 +1,11 @@
import 'server-only';
/*
* Support both Cloudflare and Vercel, environment variables can be bundled.
* To avoid leaking them on the client-side, they should be accessed from this file
* and not from the `process.env` object.
*/
/**
* Main host on which GitBook is running.
*/
@@ -14,12 +22,12 @@ export const GITBOOK_URL =
export const GITBOOK_ASSETS_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: process.env.GITBOOK_ASSETS_PREFIX || GITBOOK_URL;
: process.env.GITBOOK_ASSETS_PREFIX;
/**
* 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.GITBOOK_APP_URL || 'https://app.gitbook.com';
/**
* Default GitBook API URL endpoint.
@@ -30,7 +38,7 @@ export const GITBOOK_API_URL = process.env.GITBOOK_API_URL || 'https://api.gitbo
* Default GitBook API token.
* It can be use to avoid rate-limiting.
*/
export const GITBOOK_API_TOKEN = process.env.GITBOOK_API_TOKEN ?? null;
export const GITBOOK_API_TOKEN = process.env.GITBOOK_API_TOKEN || null;
/**
* User agent to use for API requests.
@@ -59,6 +67,17 @@ export const GITBOOK_IMAGE_RESIZE_URL = process.env.GITBOOK_IMAGE_RESIZE_URL ??
export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null;
/**
* Endpoint where icons are served.
*/
export const GITBOOK_ICONS_URL =
process.env.GITBOOK_ICONS_URL || `${GITBOOK_ASSETS_URL || ''}/~gitbook/static/icons`;
/**
* Token passed to the icons endpoint.
*/
export const GITBOOK_ICONS_TOKEN = process.env.GITBOOK_ICONS_TOKEN;
/**
* Secret used to validate requests from the GitBook app.
*/
+20
View File
@@ -36,6 +36,12 @@ export enum MiddlewareHeaders {
* The visitor token used to access this content
*/
VisitorAuthToken = 'x-gitbook-visitor-token',
/**
* The API token used to fetch the content.
* This should only be passed for non-site dynamic routes.
*/
APIToken = 'x-gitbook-api-token',
}
/**
@@ -112,3 +118,17 @@ export async function getVisitorAuthTokenFromMiddleware(): Promise<string | null
return visitorAuthToken;
}
/**
* Get the API token from the middleware headers.
* This function should only be called in a dynamic route.
*/
export async function getAPITokenFromMiddleware(): Promise<string> {
const headersList = await headers();
const apiToken = headersList.get(MiddlewareHeaders.APIToken);
if (!apiToken) {
throw new Error('API token is not set by the middleware');
}
return apiToken;
}
+190 -61
View File
@@ -1,13 +1,25 @@
import { CustomizationThemeMode, GitBookAPIError } from '@gitbook/api';
import { CustomizationThemeMode } from '@gitbook/api';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getContentSecurityPolicy } from '@/lib/csp';
import { validateSerializedCustomization } from '@/lib/customization';
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import { getResponseCookiesForVisitorAuth, getVisitorToken } from '@/lib/visitor-token';
import {
type ResponseCookies,
getPathScopedCookieName,
getResponseCookiesForVisitorAuth,
getVisitorToken,
normalizeVisitorAuthURL,
} from '@/lib/visitor-token';
import { serveResizedImage } from '@/routes/image';
import { getPublishedContentByURL } from '@v2/lib/data';
import { getLinkerForSiteURL } from '@v2/lib/context';
import {
DataFetcherError,
getPublishedContentByURL,
normalizeURL,
throwIfDataError,
} from '@v2/lib/data';
import { isGitBookAssetsHostURL, isGitBookHostURL } from '@v2/lib/env';
import { MiddlewareHeaders } from '@v2/lib/middleware';
@@ -21,27 +33,21 @@ type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
export async function middleware(request: NextRequest) {
try {
// Route all requests to a site
const extracted = getSiteURLFromRequest(request);
if (extracted) {
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (extracted.url.pathname.endsWith('/~gitbook/image')) {
return await serveResizedImage(request, {
host: extracted.url.host,
});
}
const requestURL = new URL(request.url);
return await serveSiteByURL(request, extracted);
// Redirect to normalize the URL
const normalized = normalizeURL(requestURL);
if (normalized.toString() !== requestURL.toString()) {
return NextResponse.redirect(normalized.toString());
}
for (const handler of [serveSiteRoutes, servePreviewRoutes]) {
const result = await handler(requestURL, request);
if (result) {
return result;
}
}
// Handle the rest with the router default logic
return NextResponse.next();
} catch (error) {
return serveErrorResponse(error as Error);
@@ -49,50 +55,111 @@ export async function middleware(request: NextRequest) {
}
/**
* Serve site by URL.
* Handle request that are targetting the site routes group.
*/
async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
const { url, mode } = urlWithMode;
// Visitor authentication
// @ts-ignore - request typing
const visitorToken = getVisitorToken(request, url);
const result = await getPublishedContentByURL({
url: url.toString(),
visitorAuthToken: visitorToken?.token ?? null,
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
// For example when the VA backend signature has changed but the token stored in the cookie is not yet expired.
redirectOnError: visitorToken?.source === 'visitor-auth-cookie',
});
if (result.error) {
throw result.error;
async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
const match = getSiteURLFromRequest(request);
if (!match) {
return null;
}
const { data } = result;
const { url: siteURL, mode } = match;
/**
* Serve image resizing requests (all requests containing `/~gitbook/image`).
* All URLs containing `/~gitbook/image` are rewritten to `/~gitbook/image`
* and serve from a single route handler.
*
* In GitBook v1: image resizing was done at the root of the hostname (docs.company.com/~gitbook/image)
* In GitBook v2: image resizing is done at the content level (docs.company.com/section/variant/~gitbook/image)
*/
if (siteURL.pathname.endsWith('/~gitbook/image')) {
return await serveResizedImage(request, {
host: siteURL.host,
});
}
//
// Detect and extract the visitor authentication token from the request
//
// @ts-ignore - request typing
const visitorToken = getVisitorToken(request, siteURL);
const data = await throwIfDataError(
getPublishedContentByURL({
url: siteURL.toString(),
visitorAuthToken: visitorToken?.token ?? null,
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
// For example when the VA backend signature has changed but the token stored in the cookie is not yet expired.
redirectOnError: visitorToken?.source === 'visitor-auth-cookie',
})
);
let cookies: ResponseCookies = {};
//
// Handle redirects
//
if ('redirect' in data) {
// biome-ignore lint/suspicious/noConsole: we want to log the redirect
console.log('redirect', data.redirect);
if (data.target === 'content') {
// For content redirects, we use the linker to redirect the optimal URL
// during development and testing in 'url' mode.
const linker = getLinkerForSiteURL({
siteURL,
urlMode: mode,
});
const contentRedirect = new URL(linker.toLinkForContent(data.redirect), request.url);
// Keep the same search params as the original request
// as it might contain a VA token
contentRedirect.search = request.nextUrl.search;
return NextResponse.redirect(contentRedirect);
}
return NextResponse.redirect(data.redirect);
}
cookies = {
...cookies,
...getResponseCookiesForVisitorAuth(data.basePath, visitorToken),
};
//
// Make sure the URL is clean of any va token after a successful lookup
// The token is stored in a cookie that is set on the redirect response
//
const requestURLWithoutToken = normalizeVisitorAuthURL(requestURL);
if (requestURLWithoutToken.toString() !== requestURL.toString()) {
return writeResponseCookies(
NextResponse.redirect(requestURLWithoutToken.toString()),
cookies
);
}
//
// Render and serve the content
//
// When visitor has authentication (adaptive content or VA), we serve dynamic routes.
let routeType = visitorToken ? 'dynamic' : 'static';
const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${url.origin}${data.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURL, `${siteURL.origin}${data.basePath}`);
requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data));
// Preview of customization/theme
const customization = url.searchParams.get('customization');
const customization = siteURL.searchParams.get('customization');
if (customization && validateSerializedCustomization(customization)) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Customization, customization);
}
const theme = url.searchParams.get('theme');
const theme = siteURL.searchParams.get('theme');
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Theme, theme);
@@ -108,14 +175,16 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
requestHeaders.set('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin);
const siteURL = `${url.host}${data.basePath}`;
const siteURLWithoutProtocol = `${siteURL.host}${data.basePath}`;
const { pathname, routeType: routeTypeFromPathname } = encodePathInSiteContent(data.pathname);
routeType = routeTypeFromPathname ?? routeType;
const route = [
'sites',
routeType,
mode,
encodeURIComponent(siteURL),
encodePathInSiteContent(data.pathname),
encodeURIComponent(siteURLWithoutProtocol),
pathname,
].join('/');
console.log(`rewriting ${request.nextUrl.toString()} to ${route}`);
@@ -135,24 +204,68 @@ async function serveSiteByURL(request: NextRequest, urlWithMode: URLWithMode) {
response.headers.set('x-content-type-options', 'nosniff');
// Debug header
response.headers.set('x-gitbook-route-type', routeType);
response.headers.set('x-gitbook-site-url', siteURL);
response.headers.set('x-gitbook-route-site', siteURLWithoutProtocol);
if (visitorToken) {
const cookies = getResponseCookiesForVisitorAuth(data.basePath, visitorToken);
for (const [key, value] of Object.entries(cookies)) {
response.cookies.set(key, value.value, value.options);
}
return writeResponseCookies(response, cookies);
}
/**
* Serve routes for previewing unpublished content.
* Routes are:
* - PDF export for a space: /~space/:spaceId/~gitbook/pdf
* - Preview of an unpublished site: /~site/:siteId/
*/
async function servePreviewRoutes(requestURL: URL, request: NextRequest) {
const pathnameParts = requestURL.pathname.slice(1).split('/');
if (pathnameParts[0] !== '~space' && pathnameParts[0] !== '~site') {
return null;
}
return response;
// We store the API token in a cookie that is scoped to the specific preview route
// to avoid errors when multiple previews are opened in different tabs.
const cookieName = getPathScopedCookieName(
'gitbook-api-token',
pathnameParts.slice(0, 2).join('/')
);
// Extract a potential GitBook API token passed in the request
// If found, we redirect to the same URL but with the token in the cookie
const queryAPIToken = requestURL.searchParams.get('token');
if (queryAPIToken) {
requestURL.searchParams.delete('token');
return writeResponseCookies(NextResponse.redirect(requestURL.toString()), {
[cookieName]: {
value: queryAPIToken,
options: {
httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60, // 1 hour
},
},
});
}
const apiToken = request.cookies.get(cookieName)?.value;
if (!apiToken) {
throw new DataFetcherError('Missing API token', 400);
}
// Handle the rest with the router default logic
return NextResponse.next({
headers: {
[MiddlewareHeaders.APIToken]: apiToken,
},
});
}
/**
* Serve an error response.
*/
function serveErrorResponse(error: Error) {
if (error instanceof GitBookAPIError) {
return new Response(error.errorMessage, {
if (error instanceof DataFetcherError) {
return new Response(error.message, {
status: error.code,
headers: { 'content-type': 'text/plain' },
});
@@ -219,22 +332,27 @@ function getSiteURLFromRequest(request: NextRequest): URLWithMode | 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) {
function encodePathInSiteContent(rawPathname: string): {
pathname: string;
routeType?: 'static' | 'dynamic';
} {
const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname));
if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) {
return pathname;
return { pathname };
}
switch (pathname) {
case '~gitbook/icon':
case '~gitbook/image':
case 'llms.txt':
case 'sitemap.xml':
case 'robots.txt':
return pathname;
return { pathname };
case '~gitbook/pdf':
// PDF routes are always dynamic as they depend on the search params.
return { pathname, routeType: 'dynamic' };
default:
return encodeURIComponent(pathname || '/');
return { pathname: encodeURIComponent(pathname || '/') };
}
}
@@ -248,3 +366,14 @@ function appendQueryParams(url: URL, from: URLSearchParams) {
return url;
}
/**
* Write the cookies to a response.
*/
function writeResponseCookies<R extends NextResponse>(response: R, cookies: ResponseCookies): R {
Object.entries(cookies).forEach(([key, { value, options }]) => {
response.cookies.set(key, value, options);
});
return response;
}
+26
View File
@@ -1,5 +1,31 @@
# gitbook
## 0.7.3
### Patch Changes
- eaf2d68: OpenAPI operation title fallback in sections
- Updated dependencies [844059f]
- Updated dependencies [88f64b0]
- @gitbook/react-openapi@1.1.3
- @gitbook/icons@0.2.0
- @gitbook/react-contentkit@0.6.2
## 0.7.2
### Patch Changes
- f127d28: Rename OpenAPIModels to OpenAPISchemas
- Updated dependencies [f127d28]
- @gitbook/react-openapi@1.1.2
## 0.7.1
### Patch Changes
- Updated dependencies [f574858]
- @gitbook/react-openapi@1.1.1
## 0.7.0
### Minor Changes
+45 -45
View File
@@ -4,7 +4,7 @@ import { type TestsCase, runTestCases } from './util';
const testCases: TestsCase[] = [
{
name: 'Snyk',
baseUrl: 'https://docs.snyk.io',
contentBaseURL: 'https://docs.snyk.io',
tests: [
{ name: 'Home', url: '/' },
{ name: 'OpenAPI', url: '/snyk-api/reference/apps' },
@@ -12,222 +12,222 @@ const testCases: TestsCase[] = [
},
{
name: 'Nexthink',
baseUrl: 'https://docs.nexthink.com',
contentBaseURL: 'https://docs.nexthink.com',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
},
{
name: 'asiksupport-stg.dto.kemkes.go.id',
baseUrl: 'https://asiksupport-stg.dto.kemkes.go.id',
contentBaseURL: 'https://asiksupport-stg.dto.kemkes.go.id',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'jasons-tutorials.gitbook.io',
baseUrl: 'https://jasons-tutorials.gitbook.io',
contentBaseURL: 'https://jasons-tutorials.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'faq.deltaemulator.com',
baseUrl: 'https://faq.deltaemulator.com',
contentBaseURL: 'https://faq.deltaemulator.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.dify.ai',
baseUrl: 'https://docs.dify.ai',
contentBaseURL: 'https://docs.dify.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'seeddao.gitbook.io',
baseUrl: 'https://seeddao.gitbook.io',
contentBaseURL: 'https://seeddao.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'faq.altstore.io',
baseUrl: 'https://faq.altstore.io',
contentBaseURL: 'https://faq.altstore.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'support.audacityteam.org',
baseUrl: 'https://support.audacityteam.org',
contentBaseURL: 'https://support.audacityteam.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.gmgn.ai',
baseUrl: 'https://docs.gmgn.ai',
contentBaseURL: 'https://docs.gmgn.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.spicychat.ai',
baseUrl: 'https://docs.spicychat.ai',
contentBaseURL: 'https://docs.spicychat.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.portainer.io',
baseUrl: 'https://docs.portainer.io',
contentBaseURL: 'https://docs.portainer.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.chirptoken.io',
baseUrl: 'https://docs.chirptoken.io',
contentBaseURL: 'https://docs.chirptoken.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.dexscreener.com',
baseUrl: 'https://docs.dexscreener.com',
contentBaseURL: 'https://docs.dexscreener.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.pancakeswap.finance',
baseUrl: 'https://docs.pancakeswap.finance',
contentBaseURL: 'https://docs.pancakeswap.finance',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'book.character.ai',
baseUrl: 'https://book.character.ai',
contentBaseURL: 'https://book.character.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.tradeonnova.io',
baseUrl: 'https://docs.tradeonnova.io',
contentBaseURL: 'https://docs.tradeonnova.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'azcoiner.gitbook.io',
baseUrl: 'https://azcoiner.gitbook.io',
contentBaseURL: 'https://azcoiner.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.midas.app',
baseUrl: 'https://docs.midas.app',
contentBaseURL: 'https://docs.midas.app',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.keeper.io',
baseUrl: 'https://docs.keeper.io',
contentBaseURL: 'https://docs.keeper.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'adiblar.gitbook.io',
baseUrl: 'https://adiblar.gitbook.io',
contentBaseURL: 'https://adiblar.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.gradient.network',
baseUrl: 'https://docs.gradient.network',
contentBaseURL: 'https://docs.gradient.network',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'mygate-network.gitbook.io',
baseUrl: 'https://mygate-network.gitbook.io',
contentBaseURL: 'https://mygate-network.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'treasurenft.gitbook.io',
baseUrl: 'https://treasurenft.gitbook.io',
contentBaseURL: 'https://treasurenft.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'browndust2.gitbook.io',
baseUrl: 'https://browndust2.gitbook.io',
contentBaseURL: 'https://browndust2.gitbook.io',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
},
{
name: 'junookyo.gitbook.io',
baseUrl: 'https://junookyo.gitbook.io',
contentBaseURL: 'https://junookyo.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'meshnet.nordvpn.com',
baseUrl: 'https://meshnet.nordvpn.com',
contentBaseURL: 'https://meshnet.nordvpn.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'manual.bubble.io',
baseUrl: 'https://manual.bubble.io',
contentBaseURL: 'https://manual.bubble.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.tickettool.xyz',
baseUrl: 'https://docs.tickettool.xyz',
contentBaseURL: 'https://docs.tickettool.xyz',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'wiki.redmodding.org',
baseUrl: 'https://wiki.redmodding.org',
contentBaseURL: 'https://wiki.redmodding.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.cherry-ai.com',
baseUrl: 'https://docs.cherry-ai.com',
contentBaseURL: 'https://docs.cherry-ai.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.snyk.io',
baseUrl: 'https://docs.snyk.io',
contentBaseURL: 'https://docs.snyk.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.realapp.link',
baseUrl: 'https://docs.realapp.link',
contentBaseURL: 'https://docs.realapp.link',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.plaza.finance',
baseUrl: 'https://docs.plaza.finance',
contentBaseURL: 'https://docs.plaza.finance',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.publicai.io',
baseUrl: 'https://docs.publicai.io',
contentBaseURL: 'https://docs.publicai.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'hyperliquid.gitbook.io',
baseUrl: 'https://hyperliquid.gitbook.io',
contentBaseURL: 'https://hyperliquid.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.umbraco.com',
baseUrl: 'https://docs.umbraco.com',
contentBaseURL: 'https://docs.umbraco.com',
tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }],
},
{
name: 'sosovalue-white-paper.gitbook.io',
baseUrl: 'https://sosovalue-white-paper.gitbook.io',
contentBaseURL: 'https://sosovalue-white-paper.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.revrobotics.com',
baseUrl: 'https://docs.revrobotics.com',
contentBaseURL: 'https://docs.revrobotics.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'chartschool.stockcharts.com',
baseUrl: 'https://chartschool.stockcharts.com',
contentBaseURL: 'https://chartschool.stockcharts.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.soniclabs.com',
baseUrl: 'https://docs.soniclabs.com',
contentBaseURL: 'https://docs.soniclabs.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.meshchain.ai',
baseUrl: 'https://docs.meshchain.ai',
contentBaseURL: 'https://docs.meshchain.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.thousandeyes.com',
baseUrl: 'https://docs.thousandeyes.com',
contentBaseURL: 'https://docs.thousandeyes.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.raydium.io',
baseUrl: 'https://docs.raydium.io',
contentBaseURL: 'https://docs.raydium.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.fluentbit.io',
baseUrl: 'https://docs.fluentbit.io',
contentBaseURL: 'https://docs.fluentbit.io',
tests: [{ name: 'Home', url: '/' }],
},
];
+113 -63
View File
@@ -14,6 +14,7 @@ import {
getVisitorAuthCookieValue,
} from '@/lib/visitor-token';
import { getSiteAPIToken } from '../tests/utils';
import {
type TestsCase,
allDeprecatedThemePresets,
@@ -31,7 +32,7 @@ import {
const testCases: TestsCase[] = [
{
name: 'GitBook Site (Single Variant)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [
{
name: 'Home',
@@ -84,7 +85,7 @@ const testCases: TestsCase[] = [
},
{
name: 'GitBook Site (Multi Variants)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/multi-variants/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/multi-variants/',
tests: [
{
name: 'Variants dropdown',
@@ -135,7 +136,7 @@ const testCases: TestsCase[] = [
},
{
name: 'GitBook Site (Navigation when switching variant)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/',
tests: [
{
name: 'Keep navigation path/route when switching variant (Public)',
@@ -155,8 +156,8 @@ const testCases: TestsCase[] = [
.click();
// 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'
await page.waitForURL((url) =>
url.pathname.includes('api-multi-versions/2.0/reference/api-reference/pets')
);
},
},
@@ -178,15 +179,17 @@ const testCases: TestsCase[] = [
.click();
// 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'
await page.waitForURL((url) =>
url.pathname.includes(
'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets'
)
);
},
},
{
name: 'Keep navigation path/route when switching variant (VA)',
screenshot: false,
url: (() => {
url: () => {
const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953';
const token = jwt.sign(
{
@@ -198,7 +201,7 @@ const testCases: TestsCase[] = [
}
);
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
})(),
},
run: async (page) => {
const spaceDrowpdown = await page
.locator('[data-testid="space-dropdown-button"]')
@@ -213,8 +216,10 @@ const testCases: TestsCase[] = [
.click();
// 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'
await page.waitForURL((url) =>
url.pathname.includes(
'api-multi-versions-va/2.0/reference/api-reference/pets'
)
);
},
},
@@ -222,7 +227,7 @@ const testCases: TestsCase[] = [
},
{
name: 'GitBook Site (Sections and Section Groups)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/sections/',
tests: [
{
name: 'Site with sections and section groups',
@@ -244,16 +249,14 @@ const testCases: TestsCase[] = [
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'
);
await page.waitForURL((url) => url.pathname.includes('/sections/sections-4'));
},
},
],
},
{
name: 'GitBook',
baseUrl: 'https://docs.gitbook.com',
contentBaseURL: 'https://docs.gitbook.com',
tests: [
{
name: 'Home',
@@ -297,7 +300,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Versioning',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Revision',
@@ -308,7 +311,7 @@ const testCases: TestsCase[] = [
},
{
name: 'PDF',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'PDF',
@@ -316,12 +319,56 @@ const testCases: TestsCase[] = [
screenshot: {
waitForTOCScrolling: false,
},
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
},
],
},
{
name: 'Space PDF',
tests: [
{
name: 'Main content',
url: async () => {
const data = await getSiteAPIToken(
'https://gitbook.gitbook.io/test-gitbook-open/'
);
const searchParams = new URLSearchParams();
searchParams.set('limit', '10');
searchParams.set('token', data.apiToken);
return `~space/${data.space}/~gitbook/pdf?${searchParams.toString()}`;
},
screenshot: false,
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
},
{
name: 'Change request',
url: async () => {
const data = await getSiteAPIToken(
'https://gitbook.gitbook.io/test-gitbook-open/'
);
const searchParams = new URLSearchParams();
searchParams.set('limit', '10');
searchParams.set('token', data.apiToken);
return `~space/${data.space}/~/changes/HrtgUd5MlFusCMv1elA7/~gitbook/pdf?${searchParams.toString()}`;
},
screenshot: false,
run: async (page) => {
await expect(page.locator('[data-testid="print-button"]')).toBeVisible();
},
},
],
},
{
name: 'Content tests',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Text',
@@ -484,7 +531,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Page options',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Hidden',
@@ -518,7 +565,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Customization',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allThemeModes.flatMap((themeMode) => [
{
name: `Without header - Theme mode ${themeMode}`,
@@ -652,7 +699,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Ads',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Without previewed ads',
@@ -663,7 +710,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Shared space navigation (first site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
tests: [
{
name: 'Navigation to shared space',
@@ -684,7 +731,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Shared space navigation (second site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
tests: [
{
name: 'Navigation to shared space',
@@ -704,7 +751,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Site Redirects',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [
{
name: 'Redirect to SSO page',
@@ -718,7 +765,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Share links',
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
contentBaseURL: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
tests: [
{
name: 'Valid link',
@@ -738,11 +785,11 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Space',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-space/',
contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-space/',
tests: [
{
name: 'First',
url: (() => {
url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign(
{
@@ -754,7 +801,7 @@ const testCases: TestsCase[] = [
}
);
return `first?jwt_token=${token}`;
})(),
},
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' })
@@ -764,7 +811,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Second',
url: (() => {
url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign(
{
@@ -776,7 +823,7 @@ const testCases: TestsCase[] = [
}
);
return `second?jwt_token=${token}`;
})(),
},
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'second' })
@@ -788,11 +835,11 @@ const testCases: TestsCase[] = [
},
{
name: 'Visitor Auth - Collection',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-collection/',
contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-collection/',
tests: [
{
name: 'Root',
url: (() => {
url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign(
{
@@ -804,12 +851,12 @@ const testCases: TestsCase[] = [
}
);
return `?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
{
name: 'Primary (Space A)',
url: (() => {
url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign(
{
@@ -820,13 +867,16 @@ const testCases: TestsCase[] = [
expiresIn: '24h',
}
);
// Test that when accessing the non-canonical URL, we are redirected to the canonical URL
// with the jwt token in the query string
return `spacea?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
{
name: 'Space B',
url: (() => {
url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign(
{
@@ -838,12 +888,12 @@ const testCases: TestsCase[] = [
}
);
return `spaceb?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
{
name: 'Space C',
url: (() => {
url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign(
{
@@ -855,18 +905,18 @@ const testCases: TestsCase[] = [
}
);
return `spacec?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
],
},
{
name: 'Visitor Auth - Space (custom domain)',
baseUrl: 'https://test.gitbook.community/',
contentBaseURL: 'https://test.gitbook.community/',
tests: [
{
name: 'Root',
url: (() => {
url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign(
{
@@ -878,12 +928,12 @@ const testCases: TestsCase[] = [
}
);
return `?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
{
name: 'First',
url: (() => {
url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign(
{
@@ -895,7 +945,7 @@ const testCases: TestsCase[] = [
}
);
return `first?jwt_token=${token}`;
})(),
},
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' })
@@ -905,7 +955,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Custom page',
url: (() => {
url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign(
{
@@ -917,12 +967,12 @@ const testCases: TestsCase[] = [
}
);
return `custom-page?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
{
name: 'Inner page',
url: (() => {
url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign(
{
@@ -934,14 +984,14 @@ const testCases: TestsCase[] = [
}
);
return `custom-page/inner-page?jwt_token=${token}`;
})(),
},
run: waitForCookiesDialog,
},
],
},
{
name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/',
tests: [
{
name: 'Redirect to fallback on invalid token pulled from cookie',
@@ -973,7 +1023,7 @@ const testCases: TestsCase[] = [
{
name: 'Show error message when invalid token is passed to url',
screenshot: false,
url: (() => {
url: () => {
const token = jwt.sign(
{
name: 'gitbook-open-tests',
@@ -984,7 +1034,7 @@ const testCases: TestsCase[] = [
}
);
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.'
@@ -995,7 +1045,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Languages',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allLocales.map((locale) => ({
name: locale,
url: getCustomizationURL({
@@ -1011,7 +1061,7 @@ const testCases: TestsCase[] = [
},
{
name: 'SEO',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Index by default',
@@ -1062,11 +1112,11 @@ const testCases: TestsCase[] = [
},
{
name: 'Adaptive Content - VA',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/',
tests: [
{
name: 'isAlphaUser',
url: (() => {
url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign(
{
@@ -1079,7 +1129,7 @@ const testCases: TestsCase[] = [
}
);
return `?jwt_token=${token}`;
})(),
},
run: async (page) => {
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
@@ -1093,7 +1143,7 @@ const testCases: TestsCase[] = [
},
{
name: 'isBetaUser',
url: (() => {
url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign(
{
@@ -1106,7 +1156,7 @@ const testCases: TestsCase[] = [
}
);
return `?jwt_token=${token}`;
})(),
},
run: async (page) => {
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
@@ -1120,7 +1170,7 @@ const testCases: TestsCase[] = [
},
{
name: 'isAlphaUser & isBetaUser',
url: (() => {
url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign(
{
@@ -1134,7 +1184,7 @@ const testCases: TestsCase[] = [
}
);
return `?jwt_token=${token}`;
})(),
},
run: async (page) => {
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
@@ -1150,7 +1200,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Adaptive Content - Public',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/',
tests: [
{
name: 'No custom cookie',
@@ -1293,7 +1343,7 @@ const testCases: TestsCase[] = [
},
{
name: 'Tables',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: 'Default table',
+13 -8
View File
@@ -20,14 +20,14 @@ import deepMerge from 'deepmerge';
import rison from 'rison';
import type { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils';
import { getContentTestURL, getTestURL } from '../tests/utils';
export interface Test {
name: string;
/**
* URL to visit for testing.
*/
url: string;
url: string | (() => string | Promise<string>);
cookies?: Parameters<BrowserContext['addCookies']>[0];
/**
* Test to run
@@ -60,11 +60,11 @@ export interface Test {
only?: boolean;
}
export interface TestsCase {
export type TestsCase = {
name: string;
baseUrl: string;
tests: Array<Test>;
}
contentBaseURL?: string;
};
export const allLocales: CustomizationLocale[] = [
CustomizationLocale.Fr,
@@ -142,9 +142,14 @@ export function runTestCases(testCases: TestsCase[]) {
test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) {
const testFn = testEntry.only ? test.only : test;
testFn(testEntry.name, async ({ page, baseURL, context }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl);
const url = getContentTestURL(contentUrl.toString(), baseURL);
testFn(testEntry.name, async ({ page, context }) => {
const testEntryPathname =
typeof testEntry.url === 'function' ? await testEntry.url() : testEntry.url;
const url = testCase.contentBaseURL
? getContentTestURL(
new URL(testEntryPathname, testCase.contentBaseURL).toString()
)
: getTestURL(testEntryPathname);
if (testEntry.cookies) {
await context.addCookies(
testEntry.cookies.map((cookie) => ({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "0.7.0",
"version": "0.7.3",
"private": true,
"scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev",
-1
View File
@@ -16,7 +16,6 @@ export default defineConfig({
},
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
@@ -38,10 +38,9 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
}
async function getSitePageProps(props: PageProps) {
const { params: rawParams, searchParams: rawSearchParams } = props;
const { params: rawParams } = props;
const params = await rawParams;
const searchParams = await rawSearchParams;
const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer);
@@ -49,7 +48,5 @@ async function getSitePageProps(props: PageProps) {
return {
context,
pageParams: params,
redirectOnFallback: true,
fallback: !!searchParams.fallback,
};
}
@@ -1,24 +1,9 @@
import { CustomizationRootLayout } from '@/components/RootLayout';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { PDFRootLayout } from '@/components/PDF';
import { getV1ContextForPDF } from './pointer';
/**
* Layout to be used for the site root. It fetches the customization data for the
* site or space and initializes the CustomizationRootLayout with it.
*/
export default async function PDFRootLayout(props: { children: React.ReactNode }) {
export default async function RootLayout(props: { children: React.ReactNode }) {
const { children } = props;
const context = await getV1ContextForPDF();
return (
<CustomizationRootLayout
customization={
'customization' in context ? context.customization : defaultCustomizationForSpace()
}
>
{children}
</CustomizationRootLayout>
);
return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
}
@@ -1,361 +1,17 @@
import {
type CustomizationSettings,
type Revision,
type RevisionPageDocument,
type RevisionPageGroup,
RevisionPageType,
type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data';
import type { GitBookSpaceLinker } from '@v2/lib/links';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate';
import { getAbsoluteHref, getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { type PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { PageControlButtons } from './PageControlButtons';
import { PrintButton } from './PrintButton';
import './pdf.css';
import { PDFPage, generatePDFMetadata } from '@/components/PDF';
import { getV1ContextForPDF } from './pointer';
const DEFAULT_LIMIT = 100;
export const runtime = 'edge';
export const dynamic = 'force-dynamic';
export async function generateMetadata(): Promise<Metadata> {
export async function generateMetadata() {
const context = await getV1ContextForPDF();
return {
title: 'site' in context ? context.site.title : context.space.title,
robots: 'noindex, nofollow',
};
return generatePDFMetadata(context);
}
/**
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export default async function PDFHTMLOutput(props: {
export default async function Page(props: {
searchParams: Promise<{ [key: string]: string }>;
}) {
const searchParams = new URLSearchParams(await props.searchParams);
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
// Build current PDF URL and preserve all search params
let currentPDFUrl = await getAbsoluteHref('~gitbook/pdf', true);
currentPDFUrl += `?${searchParams.toString()}`;
// Fetch the context
const baseContext = await getV1ContextForPDF();
const customization =
'customization' in baseContext ? baseContext.customization : defaultCustomizationForSpace();
const language = getSpaceLanguage(customization);
// Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
);
// Build a linker that create anchor links for the pages rendered in the PDF page.
const linker: GitBookSpaceLinker = {
...baseContext.linker,
toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) {
return `#${getPagePDFContainerId(input.page, input.anchor)}`;
}
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
},
};
const context: GitBookSpaceContext = {
...baseContext,
linker,
};
return (
<div className="print-mode">
{pdfParams.back !== 'false' ? (
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a
title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="arrow-left" className={tcls('size-6')} />
</a>
</div>
) : null}
<div className={tcls('fixed', 'right-12', 'top-12', 'print:hidden', 'z-50')}>
<PrintButton
title={tString(language, 'pdf_print')}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="print" className={tcls('size-6')} />
</PrintButton>
</div>
<PageControlButtons
pageIds={pageIds}
pdfHref={currentPDFUrl}
singlePageMode={!!pdfParams.only}
total={total}
limit={pdfParams.limit ?? DEFAULT_LIMIT}
trademark={
customization.trademark.enabled ? (
<TrademarkLink
space={context.space}
customization={customization}
placement={SiteInsightsTrademarkPlacement.Pdf}
/>
) : null
}
/>
{pdfParams.only ? null : (
<PDFSpaceIntro space={context.space} customization={customization} />
)}
{pages.map(({ page }) =>
page.type === 'group' ? (
<PDFPageGroup key={page.id} space={context.space} page={page} />
) : (
<React.Suspense
key={page.id}
fallback={
<PrintPage id={getPagePDFContainerId(page)}>
<p>Loading...</p>
</PrintPage>
}
>
<PDFPageDocument page={page} context={context} />
</React.Suspense>
)
)}
</div>
);
}
async function PDFSpaceIntro(props: {
space: Space;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { space, customization } = props;
return (
<PrintPage isFirst>
<div className={tcls('flex', 'items-center', 'justify-center', 'py-12')}>
<h1 className={tcls('text-6xl', 'font-bold')}>
{customization.title ?? space.title}
</h1>
</div>
</PrintPage>
);
}
async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
const { page } = props;
return (
<PrintPage id={getPagePDFContainerId(page)}>
<div
className={tcls(
'break-before-page',
'mt-10',
'print:mt-0',
'flex',
'items-center',
'justify-center',
'py-12'
)}
>
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
</div>
</PrintPage>
);
}
async function PDFPageDocument(props: {
page: RevisionPageDocument;
context: GitBookSpaceContext;
}) {
const { page, context } = props;
const { space } = context;
const document = await getPageDocument(context.dataFetcher, space, page);
return (
<PrintPage id={getPagePDFContainerId(page)}>
<h1 className={tcls('text-4xl', 'font-bold')}>{page.title}</h1>
{page.description ? (
<p className={tcls('decoration-primary/6', 'mt-2', 'mb-3')}>{page.description}</p>
) : null}
{document ? (
<DocumentView
document={document}
style="mt-6 space-y-6"
blockStyle="max-w-full"
context={{
mode: 'print',
contentContext: {
...context,
page,
},
getId: (id) => getPagePDFContainerId(page, id),
}}
/>
) : null}
</PrintPage>
);
}
function PrintPage(
props: PolymorphicComponentProp<
'div',
{
isFirst?: boolean;
}
>
) {
const { children, isFirst, className, ...rest } = props;
return (
<div
{...rest}
className={tcls(
className,
'my-11',
'print:my-0',
'mx-auto',
'max-w-4xl',
'w-full',
'p-12',
'print:p-0',
'shadow-xl',
'print:shadow-none',
'rounded-sm',
'bg-white',
'min-h-[29.7cm]',
'print:min-h-0',
isFirst ? null : 'break-before-page',
'break-anywhere'
)}
>
{children}
</div>
);
}
type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: number };
/**
* Compute the ordered flat set of pages to render.
*/
function selectPages(
rootPages: Revision['pages'],
params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number
): FlatPageEntry[] => {
return [
{ page, depth },
...page.pages.flatMap((child) => {
if (child.type !== 'document') {
return [];
}
if (child.hidden) {
return [];
}
return flattenPage(child, depth + 1);
}),
];
};
const limitTo = (entries: FlatPageEntry[]) => {
return {
// Apply a soft-limit, the limit can be controlled by the URL to allow testing
pages: entries.slice(0, params.limit ?? DEFAULT_LIMIT),
total: entries.length,
};
};
if (params.page) {
const found = resolvePageId(rootPages, params.page);
if (!found) {
notFound();
}
if (!params.only) {
return limitTo([{ page: found.page, depth: 0 }]);
}
return limitTo(flattenPage(found.page, 0));
}
const allPages = rootPages.flatMap((page) => {
if (page.type !== 'document' && page.type !== 'group') {
return [];
}
if (page.hidden) {
return [];
}
return flattenPage(page, 0);
});
return limitTo(allPages);
const context = await getV1ContextForPDF();
return <PDFPage context={context} searchParams={await props.searchParams} />;
}
@@ -4,23 +4,6 @@ import type { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1';
/**
* PDF generation can be done at the site level (e.g. docs.foo.com/~gitbook/pdf) or
* at the space level (e.g. open.gitbook.com/~space/:spaceId/~gitbook/pdf) which is
* for PDF export of in-app private spaces.
*
* This function returns the pointer depending on the context.
*/
export async function getSiteOrSpacePointerForPDF(): Promise<
SiteContentPointer | SpaceContentPointer
> {
try {
return await getSiteContentPointer();
} catch (_error) {
return getSpacePointer();
}
}
/**
* Get the context for the PDF pointer.
*/
@@ -31,3 +14,18 @@ export async function getV1ContextForPDF(): Promise<GitBookSiteContext | GitBook
? await fetchV1ContextForSitePointer(pointer)
: await fetchV1ContextForSpacePointer(pointer);
}
/**
* PDF generation can be done at the site level (e.g. docs.foo.com/~gitbook/pdf) or
* at the space level (e.g. open.gitbook.com/~space/:spaceId/~gitbook/pdf) which is
* for PDF export of in-app private spaces.
*
* This function returns the pointer depending on the context.
*/
async function getSiteOrSpacePointerForPDF(): Promise<SiteContentPointer | SpaceContentPointer> {
try {
return await getSiteContentPointer();
} catch (_error) {
return getSpacePointer();
}
}
@@ -48,7 +48,7 @@ function ToolbarLayout(props: { children: React.ReactNode }) {
*/
export async function AdminToolbar(props: AdminToolbarProps) {
const { context } = props;
const mode = await headers().get('x-gitbook-mode');
const mode = (await headers()).get('x-gitbook-mode');
if (mode === 'multi-id') {
// We don't show the admin toolbar in multi-id mode, as it's used for previewing in the dashboard.
@@ -42,16 +42,18 @@ type UnwrappedBlocksProps<TBlock extends DocumentBlock> = DocumentContextProps &
/** Style passed to all blocks */
blockStyle?: ClassValue;
/** True if all blocks should be considered offscreen */
isOffscreen?: boolean;
};
/**
* Renders a list of blocks without a wrapper element.
*/
export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) {
const { nodes, blockStyle, ...contextProps } = props;
let isOffscreen = false;
const { nodes, blockStyle, isOffscreen: defaultIsOffscreen = false, ...contextProps } = props;
let isOffscreen = defaultIsOffscreen;
return nodes.map((node) => {
isOffscreen =
isOffscreen ||
@@ -46,9 +46,12 @@ export function DocumentView(
/** Style passed to all blocks */
blockStyle?: ClassValue;
/** True if the document should be considered offscreen */
isOffscreen?: boolean;
}
) {
const { document, style, blockStyle = [], context } = props;
const { document, style, blockStyle = [], context, isOffscreen = false } = props;
return (
<Blocks
@@ -62,6 +65,7 @@ export function DocumentView(
'whitespace-pre-wrap',
]}
context={context}
isOffscreen={isOffscreen}
/>
);
}
@@ -3,7 +3,7 @@
@apply flex-1 flex flex-col gap-4 mb-14;
}
.openapi-models {
.openapi-schemas {
@apply flex flex-col mb-14 flex-1;
}
@@ -620,10 +620,10 @@
@apply space-y-2.5;
}
.openapi-section-models {
.openapi-section-schemas {
@apply border border-tint-subtle rounded-lg;
}
.openapi-section-models > .openapi-section-body > .openapi-schema-properties > .openapi-schema {
.openapi-section-schemas > .openapi-section-body > .openapi-schema-properties > .openapi-schema {
@apply p-2.5;
}
@@ -63,6 +63,7 @@ const InsightsContext = React.createContext<TrackEventCallback>(() => {});
interface InsightsProviderProps extends InsightsEventContext {
enabled: boolean;
appURL: string;
apiHost: string;
visitorAuthToken: string | null;
children: React.ReactNode;
@@ -72,7 +73,7 @@ interface InsightsProviderProps extends InsightsEventContext {
* Wrap the content of the app with the InsightsProvider to track events.
*/
export function InsightsProvider(props: InsightsProviderProps) {
const { enabled, apiHost, visitorAuthToken, children, ...context } = props;
const { enabled, appURL, apiHost, visitorAuthToken, children, ...context } = props;
const visitorIdRef = React.useRef<string | null>(null);
const eventsRef = React.useRef<{
@@ -140,7 +141,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
});
const flushBatchedEvents = useDebounceCallback(async () => {
const visitorId = visitorIdRef.current ?? (await getVisitorId());
const visitorId = visitorIdRef.current ?? (await getVisitorId(appURL));
visitorIdRef.current = visitorId;
flushEventsSync();
@@ -184,7 +185,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
* Get the visitor ID and store it in a ref.
*/
React.useEffect(() => {
getVisitorId().then((visitorId) => {
getVisitorId(appURL).then((visitorId) => {
visitorIdRef.current = visitorId;
// When the page is unloaded, flush all events, but only if the visitor ID is set
window.addEventListener('beforeunload', flushEventsSync);
@@ -192,7 +193,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
return () => {
window.removeEventListener('beforeunload', flushEventsSync);
};
}, [flushEventsSync]);
}, [flushEventsSync, appURL]);
return (
<InsightsContext.Provider value={trackEvent}>
@@ -13,10 +13,10 @@ let pendingVisitorId: Promise<string> | null = null;
/**
* Return the current visitor identifier.
*/
export async function getVisitorId(): Promise<string> {
export async function getVisitorId(appURL: string): Promise<string> {
if (!visitorId) {
if (!pendingVisitorId) {
pendingVisitorId = fetchVisitorID().finally(() => {
pendingVisitorId = fetchVisitorID(appURL).finally(() => {
pendingVisitorId = null;
});
}
@@ -30,7 +30,7 @@ export async function getVisitorId(): Promise<string> {
/**
* Propose a visitor identifier to the GitBook.com server and get the devideId back.
*/
async function fetchVisitorID(): Promise<string> {
async function fetchVisitorID(appURL: string): Promise<string> {
const withoutCookies = isCookiesTrackingDisabled();
if (withoutCookies) {
@@ -46,7 +46,7 @@ async function fetchVisitorID(): Promise<string> {
// No tracking deviceId set, we'll need to consolidate with the server.
const proposed = generateRandomId();
const url = new URL(process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? 'https://app.gitbook.com');
const url = new URL(appURL);
url.pathname = '/__session';
url.searchParams.set('proposed', proposed);
@@ -0,0 +1,356 @@
import {
type CustomizationSettings,
type Revision,
type RevisionPageDocument,
type RevisionPageGroup,
RevisionPageType,
type SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
import { getPageDocument } from '@v2/lib/data';
import type { GitBookSpaceLinker } from '@v2/lib/links';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import type { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
import { tString } from '@/intl/translate';
import { getPagePDFContainerId } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { type PDFSearchParams, getPDFSearchParams } from './urls';
import { PageControlButtons } from './PageControlButtons';
import { PrintButton } from './PrintButton';
import './pdf.css';
const DEFAULT_LIMIT = 100;
/**
* Generate the metadata for the PDF page.
*/
export async function generatePDFMetadata(
context: GitBookSpaceContext | GitBookSiteContext
): Promise<Metadata> {
return {
title: 'site' in context ? context.site.title : context.space.title,
robots: 'noindex, nofollow',
};
}
/**
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export async function PDFPage(props: {
context: GitBookSpaceContext | GitBookSiteContext;
searchParams: { [key: string]: string };
}) {
const baseContext = props.context;
const searchParams = new URLSearchParams(props.searchParams);
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
const customization =
'customization' in baseContext ? baseContext.customization : defaultCustomizationForSpace();
const language = getSpaceLanguage(customization);
// Compute the pages to render
const { pages, total } = selectPages(baseContext.pages, pdfParams);
const pageIds = pages.map(
({ page }) => [page.id, getPagePDFContainerId(page)] as [string, string]
);
// Build a linker that create anchor links for the pages rendered in the PDF page.
const linker: GitBookSpaceLinker = {
...baseContext.linker,
toPathForPage(input) {
if (pages.some((p) => p.page.id === input.page.id)) {
return `#${getPagePDFContainerId(input.page, input.anchor)}`;
}
if (input.page.type === RevisionPageType.Group) {
return '#';
}
// Use an absolute URL to the page
return input.page.urls.app;
},
};
const context: GitBookSpaceContext = {
...baseContext,
linker,
};
return (
<div className="print-mode">
{pdfParams.back !== 'false' ? (
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
<a
title={tString(language, 'pdf_goback')}
href={pdfParams.back ?? linker.toAbsoluteURL(linker.toPathInContent(''))}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="arrow-left" className={tcls('size-6')} />
</a>
</div>
) : null}
<div className={tcls('fixed', 'right-12', 'top-12', 'print:hidden', 'z-50')}>
<PrintButton
title={tString(language, 'pdf_print')}
className={tcls(
'flex',
'flex-row',
'items-center',
'justify-center',
'text-sm',
'text-tint',
'hover:text-primary',
'p-4',
'rounded-full',
'bg-white',
'shadow-sm',
'hover:shadow-md',
'border-slate-300',
'border'
)}
>
<Icon icon="print" className={tcls('size-6')} />
</PrintButton>
</div>
<PageControlButtons
params={pdfParams}
pageIds={pageIds}
total={total}
trademark={
customization.trademark.enabled ? (
<TrademarkLink
space={context.space}
customization={customization}
placement={SiteInsightsTrademarkPlacement.Pdf}
/>
) : null
}
/>
{pdfParams.only ? null : (
<PDFSpaceIntro space={context.space} customization={customization} />
)}
{pages.map(({ page }) =>
page.type === 'group' ? (
<PDFPageGroup key={page.id} space={context.space} page={page} />
) : (
<React.Suspense
key={page.id}
fallback={
<PrintPage id={getPagePDFContainerId(page)}>
<p>Loading...</p>
</PrintPage>
}
>
<PDFPageDocument page={page} context={context} />
</React.Suspense>
)
)}
</div>
);
}
async function PDFSpaceIntro(props: {
space: Space;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { space, customization } = props;
return (
<PrintPage isFirst>
<div className={tcls('flex', 'items-center', 'justify-center', 'py-12')}>
<h1 className={tcls('text-6xl', 'font-bold')}>
{customization.title ?? space.title}
</h1>
</div>
</PrintPage>
);
}
async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
const { page } = props;
return (
<PrintPage id={getPagePDFContainerId(page)}>
<div
className={tcls(
'break-before-page',
'mt-10',
'print:mt-0',
'flex',
'items-center',
'justify-center',
'py-12'
)}
>
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
</div>
</PrintPage>
);
}
async function PDFPageDocument(props: {
page: RevisionPageDocument;
context: GitBookSpaceContext;
}) {
const { page, context } = props;
const { space } = context;
const document = await getPageDocument(context.dataFetcher, space, page);
return (
<PrintPage id={getPagePDFContainerId(page)}>
<h1 className={tcls('text-4xl', 'font-bold')}>{page.title}</h1>
{page.description ? (
<p className={tcls('decoration-primary/6', 'mt-2', 'mb-3')}>{page.description}</p>
) : null}
{document ? (
<DocumentView
document={document}
style="mt-6 space-y-6"
blockStyle="max-w-full"
context={{
mode: 'print',
contentContext: {
...context,
page,
},
getId: (id) => getPagePDFContainerId(page, id),
}}
// We consider all pages as offscreen in PDF mode
// to ensure we can efficiently render as many pages as possible
isOffscreen={true}
/>
) : null}
</PrintPage>
);
}
function PrintPage(
props: PolymorphicComponentProp<
'div',
{
isFirst?: boolean;
}
>
) {
const { children, isFirst, className, ...rest } = props;
return (
<div
{...rest}
className={tcls(
className,
'my-11',
'print:my-0',
'mx-auto',
'max-w-4xl',
'w-full',
'p-12',
'print:p-0',
'shadow-xl',
'print:shadow-none',
'rounded-sm',
'bg-white',
'min-h-[29.7cm]',
'print:min-h-0',
isFirst ? null : 'break-before-page',
'break-anywhere'
)}
>
{children}
</div>
);
}
type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: number };
/**
* Compute the ordered flat set of pages to render.
*/
function selectPages(
rootPages: Revision['pages'],
params: PDFSearchParams
): { pages: FlatPageEntry[]; total: number } {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number
): FlatPageEntry[] => {
return [
{ page, depth },
...page.pages.flatMap((child) => {
if (child.type !== 'document') {
return [];
}
if (child.hidden) {
return [];
}
return flattenPage(child, depth + 1);
}),
];
};
const limitTo = (entries: FlatPageEntry[]) => {
return {
// Apply a soft-limit, the limit can be controlled by the URL to allow testing
pages: entries.slice(0, params.limit ?? DEFAULT_LIMIT),
total: entries.length,
};
};
if (params.page) {
const found = resolvePageId(rootPages, params.page);
if (!found) {
notFound();
}
if (!params.only) {
return limitTo([{ page: found.page, depth: 0 }]);
}
return limitTo(flattenPage(found.page, 0));
}
const allPages = rootPages.flatMap((page) => {
if (page.type !== 'document' && page.type !== 'group') {
return [];
}
if (page.hidden) {
return [];
}
return flattenPage(page, 0);
});
return limitTo(allPages);
}
@@ -0,0 +1,23 @@
import { CustomizationRootLayout } from '@/components/RootLayout';
import { defaultCustomizationForSpace } from '@/lib/utils';
import type { GitBookSiteContext, GitBookSpaceContext } from '@v2/lib/context';
/**
* Layout to be used for rendering the PDF.
*/
export async function PDFRootLayout(props: {
context: GitBookSpaceContext | GitBookSiteContext;
children: React.ReactNode;
}) {
const { context, children } = props;
return (
<CustomizationRootLayout
customization={
'customization' in context ? context.customization : defaultCustomizationForSpace()
}
>
{children}
</CustomizationRootLayout>
);
}
@@ -7,7 +7,7 @@ import { useScrollActiveId } from '@/components/hooks';
import { Button } from '@/components/primitives';
import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
import { getPDFUrl } from '@/lib/urls';
import { type PDFSearchParams, getPDFURLSearchParams } from './urls';
const limitExtend = 50;
@@ -15,18 +15,15 @@ const limitExtend = 50;
* Dynamic controls to show active page and to let the user select between modes.
*/
export function PageControlButtons(props: {
pdfHref: string;
singlePageMode: boolean;
params: PDFSearchParams;
/** Array of the [pageId, divId] */
pageIds: Array<[string, string]>;
/** Current limit */
limit: number;
/** Total number of pages targetted by the generation */
total: number;
/** Trademark to display */
trademark?: React.ReactNode;
}) {
const { pdfHref, singlePageMode, pageIds, limit, total, trademark } = props;
const { params, pageIds, total, trademark } = props;
const language = useLanguage();
@@ -53,19 +50,24 @@ export function PageControlButtons(props: {
'z-50'
)}
>
{singlePageMode ? null : (
{params.only ? null : (
<Button
href={getPDFUrl(new URL(pdfHref), {
href={`?${getPDFURLSearchParams({
...params,
page: activePageId,
only: true,
}).toString()}
}).toString()}`}
variant="secondary"
>
{t(language, 'pdf_mode_only_page')}
</Button>
)}
<Button
href={getPDFUrl(new URL(pdfHref), { page: undefined, only: false }).toString()}
href={`?${getPDFURLSearchParams({
...params,
page: undefined,
only: false,
}).toString()}`}
variant="secondary"
>
{t(language, 'pdf_mode_all')}
@@ -113,11 +115,12 @@ export function PageControlButtons(props: {
<div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div>
<div>
<a
href={getPDFUrl(new URL(pdfHref), {
href={`?${getPDFURLSearchParams({
...params,
page: undefined,
only: false,
limit: limit + limitExtend,
}).toString()}
limit: params.limit + limitExtend,
}).toString()}`}
className={tcls('underline')}
>
{t(language, 'pdf_limit_reached_continue', limitExtend)}
@@ -12,7 +12,7 @@ export function PrintButton(props: PolymorphicComponentProp<'button'>) {
}, []);
return (
<button {...rest} onClick={onClick} className={className}>
<button {...rest} data-testid="print-button" onClick={onClick} className={className}>
{children}
</button>
);
@@ -0,0 +1,3 @@
export * from './PDFRootLayout';
export * from './PDFPage';
export * from './urls';
@@ -1,10 +1,12 @@
const DEFAULT_LIMIT = 100;
export interface PDFSearchParams {
/** Page to export. If none is passed, all pages are exported. */
page?: string;
/** If true, only the `page` is exported, and not its descendant */
only?: boolean;
/** Limit the number of pages */
limit?: number;
limit: number;
/** URL to redirect back to */
back?: string;
}
@@ -13,7 +15,9 @@ export interface PDFSearchParams {
* Get the PDF export params from the URL serch params.
*/
export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchParams {
const params: PDFSearchParams = {};
const params: PDFSearchParams = {
limit: DEFAULT_LIMIT,
};
if (searchParams.has('page')) {
params.page = searchParams.get('page') ?? '';
@@ -32,15 +36,9 @@ export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchPara
}
/**
* Update the URL with the PDF export params.
* Get the URL search params to use for a PDF export.
*/
export function getPDFUrl(url: URL, params: PDFSearchParams): URL {
const copy = new URL(url);
getPDFUrlSearchParams(params, copy.searchParams);
return copy;
}
export function getPDFUrlSearchParams(
export function getPDFURLSearchParams(
params: PDFSearchParams,
searchParams = new URLSearchParams({})
): URLSearchParams {
@@ -13,9 +13,9 @@ import urlJoin from 'url-join';
import { getSpaceLanguage, t } from '@/intl/server';
import { getDocumentSections } from '@/lib/document-sections';
import { tcls } from '@/lib/tailwind';
import { getPDFUrlSearchParams } from '@/lib/urls';
import { Ad } from '../Ads';
import { getPDFURLSearchParams } from '../PDF';
import { PageFeedbackForm } from '../PageFeedback';
import { ThemeToggler } from '../ThemeToggler';
import { ScrollSectionsList } from './ScrollSectionsList';
@@ -36,9 +36,10 @@ export function PageAside(props: {
const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInContent(
`~gitbook/pdf?${getPDFUrlSearchParams({
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
);
return (
@@ -31,6 +31,7 @@ import { ClientContexts } from './ClientContexts';
import '@gitbook/icons/style.css';
import './globals.css';
import { GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_URL } from '@v2/lib/env';
/**
* Layout shared between the content and the PDF renderer.
@@ -127,8 +128,8 @@ export async function CustomizationRootLayout(props: {
)}
>
<IconsProvider
assetsURL={process.env.GITBOOK_ICONS_URL ?? getAssetURL('icons')}
assetsURLToken={process.env.GITBOOK_ICONS_TOKEN}
assetsURL={GITBOOK_ICONS_URL}
assetsURLToken={GITBOOK_ICONS_TOKEN}
assetsByStyles={{
'custom-icons': {
assetsURL: getAssetURL('icons'),
@@ -101,7 +101,6 @@ export async function generateSiteLayoutMetadata(context: GitBookSiteContext): P
return {
title: site.title,
generator: `GitBook (${buildVersion()})`,
// metadataBase: new URL(await getBaseUrl()),
icons: {
icon: [
{
@@ -7,7 +7,7 @@ import React from 'react';
import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody';
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
import { getPagePath } from '@/lib/pages';
import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { PageClientLayout } from './PageClientLayout';
@@ -19,8 +19,6 @@ export const dynamic = 'force-dynamic';
export type SitePageProps = {
context: GitBookSiteContext;
pageParams: PagePathParams;
redirectOnFallback: boolean;
fallback?: boolean;
};
/**
@@ -30,8 +28,6 @@ export async function SitePage(props: SitePageProps) {
const { context, pageTarget } = await getPageDataWithFallback({
context: props.context,
pagePathParams: props.pageParams,
fallback: props.fallback,
redirectOnFallback: props.redirectOnFallback,
});
const rawPathname = getPathnameParam(props.pageParams);
@@ -115,7 +111,6 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
const { context, pageTarget } = await getPageDataWithFallback({
context: props.context,
pagePathParams: props.pageParams,
fallback: props.fallback,
});
if (!pageTarget) {
@@ -153,28 +148,9 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
async function getPageDataWithFallback(args: {
context: GitBookSiteContext;
pagePathParams: PagePathParams;
fallback?: boolean;
redirectOnFallback?: boolean;
}) {
const { context: baseContext, pagePathParams, fallback, redirectOnFallback = false } = args;
let { context, pageTarget } = await fetchPageData(baseContext, pagePathParams);
const canFallback = !!fallback;
if (!pageTarget && canFallback) {
const rootPage = resolveFirstDocument(context.pages, []);
if (redirectOnFallback && rootPage?.page) {
redirect(
context.linker.toPathForPage({
pages: context.pages,
page: rootPage?.page,
})
);
}
pageTarget = rootPage;
}
const { context: baseContext, pagePathParams } = args;
const { context, pageTarget } = await fetchPageData(baseContext, pagePathParams);
return {
context: {
@@ -3,12 +3,26 @@
import { TrackPageViewEvent } from '@/components/Insights';
import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';
import { useSpaceBasePath } from '../SpaceLayout/SpaceLayoutContext';
/**
* Component that displays a "page not found" message.
*/
export function SitePageNotFound() {
const basePath = useSpaceBasePath();
const language = useLanguage();
const router = useRouter();
const searchParams = useSearchParams();
// If ?fallback=true, redirect to the root page.
const fallback = searchParams.get('fallback');
useEffect(() => {
if (fallback) {
router.replace(basePath);
}
}, [basePath, fallback, router]);
return (
<div
@@ -11,9 +11,11 @@ import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate';
import { tcls } from '@/lib/tailwind';
import { GITBOOK_APP_URL } from '@v2/lib/env';
import { SpacesDropdown } from '../Header/SpacesDropdown';
import { InsightsProvider } from '../Insights';
import { SiteSectionList, encodeClientSiteSections } from '../SiteSections';
import { SpaceLayoutContextProvider } from './SpaceLayoutContext';
/**
* Render the entire layout of the space (header, table of contents, footer).
@@ -45,97 +47,100 @@ export function SpaceLayout(props: {
customization.footer.groups?.length;
return (
<InsightsProvider
enabled={withTracking}
apiHost={context.dataFetcher.apiEndpoint}
visitorAuthToken={visitorAuthToken}
organizationId={context.organizationId}
siteId={context.site.id}
siteSectionId={context.sections?.current?.id ?? null}
siteSpaceId={context.siteSpace.id}
siteShareKey={context.shareKey ?? null}
revisionId={context.revisionId}
spaceId={context.space.id}
>
<Header withTopHeader={withTopHeader} context={context} />
<div
className={tcls(
'flex',
'flex-col',
'lg:flex-row',
CONTAINER_STYLE,
// Ensure the footer is display below the viewport even if the content is not enough
withFooter && 'min-h-[calc(100vh-64px)]',
withTopHeader ? null : 'lg:min-h-screen'
)}
<SpaceLayoutContextProvider basePath={context.linker.toPathInContent('')}>
<InsightsProvider
enabled={withTracking}
appURL={GITBOOK_APP_URL}
apiHost={context.dataFetcher.apiEndpoint}
visitorAuthToken={visitorAuthToken}
organizationId={context.organizationId}
siteId={context.site.id}
siteSectionId={context.sections?.current?.id ?? null}
siteSpaceId={context.siteSpace.id}
siteShareKey={context.shareKey ?? null}
revisionId={context.revisionId}
spaceId={context.space.id}
>
<TableOfContents
context={context}
header={
withTopHeader ? null : (
<div
className={tcls(
'hidden',
'pr-4',
'lg:flex',
'grow-0',
'flex-wrap',
'dark:shadow-light/1'
)}
>
<HeaderLogo context={context} />
</div>
)
}
innerHeader={
// displays the search button and/or the space dropdown in the ToC according to the header/variant settings. E.g if there is no header, the search button will be displayed in the ToC.
<>
{!withTopHeader && (
<div className={tcls('hidden', 'lg:block')}>
<React.Suspense fallback={null}>
<SearchButton>
<span className={tcls('flex-1')}>
{t(
getSpaceLanguage(customization),
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
</span>
</SearchButton>
</React.Suspense>
<Header withTopHeader={withTopHeader} context={context} />
<div
className={tcls(
'flex',
'flex-col',
'lg:flex-row',
CONTAINER_STYLE,
// Ensure the footer is display below the viewport even if the content is not enough
withFooter && 'min-h-[calc(100vh-64px)]',
withTopHeader ? null : 'lg:min-h-screen'
)}
>
<TableOfContents
context={context}
header={
withTopHeader ? null : (
<div
className={tcls(
'hidden',
'pr-4',
'lg:flex',
'grow-0',
'flex-wrap',
'dark:shadow-light/1'
)}
>
<HeaderLogo context={context} />
</div>
)}
{!withTopHeader && withSections && sections && (
<SiteSectionList
className={tcls('hidden', 'lg:block')}
sections={encodeClientSiteSections(context, sections)}
/>
)}
{isMultiVariants && (
<SpacesDropdown
context={context}
siteSpace={siteSpace}
siteSpaces={siteSpaces}
className={tcls('w-full')}
/>
)}
</>
}
/>
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div>
</div>
)
}
innerHeader={
// displays the search button and/or the space dropdown in the ToC according to the header/variant settings. E.g if there is no header, the search button will be displayed in the ToC.
<>
{!withTopHeader && (
<div className={tcls('hidden', 'lg:block')}>
<React.Suspense fallback={null}>
<SearchButton>
<span className={tcls('flex-1')}>
{t(
getSpaceLanguage(customization),
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
</span>
</SearchButton>
</React.Suspense>
</div>
)}
{!withTopHeader && withSections && sections && (
<SiteSectionList
className={tcls('hidden', 'lg:block')}
sections={encodeClientSiteSections(context, sections)}
/>
)}
{isMultiVariants && (
<SpacesDropdown
context={context}
siteSpace={siteSpace}
siteSpaces={siteSpaces}
className={tcls('w-full')}
/>
)}
</>
}
/>
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div>
</div>
{withFooter ? <Footer context={context} /> : null}
{withFooter ? <Footer context={context} /> : null}
<React.Suspense fallback={null}>
<SearchModal
spaceTitle={siteSpace.title}
withAsk={customization.aiSearch.enabled}
isMultiVariants={isMultiVariants}
/>
</React.Suspense>
</InsightsProvider>
<React.Suspense fallback={null}>
<SearchModal
spaceTitle={siteSpace.title}
withAsk={customization.aiSearch.enabled}
isMultiVariants={isMultiVariants}
/>
</React.Suspense>
</InsightsProvider>
</SpaceLayoutContextProvider>
);
}
@@ -0,0 +1,33 @@
'use client';
import React from 'react';
const SpaceLayoutContext = React.createContext({
basePath: '',
});
/**
* Provide the client context about the currently rendered space.
*/
export function SpaceLayoutContextProvider(
props: React.PropsWithChildren<{
basePath: string;
}>
) {
const { basePath, children } = props;
const value = React.useMemo(() => ({ basePath }), [basePath]);
return <SpaceLayoutContext.Provider value={value}>{children}</SpaceLayoutContext.Provider>;
}
/**
* Return the base path of the currently rendered space.
*/
export function useSpaceBasePath() {
const context = React.useContext(SpaceLayoutContext);
if (!context) {
throw new Error('SpaceLayoutContext not found');
}
return context.basePath;
}
+1 -1
View File
@@ -4,5 +4,5 @@ import { GITBOOK_ASSETS_URL } from '@v2/lib/env';
* Create a public URL for an asset.
*/
export function getAssetURL(path: string): string {
return `${GITBOOK_ASSETS_URL}/~gitbook/static/${path}`;
return `${GITBOOK_ASSETS_URL || ''}/~gitbook/static/${path}`;
}
@@ -46,7 +46,7 @@ export async function getDocumentSections(
sections.push({
id: block.meta.id,
tag: operation.method.toUpperCase(),
title: operation.operation.summary ?? operation.path,
title: operation.operation.summary || operation.path,
depth: 1,
deprecated: operation.operation.deprecated,
});
+2 -1
View File
@@ -8,6 +8,7 @@ import {
} from '@gitbook/api';
import { headers } from 'next/headers';
import { GITBOOK_APP_URL } from '@v2/lib/env';
import { getPagePath } from './pages';
import { assertIsNotV2 } from './v2';
@@ -100,7 +101,7 @@ export async function getAbsoluteHref(href: string, withHost = false): Promise<s
* Create an absolute href in the GitBook application.
*/
export function getGitbookAppHref(pathname: string): string {
const appUrl = new URL(process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? 'https://app.gitbook.com');
const appUrl = new URL(GITBOOK_APP_URL);
appUrl.pathname = pathname;
return appUrl.toString();
@@ -1,35 +1,35 @@
import { fetchOpenAPIFilesystem } from '@/lib/openapi/fetch';
import type { ResolveOpenAPIBlockResult } from '@/lib/openapi/types';
import { OpenAPIParseError } from '@gitbook/openapi-parser';
import { type OpenAPIModelsData, resolveOpenAPIModels } from '@gitbook/react-openapi';
import { type OpenAPISchemasData, resolveOpenAPISchemas } from '@gitbook/react-openapi';
import type { AnyOpenAPIBlock, ResolveOpenAPIBlockArgs } from './types';
type ResolveOpenAPIModelsBlockResult = ResolveOpenAPIBlockResult<OpenAPIModelsData>;
type ResolveOpenAPISchemasBlockResult = ResolveOpenAPIBlockResult<OpenAPISchemasData>;
const weakmap = new WeakMap<AnyOpenAPIBlock, Promise<ResolveOpenAPIModelsBlockResult>>();
const weakmap = new WeakMap<AnyOpenAPIBlock, Promise<ResolveOpenAPISchemasBlockResult>>();
/**
* Cache the result of resolving an OpenAPI block.
* It is important because the resolve is called in sections and in the block itself.
*/
export function resolveOpenAPIModelsBlock(
export function resolveOpenAPISchemasBlock(
args: ResolveOpenAPIBlockArgs
): Promise<ResolveOpenAPIModelsBlockResult> {
): Promise<ResolveOpenAPISchemasBlockResult> {
if (weakmap.has(args.block)) {
return weakmap.get(args.block)!;
}
const result = baseResolveOpenAPIModelsBlock(args);
const result = baseResolveOpenAPISchemasBlock(args);
weakmap.set(args.block, result);
return result;
}
/**
* Resolve OpenAPI models block.
* Resolve OpenAPI schemas block.
*/
async function baseResolveOpenAPIModelsBlock(
async function baseResolveOpenAPISchemasBlock(
args: ResolveOpenAPIBlockArgs
): Promise<ResolveOpenAPIModelsBlockResult> {
): Promise<ResolveOpenAPISchemasBlockResult> {
const { context, block } = args;
if (!block.data.path || !block.data.method) {
return { data: null, specUrl: null };
@@ -42,7 +42,7 @@ async function baseResolveOpenAPIModelsBlock(
return { data: null, specUrl: null };
}
const data = await resolveOpenAPIModels(filesystem);
const data = await resolveOpenAPISchemas(filesystem);
return { data, specUrl };
} catch (error) {
+1 -1
View File
@@ -2,7 +2,7 @@ import type { DocumentBlockOpenAPI, DocumentBlockOpenAPIOperation } from '@gitbo
import type { Filesystem, OpenAPIParseError, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
import type { GitBookAnyContext } from '@v2/lib/context';
//!!TODO: Add DocumentBlockOpenAPIModels when available in @gitbook/api
//!!TODO: Add DocumentBlockOpenAPISchemas when available in @gitbook/api
export type AnyOpenAPIBlock = DocumentBlockOpenAPI | DocumentBlockOpenAPIOperation;
/**
+9 -2
View File
@@ -3,7 +3,6 @@ import type { NextRequest } from 'next/server';
import hash from 'object-hash';
const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_AUTH_COOKIE_ROOT = 'gitbook-visitor-token~';
export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token';
export type ResponseCookie = {
@@ -127,7 +126,7 @@ export function getResponseCookiesForVisitorAuth(
* different content hosted on the same subdomain.
*/
export function getVisitorAuthCookieName(basePath: string): string {
return `${VISITOR_AUTH_COOKIE_ROOT}${hash(basePath)}`;
return getPathScopedCookieName(VISITOR_TOKEN_COOKIE, basePath);
}
/**
@@ -147,6 +146,14 @@ export function normalizeVisitorAuthURL(url: URL): URL {
return withoutVAParam;
}
/**
* Get the name of a cookie to be scoped to a given path.
* It is used to avoid conflict between used of similar cookies under a same domain.
*/
export function getPathScopedCookieName(prefix: string, path: string): string {
return `${prefix}~${hash(path)}`;
}
/**
* Get all possible basePaths for a given URL. This is used to find the visitor
* authentication cookie token.
+55 -14
View File
@@ -1,25 +1,34 @@
import { GitBookAPI } from '@gitbook/api';
/**
* Get the target URL from the command line arguments.
* Get the base URL of the deployment to test.
*/
export function getTargetURL() {
const targetUrl = Bun.argv[2];
if (!targetUrl) {
process.exit(1);
function getBaseURL() {
const baseUrl = process.env.BASE_URL;
if (!baseUrl) {
throw new Error('BASE_URL is not set');
}
return targetUrl;
}
export function getContentPathName(input: string): string {
const contentUrl = new URL(input);
return `${contentUrl.host}${contentUrl.pathname}`;
return baseUrl;
}
/**
* Get the URL to load for a content
* Get the site base URL of the deployment to test.
*/
export function getContentTestURL(input: string, baseUrl: string = getTargetURL()): string {
const url = new URL(baseUrl);
function getSiteBaseURL() {
const siteBaseUrl = process.env.SITE_BASE_URL;
if (!siteBaseUrl) {
return getBaseURL();
}
return siteBaseUrl;
}
/**
* Get the URL to load for a site
*/
export function getContentTestURL(input: string): string {
const url = new URL(getSiteBaseURL());
const contentUrl = new URL(input);
url.pathname = `${url.pathname.replace(/\/$/, '')}/${contentUrl.host}${contentUrl.pathname}`;
@@ -27,3 +36,35 @@ export function getContentTestURL(input: string, baseUrl: string = getTargetURL(
return url.toString();
}
/**
* Get the URL to load on the deployment being tested.
*/
export function getTestURL(urlRest: string): string {
const url = new URL(urlRest, getBaseURL());
return url.toString();
}
/**
* Get an API token for a site by its URL.
*/
export async function getSiteAPIToken(url: string) {
const api = new GitBookAPI();
const { data } = await api.urls.getPublishedContentByUrl(
{
url,
cache: true,
},
{
headers: {
'x-gitbook-force-cache': 'true',
},
}
);
if ('redirect' in data) {
throw new Error(`Invalid site URL, it resulted in a redirect: ${data.redirect}`);
}
return data;
}
+6
View File
@@ -1,5 +1,11 @@
# @gitbook/icons
## 0.2.0
### Minor Changes
- 88f64b0: Fix the build to support Node.js v20
## 0.1.0
### Minor Changes
+5 -2
View File
@@ -16,7 +16,7 @@
"default": "./src/style.css"
}
},
"version": "0.1.0",
"version": "0.2.0",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.6.0",
"@fortawesome/fontawesome-free": "^6.6.0"
@@ -41,5 +41,8 @@
"bin": {
"gitbook-icons": "./bin/gitbook-icons.js"
},
"files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"]
"files": ["dist", "src", "bin", "data", "README.md", "CHANGELOG.md"],
"engines": {
"node": ">=20.0.0"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import stylesMap from './data/styles-map.json';
import stylesMap from './data/styles-map.json' with { type: 'json' };
import type { IconName, IconStyle } from './types';
const cache = new Map<IconName, Map<IconStyle, [string, IconName]>>();
+1 -1
View File
@@ -1,4 +1,4 @@
import rawIcons from './data/icons.json';
import rawIcons from './data/icons.json' with { type: 'json' };
import type { IconName, IconStyle } from './types';
export interface IconStyleDefinition {
+7 -7
View File
@@ -1,16 +1,16 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"lib": ["es2023"],
"module": "ESNext",
"target": "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowJs": true,
"noEmit": false,
"declaration": true,
"outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
+7
View File
@@ -1,5 +1,12 @@
# @gitbook/react-contentkit
## 0.6.2
### Patch Changes
- Updated dependencies [88f64b0]
- @gitbook/icons@0.2.0
## 0.6.1
### Patch Changes
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@gitbook/react-contentkit",
"version": "0.6.1",
"version": "0.6.2",
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -11,7 +11,6 @@
"dependencies": {
"classnames": "^2.5.1",
"@gitbook/api": "0.96.1",
"assert-never": "^1.2.1",
"@gitbook/icons": "workspace:*"
},
"peerDependencies": {
+18
View File
@@ -1,5 +1,23 @@
# @gitbook/react-openapi
## 1.1.3
### Patch Changes
- 844059f: Fix spacing in OpenAPISecurities
## 1.1.2
### Patch Changes
- f127d28: Rename OpenAPIModels to OpenAPISchemas
## 1.1.1
### Patch Changes
- f574858: Fix OpenAPI example display error
## 1.1.0
### Minor Changes
+1 -1
View File
@@ -8,7 +8,7 @@
"default": "./dist/index.js"
}
},
"version": "1.1.0",
"version": "1.1.3",
"sideEffects": false,
"dependencies": {
"@gitbook/openapi-parser": "workspace:*",
+2 -2
View File
@@ -217,7 +217,7 @@ function OpenAPISchemaPresentation(props: { property: OpenAPISchemaPropertyEntry
propertyName={propertyName}
required={required}
/>
{schema['x-deprecated-sunset'] ? (
{typeof schema['x-deprecated-sunset'] === 'string' ? (
<div className="openapi-deprecated-sunset openapi-schema-description openapi-markdown">
Sunset date:{' '}
<span className="openapi-deprecated-sunset-date">
@@ -228,7 +228,7 @@ function OpenAPISchemaPresentation(props: { property: OpenAPISchemaPropertyEntry
{description ? (
<Markdown source={description} className="openapi-schema-description" />
) : null}
{example ? (
{typeof example === 'string' ? (
<div className="openapi-schema-example">
Example: <code>{example}</code>
</div>
@@ -31,7 +31,7 @@ export function OpenAPISecurities(props: {
key: key,
label: key,
body: (
<div className="openapi-schema-body">
<div className="openapi-schema">
<div className="openapi-schema-presentation">
{getLabelForType(security)}
+2 -2
View File
@@ -1,5 +1,5 @@
export * from './models';
export * from './schemas';
export * from './OpenAPIOperation';
export * from './OpenAPIOperationContext';
export * from './resolveOpenAPIOperation';
export type { OpenAPIModelsData, OpenAPIOperationData } from './types';
export type { OpenAPISchemasData, OpenAPIOperationData } from './types';
@@ -1,2 +0,0 @@
export * from './OpenAPIModels';
export * from './resolveOpenAPIModels';
@@ -80,8 +80,8 @@ describe('#resolveOpenAPIOperation', () => {
it('should resolve circular refs', async () => {
const filesystem = await fetchFilesystem('https://api.gitbook.com/openapi.json');
const resolved = await resolveOpenAPIOperation(filesystem, {
method: 'post',
path: '/search/ask',
method: 'get',
path: '/spaces/{spaceId}/content/page/{pageId}',
});
expect(resolved).toMatchObject({
@@ -91,7 +91,7 @@ describe('#resolveOpenAPIOperation', () => {
},
],
operation: {
operationId: 'askQuery',
operationId: 'getPageById',
},
});
});
@@ -2,18 +2,18 @@ import clsx from 'clsx';
import { OpenAPIDisclosureGroup } from '../OpenAPIDisclosureGroup';
import { OpenAPIRootSchema } from '../OpenAPISchema';
import { Section, SectionBody } from '../StaticSection';
import type { OpenAPIClientContext, OpenAPIContextProps, OpenAPIModelsData } from '../types';
import type { OpenAPIClientContext, OpenAPIContextProps, OpenAPISchemasData } from '../types';
/**
* Display OpenAPI Models.
* Display OpenAPI Schemas.
*/
export function OpenAPIModels(props: {
export function OpenAPISchemas(props: {
className?: string;
data: OpenAPIModelsData;
data: OpenAPISchemasData;
context: OpenAPIContextProps;
}) {
const { className, data, context } = props;
const { models } = data;
const { schemas } = data;
const clientContext: OpenAPIClientContext = {
defaultInteractiveOpened: context.defaultInteractiveOpened,
@@ -21,30 +21,30 @@ export function OpenAPIModels(props: {
blockKey: context.blockKey,
};
if (!models.length) {
if (!schemas.length) {
return null;
}
return (
<div className={clsx('openapi-models', className)}>
<OpenAPIRootModelsSchema models={models} context={clientContext} />
<div className={clsx('openapi-schemas', className)}>
<OpenAPIRootSchemasSchema schemas={schemas} context={clientContext} />
</div>
);
}
/**
* Root schema for OpenAPI models.
* It displays a single model or a disclosure group for multiple models.
* Root schema for OpenAPI schemas.
* It displays a single model or a disclosure group for multiple schemas.
*/
function OpenAPIRootModelsSchema(props: {
models: OpenAPIModelsData['models'];
function OpenAPIRootSchemasSchema(props: {
schemas: OpenAPISchemasData['schemas'];
context: OpenAPIClientContext;
}) {
const { models, context } = props;
const { schemas, context } = props;
// If there is only one model, we show it directly.
if (models.length === 1) {
const schema = models?.[0]?.schema;
if (schemas.length === 1) {
const schema = schemas?.[0]?.schema;
if (!schema) {
return null;
@@ -59,12 +59,12 @@ function OpenAPIRootModelsSchema(props: {
);
}
// If there are multiple models, we use a disclosure group to show them all.
// If there are multiple schemas, we use a disclosure group to show them all.
return (
<OpenAPIDisclosureGroup
allowsMultipleExpanded
icon={context.icons.chevronRight}
groups={models.map(({ name, schema }) => ({
groups={schemas.map(({ name, schema }) => ({
id: name,
label: (
<div className="openapi-response-tab-content" key={`model-${name}`}>
@@ -75,7 +75,7 @@ function OpenAPIRootModelsSchema(props: {
{
id: 'model',
body: (
<Section className="openapi-section-models">
<Section className="openapi-section-schemas">
<SectionBody>
<OpenAPIRootSchema schema={schema} context={context} />
</SectionBody>
@@ -0,0 +1,2 @@
export * from './OpenAPISchemas';
export * from './resolveOpenAPISchemas';
@@ -6,28 +6,28 @@ import {
shouldIgnoreEntity,
} from '@gitbook/openapi-parser';
import { dereferenceFilesystem } from '../dereference';
import type { OpenAPIModel, OpenAPIModelsData } from '../types';
import type { OpenAPISchema, OpenAPISchemasData } from '../types';
//!!TODO: We should return only the models that are used in the block. Still a WIP awaiting future work.
//!!TODO: We should return only the schemas that are used in the block. Still a WIP awaiting future work.
/**
* Resolve an OpenAPI models from a file and compile it to a more usable format.
* Models are extracted from the OpenAPI components.schemas
* Resolve an OpenAPI schemas from a file and compile it to a more usable format.
* Schemas are extracted from the OpenAPI components.schemas
*/
export async function resolveOpenAPIModels(
export async function resolveOpenAPISchemas(
filesystem: Filesystem<OpenAPIV3xDocument>
): Promise<OpenAPIModelsData | null> {
): Promise<OpenAPISchemasData | null> {
const schema = await dereferenceFilesystem(filesystem);
const models = getOpenAPIComponents(schema);
const schemas = getOpenAPIComponents(schema);
return { models };
return { schemas };
}
/**
* Get OpenAPI components.schemas that are not ignored.
*/
function getOpenAPIComponents(schema: OpenAPIV3.Document | OpenAPIV3_1.Document): OpenAPIModel[] {
function getOpenAPIComponents(schema: OpenAPIV3.Document | OpenAPIV3_1.Document): OpenAPISchema[] {
const schemas = schema.components?.schemas ?? {};
return Object.entries(schemas)
.filter(([, schema]) => !shouldIgnoreEntity(schema))
+4 -4
View File
@@ -56,12 +56,12 @@ export interface OpenAPIOperationData extends OpenAPICustomSpecProperties {
securities: [string, OpenAPIV3.SecuritySchemeObject][];
}
export type OpenAPIModel = {
export type OpenAPISchema = {
name: string;
schema: OpenAPIV3.SchemaObject;
};
export interface OpenAPIModelsData {
/** Components schemas to be used for models */
models: OpenAPIModel[];
export interface OpenAPISchemasData {
/** Components schemas to be used for schemas */
schemas: OpenAPISchema[];
}
+2 -2
View File
@@ -51,12 +51,12 @@ export function extractDescriptions(object: AnyObject) {
/**
* Resolve the first example from an object.
*/
export function resolveFirstExample(object: AnyObject) {
export function resolveFirstExample(object: AnyObject): string | undefined {
if ('examples' in object && typeof object.examples === 'object' && object.examples) {
const keys = Object.keys(object.examples);
const firstKey = keys[0];
if (firstKey && object.examples[firstKey]) {
return object.examples[firstKey];
return formatExample(object.examples[firstKey]);
}
}
+12 -5
View File
@@ -1,7 +1,15 @@
{
"$schema": "https://turbo.build/schema.json",
"ui": "stream",
"globalEnv": ["NODE_ENV", "CI", "ARGOS_*", "GITHUB_*", "GITBOOK_*", "SENTRY_*"],
"globalEnv": [
"NODE_ENV",
"CI",
"ARGOS_*",
"GITHUB_*",
"GITBOOK_*",
"SENTRY_*",
"NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"
],
"tasks": {
// Prepare the package for all other tasks
"generate": {
@@ -25,8 +33,7 @@
},
// Build the package for Cloudflare Pages
"build:cloudflare": {
"dependsOn": ["^build", "generate"],
"env": ["NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"]
"dependsOn": ["^build", "generate"]
},
// Check the package for type errors
"typecheck": {
@@ -43,12 +50,12 @@
// Run end-to-end tests
"e2e": {
"dependsOn": ["^e2e"],
"env": ["BASE_URL"]
"env": ["BASE_URL", "SITE_BASE_URL"]
},
// Run end-to-end tests for customers
"e2e-customers": {
"dependsOn": ["^e2e-customers"],
"env": ["BASE_URL"]
"env": ["BASE_URL", "SITE_BASE_URL"]
},
// Start the package in development mode
"dev": {