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' name: 'Deploy cloudflare'
description: 'Deploy GitBook to Cloudflare' description: 'Deploy GitBook to Cloudflare'
inputs: inputs:
opItem:
description: '1Password item to load secrets from'
required: true
opServiceAccount:
description: '1Password service account token'
required: true
apiToken: apiToken:
description: 'Cloudflare API token' description: 'Cloudflare API token'
required: true required: true
@@ -8,44 +14,11 @@ inputs:
description: 'Cloudflare account ID' description: 'Cloudflare account ID'
required: true required: true
environment: environment:
description: 'Environment to deploy to' description: 'Cloudflare environment to deploy to (staging, production, preview)'
required: true required: true
deploy: deploy:
description: 'Deploy as main version for all traffic instead of uploading versions' description: 'Deploy as main version for all traffic instead of uploading versions'
required: true 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: outputs:
deployment-url: deployment-url:
description: "Deployment URL" description: "Deployment URL"
@@ -60,21 +33,25 @@ runs:
shell: bash shell: bash
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 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 - name: Build worker
run: bun run turbo build:v2:cloudflare run: bun run turbo build:v2:cloudflare
shell: bash 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 - id: deploy
name: Deploy to Cloudflare name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3.14.0 uses: cloudflare/wrangler-action@v3.14.0
@@ -84,7 +61,7 @@ runs:
workingDirectory: ./ workingDirectory: ./
wranglerVersion: '3.112.0' wranglerVersion: '3.112.0'
environment: ${{ inputs.environment }} 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 - name: Outputs
shell: bash shell: bash
env: env:
+33 -16
View File
@@ -1,15 +1,21 @@
name: 'Deploy vercel' name: 'Deploy vercel'
description: 'Deploy GitBook to Vercel' description: 'Deploy GitBook to Vercel'
inputs: inputs:
vercel-org: vercelOrg:
description: 'Vercel organization' description: 'Vercel organization'
required: true required: true
vercel-project: vercelProject:
description: 'Vercel project' description: 'Vercel project'
required: true required: true
vercel-token: vercelToken:
description: 'Vercel token' description: 'Vercel token'
required: true required: true
opItem:
description: '1Password item to load secrets from'
required: true
opServiceAccount:
description: '1Password service account token'
required: true
environment: environment:
description: 'Environment to deploy to' description: 'Environment to deploy to'
required: true required: true
@@ -27,31 +33,42 @@ runs:
shell: bash shell: bash
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 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 - 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 shell: bash
env: env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }} VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }} 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 - 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 shell: bash
env: env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }} VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }} VERCEL_PROJECT_ID: ${{ inputs.vercelProject }}
- name: Deploy Project Artifacts to Vercel - name: Deploy Project Artifacts to Vercel
id: deploy id: deploy
shell: bash shell: bash
run: | 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" echo "deployment-url=$DEPLOYMENT_URL" >> "$GITHUB_OUTPUT"
env: env:
VERCEL_ORG_ID: ${{ inputs.vercel-org }} VERCEL_ORG_ID: ${{ inputs.vercelOrg }}
VERCEL_PROJECT_ID: ${{ inputs.vercel-project }} VERCEL_PROJECT_ID: ${{ inputs.vercelProject }}
- name: Outputs - name: Outputs
shell: bash shell: bash
run: | run: |
+26 -32
View File
@@ -10,6 +10,9 @@ jobs:
deploy-v1-cloudflare: deploy-v1-cloudflare:
name: Deploy v1 to Cloudflare Pages name: Deploy v1 to Cloudflare Pages
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment:
name: ${{ github.ref == 'refs/heads/main' && '1c-production' || '1c-preview' }}
url: ${{ steps.deploy.outputs.deployment-url }}
permissions: permissions:
contents: read contents: read
deployments: write deployments: write
@@ -63,56 +66,45 @@ jobs:
deploy-v2-vercel: deploy-v2-vercel:
name: Deploy v2 to Vercel (preview) name: Deploy v2 to Vercel (preview)
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: environment:
contents: read name: 2v-preview
deployments: write url: ${{ steps.deploy.outputs.deployment-url }}
issues: write
pull-requests: write
checks: write
statuses: write
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }} - name: Deploy to Vercel
id: deploy id: deploy
uses: ./.github/composite/deploy-vercel uses: ./.github/composite/deploy-vercel
with: with:
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }} environment: preview
vercel-org: ${{ secrets.VERCEL_ORG_ID }} vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }} vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }} vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-preview
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare: deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (preview) name: Deploy v2 to Cloudflare Worker (preview)
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: environment:
contents: read name: 2c-preview
deployments: write url: ${{ steps.deploy.outputs.deployment-url }}
issues: write
pull-requests: write
checks: write
statuses: write
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }} - name: Deploy to Cloudflare
id: deploy id: deploy
uses: ./.github/composite/deploy-cloudflare uses: ./.github/composite/deploy-cloudflare
with: with:
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }} environment: preview
deploy: ${{ github.ref == 'refs/heads/main' }} deploy: ${{ github.ref == 'refs/heads/main' }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} opItem: op://gitbook-open/2c-preview
GITBOOK_URL: ${{ github.ref == 'refs/heads/main' && vars.PRODUCTION_2C_GITBOOK_URL || vars.PREVIEW_2C_GITBOOK_URL }} opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
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|| '' }}
- name: Outputs - name: Outputs
run: | run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}" echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
@@ -198,7 +190,8 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e run: bun e2e
env: 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_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'v2-vercel' ARGOS_BUILD_NAME: 'v2-vercel'
visual-testing-customers-v1: visual-testing-customers-v1:
@@ -238,7 +231,8 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: bun e2e-customers run: bun e2e-customers
env: 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_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: 'customers-v2' ARGOS_BUILD_NAME: 'customers-v2'
pagespeed-testing-v1: pagespeed-testing-v1:
@@ -255,7 +249,7 @@ jobs:
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 PUPPETEER_SKIP_DOWNLOAD: 1
- name: Run pagespeed tests - name: Run pagespeed tests
run: bun ./packages/gitbook/tests/pagespeed-testing.ts $DEPLOYMENT_URL run: bun ./packages/gitbook/tests/pagespeed-testing.ts
env: 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 }} PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
+16 -12
View File
@@ -9,6 +9,9 @@ jobs:
deploy-v2-vercel: deploy-v2-vercel:
name: Deploy v2 to Vercel (production) name: Deploy v2 to Vercel (production)
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment:
name: 2v-production
url: ${{ steps.deploy.outputs.deployment-url }}
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
@@ -18,13 +21,18 @@ jobs:
id: deploy id: deploy
uses: ./.github/composite/deploy-vercel uses: ./.github/composite/deploy-vercel
with: with:
environment: production environment: production
vercel-org: ${{ secrets.VERCEL_ORG_ID }} vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }} vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }} vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-production
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare: deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (production) name: Deploy v2 to Cloudflare Worker (production)
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment:
name: 2c-production
url: ${{ steps.deploy.outputs.deployment-url }}
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
@@ -34,16 +42,12 @@ jobs:
id: deploy id: deploy
uses: ./.github/composite/deploy-cloudflare uses: ./.github/composite/deploy-cloudflare
with: with:
environment: staging environment: production
deploy: true
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} opItem: op://gitbook-open/2c-production
GITBOOK_URL: ${{ vars.STAGING_2C_GITBOOK_URL }} opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
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 }}
- name: Outputs - name: Outputs
run: | run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}" echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+14 -15
View File
@@ -9,6 +9,9 @@ jobs:
deploy-v2-vercel: deploy-v2-vercel:
name: Deploy v2 to Vercel (staging) name: Deploy v2 to Vercel (staging)
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment:
name: 2v-staging
url: ${{ steps.deploy.outputs.deployment-url }}
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
@@ -18,13 +21,18 @@ jobs:
id: deploy id: deploy
uses: ./.github/composite/deploy-vercel uses: ./.github/composite/deploy-vercel
with: with:
environment: staging environment: staging
vercel-org: ${{ secrets.VERCEL_ORG_ID }} vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }} vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-token: ${{ secrets.VERCEL_TOKEN }} vercelToken: ${{ secrets.VERCEL_TOKEN }}
opItem: op://gitbook-open/2v-staging
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
deploy-v2-cloudflare: deploy-v2-cloudflare:
name: Deploy v2 to Cloudflare Worker (staging) name: Deploy v2 to Cloudflare Worker (staging)
runs-on: ubuntu-latest runs-on: ubuntu-latest
environment:
name: 2c-staging
url: ${{ steps.deploy.outputs.deployment-url }}
outputs: outputs:
deployment-url: ${{ steps.deploy.outputs.deployment-url }} deployment-url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
@@ -38,17 +46,8 @@ jobs:
deploy: true deploy: true
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} opItem: op://gitbook-open/2c-staging
GITBOOK_URL: ${{ vars.STAGING_2C_GITBOOK_URL }} opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
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 }}
- name: Outputs - name: Outputs
run: | run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}" echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
+6 -7
View File
@@ -49,7 +49,7 @@
}, },
"packages/gitbook": { "packages/gitbook": {
"name": "gitbook", "name": "gitbook",
"version": "0.6.5", "version": "0.7.2",
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/cache-do": "workspace:*", "@gitbook/cache-do": "workspace:*",
@@ -132,7 +132,7 @@
}, },
"packages/gitbook-v2": { "packages/gitbook-v2": {
"name": "gitbook-v2", "name": "gitbook-v2",
"version": "0.1.2", "version": "0.2.0",
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/cache-tags": "workspace:*", "@gitbook/cache-tags": "workspace:*",
@@ -144,7 +144,7 @@
"warn-once": "^0.1.1", "warn-once": "^0.1.1",
}, },
"devDependencies": { "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": "*", "gitbook": "*",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
@@ -172,7 +172,7 @@
}, },
"packages/openapi-parser": { "packages/openapi-parser": {
"name": "@gitbook/openapi-parser", "name": "@gitbook/openapi-parser",
"version": "2.0.2", "version": "2.1.0",
"dependencies": { "dependencies": {
"@scalar/openapi-parser": "^0.10.9", "@scalar/openapi-parser": "^0.10.9",
"@scalar/openapi-types": "^0.1.9", "@scalar/openapi-types": "^0.1.9",
@@ -198,7 +198,6 @@
"dependencies": { "dependencies": {
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"@gitbook/icons": "workspace:*", "@gitbook/icons": "workspace:*",
"assert-never": "^1.2.1",
"classnames": "^2.5.1", "classnames": "^2.5.1",
}, },
"devDependencies": { "devDependencies": {
@@ -227,7 +226,7 @@
}, },
"packages/react-openapi": { "packages/react-openapi": {
"name": "@gitbook/react-openapi", "name": "@gitbook/react-openapi",
"version": "1.0.5", "version": "1.1.2",
"dependencies": { "dependencies": {
"@gitbook/openapi-parser": "workspace:*", "@gitbook/openapi-parser": "workspace:*",
"@scalar/api-client-react": "^1.1.36", "@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/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=="], "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+9 -4
View File
@@ -10,16 +10,21 @@ const nextConfig = {
env: { env: {
BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7), 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_API_URL: process.env.GITBOOK_API_URL,
GITBOOK_APP_URL: process.env.GITBOOK_APP_URL, GITBOOK_APP_URL: process.env.GITBOOK_APP_URL,
GITBOOK_INTEGRATIONS_HOST: process.env.GITBOOK_INTEGRATIONS_HOST, 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_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_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN, 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, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
// Used to detect if the app is running in V2 mode // Used to detect if the app is running in V2 mode
+1 -1
View File
@@ -14,7 +14,7 @@
}, },
"devDependencies": { "devDependencies": {
"gitbook": "*", "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", "tailwindcss": "^3.4.0",
"postcss": "^8" "postcss": "^8"
}, },
@@ -16,7 +16,7 @@ export default async function Page(props: PageProps) {
const context = await getDynamicSiteContext(params); const context = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(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> { 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> { 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 context = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params); const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({ return generateSitePageMetadata({
context, context,
pageParams: { pathname }, 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> { export async function generateViewport(props: PageProps): Promise<Viewport> {
@@ -44,6 +44,5 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
return generateSitePageMetadata({ return generateSitePageMetadata({
context, context,
pageParams: { pathname }, pageParams: { pathname },
redirectOnFallback: true,
}); });
} }
+10
View File
@@ -1,11 +1,15 @@
import { type NextRequest, NextResponse } from 'next/server'; import { type NextRequest, NextResponse } from 'next/server';
import { import {
GITBOOK_API_TOKEN,
GITBOOK_API_URL, GITBOOK_API_URL,
GITBOOK_APP_URL, GITBOOK_APP_URL,
GITBOOK_ASSETS_URL, GITBOOK_ASSETS_URL,
GITBOOK_DISABLE_TRACKING, GITBOOK_DISABLE_TRACKING,
GITBOOK_ICONS_URL,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_INTEGRATIONS_HOST, GITBOOK_INTEGRATIONS_HOST,
GITBOOK_SECRET,
GITBOOK_URL, GITBOOK_URL,
GITBOOK_USER_AGENT, GITBOOK_USER_AGENT,
} from '@v2/lib/env'; } from '@v2/lib/env';
@@ -19,8 +23,14 @@ export async function GET(_req: NextRequest) {
GITBOOK_APP_URL, GITBOOK_APP_URL,
GITBOOK_API_URL, GITBOOK_API_URL,
GITBOOK_ASSETS_URL, GITBOOK_ASSETS_URL,
GITBOOK_ICONS_URL,
GITBOOK_USER_AGENT, GITBOOK_USER_AGENT,
GITBOOK_INTEGRATIONS_HOST, GITBOOK_INTEGRATIONS_HOST,
GITBOOK_DISABLE_TRACKING, 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, apiToken: input.apiToken ?? GITBOOK_API_TOKEN,
apiEndpoint: GITBOOK_API_URL, apiEndpoint: GITBOOK_API_URL,
}); });
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
const linker = const linker = getLinkerForSiteURL({
urlMode === 'url-host' siteURL: url,
? createLinker({ urlMode,
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 imageResizer = createImageResizer({ const imageResizer = createImageResizer({
host: url.host, 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. * 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) { if (error instanceof GitBookAPIError) {
return { return {
code: error.code, code: error.code,
@@ -3,3 +3,4 @@ export * from './types';
export * from './pages'; export * from './pages';
export * from './urls'; export * from './urls';
export * from './errors'; 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. * 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. * 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. * Main host on which GitBook is running.
*/ */
@@ -14,12 +22,12 @@ export const GITBOOK_URL =
export const GITBOOK_ASSETS_URL = export const GITBOOK_ASSETS_URL =
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? 'http://localhost:3000' ? 'http://localhost:3000'
: process.env.GITBOOK_ASSETS_PREFIX || GITBOOK_URL; : process.env.GITBOOK_ASSETS_PREFIX;
/** /**
* GitBook app URL. * GitBook app URL.
*/ */
export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL || 'https://app.gitbook.com'; export const GITBOOK_APP_URL = process.env.GITBOOK_APP_URL || 'https://app.gitbook.com';
/** /**
* Default GitBook API URL endpoint. * 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. * Default GitBook API token.
* It can be use to avoid rate-limiting. * 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. * 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 = export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null; 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. * 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 * The visitor token used to access this content
*/ */
VisitorAuthToken = 'x-gitbook-visitor-token', 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; 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 type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { getContentSecurityPolicy } from '@/lib/csp'; import { getContentSecurityPolicy } from '@/lib/csp';
import { validateSerializedCustomization } from '@/lib/customization'; import { validateSerializedCustomization } from '@/lib/customization';
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths'; 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 { 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 { isGitBookAssetsHostURL, isGitBookHostURL } from '@v2/lib/env';
import { MiddlewareHeaders } from '@v2/lib/middleware'; import { MiddlewareHeaders } from '@v2/lib/middleware';
@@ -21,27 +33,21 @@ type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
try { try {
// Route all requests to a site const requestURL = new URL(request.url);
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,
});
}
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(); return NextResponse.next();
} catch (error) { } catch (error) {
return serveErrorResponse(error as 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) { async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
const { url, mode } = urlWithMode; const match = getSiteURLFromRequest(request);
if (!match) {
// Visitor authentication return null;
// @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;
} }
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) { 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); 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. // When visitor has authentication (adaptive content or VA), we serve dynamic routes.
let routeType = visitorToken ? 'dynamic' : 'static'; let routeType = visitorToken ? 'dynamic' : 'static';
const requestHeaders = new Headers(request.headers); const requestHeaders = new Headers(request.headers);
requestHeaders.set(MiddlewareHeaders.RouteType, routeType); requestHeaders.set(MiddlewareHeaders.RouteType, routeType);
requestHeaders.set(MiddlewareHeaders.URLMode, mode); 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)); requestHeaders.set(MiddlewareHeaders.SiteURLData, JSON.stringify(data));
// Preview of customization/theme // Preview of customization/theme
const customization = url.searchParams.get('customization'); const customization = siteURL.searchParams.get('customization');
if (customization && validateSerializedCustomization(customization)) { if (customization && validateSerializedCustomization(customization)) {
routeType = 'dynamic'; routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Customization, customization); requestHeaders.set(MiddlewareHeaders.Customization, customization);
} }
const theme = url.searchParams.get('theme'); const theme = siteURL.searchParams.get('theme');
if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) { if (theme === CustomizationThemeMode.Dark || theme === CustomizationThemeMode.Light) {
routeType = 'dynamic'; routeType = 'dynamic';
requestHeaders.set(MiddlewareHeaders.Theme, theme); 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('x-forwarded-host', request.nextUrl.host);
requestHeaders.set('origin', request.nextUrl.origin); 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 = [ const route = [
'sites', 'sites',
routeType, routeType,
mode, mode,
encodeURIComponent(siteURL), encodeURIComponent(siteURLWithoutProtocol),
encodePathInSiteContent(data.pathname), pathname,
].join('/'); ].join('/');
console.log(`rewriting ${request.nextUrl.toString()} to ${route}`); 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'); response.headers.set('x-content-type-options', 'nosniff');
// Debug header // Debug header
response.headers.set('x-gitbook-route-type', routeType); 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) { return writeResponseCookies(response, cookies);
const cookies = getResponseCookiesForVisitorAuth(data.basePath, visitorToken); }
for (const [key, value] of Object.entries(cookies)) {
response.cookies.set(key, value.value, value.options); /**
} * 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. * Serve an error response.
*/ */
function serveErrorResponse(error: Error) { function serveErrorResponse(error: Error) {
if (error instanceof GitBookAPIError) { if (error instanceof DataFetcherError) {
return new Response(error.errorMessage, { return new Response(error.message, {
status: error.code, status: error.code,
headers: { 'content-type': 'text/plain' }, headers: { 'content-type': 'text/plain' },
}); });
@@ -219,22 +332,27 @@ function getSiteURLFromRequest(request: NextRequest): URLWithMode | null {
* Encode path in a site content. * Encode path in a site content.
* Special paths are not encoded and passed to be handled by the route handlers. * 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)); const pathname = removeLeadingSlash(removeTrailingSlash(rawPathname));
if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) { if (pathname.match(/^~gitbook\/ogimage\/\S+$/)) {
return pathname; return { pathname };
} }
switch (pathname) { switch (pathname) {
case '~gitbook/icon': case '~gitbook/icon':
case '~gitbook/image':
case 'llms.txt': case 'llms.txt':
case 'sitemap.xml': case 'sitemap.xml':
case 'robots.txt': 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: default:
return encodeURIComponent(pathname || '/'); return { pathname: encodeURIComponent(pathname || '/') };
} }
} }
@@ -248,3 +366,14 @@ function appendQueryParams(url: URL, from: URLSearchParams) {
return url; 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 # 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 ## 0.7.0
### Minor Changes ### Minor Changes
+45 -45
View File
@@ -4,7 +4,7 @@ import { type TestsCase, runTestCases } from './util';
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
{ {
name: 'Snyk', name: 'Snyk',
baseUrl: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [ tests: [
{ name: 'Home', url: '/' }, { name: 'Home', url: '/' },
{ name: 'OpenAPI', url: '/snyk-api/reference/apps' }, { name: 'OpenAPI', url: '/snyk-api/reference/apps' },
@@ -12,222 +12,222 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Nexthink', name: 'Nexthink',
baseUrl: 'https://docs.nexthink.com', contentBaseURL: 'https://docs.nexthink.com',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'asiksupport-stg.dto.kemkes.go.id', 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: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'jasons-tutorials.gitbook.io', name: 'jasons-tutorials.gitbook.io',
baseUrl: 'https://jasons-tutorials.gitbook.io', contentBaseURL: 'https://jasons-tutorials.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'faq.deltaemulator.com', name: 'faq.deltaemulator.com',
baseUrl: 'https://faq.deltaemulator.com', contentBaseURL: 'https://faq.deltaemulator.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.dify.ai', name: 'docs.dify.ai',
baseUrl: 'https://docs.dify.ai', contentBaseURL: 'https://docs.dify.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'seeddao.gitbook.io', name: 'seeddao.gitbook.io',
baseUrl: 'https://seeddao.gitbook.io', contentBaseURL: 'https://seeddao.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'faq.altstore.io', name: 'faq.altstore.io',
baseUrl: 'https://faq.altstore.io', contentBaseURL: 'https://faq.altstore.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'support.audacityteam.org', name: 'support.audacityteam.org',
baseUrl: 'https://support.audacityteam.org', contentBaseURL: 'https://support.audacityteam.org',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.gmgn.ai', name: 'docs.gmgn.ai',
baseUrl: 'https://docs.gmgn.ai', contentBaseURL: 'https://docs.gmgn.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.spicychat.ai', name: 'docs.spicychat.ai',
baseUrl: 'https://docs.spicychat.ai', contentBaseURL: 'https://docs.spicychat.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.portainer.io', name: 'docs.portainer.io',
baseUrl: 'https://docs.portainer.io', contentBaseURL: 'https://docs.portainer.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.chirptoken.io', name: 'docs.chirptoken.io',
baseUrl: 'https://docs.chirptoken.io', contentBaseURL: 'https://docs.chirptoken.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.dexscreener.com', name: 'docs.dexscreener.com',
baseUrl: 'https://docs.dexscreener.com', contentBaseURL: 'https://docs.dexscreener.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.pancakeswap.finance', name: 'docs.pancakeswap.finance',
baseUrl: 'https://docs.pancakeswap.finance', contentBaseURL: 'https://docs.pancakeswap.finance',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'book.character.ai', name: 'book.character.ai',
baseUrl: 'https://book.character.ai', contentBaseURL: 'https://book.character.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.tradeonnova.io', name: 'docs.tradeonnova.io',
baseUrl: 'https://docs.tradeonnova.io', contentBaseURL: 'https://docs.tradeonnova.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'azcoiner.gitbook.io', name: 'azcoiner.gitbook.io',
baseUrl: 'https://azcoiner.gitbook.io', contentBaseURL: 'https://azcoiner.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.midas.app', name: 'docs.midas.app',
baseUrl: 'https://docs.midas.app', contentBaseURL: 'https://docs.midas.app',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.keeper.io', name: 'docs.keeper.io',
baseUrl: 'https://docs.keeper.io', contentBaseURL: 'https://docs.keeper.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'adiblar.gitbook.io', name: 'adiblar.gitbook.io',
baseUrl: 'https://adiblar.gitbook.io', contentBaseURL: 'https://adiblar.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.gradient.network', name: 'docs.gradient.network',
baseUrl: 'https://docs.gradient.network', contentBaseURL: 'https://docs.gradient.network',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'mygate-network.gitbook.io', name: 'mygate-network.gitbook.io',
baseUrl: 'https://mygate-network.gitbook.io', contentBaseURL: 'https://mygate-network.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'treasurenft.gitbook.io', name: 'treasurenft.gitbook.io',
baseUrl: 'https://treasurenft.gitbook.io', contentBaseURL: 'https://treasurenft.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'browndust2.gitbook.io', name: 'browndust2.gitbook.io',
baseUrl: 'https://browndust2.gitbook.io', contentBaseURL: 'https://browndust2.gitbook.io',
tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'junookyo.gitbook.io', name: 'junookyo.gitbook.io',
baseUrl: 'https://junookyo.gitbook.io', contentBaseURL: 'https://junookyo.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'meshnet.nordvpn.com', name: 'meshnet.nordvpn.com',
baseUrl: 'https://meshnet.nordvpn.com', contentBaseURL: 'https://meshnet.nordvpn.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'manual.bubble.io', name: 'manual.bubble.io',
baseUrl: 'https://manual.bubble.io', contentBaseURL: 'https://manual.bubble.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.tickettool.xyz', name: 'docs.tickettool.xyz',
baseUrl: 'https://docs.tickettool.xyz', contentBaseURL: 'https://docs.tickettool.xyz',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'wiki.redmodding.org', name: 'wiki.redmodding.org',
baseUrl: 'https://wiki.redmodding.org', contentBaseURL: 'https://wiki.redmodding.org',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.cherry-ai.com', name: 'docs.cherry-ai.com',
baseUrl: 'https://docs.cherry-ai.com', contentBaseURL: 'https://docs.cherry-ai.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.snyk.io', name: 'docs.snyk.io',
baseUrl: 'https://docs.snyk.io', contentBaseURL: 'https://docs.snyk.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.realapp.link', name: 'docs.realapp.link',
baseUrl: 'https://docs.realapp.link', contentBaseURL: 'https://docs.realapp.link',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.plaza.finance', name: 'docs.plaza.finance',
baseUrl: 'https://docs.plaza.finance', contentBaseURL: 'https://docs.plaza.finance',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.publicai.io', name: 'docs.publicai.io',
baseUrl: 'https://docs.publicai.io', contentBaseURL: 'https://docs.publicai.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'hyperliquid.gitbook.io', name: 'hyperliquid.gitbook.io',
baseUrl: 'https://hyperliquid.gitbook.io', contentBaseURL: 'https://hyperliquid.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.umbraco.com', name: 'docs.umbraco.com',
baseUrl: 'https://docs.umbraco.com', contentBaseURL: 'https://docs.umbraco.com',
tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }], tests: [{ name: 'Home', url: '/welcome', screenshot: { waitForTOCScrolling: false } }],
}, },
{ {
name: 'sosovalue-white-paper.gitbook.io', name: 'sosovalue-white-paper.gitbook.io',
baseUrl: 'https://sosovalue-white-paper.gitbook.io', contentBaseURL: 'https://sosovalue-white-paper.gitbook.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.revrobotics.com', name: 'docs.revrobotics.com',
baseUrl: 'https://docs.revrobotics.com', contentBaseURL: 'https://docs.revrobotics.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'chartschool.stockcharts.com', name: 'chartschool.stockcharts.com',
baseUrl: 'https://chartschool.stockcharts.com', contentBaseURL: 'https://chartschool.stockcharts.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.soniclabs.com', name: 'docs.soniclabs.com',
baseUrl: 'https://docs.soniclabs.com', contentBaseURL: 'https://docs.soniclabs.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.meshchain.ai', name: 'docs.meshchain.ai',
baseUrl: 'https://docs.meshchain.ai', contentBaseURL: 'https://docs.meshchain.ai',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.thousandeyes.com', name: 'docs.thousandeyes.com',
baseUrl: 'https://docs.thousandeyes.com', contentBaseURL: 'https://docs.thousandeyes.com',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.raydium.io', name: 'docs.raydium.io',
baseUrl: 'https://docs.raydium.io', contentBaseURL: 'https://docs.raydium.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
{ {
name: 'docs.fluentbit.io', name: 'docs.fluentbit.io',
baseUrl: 'https://docs.fluentbit.io', contentBaseURL: 'https://docs.fluentbit.io',
tests: [{ name: 'Home', url: '/' }], tests: [{ name: 'Home', url: '/' }],
}, },
]; ];
+113 -63
View File
@@ -14,6 +14,7 @@ import {
getVisitorAuthCookieValue, getVisitorAuthCookieValue,
} from '@/lib/visitor-token'; } from '@/lib/visitor-token';
import { getSiteAPIToken } from '../tests/utils';
import { import {
type TestsCase, type TestsCase,
allDeprecatedThemePresets, allDeprecatedThemePresets,
@@ -31,7 +32,7 @@ import {
const testCases: TestsCase[] = [ const testCases: TestsCase[] = [
{ {
name: 'GitBook Site (Single Variant)', 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: [ tests: [
{ {
name: 'Home', name: 'Home',
@@ -84,7 +85,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'GitBook Site (Multi Variants)', 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: [ tests: [
{ {
name: 'Variants dropdown', name: 'Variants dropdown',
@@ -135,7 +136,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'GitBook Site (Navigation when switching variant)', name: 'GitBook Site (Navigation when switching variant)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/',
tests: [ tests: [
{ {
name: 'Keep navigation path/route when switching variant (Public)', name: 'Keep navigation path/route when switching variant (Public)',
@@ -155,8 +156,8 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true' url.pathname.includes('api-multi-versions/2.0/reference/api-reference/pets')
); );
}, },
}, },
@@ -178,15 +179,17 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true' url.pathname.includes(
'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets'
)
); );
}, },
}, },
{ {
name: 'Keep navigation path/route when switching variant (VA)', name: 'Keep navigation path/route when switching variant (VA)',
screenshot: false, screenshot: false,
url: (() => { url: () => {
const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953'; const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -198,7 +201,7 @@ const testCases: TestsCase[] = [
} }
); );
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`; return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const spaceDrowpdown = await page const spaceDrowpdown = await page
.locator('[data-testid="space-dropdown-button"]') .locator('[data-testid="space-dropdown-button"]')
@@ -213,8 +216,10 @@ const testCases: TestsCase[] = [
.click(); .click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant // It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL( await page.waitForURL((url) =>
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true' 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)', 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: [ tests: [
{ {
name: 'Site with sections and section groups', name: 'Site with sections and section groups',
@@ -244,16 +249,14 @@ const testCases: TestsCase[] = [
const sectionGroupDropdown = await page.getByText('Test Section Group 1'); const sectionGroupDropdown = await page.getByText('Test Section Group 1');
await sectionGroupDropdown.hover(); await sectionGroupDropdown.hover();
await page.getByText('Section B').click(); await page.getByText('Section B').click();
await page.waitForURL( await page.waitForURL((url) => url.pathname.includes('/sections/sections-4'));
'https://gitbook-open-e2e-sites.gitbook.io/sections/sections-4'
);
}, },
}, },
], ],
}, },
{ {
name: 'GitBook', name: 'GitBook',
baseUrl: 'https://docs.gitbook.com', contentBaseURL: 'https://docs.gitbook.com',
tests: [ tests: [
{ {
name: 'Home', name: 'Home',
@@ -297,7 +300,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Versioning', name: 'Versioning',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Revision', name: 'Revision',
@@ -308,7 +311,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'PDF', name: 'PDF',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'PDF', name: 'PDF',
@@ -316,12 +319,56 @@ const testCases: TestsCase[] = [
screenshot: { screenshot: {
waitForTOCScrolling: false, 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', name: 'Content tests',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Text', name: 'Text',
@@ -484,7 +531,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Page options', name: 'Page options',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Hidden', name: 'Hidden',
@@ -518,7 +565,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Customization', name: 'Customization',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allThemeModes.flatMap((themeMode) => [ tests: allThemeModes.flatMap((themeMode) => [
{ {
name: `Without header - Theme mode ${themeMode}`, name: `Without header - Theme mode ${themeMode}`,
@@ -652,7 +699,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Ads', name: 'Ads',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Without previewed ads', name: 'Without previewed ads',
@@ -663,7 +710,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Shared space navigation (first site)', 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: [ tests: [
{ {
name: 'Navigation to shared space', name: 'Navigation to shared space',
@@ -684,7 +731,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Shared space navigation (second site)', 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: [ tests: [
{ {
name: 'Navigation to shared space', name: 'Navigation to shared space',
@@ -704,7 +751,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Site Redirects', name: 'Site Redirects',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/', contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [ tests: [
{ {
name: 'Redirect to SSO page', name: 'Redirect to SSO page',
@@ -718,7 +765,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Share links', name: 'Share links',
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
tests: [ tests: [
{ {
name: 'Valid link', name: 'Valid link',
@@ -738,11 +785,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Space', name: 'Visitor Auth - Space',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-space/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-space/',
tests: [ tests: [
{ {
name: 'First', name: 'First',
url: (() => { url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537'; const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -754,7 +801,7 @@ const testCases: TestsCase[] = [
} }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }) page.getByRole('heading', { level: 1, name: 'first' })
@@ -764,7 +811,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Second', name: 'Second',
url: (() => { url: () => {
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537'; const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -776,7 +823,7 @@ const testCases: TestsCase[] = [
} }
); );
return `second?jwt_token=${token}`; return `second?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'second' }) page.getByRole('heading', { level: 1, name: 'second' })
@@ -788,11 +835,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Visitor Auth - Collection', name: 'Visitor Auth - Collection',
baseUrl: 'https://gitbook.gitbook.io/gbo-va-collection/', contentBaseURL: 'https://gitbook.gitbook.io/gbo-va-collection/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -804,12 +851,12 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Primary (Space A)', name: 'Primary (Space A)',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -820,13 +867,16 @@ const testCases: TestsCase[] = [
expiresIn: '24h', 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}`; return `spacea?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Space B', name: 'Space B',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -838,12 +888,12 @@ const testCases: TestsCase[] = [
} }
); );
return `spaceb?jwt_token=${token}`; return `spaceb?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Space C', name: 'Space C',
url: (() => { url: () => {
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980'; const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -855,18 +905,18 @@ const testCases: TestsCase[] = [
} }
); );
return `spacec?jwt_token=${token}`; return `spacec?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
], ],
}, },
{ {
name: 'Visitor Auth - Space (custom domain)', name: 'Visitor Auth - Space (custom domain)',
baseUrl: 'https://test.gitbook.community/', contentBaseURL: 'https://test.gitbook.community/',
tests: [ tests: [
{ {
name: 'Root', name: 'Root',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -878,12 +928,12 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'First', name: 'First',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -895,7 +945,7 @@ const testCases: TestsCase[] = [
} }
); );
return `first?jwt_token=${token}`; return `first?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect( await expect(
page.getByRole('heading', { level: 1, name: 'first' }) page.getByRole('heading', { level: 1, name: 'first' })
@@ -905,7 +955,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Custom page', name: 'Custom page',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -917,12 +967,12 @@ const testCases: TestsCase[] = [
} }
); );
return `custom-page?jwt_token=${token}`; return `custom-page?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
{ {
name: 'Inner page', name: 'Inner page',
url: (() => { url: () => {
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021'; const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -934,14 +984,14 @@ const testCases: TestsCase[] = [
} }
); );
return `custom-page/inner-page?jwt_token=${token}`; return `custom-page/inner-page?jwt_token=${token}`;
})(), },
run: waitForCookiesDialog, run: waitForCookiesDialog,
}, },
], ],
}, },
{ {
name: 'Visitor Auth - Site (redirects to fallback/auth URL)', 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: [ tests: [
{ {
name: 'Redirect to fallback on invalid token pulled from cookie', 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', name: 'Show error message when invalid token is passed to url',
screenshot: false, screenshot: false,
url: (() => { url: () => {
const token = jwt.sign( const token = jwt.sign(
{ {
name: 'gitbook-open-tests', name: 'gitbook-open-tests',
@@ -984,7 +1034,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
await expect(page.locator('pre')).toContainText( await expect(page.locator('pre')).toContainText(
'Error while validating the JWT token. Reason: The token signature is invalid.' 'Error while validating the JWT token. Reason: The token signature is invalid.'
@@ -995,7 +1045,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Languages', name: 'Languages',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allLocales.map((locale) => ({ tests: allLocales.map((locale) => ({
name: locale, name: locale,
url: getCustomizationURL({ url: getCustomizationURL({
@@ -1011,7 +1061,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'SEO', name: 'SEO',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Index by default', name: 'Index by default',
@@ -1062,11 +1112,11 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - VA', 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: [ tests: [
{ {
name: 'isAlphaUser', name: 'isAlphaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1079,7 +1129,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1093,7 +1143,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'isBetaUser', name: 'isBetaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1106,7 +1156,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1120,7 +1170,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'isAlphaUser & isBetaUser', name: 'isAlphaUser & isBetaUser',
url: (() => { url: () => {
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9'; const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
const token = jwt.sign( const token = jwt.sign(
{ {
@@ -1134,7 +1184,7 @@ const testCases: TestsCase[] = [
} }
); );
return `?jwt_token=${token}`; return `?jwt_token=${token}`;
})(), },
run: async (page) => { run: async (page) => {
const alphaUserPage = page const alphaUserPage = page
.locator('a[class*="group\\/toclink"]') .locator('a[class*="group\\/toclink"]')
@@ -1150,7 +1200,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Adaptive Content - Public', 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: [ tests: [
{ {
name: 'No custom cookie', name: 'No custom cookie',
@@ -1293,7 +1343,7 @@ const testCases: TestsCase[] = [
}, },
{ {
name: 'Tables', name: 'Tables',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [ tests: [
{ {
name: 'Default table', name: 'Default table',
+13 -8
View File
@@ -20,14 +20,14 @@ import deepMerge from 'deepmerge';
import rison from 'rison'; import rison from 'rison';
import type { DeepPartial } from 'ts-essentials'; import type { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils'; import { getContentTestURL, getTestURL } from '../tests/utils';
export interface Test { export interface Test {
name: string; name: string;
/** /**
* URL to visit for testing. * URL to visit for testing.
*/ */
url: string; url: string | (() => string | Promise<string>);
cookies?: Parameters<BrowserContext['addCookies']>[0]; cookies?: Parameters<BrowserContext['addCookies']>[0];
/** /**
* Test to run * Test to run
@@ -60,11 +60,11 @@ export interface Test {
only?: boolean; only?: boolean;
} }
export interface TestsCase { export type TestsCase = {
name: string; name: string;
baseUrl: string;
tests: Array<Test>; tests: Array<Test>;
} contentBaseURL?: string;
};
export const allLocales: CustomizationLocale[] = [ export const allLocales: CustomizationLocale[] = [
CustomizationLocale.Fr, CustomizationLocale.Fr,
@@ -142,9 +142,14 @@ export function runTestCases(testCases: TestsCase[]) {
test.describe(testCase.name, () => { test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) { for (const testEntry of testCase.tests) {
const testFn = testEntry.only ? test.only : test; const testFn = testEntry.only ? test.only : test;
testFn(testEntry.name, async ({ page, baseURL, context }) => { testFn(testEntry.name, async ({ page, context }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl); const testEntryPathname =
const url = getContentTestURL(contentUrl.toString(), baseURL); 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) { if (testEntry.cookies) {
await context.addCookies( await context.addCookies(
testEntry.cookies.map((cookie) => ({ testEntry.cookies.map((cookie) => ({
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.7.0", "version": "0.7.3",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev", "dev": "env-cmd --silent -f ../../.env.local next dev",
-1
View File
@@ -16,7 +16,6 @@ export default defineConfig({
}, },
], ],
use: { use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry', trace: 'on-first-retry',
screenshot: 'only-on-failure', screenshot: 'only-on-failure',
}, },
@@ -38,10 +38,9 @@ export async function generateMetadata(props: PageProps): Promise<Metadata> {
} }
async function getSitePageProps(props: PageProps) { async function getSitePageProps(props: PageProps) {
const { params: rawParams, searchParams: rawSearchParams } = props; const { params: rawParams } = props;
const params = await rawParams; const params = await rawParams;
const searchParams = await rawSearchParams;
const pointer = await getSiteContentPointer(); const pointer = await getSiteContentPointer();
const context = await fetchV1ContextForSitePointer(pointer); const context = await fetchV1ContextForSitePointer(pointer);
@@ -49,7 +48,5 @@ async function getSitePageProps(props: PageProps) {
return { return {
context, context,
pageParams: params, pageParams: params,
redirectOnFallback: true,
fallback: !!searchParams.fallback,
}; };
} }
@@ -1,24 +1,9 @@
import { CustomizationRootLayout } from '@/components/RootLayout'; import { PDFRootLayout } from '@/components/PDF';
import { defaultCustomizationForSpace } from '@/lib/utils';
import { getV1ContextForPDF } from './pointer'; import { getV1ContextForPDF } from './pointer';
/** export default async function RootLayout(props: { children: React.ReactNode }) {
* 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 }) {
const { children } = props; const { children } = props;
const context = await getV1ContextForPDF(); const context = await getV1ContextForPDF();
return ( return <PDFRootLayout context={context}>{children}</PDFRootLayout>;
<CustomizationRootLayout
customization={
'customization' in context ? context.customization : defaultCustomizationForSpace()
}
>
{children}
</CustomizationRootLayout>
);
} }
@@ -1,361 +1,17 @@
import { import { PDFPage, generatePDFMetadata } from '@/components/PDF';
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 { getV1ContextForPDF } from './pointer'; import { getV1ContextForPDF } from './pointer';
const DEFAULT_LIMIT = 100;
export const runtime = 'edge'; export const runtime = 'edge';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata() {
const context = await getV1ContextForPDF(); const context = await getV1ContextForPDF();
return generatePDFMetadata(context);
return {
title: 'site' in context ? context.site.title : context.space.title,
robots: 'noindex, nofollow',
};
} }
/** export default async function Page(props: {
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export default async function PDFHTMLOutput(props: {
searchParams: Promise<{ [key: string]: string }>; searchParams: Promise<{ [key: string]: string }>;
}) { }) {
const searchParams = new URLSearchParams(await props.searchParams); const context = await getV1ContextForPDF();
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams)); return <PDFPage context={context} searchParams={await props.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);
} }
@@ -4,23 +4,6 @@ import type { SiteContentPointer, SpaceContentPointer } from '@/lib/api';
import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer'; import { getSiteContentPointer, getSpacePointer } from '@/lib/pointer';
import { fetchV1ContextForSitePointer, fetchV1ContextForSpacePointer } from '@/lib/v1'; 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. * Get the context for the PDF pointer.
*/ */
@@ -31,3 +14,18 @@ export async function getV1ContextForPDF(): Promise<GitBookSiteContext | GitBook
? await fetchV1ContextForSitePointer(pointer) ? await fetchV1ContextForSitePointer(pointer)
: await fetchV1ContextForSpacePointer(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) { export async function AdminToolbar(props: AdminToolbarProps) {
const { context } = props; const { context } = props;
const mode = await headers().get('x-gitbook-mode'); const mode = (await headers()).get('x-gitbook-mode');
if (mode === 'multi-id') { if (mode === 'multi-id') {
// We don't show the admin toolbar in multi-id mode, as it's used for previewing in the dashboard. // 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 */ /** Style passed to all blocks */
blockStyle?: ClassValue; blockStyle?: ClassValue;
/** True if all blocks should be considered offscreen */
isOffscreen?: boolean;
}; };
/** /**
* Renders a list of blocks without a wrapper element. * Renders a list of blocks without a wrapper element.
*/ */
export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) { export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) {
const { nodes, blockStyle, ...contextProps } = props; const { nodes, blockStyle, isOffscreen: defaultIsOffscreen = false, ...contextProps } = props;
let isOffscreen = false;
let isOffscreen = defaultIsOffscreen;
return nodes.map((node) => { return nodes.map((node) => {
isOffscreen = isOffscreen =
isOffscreen || isOffscreen ||
@@ -46,9 +46,12 @@ export function DocumentView(
/** Style passed to all blocks */ /** Style passed to all blocks */
blockStyle?: ClassValue; 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 ( return (
<Blocks <Blocks
@@ -62,6 +65,7 @@ export function DocumentView(
'whitespace-pre-wrap', 'whitespace-pre-wrap',
]} ]}
context={context} context={context}
isOffscreen={isOffscreen}
/> />
); );
} }
@@ -3,7 +3,7 @@
@apply flex-1 flex flex-col gap-4 mb-14; @apply flex-1 flex flex-col gap-4 mb-14;
} }
.openapi-models { .openapi-schemas {
@apply flex flex-col mb-14 flex-1; @apply flex flex-col mb-14 flex-1;
} }
@@ -620,10 +620,10 @@
@apply space-y-2.5; @apply space-y-2.5;
} }
.openapi-section-models { .openapi-section-schemas {
@apply border border-tint-subtle rounded-lg; @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; @apply p-2.5;
} }
@@ -63,6 +63,7 @@ const InsightsContext = React.createContext<TrackEventCallback>(() => {});
interface InsightsProviderProps extends InsightsEventContext { interface InsightsProviderProps extends InsightsEventContext {
enabled: boolean; enabled: boolean;
appURL: string;
apiHost: string; apiHost: string;
visitorAuthToken: string | null; visitorAuthToken: string | null;
children: React.ReactNode; children: React.ReactNode;
@@ -72,7 +73,7 @@ interface InsightsProviderProps extends InsightsEventContext {
* Wrap the content of the app with the InsightsProvider to track events. * Wrap the content of the app with the InsightsProvider to track events.
*/ */
export function InsightsProvider(props: InsightsProviderProps) { 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 visitorIdRef = React.useRef<string | null>(null);
const eventsRef = React.useRef<{ const eventsRef = React.useRef<{
@@ -140,7 +141,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
}); });
const flushBatchedEvents = useDebounceCallback(async () => { const flushBatchedEvents = useDebounceCallback(async () => {
const visitorId = visitorIdRef.current ?? (await getVisitorId()); const visitorId = visitorIdRef.current ?? (await getVisitorId(appURL));
visitorIdRef.current = visitorId; visitorIdRef.current = visitorId;
flushEventsSync(); flushEventsSync();
@@ -184,7 +185,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
* Get the visitor ID and store it in a ref. * Get the visitor ID and store it in a ref.
*/ */
React.useEffect(() => { React.useEffect(() => {
getVisitorId().then((visitorId) => { getVisitorId(appURL).then((visitorId) => {
visitorIdRef.current = visitorId; visitorIdRef.current = visitorId;
// When the page is unloaded, flush all events, but only if the visitor ID is set // When the page is unloaded, flush all events, but only if the visitor ID is set
window.addEventListener('beforeunload', flushEventsSync); window.addEventListener('beforeunload', flushEventsSync);
@@ -192,7 +193,7 @@ export function InsightsProvider(props: InsightsProviderProps) {
return () => { return () => {
window.removeEventListener('beforeunload', flushEventsSync); window.removeEventListener('beforeunload', flushEventsSync);
}; };
}, [flushEventsSync]); }, [flushEventsSync, appURL]);
return ( return (
<InsightsContext.Provider value={trackEvent}> <InsightsContext.Provider value={trackEvent}>
@@ -13,10 +13,10 @@ let pendingVisitorId: Promise<string> | null = null;
/** /**
* Return the current visitor identifier. * Return the current visitor identifier.
*/ */
export async function getVisitorId(): Promise<string> { export async function getVisitorId(appURL: string): Promise<string> {
if (!visitorId) { if (!visitorId) {
if (!pendingVisitorId) { if (!pendingVisitorId) {
pendingVisitorId = fetchVisitorID().finally(() => { pendingVisitorId = fetchVisitorID(appURL).finally(() => {
pendingVisitorId = null; 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. * 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(); const withoutCookies = isCookiesTrackingDisabled();
if (withoutCookies) { if (withoutCookies) {
@@ -46,7 +46,7 @@ async function fetchVisitorID(): Promise<string> {
// No tracking deviceId set, we'll need to consolidate with the server. // No tracking deviceId set, we'll need to consolidate with the server.
const proposed = generateRandomId(); 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.pathname = '/__session';
url.searchParams.set('proposed', proposed); 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 { Button } from '@/components/primitives';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { getPDFUrl } from '@/lib/urls'; import { type PDFSearchParams, getPDFURLSearchParams } from './urls';
const limitExtend = 50; const limitExtend = 50;
@@ -15,18 +15,15 @@ const limitExtend = 50;
* Dynamic controls to show active page and to let the user select between modes. * Dynamic controls to show active page and to let the user select between modes.
*/ */
export function PageControlButtons(props: { export function PageControlButtons(props: {
pdfHref: string; params: PDFSearchParams;
singlePageMode: boolean;
/** Array of the [pageId, divId] */ /** Array of the [pageId, divId] */
pageIds: Array<[string, string]>; pageIds: Array<[string, string]>;
/** Current limit */
limit: number;
/** Total number of pages targetted by the generation */ /** Total number of pages targetted by the generation */
total: number; total: number;
/** Trademark to display */ /** Trademark to display */
trademark?: React.ReactNode; trademark?: React.ReactNode;
}) { }) {
const { pdfHref, singlePageMode, pageIds, limit, total, trademark } = props; const { params, pageIds, total, trademark } = props;
const language = useLanguage(); const language = useLanguage();
@@ -53,19 +50,24 @@ export function PageControlButtons(props: {
'z-50' 'z-50'
)} )}
> >
{singlePageMode ? null : ( {params.only ? null : (
<Button <Button
href={getPDFUrl(new URL(pdfHref), { href={`?${getPDFURLSearchParams({
...params,
page: activePageId, page: activePageId,
only: true, only: true,
}).toString()} }).toString()}`}
variant="secondary" variant="secondary"
> >
{t(language, 'pdf_mode_only_page')} {t(language, 'pdf_mode_only_page')}
</Button> </Button>
)} )}
<Button <Button
href={getPDFUrl(new URL(pdfHref), { page: undefined, only: false }).toString()} href={`?${getPDFURLSearchParams({
...params,
page: undefined,
only: false,
}).toString()}`}
variant="secondary" variant="secondary"
> >
{t(language, 'pdf_mode_all')} {t(language, 'pdf_mode_all')}
@@ -113,11 +115,12 @@ export function PageControlButtons(props: {
<div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div> <div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div>
<div> <div>
<a <a
href={getPDFUrl(new URL(pdfHref), { href={`?${getPDFURLSearchParams({
...params,
page: undefined, page: undefined,
only: false, only: false,
limit: limit + limitExtend, limit: params.limit + limitExtend,
}).toString()} }).toString()}`}
className={tcls('underline')} className={tcls('underline')}
> >
{t(language, 'pdf_limit_reached_continue', limitExtend)} {t(language, 'pdf_limit_reached_continue', limitExtend)}
@@ -12,7 +12,7 @@ export function PrintButton(props: PolymorphicComponentProp<'button'>) {
}, []); }, []);
return ( return (
<button {...rest} onClick={onClick} className={className}> <button {...rest} data-testid="print-button" onClick={onClick} className={className}>
{children} {children}
</button> </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 { export interface PDFSearchParams {
/** Page to export. If none is passed, all pages are exported. */ /** Page to export. If none is passed, all pages are exported. */
page?: string; page?: string;
/** If true, only the `page` is exported, and not its descendant */ /** If true, only the `page` is exported, and not its descendant */
only?: boolean; only?: boolean;
/** Limit the number of pages */ /** Limit the number of pages */
limit?: number; limit: number;
/** URL to redirect back to */ /** URL to redirect back to */
back?: string; back?: string;
} }
@@ -13,7 +15,9 @@ export interface PDFSearchParams {
* Get the PDF export params from the URL serch params. * Get the PDF export params from the URL serch params.
*/ */
export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchParams { export function getPDFSearchParams(searchParams: URLSearchParams): PDFSearchParams {
const params: PDFSearchParams = {}; const params: PDFSearchParams = {
limit: DEFAULT_LIMIT,
};
if (searchParams.has('page')) { if (searchParams.has('page')) {
params.page = searchParams.get('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 { export function getPDFURLSearchParams(
const copy = new URL(url);
getPDFUrlSearchParams(params, copy.searchParams);
return copy;
}
export function getPDFUrlSearchParams(
params: PDFSearchParams, params: PDFSearchParams,
searchParams = new URLSearchParams({}) searchParams = new URLSearchParams({})
): URLSearchParams { ): URLSearchParams {
@@ -13,9 +13,9 @@ import urlJoin from 'url-join';
import { getSpaceLanguage, t } from '@/intl/server'; import { getSpaceLanguage, t } from '@/intl/server';
import { getDocumentSections } from '@/lib/document-sections'; import { getDocumentSections } from '@/lib/document-sections';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { getPDFUrlSearchParams } from '@/lib/urls';
import { Ad } from '../Ads'; import { Ad } from '../Ads';
import { getPDFURLSearchParams } from '../PDF';
import { PageFeedbackForm } from '../PageFeedback'; import { PageFeedbackForm } from '../PageFeedback';
import { ThemeToggler } from '../ThemeToggler'; import { ThemeToggler } from '../ThemeToggler';
import { ScrollSectionsList } from './ScrollSectionsList'; import { ScrollSectionsList } from './ScrollSectionsList';
@@ -36,9 +36,10 @@ export function PageAside(props: {
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInContent( const pdfHref = context.linker.toPathInContent(
`~gitbook/pdf?${getPDFUrlSearchParams({ `~gitbook/pdf?${getPDFURLSearchParams({
page: page.id, page: page.id,
only: true, only: true,
limit: 100,
}).toString()}` }).toString()}`
); );
return ( return (
@@ -31,6 +31,7 @@ import { ClientContexts } from './ClientContexts';
import '@gitbook/icons/style.css'; import '@gitbook/icons/style.css';
import './globals.css'; import './globals.css';
import { GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_URL } from '@v2/lib/env';
/** /**
* Layout shared between the content and the PDF renderer. * Layout shared between the content and the PDF renderer.
@@ -127,8 +128,8 @@ export async function CustomizationRootLayout(props: {
)} )}
> >
<IconsProvider <IconsProvider
assetsURL={process.env.GITBOOK_ICONS_URL ?? getAssetURL('icons')} assetsURL={GITBOOK_ICONS_URL}
assetsURLToken={process.env.GITBOOK_ICONS_TOKEN} assetsURLToken={GITBOOK_ICONS_TOKEN}
assetsByStyles={{ assetsByStyles={{
'custom-icons': { 'custom-icons': {
assetsURL: getAssetURL('icons'), assetsURL: getAssetURL('icons'),
@@ -101,7 +101,6 @@ export async function generateSiteLayoutMetadata(context: GitBookSiteContext): P
return { return {
title: site.title, title: site.title,
generator: `GitBook (${buildVersion()})`, generator: `GitBook (${buildVersion()})`,
// metadataBase: new URL(await getBaseUrl()),
icons: { icons: {
icon: [ icon: [
{ {
@@ -7,7 +7,7 @@ import React from 'react';
import { PageAside } from '@/components/PageAside'; import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody'; import { PageBody, PageCover } from '@/components/PageBody';
import { getPagePath, resolveFirstDocument } from '@/lib/pages'; import { getPagePath } from '@/lib/pages';
import { isPageIndexable, isSiteIndexable } from '@/lib/seo'; import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { PageClientLayout } from './PageClientLayout'; import { PageClientLayout } from './PageClientLayout';
@@ -19,8 +19,6 @@ export const dynamic = 'force-dynamic';
export type SitePageProps = { export type SitePageProps = {
context: GitBookSiteContext; context: GitBookSiteContext;
pageParams: PagePathParams; pageParams: PagePathParams;
redirectOnFallback: boolean;
fallback?: boolean;
}; };
/** /**
@@ -30,8 +28,6 @@ export async function SitePage(props: SitePageProps) {
const { context, pageTarget } = await getPageDataWithFallback({ const { context, pageTarget } = await getPageDataWithFallback({
context: props.context, context: props.context,
pagePathParams: props.pageParams, pagePathParams: props.pageParams,
fallback: props.fallback,
redirectOnFallback: props.redirectOnFallback,
}); });
const rawPathname = getPathnameParam(props.pageParams); const rawPathname = getPathnameParam(props.pageParams);
@@ -115,7 +111,6 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
const { context, pageTarget } = await getPageDataWithFallback({ const { context, pageTarget } = await getPageDataWithFallback({
context: props.context, context: props.context,
pagePathParams: props.pageParams, pagePathParams: props.pageParams,
fallback: props.fallback,
}); });
if (!pageTarget) { if (!pageTarget) {
@@ -153,28 +148,9 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
async function getPageDataWithFallback(args: { async function getPageDataWithFallback(args: {
context: GitBookSiteContext; context: GitBookSiteContext;
pagePathParams: PagePathParams; pagePathParams: PagePathParams;
fallback?: boolean;
redirectOnFallback?: boolean;
}) { }) {
const { context: baseContext, pagePathParams, fallback, redirectOnFallback = false } = args; const { context: baseContext, pagePathParams } = args;
const { context, pageTarget } = await fetchPageData(baseContext, pagePathParams);
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;
}
return { return {
context: { context: {
@@ -3,12 +3,26 @@
import { TrackPageViewEvent } from '@/components/Insights'; import { TrackPageViewEvent } from '@/components/Insights';
import { t, useLanguage } from '@/intl/client'; import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind'; 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. * Component that displays a "page not found" message.
*/ */
export function SitePageNotFound() { export function SitePageNotFound() {
const basePath = useSpaceBasePath();
const language = useLanguage(); 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 ( return (
<div <div
@@ -11,9 +11,11 @@ import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate'; import { t } from '@/intl/translate';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { GITBOOK_APP_URL } from '@v2/lib/env';
import { SpacesDropdown } from '../Header/SpacesDropdown'; import { SpacesDropdown } from '../Header/SpacesDropdown';
import { InsightsProvider } from '../Insights'; import { InsightsProvider } from '../Insights';
import { SiteSectionList, encodeClientSiteSections } from '../SiteSections'; import { SiteSectionList, encodeClientSiteSections } from '../SiteSections';
import { SpaceLayoutContextProvider } from './SpaceLayoutContext';
/** /**
* Render the entire layout of the space (header, table of contents, footer). * Render the entire layout of the space (header, table of contents, footer).
@@ -45,97 +47,100 @@ export function SpaceLayout(props: {
customization.footer.groups?.length; customization.footer.groups?.length;
return ( return (
<InsightsProvider <SpaceLayoutContextProvider basePath={context.linker.toPathInContent('')}>
enabled={withTracking} <InsightsProvider
apiHost={context.dataFetcher.apiEndpoint} enabled={withTracking}
visitorAuthToken={visitorAuthToken} appURL={GITBOOK_APP_URL}
organizationId={context.organizationId} apiHost={context.dataFetcher.apiEndpoint}
siteId={context.site.id} visitorAuthToken={visitorAuthToken}
siteSectionId={context.sections?.current?.id ?? null} organizationId={context.organizationId}
siteSpaceId={context.siteSpace.id} siteId={context.site.id}
siteShareKey={context.shareKey ?? null} siteSectionId={context.sections?.current?.id ?? null}
revisionId={context.revisionId} siteSpaceId={context.siteSpace.id}
spaceId={context.space.id} siteShareKey={context.shareKey ?? null}
> revisionId={context.revisionId}
<Header withTopHeader={withTopHeader} context={context} /> spaceId={context.space.id}
<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 <Header withTopHeader={withTopHeader} context={context} />
context={context} <div
header={ className={tcls(
withTopHeader ? null : ( 'flex',
<div 'flex-col',
className={tcls( 'lg:flex-row',
'hidden', CONTAINER_STYLE,
'pr-4',
'lg:flex', // Ensure the footer is display below the viewport even if the content is not enough
'grow-0', withFooter && 'min-h-[calc(100vh-64px)]',
'flex-wrap', withTopHeader ? null : 'lg:min-h-screen'
'dark:shadow-light/1' )}
)} >
> <TableOfContents
<HeaderLogo context={context} /> context={context}
</div> header={
) withTopHeader ? null : (
} <div
innerHeader={ className={tcls(
// 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. 'hidden',
<> 'pr-4',
{!withTopHeader && ( 'lg:flex',
<div className={tcls('hidden', 'lg:block')}> 'grow-0',
<React.Suspense fallback={null}> 'flex-wrap',
<SearchButton> 'dark:shadow-light/1'
<span className={tcls('flex-1')}> )}
{t( >
getSpaceLanguage(customization), <HeaderLogo context={context} />
customization.aiSearch.enabled
? 'search_or_ask'
: 'search'
)}
</span>
</SearchButton>
</React.Suspense>
</div> </div>
)} )
{!withTopHeader && withSections && sections && ( }
<SiteSectionList innerHeader={
className={tcls('hidden', 'lg:block')} // 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.
sections={encodeClientSiteSections(context, sections)} <>
/> {!withTopHeader && (
)} <div className={tcls('hidden', 'lg:block')}>
{isMultiVariants && ( <React.Suspense fallback={null}>
<SpacesDropdown <SearchButton>
context={context} <span className={tcls('flex-1')}>
siteSpace={siteSpace} {t(
siteSpaces={siteSpaces} getSpaceLanguage(customization),
className={tcls('w-full')} customization.aiSearch.enabled
/> ? 'search_or_ask'
)} : 'search'
</> )}
} </span>
/> </SearchButton>
<div className={tcls('flex-1', 'flex', 'flex-col')}>{children}</div> </React.Suspense>
</div> </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}> <React.Suspense fallback={null}>
<SearchModal <SearchModal
spaceTitle={siteSpace.title} spaceTitle={siteSpace.title}
withAsk={customization.aiSearch.enabled} withAsk={customization.aiSearch.enabled}
isMultiVariants={isMultiVariants} isMultiVariants={isMultiVariants}
/> />
</React.Suspense> </React.Suspense>
</InsightsProvider> </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. * Create a public URL for an asset.
*/ */
export function getAssetURL(path: string): string { 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({ sections.push({
id: block.meta.id, id: block.meta.id,
tag: operation.method.toUpperCase(), tag: operation.method.toUpperCase(),
title: operation.operation.summary ?? operation.path, title: operation.operation.summary || operation.path,
depth: 1, depth: 1,
deprecated: operation.operation.deprecated, deprecated: operation.operation.deprecated,
}); });
+2 -1
View File
@@ -8,6 +8,7 @@ import {
} from '@gitbook/api'; } from '@gitbook/api';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
import { GITBOOK_APP_URL } from '@v2/lib/env';
import { getPagePath } from './pages'; import { getPagePath } from './pages';
import { assertIsNotV2 } from './v2'; 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. * Create an absolute href in the GitBook application.
*/ */
export function getGitbookAppHref(pathname: string): string { 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; appUrl.pathname = pathname;
return appUrl.toString(); return appUrl.toString();
@@ -1,35 +1,35 @@
import { fetchOpenAPIFilesystem } from '@/lib/openapi/fetch'; import { fetchOpenAPIFilesystem } from '@/lib/openapi/fetch';
import type { ResolveOpenAPIBlockResult } from '@/lib/openapi/types'; import type { ResolveOpenAPIBlockResult } from '@/lib/openapi/types';
import { OpenAPIParseError } from '@gitbook/openapi-parser'; 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'; 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. * Cache the result of resolving an OpenAPI block.
* It is important because the resolve is called in sections and in the block itself. * It is important because the resolve is called in sections and in the block itself.
*/ */
export function resolveOpenAPIModelsBlock( export function resolveOpenAPISchemasBlock(
args: ResolveOpenAPIBlockArgs args: ResolveOpenAPIBlockArgs
): Promise<ResolveOpenAPIModelsBlockResult> { ): Promise<ResolveOpenAPISchemasBlockResult> {
if (weakmap.has(args.block)) { if (weakmap.has(args.block)) {
return weakmap.get(args.block)!; return weakmap.get(args.block)!;
} }
const result = baseResolveOpenAPIModelsBlock(args); const result = baseResolveOpenAPISchemasBlock(args);
weakmap.set(args.block, result); weakmap.set(args.block, result);
return result; return result;
} }
/** /**
* Resolve OpenAPI models block. * Resolve OpenAPI schemas block.
*/ */
async function baseResolveOpenAPIModelsBlock( async function baseResolveOpenAPISchemasBlock(
args: ResolveOpenAPIBlockArgs args: ResolveOpenAPIBlockArgs
): Promise<ResolveOpenAPIModelsBlockResult> { ): Promise<ResolveOpenAPISchemasBlockResult> {
const { context, block } = args; const { context, block } = args;
if (!block.data.path || !block.data.method) { if (!block.data.path || !block.data.method) {
return { data: null, specUrl: null }; return { data: null, specUrl: null };
@@ -42,7 +42,7 @@ async function baseResolveOpenAPIModelsBlock(
return { data: null, specUrl: null }; return { data: null, specUrl: null };
} }
const data = await resolveOpenAPIModels(filesystem); const data = await resolveOpenAPISchemas(filesystem);
return { data, specUrl }; return { data, specUrl };
} catch (error) { } 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 { Filesystem, OpenAPIParseError, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
import type { GitBookAnyContext } from '@v2/lib/context'; 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; export type AnyOpenAPIBlock = DocumentBlockOpenAPI | DocumentBlockOpenAPIOperation;
/** /**
+9 -2
View File
@@ -3,7 +3,6 @@ import type { NextRequest } from 'next/server';
import hash from 'object-hash'; import hash from 'object-hash';
const VISITOR_AUTH_PARAM = 'jwt_token'; const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_AUTH_COOKIE_ROOT = 'gitbook-visitor-token~';
export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token'; export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token';
export type ResponseCookie = { export type ResponseCookie = {
@@ -127,7 +126,7 @@ export function getResponseCookiesForVisitorAuth(
* different content hosted on the same subdomain. * different content hosted on the same subdomain.
*/ */
export function getVisitorAuthCookieName(basePath: string): string { 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; 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 * Get all possible basePaths for a given URL. This is used to find the visitor
* authentication cookie token. * 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() { function getBaseURL() {
const targetUrl = Bun.argv[2]; const baseUrl = process.env.BASE_URL;
if (!targetUrl) { if (!baseUrl) {
process.exit(1); throw new Error('BASE_URL is not set');
} }
return targetUrl; return baseUrl;
}
export function getContentPathName(input: string): string {
const contentUrl = new URL(input);
return `${contentUrl.host}${contentUrl.pathname}`;
} }
/** /**
* 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 { function getSiteBaseURL() {
const url = new URL(baseUrl); 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); const contentUrl = new URL(input);
url.pathname = `${url.pathname.replace(/\/$/, '')}/${contentUrl.host}${contentUrl.pathname}`; url.pathname = `${url.pathname.replace(/\/$/, '')}/${contentUrl.host}${contentUrl.pathname}`;
@@ -27,3 +36,35 @@ export function getContentTestURL(input: string, baseUrl: string = getTargetURL(
return url.toString(); 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 # @gitbook/icons
## 0.2.0
### Minor Changes
- 88f64b0: Fix the build to support Node.js v20
## 0.1.0 ## 0.1.0
### Minor Changes ### Minor Changes
+5 -2
View File
@@ -16,7 +16,7 @@
"default": "./src/style.css" "default": "./src/style.css"
} }
}, },
"version": "0.1.0", "version": "0.2.0",
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.6.0", "@fortawesome/fontawesome-svg-core": "^6.6.0",
"@fortawesome/fontawesome-free": "^6.6.0" "@fortawesome/fontawesome-free": "^6.6.0"
@@ -41,5 +41,8 @@
"bin": { "bin": {
"gitbook-icons": "./bin/gitbook-icons.js" "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'; import type { IconName, IconStyle } from './types';
const cache = new Map<IconName, Map<IconStyle, [string, IconName]>>(); 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'; import type { IconName, IconStyle } from './types';
export interface IconStyleDefinition { export interface IconStyleDefinition {
+7 -7
View File
@@ -1,16 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "esnext", "lib": ["es2023"],
"lib": ["dom", "dom.iterable", "esnext"], "module": "ESNext",
"allowJs": true, "target": "es2022",
"skipLibCheck": true,
"strict": true, "strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowJs": true,
"noEmit": false, "noEmit": false,
"declaration": true, "declaration": true,
"outDir": "dist", "outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "react-jsx", "jsx": "react-jsx",
+7
View File
@@ -1,5 +1,12 @@
# @gitbook/react-contentkit # @gitbook/react-contentkit
## 0.6.2
### Patch Changes
- Updated dependencies [88f64b0]
- @gitbook/icons@0.2.0
## 0.6.1 ## 0.6.1
### Patch Changes ### Patch Changes
+1 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@gitbook/react-contentkit", "name": "@gitbook/react-contentkit",
"version": "0.6.1", "version": "0.6.2",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
@@ -11,7 +11,6 @@
"dependencies": { "dependencies": {
"classnames": "^2.5.1", "classnames": "^2.5.1",
"@gitbook/api": "0.96.1", "@gitbook/api": "0.96.1",
"assert-never": "^1.2.1",
"@gitbook/icons": "workspace:*" "@gitbook/icons": "workspace:*"
}, },
"peerDependencies": { "peerDependencies": {
+18
View File
@@ -1,5 +1,23 @@
# @gitbook/react-openapi # @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 ## 1.1.0
### Minor Changes ### Minor Changes
+1 -1
View File
@@ -8,7 +8,7 @@
"default": "./dist/index.js" "default": "./dist/index.js"
} }
}, },
"version": "1.1.0", "version": "1.1.3",
"sideEffects": false, "sideEffects": false,
"dependencies": { "dependencies": {
"@gitbook/openapi-parser": "workspace:*", "@gitbook/openapi-parser": "workspace:*",
+2 -2
View File
@@ -217,7 +217,7 @@ function OpenAPISchemaPresentation(props: { property: OpenAPISchemaPropertyEntry
propertyName={propertyName} propertyName={propertyName}
required={required} required={required}
/> />
{schema['x-deprecated-sunset'] ? ( {typeof schema['x-deprecated-sunset'] === 'string' ? (
<div className="openapi-deprecated-sunset openapi-schema-description openapi-markdown"> <div className="openapi-deprecated-sunset openapi-schema-description openapi-markdown">
Sunset date:{' '} Sunset date:{' '}
<span className="openapi-deprecated-sunset-date"> <span className="openapi-deprecated-sunset-date">
@@ -228,7 +228,7 @@ function OpenAPISchemaPresentation(props: { property: OpenAPISchemaPropertyEntry
{description ? ( {description ? (
<Markdown source={description} className="openapi-schema-description" /> <Markdown source={description} className="openapi-schema-description" />
) : null} ) : null}
{example ? ( {typeof example === 'string' ? (
<div className="openapi-schema-example"> <div className="openapi-schema-example">
Example: <code>{example}</code> Example: <code>{example}</code>
</div> </div>
@@ -31,7 +31,7 @@ export function OpenAPISecurities(props: {
key: key, key: key,
label: key, label: key,
body: ( body: (
<div className="openapi-schema-body"> <div className="openapi-schema">
<div className="openapi-schema-presentation"> <div className="openapi-schema-presentation">
{getLabelForType(security)} {getLabelForType(security)}
+2 -2
View File
@@ -1,5 +1,5 @@
export * from './models'; export * from './schemas';
export * from './OpenAPIOperation'; export * from './OpenAPIOperation';
export * from './OpenAPIOperationContext'; export * from './OpenAPIOperationContext';
export * from './resolveOpenAPIOperation'; 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 () => { it('should resolve circular refs', async () => {
const filesystem = await fetchFilesystem('https://api.gitbook.com/openapi.json'); const filesystem = await fetchFilesystem('https://api.gitbook.com/openapi.json');
const resolved = await resolveOpenAPIOperation(filesystem, { const resolved = await resolveOpenAPIOperation(filesystem, {
method: 'post', method: 'get',
path: '/search/ask', path: '/spaces/{spaceId}/content/page/{pageId}',
}); });
expect(resolved).toMatchObject({ expect(resolved).toMatchObject({
@@ -91,7 +91,7 @@ describe('#resolveOpenAPIOperation', () => {
}, },
], ],
operation: { operation: {
operationId: 'askQuery', operationId: 'getPageById',
}, },
}); });
}); });
@@ -2,18 +2,18 @@ import clsx from 'clsx';
import { OpenAPIDisclosureGroup } from '../OpenAPIDisclosureGroup'; import { OpenAPIDisclosureGroup } from '../OpenAPIDisclosureGroup';
import { OpenAPIRootSchema } from '../OpenAPISchema'; import { OpenAPIRootSchema } from '../OpenAPISchema';
import { Section, SectionBody } from '../StaticSection'; 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; className?: string;
data: OpenAPIModelsData; data: OpenAPISchemasData;
context: OpenAPIContextProps; context: OpenAPIContextProps;
}) { }) {
const { className, data, context } = props; const { className, data, context } = props;
const { models } = data; const { schemas } = data;
const clientContext: OpenAPIClientContext = { const clientContext: OpenAPIClientContext = {
defaultInteractiveOpened: context.defaultInteractiveOpened, defaultInteractiveOpened: context.defaultInteractiveOpened,
@@ -21,30 +21,30 @@ export function OpenAPIModels(props: {
blockKey: context.blockKey, blockKey: context.blockKey,
}; };
if (!models.length) { if (!schemas.length) {
return null; return null;
} }
return ( return (
<div className={clsx('openapi-models', className)}> <div className={clsx('openapi-schemas', className)}>
<OpenAPIRootModelsSchema models={models} context={clientContext} /> <OpenAPIRootSchemasSchema schemas={schemas} context={clientContext} />
</div> </div>
); );
} }
/** /**
* Root schema for OpenAPI models. * Root schema for OpenAPI schemas.
* It displays a single model or a disclosure group for multiple models. * It displays a single model or a disclosure group for multiple schemas.
*/ */
function OpenAPIRootModelsSchema(props: { function OpenAPIRootSchemasSchema(props: {
models: OpenAPIModelsData['models']; schemas: OpenAPISchemasData['schemas'];
context: OpenAPIClientContext; context: OpenAPIClientContext;
}) { }) {
const { models, context } = props; const { schemas, context } = props;
// If there is only one model, we show it directly. // If there is only one model, we show it directly.
if (models.length === 1) { if (schemas.length === 1) {
const schema = models?.[0]?.schema; const schema = schemas?.[0]?.schema;
if (!schema) { if (!schema) {
return null; 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 ( return (
<OpenAPIDisclosureGroup <OpenAPIDisclosureGroup
allowsMultipleExpanded allowsMultipleExpanded
icon={context.icons.chevronRight} icon={context.icons.chevronRight}
groups={models.map(({ name, schema }) => ({ groups={schemas.map(({ name, schema }) => ({
id: name, id: name,
label: ( label: (
<div className="openapi-response-tab-content" key={`model-${name}`}> <div className="openapi-response-tab-content" key={`model-${name}`}>
@@ -75,7 +75,7 @@ function OpenAPIRootModelsSchema(props: {
{ {
id: 'model', id: 'model',
body: ( body: (
<Section className="openapi-section-models"> <Section className="openapi-section-schemas">
<SectionBody> <SectionBody>
<OpenAPIRootSchema schema={schema} context={context} /> <OpenAPIRootSchema schema={schema} context={context} />
</SectionBody> </SectionBody>
@@ -0,0 +1,2 @@
export * from './OpenAPISchemas';
export * from './resolveOpenAPISchemas';
@@ -6,28 +6,28 @@ import {
shouldIgnoreEntity, shouldIgnoreEntity,
} from '@gitbook/openapi-parser'; } from '@gitbook/openapi-parser';
import { dereferenceFilesystem } from '../dereference'; 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. * Resolve an OpenAPI schemas from a file and compile it to a more usable format.
* Models are extracted from the OpenAPI components.schemas * Schemas are extracted from the OpenAPI components.schemas
*/ */
export async function resolveOpenAPIModels( export async function resolveOpenAPISchemas(
filesystem: Filesystem<OpenAPIV3xDocument> filesystem: Filesystem<OpenAPIV3xDocument>
): Promise<OpenAPIModelsData | null> { ): Promise<OpenAPISchemasData | null> {
const schema = await dereferenceFilesystem(filesystem); 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. * 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 ?? {}; const schemas = schema.components?.schemas ?? {};
return Object.entries(schemas) return Object.entries(schemas)
.filter(([, schema]) => !shouldIgnoreEntity(schema)) .filter(([, schema]) => !shouldIgnoreEntity(schema))
+4 -4
View File
@@ -56,12 +56,12 @@ export interface OpenAPIOperationData extends OpenAPICustomSpecProperties {
securities: [string, OpenAPIV3.SecuritySchemeObject][]; securities: [string, OpenAPIV3.SecuritySchemeObject][];
} }
export type OpenAPIModel = { export type OpenAPISchema = {
name: string; name: string;
schema: OpenAPIV3.SchemaObject; schema: OpenAPIV3.SchemaObject;
}; };
export interface OpenAPIModelsData { export interface OpenAPISchemasData {
/** Components schemas to be used for models */ /** Components schemas to be used for schemas */
models: OpenAPIModel[]; schemas: OpenAPISchema[];
} }
+2 -2
View File
@@ -51,12 +51,12 @@ export function extractDescriptions(object: AnyObject) {
/** /**
* Resolve the first example from an object. * 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) { if ('examples' in object && typeof object.examples === 'object' && object.examples) {
const keys = Object.keys(object.examples); const keys = Object.keys(object.examples);
const firstKey = keys[0]; const firstKey = keys[0];
if (firstKey && object.examples[firstKey]) { 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", "$schema": "https://turbo.build/schema.json",
"ui": "stream", "ui": "stream",
"globalEnv": ["NODE_ENV", "CI", "ARGOS_*", "GITHUB_*", "GITBOOK_*", "SENTRY_*"], "globalEnv": [
"NODE_ENV",
"CI",
"ARGOS_*",
"GITHUB_*",
"GITBOOK_*",
"SENTRY_*",
"NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"
],
"tasks": { "tasks": {
// Prepare the package for all other tasks // Prepare the package for all other tasks
"generate": { "generate": {
@@ -25,8 +33,7 @@
}, },
// Build the package for Cloudflare Pages // Build the package for Cloudflare Pages
"build:cloudflare": { "build:cloudflare": {
"dependsOn": ["^build", "generate"], "dependsOn": ["^build", "generate"]
"env": ["NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"]
}, },
// Check the package for type errors // Check the package for type errors
"typecheck": { "typecheck": {
@@ -43,12 +50,12 @@
// Run end-to-end tests // Run end-to-end tests
"e2e": { "e2e": {
"dependsOn": ["^e2e"], "dependsOn": ["^e2e"],
"env": ["BASE_URL"] "env": ["BASE_URL", "SITE_BASE_URL"]
}, },
// Run end-to-end tests for customers // Run end-to-end tests for customers
"e2e-customers": { "e2e-customers": {
"dependsOn": ["^e2e-customers"], "dependsOn": ["^e2e-customers"],
"env": ["BASE_URL"] "env": ["BASE_URL", "SITE_BASE_URL"]
}, },
// Start the package in development mode // Start the package in development mode
"dev": { "dev": {