mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-12 14:00:28 +00:00
Compare commits
232 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0df3849ea2 | |||
| 8ed1bda2f2 | |||
| d67699a1f1 | |||
| 3363a18856 | |||
| ad1dc0b914 | |||
| e4c7307c99 | |||
| f9c942c8ff | |||
| eeb977fc03 | |||
| 4b8a62122a | |||
| e44e947fc1 | |||
| 7588cfe1c5 | |||
| a9a643f222 | |||
| 77d6cb75be | |||
| 1942d221df | |||
| 041601ed65 | |||
| 5567281a85 | |||
| 4c3753046b | |||
| 89f8e16184 | |||
| a3e1125ced | |||
| 4dae8acfed | |||
| bc081c4344 | |||
| e4275b235d | |||
| 77397cac82 | |||
| b6a08bc679 | |||
| 116575c811 | |||
| 4ba7bd5ce1 | |||
| 223ab5377f | |||
| ae43ca146c | |||
| 42342893d6 | |||
| eedefdd5c9 | |||
| f5e152dd74 | |||
| 95ea22d9c5 | |||
| f23023ddfa | |||
| da74077954 | |||
| 29aaba5949 | |||
| daf41fc728 | |||
| b08eb1af59 | |||
| 8322cd3e35 | |||
| 444039c142 | |||
| 3b0eff7f71 | |||
| c765463e38 | |||
| e8ca25b67e | |||
| 528eee3fc6 | |||
| 168a4fa998 | |||
| 3ea75adba4 | |||
| cbd768a095 | |||
| 2d01653a78 | |||
| aa3357a57d | |||
| de53946896 | |||
| d51204148e | |||
| 319761a39e | |||
| 7fbf01a348 | |||
| c22490bd80 | |||
| 860fd6d02e | |||
| c43c524804 | |||
| 66bb938d85 | |||
| 0e6d928496 | |||
| f07982d9f8 | |||
| b92ecfad58 | |||
| 416bde70bc | |||
| 580f7ade15 | |||
| cdffd7c47b | |||
| 5a959cf041 | |||
| 31466546a2 | |||
| 90ead98eaa | |||
| 65e9cb9d5c | |||
| e59076a074 | |||
| 653920dec9 | |||
| 23cedd2d8b | |||
| 70c4182fd8 | |||
| b62b101065 | |||
| b9c929beeb | |||
| 2b6c593289 | |||
| c0b339e406 | |||
| da485f5144 | |||
| 139a8050a5 | |||
| da7b369ffd | |||
| 432da64919 | |||
| 7d0b422200 | |||
| fb90eb0acc | |||
| b647538e41 | |||
| e50797a5c1 | |||
| 5b1e01c786 | |||
| 813b2af06b | |||
| 6f71da88d8 | |||
| fa91eb7eaf | |||
| c756761591 | |||
| 434af90366 | |||
| 0f41e194cb | |||
| bd353489e9 | |||
| 77fd393f15 | |||
| 8701b5e078 | |||
| 61db166f92 | |||
| 0d9b9cea0f | |||
| 7bb37c7f0a | |||
| 5b2bf828e3 | |||
| c85d3f9752 | |||
| 4d7088bbf0 | |||
| dd6ab6044c | |||
| d236bf029c | |||
| d70d566abe | |||
| a25fdedea9 | |||
| 373183a2cd | |||
| e9fa50dfb5 | |||
| 57ca4e0e88 | |||
| bc90adb73a | |||
| 1505ddbd5a | |||
| cd99ed57fb | |||
| 27de1cd01d | |||
| ae78fc5394 | |||
| 40e8e69c6d | |||
| e84a46a558 | |||
| 18a72d4466 | |||
| d7aa5fa003 | |||
| 27532a5f41 | |||
| 48c18c03b9 | |||
| bba2e52e24 | |||
| 54ee0149e1 | |||
| 8fda9d2fab | |||
| 77a72d79ce | |||
| 73e2b472ef | |||
| 2f28cc1323 | |||
| f5516d4e21 | |||
| d2facb2db1 | |||
| 6eae764b7c | |||
| 970ef8f886 | |||
| ed0720699e | |||
| ad94d00d5f | |||
| c7843f7f52 | |||
| 1fe3286bdb | |||
| ce030fdf76 | |||
| 9ba8783952 | |||
| 2f3966cc53 | |||
| 8f65a22e13 | |||
| 2787d884cd | |||
| fc00b51683 | |||
| f80c3a7b37 | |||
| 4e5d6c7487 | |||
| 96f84b5917 | |||
| 6b8a5fdd1b | |||
| 89083ac790 | |||
| 70be2c6b2b | |||
| bcf877841b | |||
| a84b06bb19 | |||
| 24b7808d9a | |||
| 8364ee988e | |||
| 07f6e2d233 | |||
| 7212973f34 | |||
| af44e0436b | |||
| 3f9c35d505 | |||
| 2c13f8b95c | |||
| 4dab1c56e5 | |||
| 4723f03ef1 | |||
| 278689e0a0 | |||
| 886e204e68 | |||
| c59947ab39 | |||
| 4f0a772a21 | |||
| 903f962673 | |||
| 31d800e48b | |||
| c1c58eb919 | |||
| eec3eed100 | |||
| 99da8df3d1 | |||
| c9ea23919e | |||
| 16292def79 | |||
| 9108c56ca1 | |||
| b011ea0af8 | |||
| d33171b779 | |||
| 6aaeae269e | |||
| e5f0cc8663 | |||
| 9b5f971aa1 | |||
| ff3b708ad3 | |||
| e996904013 | |||
| f32bf1f15d | |||
| 6cda2dd57b | |||
| c60e9ba27f | |||
| 9bc3d504c8 | |||
| b5e4fd75e9 | |||
| a92cb49445 | |||
| 88f64b0d63 | |||
| 844059f9a5 | |||
| eaf2d68308 | |||
| 12bdbf988d | |||
| 29bab79005 | |||
| 8d5de97ddf | |||
| d9b5a898ab | |||
| f127d28675 | |||
| 65c1bdc455 | |||
| 0711a171d4 | |||
| c58c551f9e | |||
| f574858b9b | |||
| 3e1592e16b | |||
| 90604c4c3b | |||
| 9ffc3b606d | |||
| e00c87d3e6 | |||
| bb3ca9c165 | |||
| 8ee9757132 | |||
| 946a463979 | |||
| 7aad9f7ff8 | |||
| 3fe8f7c219 | |||
| 0278a14e8e | |||
| e5366d3a49 | |||
| 38e84ffe1a | |||
| 052e07a936 | |||
| 7e67ebc11d | |||
| c9dea94717 | |||
| 1344754ca9 | |||
| 0f4759fb89 | |||
| 6d77b647a4 | |||
| 5907bd9af4 | |||
| b66d04c9c5 | |||
| 3173d8ec2d | |||
| 31e381035e | |||
| 259074b81f | |||
| 9a2f5b9295 | |||
| 58cd70b0c1 | |||
| 821899a767 | |||
| bfcc119ff3 | |||
| 76c797498e | |||
| 13514bf6fa | |||
| 05ffd0e321 | |||
| 701eaad92a | |||
| c66ef5dd10 | |||
| f774f9b3a0 | |||
| 29dc7ccb1a | |||
| 80237c34f9 | |||
| 979233c5c0 | |||
| 2f03e6acee | |||
| c492f09a19 | |||
| 2c3af5e73c | |||
| 6597f8508d | |||
| 8beb5d6bcf | |||
| 53f5dbea26 |
@@ -0,0 +1,81 @@
|
|||||||
|
name: 'Deploy cloudflare'
|
||||||
|
description: 'Deploy GitBook to Cloudflare'
|
||||||
|
inputs:
|
||||||
|
opItem:
|
||||||
|
description: '1Password item to load secrets from'
|
||||||
|
required: true
|
||||||
|
opServiceAccount:
|
||||||
|
description: '1Password service account token'
|
||||||
|
required: true
|
||||||
|
apiToken:
|
||||||
|
description: 'Cloudflare API token'
|
||||||
|
required: true
|
||||||
|
accountId:
|
||||||
|
description: 'Cloudflare account ID'
|
||||||
|
required: true
|
||||||
|
environment:
|
||||||
|
description: 'Cloudflare environment to deploy to (staging, production, preview)'
|
||||||
|
required: true
|
||||||
|
deploy:
|
||||||
|
description: 'Deploy as main version for all traffic instead of uploading versions'
|
||||||
|
required: true
|
||||||
|
commitTag:
|
||||||
|
description: 'Commit branch to associate with the deployment'
|
||||||
|
required: true
|
||||||
|
commitMessage:
|
||||||
|
description: 'Commit message to associate with the deployment'
|
||||||
|
required: true
|
||||||
|
outputs:
|
||||||
|
deployment-url:
|
||||||
|
description: "Deployment URL"
|
||||||
|
value: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
runs:
|
||||||
|
using: 'composite'
|
||||||
|
steps:
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||||
|
- name: 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_PUBLIC_URL: ${{ inputs.opItem }}/GITBOOK_API_PUBLIC_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_IMAGE_RESIZE_MODE: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_MODE
|
||||||
|
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
|
||||||
|
GITBOOK_FONTS_URL: ${{ inputs.opItem }}/GITBOOK_FONTS_URL
|
||||||
|
- name: Build worker
|
||||||
|
run: bun run turbo build:v2:cloudflare
|
||||||
|
env:
|
||||||
|
GITBOOK_RUNTIME: cloudflare
|
||||||
|
shell: bash
|
||||||
|
- id: deploy
|
||||||
|
name: Deploy to Cloudflare
|
||||||
|
uses: cloudflare/wrangler-action@v3.14.0
|
||||||
|
with:
|
||||||
|
apiToken: ${{ inputs.apiToken }}
|
||||||
|
accountId: ${{ inputs.accountId }}
|
||||||
|
workingDirectory: ./
|
||||||
|
wranglerVersion: '4.10.0'
|
||||||
|
environment: ${{ inputs.environment }}
|
||||||
|
command: ${{ inputs.deploy == 'true' && 'deploy' || format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook-v2/wrangler.jsonc
|
||||||
|
- name: Outputs
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
run: |
|
||||||
|
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||||
@@ -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,32 +33,48 @@ 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_PUBLIC_URL: ${{ inputs.opItem }}/GITBOOK_API_PUBLIC_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_IMAGE_RESIZE_MODE: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_MODE
|
||||||
|
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
|
||||||
|
GITBOOK_FONTS_URL: ${{ inputs.opItem }}/GITBOOK_FONTS_URL
|
||||||
- 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 }}
|
||||||
|
GITBOOK_RUNTIME: vercel
|
||||||
- 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: |
|
||||||
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,6 @@ description: 'Install Bun and cache dependencies'
|
|||||||
runs:
|
runs:
|
||||||
using: 'composite'
|
using: 'composite'
|
||||||
steps:
|
steps:
|
||||||
# We cache dependencies even if Bun is fast to avoid downloading fontawesome too many times
|
|
||||||
# and impacting bandwidth there.
|
|
||||||
- name: Cache bun
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.bun/install/cache
|
|
||||||
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/bun.lock') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-bun-
|
|
||||||
- name: Setup bun
|
- name: Setup bun
|
||||||
uses: oven-sh/setup-bun@v2
|
uses: oven-sh/setup-bun@v2
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -7,316 +7,6 @@ on:
|
|||||||
env:
|
env:
|
||||||
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
|
||||||
name: Deploy to Cloudflare Pages
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
deployments: write
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
checks: write
|
|
||||||
statuses: write
|
|
||||||
outputs:
|
|
||||||
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
|
||||||
deployment-alias-url: ${{ steps.deploy.outputs.deployment-alias-url }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
env:
|
|
||||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
|
||||||
- name: Sets env vars for production
|
|
||||||
run: |
|
|
||||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
|
||||||
echo "GITBOOK_ASSETS_PREFIX=https://static.gitbook.com" >> $GITHUB_ENV
|
|
||||||
if: startsWith(github.ref, 'refs/heads/main')
|
|
||||||
- name: Sets env vars for preview
|
|
||||||
run: |
|
|
||||||
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
|
|
||||||
if: 1 && !startsWith(github.ref, 'refs/heads/main')
|
|
||||||
- name: Build Next.js with next-on-pages
|
|
||||||
run: bun run turbo gitbook#build:cloudflare
|
|
||||||
env:
|
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
|
||||||
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
|
|
||||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
|
||||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
|
|
||||||
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
|
|
||||||
SENTRY_RELEASE: ${{ github.sha }}
|
|
||||||
- id: deploy
|
|
||||||
name: Deploy to Cloudflare
|
|
||||||
uses: cloudflare/wrangler-action@v3.14.0
|
|
||||||
with:
|
|
||||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
|
||||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
||||||
workingDirectory: ./
|
|
||||||
wranglerVersion: '3.82.0'
|
|
||||||
command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
|
|
||||||
- name: Outputs
|
|
||||||
run: |
|
|
||||||
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
|
||||||
echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}"
|
|
||||||
- name: Archive build output
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: build-output
|
|
||||||
path: .vercel/
|
|
||||||
# Until https://github.com/cloudflare/wrangler-action/issues/301 is done
|
|
||||||
- name: Update Deployment Status to Success
|
|
||||||
env:
|
|
||||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
|
|
||||||
run: |
|
|
||||||
curl -X POST \
|
|
||||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
|
||||||
-H "Accept: application/vnd.github.v3+json" \
|
|
||||||
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.deployment-url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
|
|
||||||
https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.sha }}
|
|
||||||
deploy-v2-vercel:
|
|
||||||
name: Deploy v2 to Vercel
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
deployments: write
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
checks: write
|
|
||||||
statuses: write
|
|
||||||
outputs:
|
|
||||||
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
|
|
||||||
id: deploy
|
|
||||||
uses: ./.github/composite/deploy-vercel
|
|
||||||
with:
|
|
||||||
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
|
|
||||||
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
|
|
||||||
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
|
|
||||||
vercel-token: ${{ secrets.VERCEL_TOKEN }}
|
|
||||||
deploy-v2-vercel-staging:
|
|
||||||
name: Deploy v2 to Vercel (staging)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
deployments: write
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
checks: write
|
|
||||||
statuses: write
|
|
||||||
if: startsWith(github.ref, 'refs/heads/main')
|
|
||||||
outputs:
|
|
||||||
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Deploy staging
|
|
||||||
id: deploy
|
|
||||||
uses: ./.github/composite/deploy-vercel
|
|
||||||
with:
|
|
||||||
environment: staging
|
|
||||||
vercel-org: ${{ secrets.VERCEL_ORG_ID }}
|
|
||||||
vercel-project: ${{ secrets.VERCEL_PROJECT_ID }}
|
|
||||||
vercel-token: ${{ secrets.VERCEL_TOKEN }}
|
|
||||||
deploy-v2-cloudflare:
|
|
||||||
name: Deploy v2 to Cloudflare Worker
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
deployments: write
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
checks: write
|
|
||||||
statuses: write
|
|
||||||
outputs:
|
|
||||||
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
env:
|
|
||||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
|
||||||
- name: Sets env vars for production
|
|
||||||
run: |
|
|
||||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
|
||||||
echo "GITBOOK_URL=https://open-2c.gitbook.com" >> $GITHUB_ENV
|
|
||||||
echo "GITBOOK_ASSETS_PREFIX=https://static-2c.gitbook.com" >> $GITHUB_ENV
|
|
||||||
if: startsWith(github.ref, 'refs/heads/main')
|
|
||||||
- name: Sets env vars for preview
|
|
||||||
run: |
|
|
||||||
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
|
|
||||||
if: 1 && !startsWith(github.ref, 'refs/heads/main')
|
|
||||||
- name: Build worker
|
|
||||||
run: bun run turbo build:v2:cloudflare
|
|
||||||
env:
|
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
|
||||||
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
|
|
||||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
|
||||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
|
|
||||||
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
|
|
||||||
SENTRY_RELEASE: ${{ github.sha }}
|
|
||||||
- id: deploy
|
|
||||||
name: Deploy to Cloudflare
|
|
||||||
uses: cloudflare/wrangler-action@v3.14.0
|
|
||||||
with:
|
|
||||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
|
||||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
||||||
workingDirectory: ./
|
|
||||||
wranglerVersion: '3.82.0'
|
|
||||||
command: versions upload --config ./packages/gitbook-v2/wrangler.toml
|
|
||||||
- name: Outputs
|
|
||||||
run: |
|
|
||||||
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
|
||||||
comment-deployments:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Comment Deployments
|
|
||||||
if: always() && !startsWith(github.ref, 'refs/heads/main')
|
|
||||||
needs:
|
|
||||||
- deploy
|
|
||||||
- deploy-v2-vercel
|
|
||||||
- deploy-v2-cloudflare
|
|
||||||
steps:
|
|
||||||
- name: Find GitHub Comment
|
|
||||||
uses: peter-evans/find-comment@v3
|
|
||||||
id: fc
|
|
||||||
with:
|
|
||||||
issue-number: ${{ github.event.pull_request.number }}
|
|
||||||
comment-author: 'github-actions[bot]'
|
|
||||||
body-includes: 'Summary of the deployments'
|
|
||||||
|
|
||||||
- name: Create or update GitHub comment
|
|
||||||
uses: peter-evans/create-or-update-comment@v4
|
|
||||||
with:
|
|
||||||
comment-id: ${{ steps.fc.outputs.comment-id }}
|
|
||||||
issue-number: ${{ github.event.pull_request.number }}
|
|
||||||
body: |
|
|
||||||
Summary of the deployments:
|
|
||||||
|
|
||||||
### Version 1 (production)
|
|
||||||
|
|
||||||
| Version | URL | Status |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Latest commit | [${{ needs.deploy.outputs.deployment-url }}](${{ needs.deploy.outputs.deployment-url }}) | ${{ needs.deploy.result == 'success' && '✅' || '❌' }} |
|
|
||||||
| PR | [${{ needs.deploy.outputs.deployment-alias-url }}](${{ needs.deploy.outputs.deployment-alias-url }}) | ${{ needs.deploy.result == 'success' && '✅' || '❌' }} |
|
|
||||||
|
|
||||||
### Version 2 (experimental)
|
|
||||||
|
|
||||||
| Version | URL | Status |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Vercel | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}](${{ needs.deploy-v2-vercel.outputs.deployment-url }}) | ${{ needs.deploy-v2-vercel.result == 'success' && '✅' || '❌' }} |
|
|
||||||
| Cloudflare | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}) | ${{ needs.deploy-v2-cloudflare.result == 'success' && '✅' || '❌' }} |
|
|
||||||
|
|
||||||
### Test content
|
|
||||||
|
|
||||||
| Site | v1 | v2 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| GitBook | [${{ needs.deploy.outputs.deployment-url }}/docs.gitbook.com](${{ needs.deploy.outputs.deployment-url }}/docs.gitbook.com) | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/docs.gitbook.com](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/docs.gitbook.com) |
|
|
||||||
| E2E | [${{ needs.deploy.outputs.deployment-url }}/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy.outputs.deployment-url }}/gitbook.gitbook.io/test-gitbook-open) | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open) |
|
|
||||||
edit-mode: replace
|
|
||||||
visual-testing:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Visual Testing
|
|
||||||
needs: deploy
|
|
||||||
timeout-minutes: 6
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
- name: Setup Playwright
|
|
||||||
uses: ./.github/actions/setup-playwright
|
|
||||||
- name: Run Playwright tests
|
|
||||||
run: bun e2e
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
|
|
||||||
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
|
||||||
visual-testing-v2:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Visual Testing v2
|
|
||||||
needs: deploy-v2-vercel
|
|
||||||
timeout-minutes: 6
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
- name: Setup Playwright
|
|
||||||
uses: ./.github/actions/setup-playwright
|
|
||||||
- name: Run Playwright tests
|
|
||||||
run: bun e2e
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
|
|
||||||
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
|
||||||
ARGOS_BUILD_NAME: 'v2'
|
|
||||||
visual-testing-customers:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Visual Testing Customers
|
|
||||||
needs: deploy
|
|
||||||
timeout-minutes: 6
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
- name: Setup Playwright
|
|
||||||
uses: ./.github/actions/setup-playwright
|
|
||||||
- name: Run Playwright tests
|
|
||||||
run: bun e2e-customers
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ needs.deploy.outputs.deployment-url }}
|
|
||||||
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
|
||||||
ARGOS_BUILD_NAME: 'customers'
|
|
||||||
visual-testing-customers-v2:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Visual Testing Customers v2
|
|
||||||
needs: deploy-v2-vercel
|
|
||||||
timeout-minutes: 6
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
- name: Setup Playwright
|
|
||||||
uses: ./.github/actions/setup-playwright
|
|
||||||
- name: Run Playwright tests
|
|
||||||
run: bun e2e-customers
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
|
|
||||||
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
|
||||||
ARGOS_BUILD_NAME: 'customers-v2'
|
|
||||||
pagespeed-testing:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: PageSpeed Testing
|
|
||||||
needs: deploy
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
- name: Setup Bun
|
|
||||||
uses: ./.github/composite/setup-bun
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
env:
|
|
||||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
|
||||||
- name: Run pagespeed tests
|
|
||||||
run: bun ./packages/gitbook/tests/pagespeed-testing.ts $DEPLOYMENT_URL
|
|
||||||
env:
|
|
||||||
DEPLOYMENT_URL: ${{needs.deploy.outputs.deployment-url}}
|
|
||||||
PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
|
|
||||||
format:
|
format:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
name: Format
|
name: Format
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
name: Preview
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
env:
|
||||||
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
|
jobs:
|
||||||
|
deploy-v1-cloudflare:
|
||||||
|
name: Deploy v1 to Cloudflare Pages
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: ${{ github.ref == 'refs/heads/main' && '1c-production' || '1c-preview' }}
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
deployments: write
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
|
checks: write
|
||||||
|
statuses: write
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
deployment-alias-url: ${{ steps.deploy.outputs.deployment-alias-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
env:
|
||||||
|
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||||
|
- name: Sets env vars for production
|
||||||
|
if: github.ref == 'refs/heads/main'
|
||||||
|
run: |
|
||||||
|
echo "GITBOOK_ASSETS_PREFIX=https://static.gitbook.com" >> $GITHUB_ENV
|
||||||
|
- name: Build Next.js with next-on-pages
|
||||||
|
run: bun run turbo gitbook#build:cloudflare
|
||||||
|
env:
|
||||||
|
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
|
||||||
|
GITBOOK_RUNTIME: cloudflare
|
||||||
|
- id: deploy
|
||||||
|
name: Deploy to Cloudflare
|
||||||
|
uses: cloudflare/wrangler-action@v3.14.0
|
||||||
|
with:
|
||||||
|
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
|
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
|
workingDirectory: ./
|
||||||
|
wranglerVersion: '3.112.0'
|
||||||
|
command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
|
||||||
|
- name: Outputs
|
||||||
|
run: |
|
||||||
|
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||||
|
echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}"
|
||||||
|
deploy-v2-vercel:
|
||||||
|
name: Deploy v2 to Vercel (preview)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2v-preview
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy to Vercel
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-vercel
|
||||||
|
with:
|
||||||
|
environment: preview
|
||||||
|
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
|
||||||
|
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||||
|
vercelToken: ${{ secrets.VERCEL_TOKEN }}
|
||||||
|
opItem: op://gitbook-open/2v-preview
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
deploy-v2-cloudflare:
|
||||||
|
name: Deploy v2 to Cloudflare Worker (preview)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2c-preview
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url || steps.extract-worker-id.outputs.worker-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy to Cloudflare
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-cloudflare
|
||||||
|
with:
|
||||||
|
environment: preview
|
||||||
|
deploy: ${{ github.ref == 'refs/heads/main' }}
|
||||||
|
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
|
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
|
opItem: op://gitbook-open/2c-preview
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
commitTag: ${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
|
||||||
|
commitMessage: ${{ github.sha }}
|
||||||
|
- name: Extract Worker ID
|
||||||
|
id: extract-worker-id
|
||||||
|
if: ${{ !steps.deploy.outputs.deployment-url }}
|
||||||
|
run: |
|
||||||
|
if [[ "${{ steps.deploy.outputs.command-output }}" =~ Worker\ Version\ ID:\ ([0-9a-f]{8})-([0-9a-f-]+) ]]; then
|
||||||
|
WORKER_ID_FIRST_PART="${BASH_REMATCH[1]}"
|
||||||
|
echo "worker-url=https://${WORKER_ID_FIRST_PART}-gitbook-open-v2-preview.gitbook.workers.dev/" >> $GITHUB_OUTPUT
|
||||||
|
fi
|
||||||
|
- name: Outputs
|
||||||
|
run: |
|
||||||
|
echo "URL: ${{ steps.deploy.outputs.deployment-url || steps.extract-worker-id.outputs.worker-url }}"
|
||||||
|
comment-deployments:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Comment Deployments (preview)
|
||||||
|
if: always() && !startsWith(github.ref, 'refs/heads/main')
|
||||||
|
needs:
|
||||||
|
- deploy-v1-cloudflare
|
||||||
|
- deploy-v2-vercel
|
||||||
|
- deploy-v2-cloudflare
|
||||||
|
steps:
|
||||||
|
- name: Find GitHub Comment
|
||||||
|
uses: peter-evans/find-comment@v3
|
||||||
|
id: fc
|
||||||
|
with:
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
comment-author: 'github-actions[bot]'
|
||||||
|
body-includes: 'Summary of the deployments'
|
||||||
|
|
||||||
|
- name: Create or update GitHub comment
|
||||||
|
uses: peter-evans/create-or-update-comment@v4
|
||||||
|
with:
|
||||||
|
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
body: |
|
||||||
|
Summary of the deployments:
|
||||||
|
|
||||||
|
### Version 1
|
||||||
|
|
||||||
|
| Version | URL | Status |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Latest commit | [${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}](${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}) | ${{ needs.deploy-v1-cloudflare.result == 'success' && '✅' || '❌' }} |
|
||||||
|
| PR | [${{ needs.deploy-v1-cloudflare.outputs.deployment-alias-url }}](${{ needs.deploy-v1-cloudflare.outputs.deployment-alias-url }}) | ${{ needs.deploy-v1-cloudflare.result == 'success' && '✅' || '❌' }} |
|
||||||
|
|
||||||
|
### Version 2
|
||||||
|
|
||||||
|
| Version | URL | Status |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Vercel | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}](${{ needs.deploy-v2-vercel.outputs.deployment-url }}) | ${{ needs.deploy-v2-vercel.result == 'success' && '✅' || '❌' }} |
|
||||||
|
| Cloudflare | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}) | ${{ needs.deploy-v2-cloudflare.result == 'success' && '✅' || '❌' }} |
|
||||||
|
|
||||||
|
### Test content
|
||||||
|
|
||||||
|
| Site | `v1` | `2v` | `2c` |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| GitBook | [${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}/docs.gitbook.com](${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}/docs.gitbook.com) | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/docs.gitbook.com](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/docs.gitbook.com) | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/docs.gitbook.com](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/docs.gitbook.com) |
|
||||||
|
| E2E | [${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}/gitbook.gitbook.io/test-gitbook-open) | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open) | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open) |
|
||||||
|
edit-mode: replace
|
||||||
|
visual-testing-v1:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing v1
|
||||||
|
needs: deploy-v1-cloudflare
|
||||||
|
timeout-minutes: 8
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
visual-testing-v2-vercel:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing v2
|
||||||
|
needs: deploy-v2-vercel
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
|
||||||
|
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
ARGOS_BUILD_NAME: 'v2-vercel'
|
||||||
|
visual-testing-v2-cloudflare:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing v2 (Cloudflare)
|
||||||
|
needs: deploy-v2-cloudflare
|
||||||
|
timeout-minutes: 10
|
||||||
|
if: startsWith(github.head_ref || github.ref_name, 'cloudflare/') || github.ref == 'refs/heads/main'
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}
|
||||||
|
SITE_BASE_URL: ${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
ARGOS_BUILD_NAME: 'v2-cloudflare'
|
||||||
|
visual-testing-customers-v1:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing Customers v1
|
||||||
|
needs: deploy-v1-cloudflare
|
||||||
|
timeout-minutes: 8
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e-customers
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v1-cloudflare.outputs.deployment-url }}
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
ARGOS_BUILD_NAME: 'customers-v1'
|
||||||
|
visual-testing-customers-v2:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing Customers v2
|
||||||
|
needs: deploy-v2-vercel
|
||||||
|
timeout-minutes: 8
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e-customers
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
|
||||||
|
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
ARGOS_BUILD_NAME: 'customers-v2'
|
||||||
|
visual-testing-customers-v2-cloudflare:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Visual Testing Customers v2 (Cloudflare)
|
||||||
|
needs: deploy-v2-cloudflare
|
||||||
|
timeout-minutes: 8
|
||||||
|
if: startsWith(github.head_ref || github.ref_name, 'cloudflare/') || github.ref == 'refs/heads/main'
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
- name: Setup Playwright
|
||||||
|
uses: ./.github/actions/setup-playwright
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: bun e2e-customers
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}
|
||||||
|
SITE_BASE_URL: ${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/
|
||||||
|
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||||
|
ARGOS_BUILD_NAME: 'customers-v2'
|
||||||
|
pagespeed-testing-v1:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: PageSpeed Testing v1
|
||||||
|
needs: deploy-v1-cloudflare
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: ./.github/composite/setup-bun
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
env:
|
||||||
|
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||||
|
- name: Run pagespeed tests
|
||||||
|
run: bun ./packages/gitbook/tests/pagespeed-testing.ts
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{needs.deploy-v1-cloudflare.outputs.deployment-url}}
|
||||||
|
PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Production
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
env:
|
||||||
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
|
jobs:
|
||||||
|
deploy-v2-vercel:
|
||||||
|
name: Deploy v2 to Vercel (production)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2v-production
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-vercel
|
||||||
|
with:
|
||||||
|
environment: production
|
||||||
|
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
|
||||||
|
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||||
|
vercelToken: ${{ secrets.VERCEL_TOKEN }}
|
||||||
|
opItem: op://gitbook-open/2v-production
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
deploy-v2-cloudflare:
|
||||||
|
name: Deploy v2 to Cloudflare Worker (production)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2c-production
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-cloudflare
|
||||||
|
with:
|
||||||
|
environment: production
|
||||||
|
deploy: true
|
||||||
|
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
|
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
|
opItem: op://gitbook-open/2c-production
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
commitTag: main
|
||||||
|
commitMessage: ${{ github.sha }}
|
||||||
|
- name: Outputs
|
||||||
|
run: |
|
||||||
|
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Staging
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
env:
|
||||||
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
|
jobs:
|
||||||
|
deploy-v2-vercel:
|
||||||
|
name: Deploy v2 to Vercel (staging)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2v-staging
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-vercel
|
||||||
|
with:
|
||||||
|
environment: staging
|
||||||
|
vercelOrg: ${{ secrets.VERCEL_ORG_ID }}
|
||||||
|
vercelProject: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||||
|
vercelToken: ${{ secrets.VERCEL_TOKEN }}
|
||||||
|
opItem: op://gitbook-open/2v-staging
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
deploy-v2-cloudflare:
|
||||||
|
name: Deploy v2 to Cloudflare Worker (staging)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: 2c-staging
|
||||||
|
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
outputs:
|
||||||
|
deployment-url: ${{ steps.deploy.outputs.deployment-url }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Deploy
|
||||||
|
id: deploy
|
||||||
|
uses: ./.github/composite/deploy-cloudflare
|
||||||
|
with:
|
||||||
|
environment: staging
|
||||||
|
deploy: true
|
||||||
|
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
|
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
|
opItem: op://gitbook-open/2c-staging
|
||||||
|
opServiceAccount: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
|
||||||
|
commitTag: main
|
||||||
|
commitMessage: ${{ github.sha }}
|
||||||
|
- name: Outputs
|
||||||
|
run: |
|
||||||
|
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||||
@@ -5,6 +5,9 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
|
env:
|
||||||
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
|
|
||||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
.next
|
|
||||||
.vercel
|
|
||||||
.open-next
|
|
||||||
|
|
||||||
# Generated
|
|
||||||
packages/emoji-codepoints/index.ts
|
|
||||||
packages/gitbook/public/~gitbook/static/
|
|
||||||
packages/icons/src/data/*.json
|
|
||||||
|
|
||||||
# Build files
|
|
||||||
dist/
|
|
||||||
|
|
||||||
README.md
|
|
||||||
CHANGELOG.md
|
|
||||||
|
|
||||||
# v2
|
|
||||||
packages/gitbook-v2/public/~gitbook/static/
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"printWidth": 100,
|
|
||||||
"singleQuote": true,
|
|
||||||
"tabWidth": 4
|
|
||||||
}
|
|
||||||
Vendored
+5
-1
@@ -11,6 +11,10 @@
|
|||||||
"prettier.enable": false,
|
"prettier.enable": false,
|
||||||
"editor.defaultFormatter": "biomejs.biome",
|
"editor.defaultFormatter": "biomejs.biome",
|
||||||
"editor.codeActionsOnSave": {
|
"editor.codeActionsOnSave": {
|
||||||
"source.organizeImports": "explicit"
|
"source.organizeImports.biome": "explicit",
|
||||||
|
"source.fixAll.biome": "explicit"
|
||||||
|
},
|
||||||
|
"[typescript]": {
|
||||||
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,15 +59,15 @@ bun install
|
|||||||
4. Start your local development server.
|
4. Start your local development server.
|
||||||
|
|
||||||
```
|
```
|
||||||
bun dev
|
bun dev:v2
|
||||||
```
|
```
|
||||||
|
|
||||||
5. Open a published GitBook space in your web browser, prefixing it with `http://localhost:3000/`.
|
5. Open a published GitBook space in your web browser, prefixing it with `http://localhost:3000/`.
|
||||||
|
|
||||||
examples:
|
examples:
|
||||||
|
|
||||||
- http://localhost:3000/docs.gitbook.com
|
- http://localhost:3000/url/docs.gitbook.com
|
||||||
- http://localhost:3000/open-source.gitbook.io/midjourney
|
- http://localhost:3000/url/open-source.gitbook.io/midjourney
|
||||||
|
|
||||||
Any published GitBook site can be accessed through your local development instance, and any updates you make to the codebase will be reflected in your browser.
|
Any published GitBook site can be accessed through your local development instance, and any updates you make to the codebase will be reflected in your browser.
|
||||||
|
|
||||||
|
|||||||
+10
-2
@@ -18,7 +18,10 @@
|
|||||||
"**/.vercel/**/*",
|
"**/.vercel/**/*",
|
||||||
"**/.cache/**/*",
|
"**/.cache/**/*",
|
||||||
"**/.wrangler/**/*",
|
"**/.wrangler/**/*",
|
||||||
"packages/openapi-parser/src/fixtures/**/*"
|
"packages/openapi-parser/src/fixtures/**/*",
|
||||||
|
"packages/emoji-codepoints/index.ts",
|
||||||
|
"packages/icons/src/data/*.json",
|
||||||
|
"packages/cache-do/worker-configuration.d.ts"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"formatter": {
|
"formatter": {
|
||||||
@@ -67,7 +70,12 @@
|
|||||||
"useThrowOnlyError": "error"
|
"useThrowOnlyError": "error"
|
||||||
},
|
},
|
||||||
"suspicious": {
|
"suspicious": {
|
||||||
"noConsole": "warn",
|
"noConsole": {
|
||||||
|
"level": "warn",
|
||||||
|
"options": {
|
||||||
|
"allow": ["assert", "error", "warn"]
|
||||||
|
}
|
||||||
|
},
|
||||||
"noExplicitAny": "warn",
|
"noExplicitAny": "warn",
|
||||||
"noImplicitAnyLet": "warn",
|
"noImplicitAnyLet": "warn",
|
||||||
"noConfusingVoidType": "warn",
|
"noConfusingVoidType": "warn",
|
||||||
|
|||||||
+4
-3
@@ -4,14 +4,15 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "^1.9.4",
|
"@biomejs/biome": "^1.9.4",
|
||||||
"@changesets/cli": "^2.27.12",
|
"@changesets/cli": "^2.27.12",
|
||||||
"turbo": "^2.4.4",
|
"turbo": "^2.5.0",
|
||||||
"vercel": "^39.3.0"
|
"vercel": "^39.3.0"
|
||||||
},
|
},
|
||||||
"packageManager": "bun@1.2.4",
|
"packageManager": "bun@1.2.8",
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"@codemirror/state": "6.4.1",
|
"@codemirror/state": "6.4.1",
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-dom": "18.3.1"
|
"react-dom": "18.3.1",
|
||||||
|
"@gitbook/api": "0.111.0"
|
||||||
},
|
},
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -21,10 +21,10 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.5.3",
|
"typescript": "^5.5.3",
|
||||||
"wrangler": "^3.109.2"
|
"wrangler": "^4.10.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"generate": "wrangler types --experimental-include-runtime",
|
"generate": "wrangler types",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"dev": "tsc -w",
|
"dev": "tsc -w",
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"incremental": true,
|
"incremental": true,
|
||||||
"types": ["./.wrangler/types/runtime.d.ts"]
|
"types": ["./worker-configuration.d.ts"]
|
||||||
},
|
},
|
||||||
"include": ["src/**/*.ts"],
|
"include": ["src/**/*.ts"],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": ["//"],
|
||||||
|
"tasks": {
|
||||||
|
"generate": {
|
||||||
|
"outputs": ["worker-configuration.d.ts"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# @gitbook/cache-tags
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- 77397ca: Fix version of @gitbook/api referenced in package.json
|
||||||
|
|
||||||
|
## 0.3.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- 116575c: Improve typing of getComputedContentSourceCacheTags to match latest API specification
|
||||||
|
|
||||||
|
## 0.2.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- f32bf1f: Export function `getCacheTagForURL` to easily get the cache tag for a URL.
|
||||||
|
|
||||||
|
## 0.1.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- 05ffd0e: Initial version of the package
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# `@gitbook/cache-tags`
|
||||||
|
|
||||||
|
Utility to generate cache tags for GitBook Open.
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@gitbook/proxy",
|
"name": "@gitbook/cache-tags",
|
||||||
"description": "Host a GitBook site on your own domain as a subpath",
|
"type": "module",
|
||||||
"version": "0.1.0",
|
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
@@ -9,15 +8,18 @@
|
|||||||
"default": "./dist/index.js"
|
"default": "./dist/index.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {},
|
"version": "0.3.1",
|
||||||
|
"dependencies": {
|
||||||
|
"@gitbook/api": "^0.111.0",
|
||||||
|
"assert-never": "^1.2.1"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.5.3"
|
"typescript": "^5.5.3"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"clean": "rm -rf ./dist",
|
"dev": "tsc -w"
|
||||||
"unit": "bun test"
|
|
||||||
},
|
},
|
||||||
"files": ["dist", "src", "README.md", "CHANGELOG.md"]
|
"files": ["dist", "src", "README.md", "CHANGELOG.md"]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
import type { ComputedContentSource } from '@gitbook/api';
|
||||||
|
import assertNever from 'assert-never';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a stringified cache tag for a given object.
|
||||||
|
*/
|
||||||
|
export function getCacheTag(
|
||||||
|
spec: /**
|
||||||
|
* All data related to a user
|
||||||
|
* @deprecated - in v2, no tag as this is an immutable data
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'user';
|
||||||
|
user: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to a space
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'space';
|
||||||
|
space: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to an integration.
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'integration';
|
||||||
|
integration: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to a change request
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'change-request';
|
||||||
|
space: string;
|
||||||
|
changeRequest: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Immutable data related to a revision
|
||||||
|
* @deprecated - in v2, no tag as this is an immutable data
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'revision';
|
||||||
|
space: string;
|
||||||
|
revision: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Immutable data related to a document
|
||||||
|
* @deprecated - in v2, no tag as this is an immutable data
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'document';
|
||||||
|
space: string;
|
||||||
|
document: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Immutable data related to a computed document
|
||||||
|
* @deprecated - in v2, no tag as this is an immutable data
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'computed-document';
|
||||||
|
space: string;
|
||||||
|
sourceType: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to the URL of a content
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'url';
|
||||||
|
hostname: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to a site
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'site';
|
||||||
|
site: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to an OpenAPI spec
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'openapi';
|
||||||
|
organization: string;
|
||||||
|
openAPISpec: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* All data related to a translation
|
||||||
|
*/
|
||||||
|
| {
|
||||||
|
tag: 'translation';
|
||||||
|
organization: string;
|
||||||
|
translationSettings: string;
|
||||||
|
}
|
||||||
|
): string {
|
||||||
|
switch (spec.tag) {
|
||||||
|
case 'user':
|
||||||
|
return `user:${spec.user}`;
|
||||||
|
case 'url':
|
||||||
|
return `url:${spec.hostname}`;
|
||||||
|
case 'space':
|
||||||
|
return `space:${spec.space}`;
|
||||||
|
case 'change-request':
|
||||||
|
return `space:${spec.space}:change-request:${spec.changeRequest}`;
|
||||||
|
case 'revision':
|
||||||
|
return `space:${spec.space}:revision:${spec.revision}`;
|
||||||
|
case 'document':
|
||||||
|
return `space:${spec.space}:document:${spec.document}`;
|
||||||
|
case 'computed-document':
|
||||||
|
return `space:${spec.space}:computed-document:${spec.sourceType}`;
|
||||||
|
case 'site':
|
||||||
|
return `site:${spec.site}`;
|
||||||
|
case 'integration':
|
||||||
|
return `integration:${spec.integration}`;
|
||||||
|
case 'openapi':
|
||||||
|
return `organization:${spec.organization}:openapi:${spec.openAPISpec}`;
|
||||||
|
case 'translation':
|
||||||
|
return `organization:${spec.organization}:translation:${spec.translationSettings}`;
|
||||||
|
default:
|
||||||
|
assertNever(spec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the cache tag for a given URL.
|
||||||
|
*/
|
||||||
|
export function getCacheTagForURL(url: string | URL) {
|
||||||
|
const parsedURL = url instanceof URL ? url : new URL(url);
|
||||||
|
return getCacheTag({
|
||||||
|
tag: 'url',
|
||||||
|
hostname: parsedURL.hostname,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the tags for a computed content source.
|
||||||
|
*/
|
||||||
|
export function getComputedContentSourceCacheTags(
|
||||||
|
inContext: {
|
||||||
|
spaceId: string;
|
||||||
|
organizationId: string;
|
||||||
|
},
|
||||||
|
source: ComputedContentSource
|
||||||
|
) {
|
||||||
|
const tags: string[] = [];
|
||||||
|
|
||||||
|
// We add the dependencies as tags, to ensure that the computed content is invalidated
|
||||||
|
// when the dependencies are updated.
|
||||||
|
const dependencies = Object.values(source.dependencies ?? {});
|
||||||
|
if (dependencies.length > 0) {
|
||||||
|
dependencies.forEach((dependency) => {
|
||||||
|
switch (dependency.ref.kind) {
|
||||||
|
case 'space':
|
||||||
|
tags.push(
|
||||||
|
getCacheTag({
|
||||||
|
tag: 'space',
|
||||||
|
space: dependency.ref.space,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'openapi':
|
||||||
|
tags.push(
|
||||||
|
getCacheTag({
|
||||||
|
tag: 'openapi',
|
||||||
|
organization: inContext.organizationId,
|
||||||
|
openAPISpec: dependency.ref.spec,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'translation-language':
|
||||||
|
tags.push(
|
||||||
|
getCacheTag({
|
||||||
|
tag: 'translation',
|
||||||
|
organization: inContext.organizationId,
|
||||||
|
translationSettings: dependency.ref.translationSettings,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// Do not throw for unknown dependency types
|
||||||
|
// as it might mean we are lacking behind the API version
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Push a dummy tag, as the v1 is only using the first tag
|
||||||
|
tags.push(
|
||||||
|
getCacheTag({
|
||||||
|
tag: 'computed-document',
|
||||||
|
space: inContext.spaceId,
|
||||||
|
sourceType: source.type,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// We invalidate the computed content when a new version of the integration is deployed.
|
||||||
|
|
||||||
|
if (source.type.startsWith('integration:')) {
|
||||||
|
const integration = source.type.split(':')[1];
|
||||||
|
tags.push(
|
||||||
|
getCacheTag({
|
||||||
|
tag: 'integration',
|
||||||
|
integration,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
@@ -13,11 +13,12 @@
|
|||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
"incremental": true,
|
"incremental": true,
|
||||||
"types": [
|
"types": [
|
||||||
"bun-types" // add Bun global
|
"bun-types" // add Bun global
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"include": ["src/**/*.ts"],
|
"include": ["src/**/*.ts", "src/**/*.tsx"],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,25 @@
|
|||||||
# @gitbook/colors
|
# @gitbook/colors
|
||||||
|
|
||||||
|
## 0.3.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- cdffd7c: Desaturate text colors by decreasing chroma for the last steps of the color scale
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- fb90eb0: Reduce chroma of first color scale step
|
||||||
|
|
||||||
|
## 0.3.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- 4f0a772: Override tint lightness if supplied color is out of bounds
|
||||||
|
|
||||||
## 0.2.0
|
## 0.2.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|
||||||
- 445baaa: Initial release
|
- 445baaa: Initial release
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
"default": "./dist/index.js"
|
"default": "./dist/index.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"version": "0.2.0",
|
"version": "0.3.2",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.5.3"
|
"typescript": "^5.5.3"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -184,6 +184,7 @@ export function colorScale(
|
|||||||
const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null;
|
const mixColor = mix?.color ? rgbToOklch(hexToRgbArray(mix.color)) : null;
|
||||||
const foregroundColor = rgbToOklch(hexToRgbArray(foreground));
|
const foregroundColor = rgbToOklch(hexToRgbArray(foreground));
|
||||||
const backgroundColor = rgbToOklch(hexToRgbArray(background));
|
const backgroundColor = rgbToOklch(hexToRgbArray(background));
|
||||||
|
let mapping = darkMode ? colorMixMapping.dark : colorMixMapping.light;
|
||||||
|
|
||||||
if (mixColor && mix?.ratio && mix.ratio > 0) {
|
if (mixColor && mix?.ratio && mix.ratio > 0) {
|
||||||
// If defined, we mix in a (tiny) bit of the mix color with the base color.
|
// If defined, we mix in a (tiny) bit of the mix color with the base color.
|
||||||
@@ -192,7 +193,20 @@ export function colorScale(
|
|||||||
baseColor.H = mix.color === DEFAULT_TINT_COLOR ? baseColor.H : mixColor.H;
|
baseColor.H = mix.color === DEFAULT_TINT_COLOR ? baseColor.H : mixColor.H;
|
||||||
}
|
}
|
||||||
|
|
||||||
const mapping = darkMode ? colorMixMapping.dark : colorMixMapping.light;
|
if (
|
||||||
|
(darkMode && baseColor.L < backgroundColor.L) ||
|
||||||
|
(!darkMode && baseColor.L > backgroundColor.L)
|
||||||
|
) {
|
||||||
|
// If the supplied color is outside of our lightness bounds, use the supplied color's lightness.
|
||||||
|
// This is mostly used to allow darker-than-dark backgrounds for brands that specifically want that look.
|
||||||
|
const difference = (backgroundColor.L - baseColor.L) / backgroundColor.L;
|
||||||
|
backgroundColor.L = baseColor.L;
|
||||||
|
// At the edges of the scale, the subtle lightness changes stop being perceptible. We need to amp up our mapping to still stand out.
|
||||||
|
const amplifier = 1;
|
||||||
|
mapping = mapping.map((step, index) =>
|
||||||
|
index < 9 ? step + step * amplifier * difference : step
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const result = [];
|
const result = [];
|
||||||
|
|
||||||
@@ -206,7 +220,7 @@ export function colorScale(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const chromaRatio = index < 8 ? (index + 1) * 0.05 : 1;
|
const chromaRatio = index === 8 || index === 9 ? 1 : index * 0.05;
|
||||||
|
|
||||||
const shade = {
|
const shade = {
|
||||||
L: targetL, // Blend lightness
|
L: targetL, // Blend lightness
|
||||||
|
|||||||
@@ -1,13 +1,62 @@
|
|||||||
# gitbook-v2
|
# gitbook-v2
|
||||||
|
|
||||||
|
## 0.2.5
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [77397ca]
|
||||||
|
- @gitbook/cache-tags@0.3.1
|
||||||
|
|
||||||
|
## 0.2.4
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- 4234289: Fix incoming URL for requests that were proxied
|
||||||
|
- Updated dependencies [116575c]
|
||||||
|
- @gitbook/cache-tags@0.3.0
|
||||||
|
|
||||||
|
## 0.2.3
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- 5b2bf82: Use stable site URL data for route rewrite in the middleware
|
||||||
|
|
||||||
|
## 0.2.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- 54ee014: Add initial support for loading custom fonts
|
||||||
|
- bba2e52: Fix site redirects when it includes a section/variant path
|
||||||
|
|
||||||
|
## 0.2.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [f32bf1f]
|
||||||
|
- @gitbook/cache-tags@0.2.0
|
||||||
|
|
||||||
|
## 0.2.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- 76c7974: Add route to revalidate cached data
|
||||||
|
|
||||||
|
## 0.1.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- 05ffd0e: Improving data cache management for computed content
|
||||||
|
- Updated dependencies [05ffd0e]
|
||||||
|
- @gitbook/cache-tags@0.1.0
|
||||||
|
|
||||||
## 0.1.1
|
## 0.1.1
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|
||||||
- 3e11678: fix: lost section groups
|
- 3e11678: fix: lost section groups
|
||||||
|
|
||||||
## 0.1.0
|
## 0.1.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|
||||||
- cfccc44: Setup structure and deployment for new version
|
- cfccc44: Setup structure and deployment for new version
|
||||||
|
|||||||
@@ -5,15 +5,37 @@
|
|||||||
*/
|
*/
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
experimental: {
|
experimental: {
|
||||||
|
// This is needed to throw "forbidden" when the api token expired during revalidation
|
||||||
|
authInterrupts: true,
|
||||||
useCache: true,
|
useCache: true,
|
||||||
|
|
||||||
|
// Content is fully static, we can cache it in the session memory cache for a long time
|
||||||
|
staleTimes: {
|
||||||
|
dynamic: 3600, // 1 hour
|
||||||
|
static: 3600, // 1 hour
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
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_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
|
// GitBook envs
|
||||||
|
GITBOOK_API_URL: process.env.GITBOOK_API_URL,
|
||||||
|
GITBOOK_APP_URL: process.env.GITBOOK_APP_URL,
|
||||||
|
GITBOOK_INTEGRATIONS_HOST: process.env.GITBOOK_INTEGRATIONS_HOST,
|
||||||
|
GITBOOK_IMAGE_RESIZE_URL: process.env.GITBOOK_IMAGE_RESIZE_URL,
|
||||||
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,
|
||||||
|
GITBOOK_IMAGE_RESIZE_MODE: process.env.GITBOOK_IMAGE_RESIZE_MODE,
|
||||||
|
GITBOOK_FONTS_URL: process.env.GITBOOK_FONTS_URL,
|
||||||
|
GITBOOK_RUNTIME: process.env.GITBOOK_RUNTIME,
|
||||||
|
|
||||||
|
// 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
|
||||||
@@ -31,6 +53,24 @@ const nextConfig = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: '/~gitbook/static/:path*',
|
||||||
|
headers: [
|
||||||
|
{
|
||||||
|
key: 'Cache-Control',
|
||||||
|
value: 'public, max-age=31536000, immutable',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'Access-Control-Allow-Origin',
|
||||||
|
value: '*',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
@@ -1,30 +1,18 @@
|
|||||||
// default open-next.config.ts file created by @opennextjs/cloudflare
|
import { defineCloudflareConfig } from '@opennextjs/cloudflare';
|
||||||
|
import r2IncrementalCache from '@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache';
|
||||||
|
import { withRegionalCache } from '@opennextjs/cloudflare/overrides/incremental-cache/regional-cache';
|
||||||
|
import doQueue from '@opennextjs/cloudflare/overrides/queue/do-queue';
|
||||||
|
import doShardedTagCache from '@opennextjs/cloudflare/overrides/tag-cache/do-sharded-tag-cache';
|
||||||
|
|
||||||
import cache from '@opennextjs/cloudflare/kvCache';
|
export default defineCloudflareConfig({
|
||||||
|
incrementalCache: withRegionalCache(r2IncrementalCache, { mode: 'long-lived' }),
|
||||||
const config = {
|
tagCache: doShardedTagCache({
|
||||||
default: {
|
baseShardSize: 12,
|
||||||
override: {
|
regionalCache: true,
|
||||||
wrapper: 'cloudflare-node',
|
shardReplication: {
|
||||||
converter: 'edge',
|
numberOfSoftReplicas: 2,
|
||||||
incrementalCache: async () => cache,
|
numberOfHardReplicas: 1,
|
||||||
tagCache: 'dummy',
|
|
||||||
queue: 'dummy',
|
|
||||||
},
|
},
|
||||||
},
|
}),
|
||||||
|
queue: doQueue,
|
||||||
middleware: {
|
});
|
||||||
external: true,
|
|
||||||
override: {
|
|
||||||
wrapper: 'cloudflare-edge',
|
|
||||||
converter: 'edge',
|
|
||||||
proxyExternalRequest: 'fetch',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
dangerous: {
|
|
||||||
enableCacheInterception: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
|
|||||||
@@ -1,18 +1,24 @@
|
|||||||
{
|
{
|
||||||
"name": "gitbook-v2",
|
"name": "gitbook-v2",
|
||||||
"version": "0.1.1",
|
"version": "0.2.5",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"next": "canary",
|
"next": "canary",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"@gitbook/api": "0.96.1",
|
"@gitbook/api": "*",
|
||||||
|
"@gitbook/cache-tags": "workspace:*",
|
||||||
"@sindresorhus/fnv1a": "^3.1.0",
|
"@sindresorhus/fnv1a": "^3.1.0",
|
||||||
"server-only": "^0.0.1"
|
"server-only": "^0.0.1",
|
||||||
|
"warn-once": "^0.1.1",
|
||||||
|
"rison": "^0.1.1",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
|
"assert-never": "^1.2.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"gitbook": "*",
|
"gitbook": "*",
|
||||||
"@opennextjs/cloudflare": "^0.5.3",
|
"@opennextjs/cloudflare": "^1.0.0-beta.3",
|
||||||
|
"@types/rison": "^0.0.9",
|
||||||
"tailwindcss": "^3.4.0",
|
"tailwindcss": "^3.4.0",
|
||||||
"postcss": "^8"
|
"postcss": "^8"
|
||||||
},
|
},
|
||||||
@@ -22,8 +28,9 @@
|
|||||||
"build": "next build",
|
"build": "next build",
|
||||||
"build:v2": "next build",
|
"build:v2": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"build:v2:cloudflare": "opennextjs-cloudflare",
|
"build:v2:cloudflare": "opennextjs-cloudflare build",
|
||||||
"dev:v2:cloudflare": "wrangler dev --port 8771",
|
"dev:v2:cloudflare": "wrangler dev --port 8771",
|
||||||
"unit": "bun test"
|
"unit": "bun test",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-7
@@ -13,26 +13,24 @@ type PageProps = {
|
|||||||
|
|
||||||
export default async function Page(props: PageProps) {
|
export default async function Page(props: PageProps) {
|
||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
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> {
|
||||||
const context = await getDynamicSiteContext(await props.params);
|
const { context } = await getDynamicSiteContext(await props.params);
|
||||||
return generateSitePageViewport(context);
|
return generateSitePageViewport(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+5
-4
@@ -16,15 +16,16 @@ export default async function SiteDynamicLayout({
|
|||||||
params,
|
params,
|
||||||
children,
|
children,
|
||||||
}: React.PropsWithChildren<SiteDynamicLayoutProps>) {
|
}: React.PropsWithChildren<SiteDynamicLayoutProps>) {
|
||||||
const context = await getDynamicSiteContext(await params);
|
const { context, visitorAuthClaims } = await getDynamicSiteContext(await params);
|
||||||
const forcedTheme = await getThemeFromMiddleware();
|
const forcedTheme = await getThemeFromMiddleware();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CustomizationRootLayout customization={context.customization}>
|
<CustomizationRootLayout forcedTheme={forcedTheme} customization={context.customization}>
|
||||||
<SiteLayout
|
<SiteLayout
|
||||||
context={context}
|
context={context}
|
||||||
forcedTheme={forcedTheme}
|
forcedTheme={forcedTheme}
|
||||||
withTracking={!GITBOOK_DISABLE_TRACKING}
|
withTracking={!GITBOOK_DISABLE_TRACKING}
|
||||||
|
visitorAuthClaims={visitorAuthClaims}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</SiteLayout>
|
</SiteLayout>
|
||||||
@@ -33,11 +34,11 @@ export default async function SiteDynamicLayout({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function generateViewport({ params }: SiteDynamicLayoutProps) {
|
export async function generateViewport({ params }: SiteDynamicLayoutProps) {
|
||||||
const context = await getDynamicSiteContext(await params);
|
const { context } = await getDynamicSiteContext(await params);
|
||||||
return generateSiteLayoutViewport(context);
|
return generateSiteLayoutViewport(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateMetadata({ params }: SiteDynamicLayoutProps) {
|
export async function generateMetadata({ params }: SiteDynamicLayoutProps) {
|
||||||
const context = await getDynamicSiteContext(await params);
|
const { context } = await getDynamicSiteContext(await params);
|
||||||
return generateSiteLayoutMetadata(context);
|
return generateSiteLayoutMetadata(context);
|
||||||
}
|
}
|
||||||
+1
-3
@@ -3,12 +3,10 @@ import type { NextRequest } from 'next/server';
|
|||||||
import { serveIcon } from '@/routes/icon';
|
import { serveIcon } from '@/routes/icon';
|
||||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
||||||
|
|
||||||
export const dynamic = 'force-static';
|
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getDynamicSiteContext(await params);
|
const { context } = await getDynamicSiteContext(await params);
|
||||||
return serveIcon(context, request);
|
return serveIcon(context, request);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -8,6 +8,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
|
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getDynamicSiteContext(await params);
|
const { context } = await getDynamicSiteContext(await params);
|
||||||
return serveOGImage(context, await params);
|
return serveOGImage(context, await params);
|
||||||
}
|
}
|
||||||
+12
@@ -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>;
|
||||||
|
}
|
||||||
+20
@@ -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} />;
|
||||||
|
}
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import type { NextRequest } from 'next/server';
|
|
||||||
|
|
||||||
import { serveLLMsTxt } from '@/routes/llms';
|
|
||||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
|
||||||
|
|
||||||
export async function GET(
|
|
||||||
_request: NextRequest,
|
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
|
||||||
) {
|
|
||||||
const context = await getDynamicSiteContext(await params);
|
|
||||||
return serveLLMsTxt(context);
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import type { NextRequest } from 'next/server';
|
|
||||||
|
|
||||||
import { serveRobotsTxt } from '@/routes/robots';
|
|
||||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
|
||||||
|
|
||||||
export async function GET(
|
|
||||||
_request: NextRequest,
|
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
|
||||||
) {
|
|
||||||
const context = await getDynamicSiteContext(await params);
|
|
||||||
return serveRobotsTxt(context);
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import type { NextRequest } from 'next/server';
|
|
||||||
|
|
||||||
import { servePagesSitemap } from '@/routes/sitemap';
|
|
||||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
|
||||||
|
|
||||||
export async function GET(
|
|
||||||
_request: NextRequest,
|
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
|
||||||
) {
|
|
||||||
const context = await getDynamicSiteContext(await params);
|
|
||||||
return servePagesSitemap(context);
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import type { NextRequest } from 'next/server';
|
|
||||||
|
|
||||||
import { serveRootSitemap } from '@/routes/sitemap';
|
|
||||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@v2/app/utils';
|
|
||||||
|
|
||||||
export async function GET(
|
|
||||||
_request: NextRequest,
|
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
|
||||||
) {
|
|
||||||
const context = await getDynamicSiteContext(await params);
|
|
||||||
return serveRootSitemap(context);
|
|
||||||
}
|
|
||||||
+5
-11
@@ -4,9 +4,8 @@ import {
|
|||||||
generateSitePageViewport,
|
generateSitePageViewport,
|
||||||
} from '@/components/SitePage';
|
} from '@/components/SitePage';
|
||||||
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@v2/app/utils';
|
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@v2/app/utils';
|
||||||
import { getSiteCacheTag } from '@v2/lib/cache';
|
|
||||||
import type { Metadata, Viewport } from 'next';
|
import type { Metadata, Viewport } from 'next';
|
||||||
import { unstable_cacheTag as cacheTag } from 'next/cache';
|
|
||||||
|
|
||||||
export const dynamic = 'force-static';
|
export const dynamic = 'force-static';
|
||||||
|
|
||||||
@@ -15,30 +14,25 @@ type PageProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function Page(props: PageProps) {
|
export default async function Page(props: PageProps) {
|
||||||
'use cache';
|
|
||||||
|
|
||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
const context = await getStaticSiteContext(params);
|
const { context } = await getStaticSiteContext(params);
|
||||||
const pathname = getPagePathFromParams(params);
|
const pathname = getPagePathFromParams(params);
|
||||||
|
|
||||||
cacheTag(getSiteCacheTag(context.site.id));
|
return <SitePage context={context} pageParams={{ pathname }} />;
|
||||||
|
|
||||||
return <SitePage context={context} pageParams={{ pathname }} redirectOnFallback={true} />;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||||
const context = await getStaticSiteContext(await props.params);
|
const { context } = await getStaticSiteContext(await props.params);
|
||||||
return generateSitePageViewport(context);
|
return generateSitePageViewport(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
const context = await getStaticSiteContext(params);
|
const { context } = await getStaticSiteContext(params);
|
||||||
const pathname = getPagePathFromParams(params);
|
const pathname = getPagePathFromParams(params);
|
||||||
|
|
||||||
return generateSitePageMetadata({
|
return generateSitePageMetadata({
|
||||||
context,
|
context,
|
||||||
pageParams: { pathname },
|
pageParams: { pathname },
|
||||||
redirectOnFallback: true,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+8
-10
@@ -5,9 +5,7 @@ import {
|
|||||||
generateSiteLayoutViewport,
|
generateSiteLayoutViewport,
|
||||||
} from '@/components/SiteLayout';
|
} from '@/components/SiteLayout';
|
||||||
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
|
import { type RouteLayoutParams, getStaticSiteContext } from '@v2/app/utils';
|
||||||
import { getSiteCacheTag } from '@v2/lib/cache';
|
|
||||||
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
|
import { GITBOOK_DISABLE_TRACKING } from '@v2/lib/env';
|
||||||
import { unstable_cacheTag as cacheTag } from 'next/cache';
|
|
||||||
|
|
||||||
interface SiteStaticLayoutProps {
|
interface SiteStaticLayoutProps {
|
||||||
params: Promise<RouteLayoutParams>;
|
params: Promise<RouteLayoutParams>;
|
||||||
@@ -17,15 +15,15 @@ export default async function SiteStaticLayout({
|
|||||||
params,
|
params,
|
||||||
children,
|
children,
|
||||||
}: React.PropsWithChildren<SiteStaticLayoutProps>) {
|
}: React.PropsWithChildren<SiteStaticLayoutProps>) {
|
||||||
'use cache';
|
const { context, visitorAuthClaims } = await getStaticSiteContext(await params);
|
||||||
|
|
||||||
const context = await getStaticSiteContext(await params);
|
|
||||||
|
|
||||||
cacheTag(getSiteCacheTag(context.site.id));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CustomizationRootLayout customization={context.customization}>
|
<CustomizationRootLayout customization={context.customization}>
|
||||||
<SiteLayout context={context} withTracking={!GITBOOK_DISABLE_TRACKING}>
|
<SiteLayout
|
||||||
|
context={context}
|
||||||
|
withTracking={!GITBOOK_DISABLE_TRACKING}
|
||||||
|
visitorAuthClaims={visitorAuthClaims}
|
||||||
|
>
|
||||||
{children}
|
{children}
|
||||||
</SiteLayout>
|
</SiteLayout>
|
||||||
</CustomizationRootLayout>
|
</CustomizationRootLayout>
|
||||||
@@ -33,11 +31,11 @@ export default async function SiteStaticLayout({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function generateViewport({ params }: SiteStaticLayoutProps) {
|
export async function generateViewport({ params }: SiteStaticLayoutProps) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return generateSiteLayoutViewport(context);
|
return generateSiteLayoutViewport(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateMetadata({ params }: SiteStaticLayoutProps) {
|
export async function generateMetadata({ params }: SiteStaticLayoutProps) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return generateSiteLayoutMetadata(context);
|
return generateSiteLayoutMetadata(context);
|
||||||
}
|
}
|
||||||
+2
-2
@@ -9,6 +9,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return serveLLMsTxt(context);
|
return serveLLMsTxt(context, { withMarkdownPages: true });
|
||||||
}
|
}
|
||||||
+1
-1
@@ -9,6 +9,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return serveRobotsTxt(context);
|
return serveRobotsTxt(context);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -9,6 +9,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return servePagesSitemap(context);
|
return servePagesSitemap(context);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -9,6 +9,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return serveRootSitemap(context);
|
return serveRootSitemap(context);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -9,6 +9,6 @@ export async function GET(
|
|||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams> }
|
{ params }: { params: Promise<RouteLayoutParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return serveIcon(context, request);
|
return serveIcon(context, request);
|
||||||
}
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
import { servePageMarkdown } from '@/routes/markdownPage';
|
||||||
|
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@v2/app/utils';
|
||||||
|
import type { NextRequest } from 'next/server';
|
||||||
|
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
|
||||||
|
export async function GET(_request: NextRequest, { params }: { params: Promise<RouteParams> }) {
|
||||||
|
const { context } = await getStaticSiteContext(await params);
|
||||||
|
const pathname = getPagePathFromParams(await params);
|
||||||
|
return servePageMarkdown(context, pathname);
|
||||||
|
}
|
||||||
+1
-1
@@ -10,6 +10,6 @@ export async function GET(
|
|||||||
_request: NextRequest,
|
_request: NextRequest,
|
||||||
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
|
{ params }: { params: Promise<RouteLayoutParams & PageIdParams> }
|
||||||
) {
|
) {
|
||||||
const context = await getStaticSiteContext(await params);
|
const { context } = await getStaticSiteContext(await params);
|
||||||
return serveOGImage(context, await params);
|
return serveOGImage(context, await params);
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { fetchSiteContextByURL } from '@v2/lib/context';
|
import { getVisitorAuthClaims, getVisitorAuthClaimsFromToken } from '@/lib/adaptive';
|
||||||
import { createDataFetcher } from '@v2/lib/data';
|
import type { SiteAPIToken } from '@gitbook/api';
|
||||||
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_URL } from '@v2/lib/env';
|
import { type SiteURLData, fetchSiteContextByURLLookup, getBaseContext } from '@v2/lib/context';
|
||||||
import { createImageResizer } from '@v2/lib/images';
|
import { jwtDecode } from 'jwt-decode';
|
||||||
import { createLinker } from '@v2/lib/links';
|
import { forbidden } from 'next/navigation';
|
||||||
import { headers } from 'next/headers';
|
import rison from 'rison';
|
||||||
|
|
||||||
export type RouteParamMode = 'url-host' | 'url';
|
export type RouteParamMode = 'url-host' | 'url';
|
||||||
|
|
||||||
@@ -12,6 +12,9 @@ export type RouteLayoutParams = {
|
|||||||
|
|
||||||
/** URL encoded site URL */
|
/** URL encoded site URL */
|
||||||
siteURL: string;
|
siteURL: string;
|
||||||
|
|
||||||
|
/** URL and Rison encoded site data from getPublishedContentByUrl */
|
||||||
|
siteData: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type RouteParams = RouteLayoutParams & {
|
export type RouteParams = RouteLayoutParams & {
|
||||||
@@ -22,28 +25,29 @@ export type RouteParams = RouteLayoutParams & {
|
|||||||
* Get the static context when rendering statically a site.
|
* Get the static context when rendering statically a site.
|
||||||
*/
|
*/
|
||||||
export async function getStaticSiteContext(params: RouteLayoutParams) {
|
export async function getStaticSiteContext(params: RouteLayoutParams) {
|
||||||
const url = getSiteURLFromParams(params);
|
const siteURL = getSiteURLFromParams(params);
|
||||||
|
const siteURLData = getSiteURLDataFromParams(params);
|
||||||
|
|
||||||
const dataFetcher = createDataFetcher();
|
// For static routes, we check the expiration of the JWT token
|
||||||
const { linker, host } = createLinkerFromParams(params);
|
// as the route might be revalidated after expiration
|
||||||
const context = await fetchSiteContextByURL(
|
const decoded = jwtDecode<SiteAPIToken & { exp: number }>(siteURLData.apiToken);
|
||||||
{
|
if (decoded.exp && decoded.exp < Date.now() / 1000 + 120) {
|
||||||
dataFetcher,
|
forbidden();
|
||||||
linker,
|
}
|
||||||
},
|
|
||||||
{
|
const context = await fetchSiteContextByURLLookup(
|
||||||
url: url.toString(),
|
getBaseContext({
|
||||||
visitorAuthToken: null,
|
siteURL,
|
||||||
redirectOnError: false,
|
siteURLData,
|
||||||
}
|
urlMode: getModeFromParams(params.mode),
|
||||||
|
}),
|
||||||
|
siteURLData
|
||||||
);
|
);
|
||||||
|
|
||||||
context.imageResizer = createImageResizer({
|
return {
|
||||||
host,
|
context,
|
||||||
linker: context.linker,
|
visitorAuthClaims: getVisitorAuthClaimsFromToken(decoded),
|
||||||
});
|
};
|
||||||
|
|
||||||
return context;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,36 +55,22 @@ export async function getStaticSiteContext(params: RouteLayoutParams) {
|
|||||||
* The context will depend on the request.
|
* The context will depend on the request.
|
||||||
*/
|
*/
|
||||||
export async function getDynamicSiteContext(params: RouteLayoutParams) {
|
export async function getDynamicSiteContext(params: RouteLayoutParams) {
|
||||||
const url = getSiteURLFromParams(params);
|
const siteURL = getSiteURLFromParams(params);
|
||||||
const headersSet = await headers();
|
const siteURLData = getSiteURLDataFromParams(params);
|
||||||
|
|
||||||
const dataFetcher = createDataFetcher({
|
const context = await fetchSiteContextByURLLookup(
|
||||||
apiToken: headersSet.get('x-gitbook-token') ?? GITBOOK_API_TOKEN,
|
getBaseContext({
|
||||||
apiEndpoint: headersSet.get('x-gitbook-api') ?? GITBOOK_API_URL,
|
siteURL,
|
||||||
});
|
siteURLData,
|
||||||
|
urlMode: getModeFromParams(params.mode),
|
||||||
const { linker, host } = createLinkerFromParams(params);
|
}),
|
||||||
|
siteURLData
|
||||||
const context = await fetchSiteContextByURL(
|
|
||||||
{
|
|
||||||
dataFetcher,
|
|
||||||
linker,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
url: url.toString(),
|
|
||||||
visitorAuthToken: headersSet.get('x-gitbook-visitor-token'),
|
|
||||||
|
|
||||||
// TODO: set it only when the token comes from the cookies.
|
|
||||||
redirectOnError: true,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
context.imageResizer = createImageResizer({
|
return {
|
||||||
host,
|
context,
|
||||||
linker: context.linker,
|
visitorAuthClaims: getVisitorAuthClaims(siteURLData),
|
||||||
});
|
};
|
||||||
|
|
||||||
return context;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -91,39 +81,6 @@ export function getPagePathFromParams(params: RouteParams) {
|
|||||||
return decoded;
|
return decoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createLinkerFromParams(params: RouteLayoutParams) {
|
|
||||||
const url = getSiteURLFromParams(params);
|
|
||||||
const mode = getModeFromParams(params.mode);
|
|
||||||
|
|
||||||
if (mode === 'url-host') {
|
|
||||||
return {
|
|
||||||
linker: createLinker({
|
|
||||||
host: url.host,
|
|
||||||
pathname: '/',
|
|
||||||
}),
|
|
||||||
host: url.host,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const gitbookURL = new URL(GITBOOK_URL);
|
|
||||||
const linker = createLinker({
|
|
||||||
protocol: gitbookURL.protocol,
|
|
||||||
host: gitbookURL.host,
|
|
||||||
pathname: `/url/${url.host}`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create link in the same format for links to other sites/sections.
|
|
||||||
linker.toLinkForContent = (rawURL: string) => {
|
|
||||||
const urlObject = new URL(rawURL);
|
|
||||||
return `/url/${urlObject.host}${urlObject.pathname}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
linker,
|
|
||||||
host: gitbookURL.host,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSiteURLFromParams(params: RouteLayoutParams) {
|
function getSiteURLFromParams(params: RouteLayoutParams) {
|
||||||
const decoded = decodeURIComponent(params.siteURL);
|
const decoded = decodeURIComponent(params.siteURL);
|
||||||
const url = new URL(`https://${decoded}`);
|
const url = new URL(`https://${decoded}`);
|
||||||
@@ -137,3 +94,11 @@ function getModeFromParams(mode: string): RouteParamMode {
|
|||||||
|
|
||||||
return 'url';
|
return 'url';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the decoded site data from the params.
|
||||||
|
*/
|
||||||
|
function getSiteURLDataFromParams(params: RouteLayoutParams): SiteURLData {
|
||||||
|
const decoded = decodeURIComponent(params.siteData);
|
||||||
|
return rison.decode(decoded);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { type NextRequest, NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import {
|
||||||
|
GITBOOK_API_PUBLIC_URL,
|
||||||
|
GITBOOK_API_TOKEN,
|
||||||
|
GITBOOK_API_URL,
|
||||||
|
GITBOOK_APP_URL,
|
||||||
|
GITBOOK_ASSETS_URL,
|
||||||
|
GITBOOK_DISABLE_TRACKING,
|
||||||
|
GITBOOK_FONTS_URL,
|
||||||
|
GITBOOK_ICONS_URL,
|
||||||
|
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
||||||
|
GITBOOK_INTEGRATIONS_HOST,
|
||||||
|
GITBOOK_SECRET,
|
||||||
|
GITBOOK_URL,
|
||||||
|
GITBOOK_USER_AGENT,
|
||||||
|
} from '@v2/lib/env';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output the public environment variables for this deployment
|
||||||
|
*/
|
||||||
|
export async function GET(_req: NextRequest) {
|
||||||
|
return NextResponse.json({
|
||||||
|
GITBOOK_URL,
|
||||||
|
GITBOOK_APP_URL,
|
||||||
|
GITBOOK_API_URL,
|
||||||
|
GITBOOK_API_PUBLIC_URL,
|
||||||
|
GITBOOK_ASSETS_URL,
|
||||||
|
GITBOOK_FONTS_URL,
|
||||||
|
GITBOOK_ICONS_URL,
|
||||||
|
GITBOOK_USER_AGENT,
|
||||||
|
GITBOOK_INTEGRATIONS_HOST,
|
||||||
|
GITBOOK_DISABLE_TRACKING,
|
||||||
|
|
||||||
|
// Secret envs
|
||||||
|
GITBOOK_SECRET: !!GITBOOK_SECRET,
|
||||||
|
GITBOOK_API_TOKEN: !!GITBOOK_API_TOKEN,
|
||||||
|
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: !!GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { type NextRequest, NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { withVerifySignature } from '@v2/lib/routes';
|
||||||
|
import { revalidateTag } from 'next/cache';
|
||||||
|
|
||||||
|
interface JsonBody {
|
||||||
|
tags: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revalidate cached data based on tags.
|
||||||
|
* The body should be a JSON with { tags: string[] }
|
||||||
|
*/
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
return withVerifySignature<JsonBody>(req, async (body) => {
|
||||||
|
if (!body.tags || !Array.isArray(body.tags)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: 'tags must be an array',
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.tags.forEach((tag) => {
|
||||||
|
// biome-ignore lint/suspicious/noConsole: we want to log here
|
||||||
|
console.log(`Revalidating tag: ${tag}`);
|
||||||
|
revalidateTag(tag);
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import {
|
||||||
|
type GitBookBaseContext,
|
||||||
|
type GitBookSpaceContext,
|
||||||
|
fetchSpaceContextByIds,
|
||||||
|
} from '@v2/lib/context';
|
||||||
|
import { createDataFetcher } from '@v2/lib/data';
|
||||||
|
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 basePath = getPDFRoutePath(params);
|
||||||
|
const linker = createLinker({
|
||||||
|
spaceBasePath: basePath,
|
||||||
|
siteBasePath: basePath,
|
||||||
|
});
|
||||||
|
const dataFetcher = createDataFetcher({
|
||||||
|
apiToken: apiToken,
|
||||||
|
});
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
|
||||||
|
export default RootLayout;
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
import PDFPage, { generateMetadata } from '@v2/app/~space/[spaceId]/~gitbook/pdf/page';
|
||||||
|
|
||||||
|
export default PDFPage;
|
||||||
|
export { generateMetadata };
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
import RootLayout from '@v2/app/~space/[spaceId]/~gitbook/pdf/layout';
|
||||||
|
export default RootLayout;
|
||||||
+4
@@ -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} />;
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
/**
|
|
||||||
* Get the cache tag for a site.
|
|
||||||
*/
|
|
||||||
export function getSiteCacheTag(siteId: string) {
|
|
||||||
return `site:${siteId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the cache tag for a hostname.
|
|
||||||
*/
|
|
||||||
export function getHostnameCacheTag(hostname: string) {
|
|
||||||
return `url:${hostname}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the cache tag for an OpenAPI spec.
|
|
||||||
*/
|
|
||||||
export function getOpenAPISpecCacheTag(organizationId: string, slug: string) {
|
|
||||||
return `organization:${organizationId}:openapi:${slug}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the cache tag for a space.
|
|
||||||
*/
|
|
||||||
export function getSpaceCacheTag(spaceId: string) {
|
|
||||||
return `space:${spaceId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the cache tag for a change request.
|
|
||||||
*/
|
|
||||||
export function getChangeRequestCacheTag(spaceId: string, changeRequestId: string) {
|
|
||||||
return `space:${spaceId}:change-request:${changeRequestId}`;
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { getSiteStructureSections } from '@/lib/sites';
|
import { getSiteStructureSections } from '@/lib/sites';
|
||||||
import type {
|
import type {
|
||||||
ChangeRequest,
|
ChangeRequest,
|
||||||
|
PublishedSiteContent,
|
||||||
RevisionPage,
|
RevisionPage,
|
||||||
RevisionPageDocument,
|
RevisionPageDocument,
|
||||||
Site,
|
Site,
|
||||||
@@ -12,11 +13,41 @@ import type {
|
|||||||
SiteStructure,
|
SiteStructure,
|
||||||
Space,
|
Space,
|
||||||
} from '@gitbook/api';
|
} from '@gitbook/api';
|
||||||
import { type GitBookDataFetcher, createDataFetcher } from '@v2/lib/data';
|
import {
|
||||||
import { redirect } from 'next/navigation';
|
type GitBookDataFetcher,
|
||||||
|
createDataFetcher,
|
||||||
|
getDataOrNull,
|
||||||
|
throwIfDataError,
|
||||||
|
} from '@v2/lib/data';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
import { assert } from 'ts-essentials';
|
import { assert } from 'ts-essentials';
|
||||||
import type { ImageResizer } from './images';
|
import { GITBOOK_URL } from './env';
|
||||||
import { type GitBookSpaceLinker, appendBasePathToLinker } from './links';
|
import { type ImageResizer, createImageResizer } from './images';
|
||||||
|
import { type GitBookLinker, createLinker } from './links';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Data about the site URL. Provided by the middleware.
|
||||||
|
* These data are stable between pages in the same site space.
|
||||||
|
*/
|
||||||
|
export type SiteURLData = Pick<
|
||||||
|
PublishedSiteContent,
|
||||||
|
| 'organization'
|
||||||
|
| 'apiToken'
|
||||||
|
| 'site'
|
||||||
|
| 'siteSpace'
|
||||||
|
| 'space'
|
||||||
|
| 'revision'
|
||||||
|
| 'changeRequest'
|
||||||
|
| 'shareKey'
|
||||||
|
| 'siteSection'
|
||||||
|
| 'siteBasePath'
|
||||||
|
| 'basePath'
|
||||||
|
> & {
|
||||||
|
/**
|
||||||
|
* Identifier used for image resizing.
|
||||||
|
*/
|
||||||
|
imagesContextId: string;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generic context when rendering content.
|
* Generic context when rendering content.
|
||||||
@@ -30,7 +61,7 @@ export type GitBookBaseContext = {
|
|||||||
/**
|
/**
|
||||||
* Linker to generate links in the current space.
|
* Linker to generate links in the current space.
|
||||||
*/
|
*/
|
||||||
linker: GitBookSpaceLinker;
|
linker: GitBookLinker;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Image resizer to resize images.
|
* Image resizer to resize images.
|
||||||
@@ -90,9 +121,6 @@ export type GitBookSiteContext = GitBookSpaceContext & {
|
|||||||
|
|
||||||
/** Scripts to load for the site. */
|
/** Scripts to load for the site. */
|
||||||
scripts: SiteIntegrationScript[];
|
scripts: SiteIntegrationScript[];
|
||||||
|
|
||||||
/** Visitor token used to fetch the site */
|
|
||||||
visitorAuthToken: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -103,54 +131,74 @@ export type GitBookPageContext = (GitBookSpaceContext | GitBookSiteContext) & {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the context of a site for a given URL and a base context.
|
* Get the base context for a request on a site.
|
||||||
*/
|
*/
|
||||||
export async function fetchSiteContextByURL(
|
export function getBaseContext(input: {
|
||||||
baseContext: GitBookBaseContext,
|
siteURL: URL | string;
|
||||||
input: {
|
siteURLData: SiteURLData;
|
||||||
url: string;
|
urlMode: 'url' | 'url-host';
|
||||||
visitorAuthToken: string | null;
|
}) {
|
||||||
redirectOnError: boolean;
|
const { urlMode, siteURLData } = input;
|
||||||
}
|
const siteURL = typeof input.siteURL === 'string' ? new URL(input.siteURL) : input.siteURL;
|
||||||
): Promise<GitBookSiteContext> {
|
|
||||||
const { dataFetcher } = baseContext;
|
const dataFetcher = createDataFetcher({
|
||||||
const data = await dataFetcher.getPublishedContentByUrl({
|
apiToken: siteURLData.apiToken ?? null,
|
||||||
url: input.url,
|
|
||||||
visitorAuthToken: input.visitorAuthToken,
|
|
||||||
redirectOnError: input.redirectOnError,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if ('redirect' in data) {
|
const gitbookURL = GITBOOK_URL ? new URL(GITBOOK_URL) : undefined;
|
||||||
redirect(data.redirect);
|
const linker =
|
||||||
|
urlMode === 'url-host'
|
||||||
|
? createLinker({
|
||||||
|
host: siteURL.host,
|
||||||
|
siteBasePath: siteURLData.siteBasePath,
|
||||||
|
spaceBasePath: siteURLData.basePath,
|
||||||
|
})
|
||||||
|
: createLinker({
|
||||||
|
protocol: gitbookURL?.protocol,
|
||||||
|
host: gitbookURL?.host,
|
||||||
|
siteBasePath: `/url/${siteURL.host}${siteURLData.siteBasePath}`,
|
||||||
|
spaceBasePath: `/url/${siteURL.host}${siteURLData.basePath}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
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}`;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = await fetchSiteContextByIds(
|
const imageResizer = createImageResizer({
|
||||||
{
|
imagesContextId: siteURLData.imagesContextId,
|
||||||
...baseContext,
|
// To ensure image resizing work for proxied sites,
|
||||||
dataFetcher: createDataFetcher({
|
// we serve images from the root of the site.
|
||||||
apiEndpoint: dataFetcher.apiEndpoint,
|
linker: linker,
|
||||||
apiToken: data.apiToken,
|
});
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
organization: data.organization,
|
|
||||||
site: data.site,
|
|
||||||
siteSection: data.siteSection,
|
|
||||||
siteSpace: data.siteSpace,
|
|
||||||
space: data.space,
|
|
||||||
shareKey: data.shareKey,
|
|
||||||
changeRequest: data.changeRequest,
|
|
||||||
revision: data.revision,
|
|
||||||
visitorAuthToken: input.visitorAuthToken,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const siteContext = {
|
return {
|
||||||
...context,
|
dataFetcher,
|
||||||
linker: appendBasePathToLinker(context.linker, data.basePath),
|
linker,
|
||||||
|
imageResizer,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return siteContext;
|
/**
|
||||||
|
* Fetch the context of a site using the resolution of a URL
|
||||||
|
*/
|
||||||
|
export async function fetchSiteContextByURLLookup(
|
||||||
|
baseContext: GitBookBaseContext,
|
||||||
|
data: SiteURLData
|
||||||
|
): Promise<GitBookSiteContext> {
|
||||||
|
return await fetchSiteContextByIds(baseContext, {
|
||||||
|
organization: data.organization,
|
||||||
|
site: data.site,
|
||||||
|
siteSection: data.siteSection,
|
||||||
|
siteSpace: data.siteSpace,
|
||||||
|
space: data.space,
|
||||||
|
shareKey: data.shareKey,
|
||||||
|
changeRequest: data.changeRequest,
|
||||||
|
revision: data.revision,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -167,18 +215,19 @@ export async function fetchSiteContextByIds(
|
|||||||
shareKey: string | undefined;
|
shareKey: string | undefined;
|
||||||
changeRequest: string | undefined;
|
changeRequest: string | undefined;
|
||||||
revision: string | undefined;
|
revision: string | undefined;
|
||||||
visitorAuthToken: string | null;
|
|
||||||
}
|
}
|
||||||
): Promise<GitBookSiteContext> {
|
): Promise<GitBookSiteContext> {
|
||||||
const { dataFetcher } = baseContext;
|
const { dataFetcher } = baseContext;
|
||||||
|
|
||||||
const [{ site: orgSite, structure: siteStructure, customizations, scripts }, spaceContext] =
|
const [{ site: orgSite, structure: siteStructure, customizations, scripts }, spaceContext] =
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
dataFetcher.getPublishedContentSite({
|
throwIfDataError(
|
||||||
organizationId: ids.organization,
|
dataFetcher.getPublishedContentSite({
|
||||||
siteId: ids.site,
|
organizationId: ids.organization,
|
||||||
siteShareKey: ids.shareKey,
|
siteId: ids.site,
|
||||||
}),
|
siteShareKey: ids.shareKey,
|
||||||
|
})
|
||||||
|
),
|
||||||
fetchSpaceContextByIds(baseContext, ids),
|
fetchSpaceContextByIds(baseContext, ids),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -233,7 +282,6 @@ export async function fetchSiteContextByIds(
|
|||||||
structure: siteStructure,
|
structure: siteStructure,
|
||||||
sections,
|
sections,
|
||||||
scripts,
|
scripts,
|
||||||
visitorAuthToken: ids.visitorAuthToken,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,27 +300,46 @@ export async function fetchSpaceContextByIds(
|
|||||||
const { dataFetcher } = baseContext;
|
const { dataFetcher } = baseContext;
|
||||||
|
|
||||||
const [space, changeRequest] = await Promise.all([
|
const [space, changeRequest] = await Promise.all([
|
||||||
dataFetcher.getSpace({
|
throwIfDataError(
|
||||||
spaceId: ids.space,
|
dataFetcher.getSpace({
|
||||||
shareKey: ids.shareKey,
|
spaceId: ids.space,
|
||||||
}),
|
shareKey: ids.shareKey,
|
||||||
|
})
|
||||||
|
),
|
||||||
ids.changeRequest
|
ids.changeRequest
|
||||||
? dataFetcher.getChangeRequest({
|
? getDataOrNull(
|
||||||
spaceId: ids.space,
|
dataFetcher.getChangeRequest({
|
||||||
changeRequestId: ids.changeRequest,
|
spaceId: ids.space,
|
||||||
})
|
changeRequestId: ids.changeRequest,
|
||||||
|
})
|
||||||
|
)
|
||||||
: null,
|
: null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const revisionId = changeRequest?.revision ?? ids.revision ?? space.revision;
|
if (ids.changeRequest && !changeRequest) {
|
||||||
|
// When trying to render a change request with an invalid / non-existing ID,
|
||||||
|
// we should return a 404.
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
const pages = await dataFetcher.getRevisionPages({
|
const revisionId = ids.revision ?? changeRequest?.revision ?? space.revision;
|
||||||
spaceId: ids.space,
|
|
||||||
revisionId,
|
const pages = await getDataOrNull(
|
||||||
// We only care about the Git metadata when the Git sync is enabled,
|
dataFetcher.getRevisionPages({
|
||||||
// otherwise we can optimize performance by not fetching it
|
spaceId: ids.space,
|
||||||
metadata: !!space.gitSync,
|
revisionId,
|
||||||
});
|
// We only care about the Git metadata when the Git sync is enabled,
|
||||||
|
// otherwise we can optimize performance by not fetching it
|
||||||
|
metadata: !!space.gitSync,
|
||||||
|
}),
|
||||||
|
|
||||||
|
// When trying to render a revision with an invalid / non-existing ID,
|
||||||
|
// we should handle gracefully the 404 and throw notFound.
|
||||||
|
ids.revision ? [404] : undefined
|
||||||
|
);
|
||||||
|
if (!pages) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...baseContext,
|
...baseContext,
|
||||||
|
|||||||
+1312
-380
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
|||||||
|
import { getCloudflareContext as getCloudflareContextOpenNext } from '@opennextjs/cloudflare';
|
||||||
|
import { GITBOOK_RUNTIME } from '../env';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the Cloudflare context or null when not running in Cloudflare.
|
||||||
|
*/
|
||||||
|
export function getCloudflareContext() {
|
||||||
|
if (GITBOOK_RUNTIME !== 'cloudflare') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return getCloudflareContextOpenNext();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an object representing the current request.
|
||||||
|
*/
|
||||||
|
export function getCloudflareRequestGlobal() {
|
||||||
|
const context = getCloudflareContext();
|
||||||
|
if (!context) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.cf;
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { GitBookAPIError } from '@gitbook/api';
|
||||||
|
import type { DataFetcherErrorData, DataFetcherResponse } from './types';
|
||||||
|
|
||||||
|
export class DataFetcherError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public readonly code: number
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throw an error if the response contains an error.
|
||||||
|
*/
|
||||||
|
export function throwIfDataError<T>(response: DataFetcherResponse<T>): T;
|
||||||
|
export function throwIfDataError<T>(response: Promise<DataFetcherResponse<T>>): Promise<T>;
|
||||||
|
export function throwIfDataError<T>(
|
||||||
|
response: DataFetcherResponse<T> | Promise<DataFetcherResponse<T>>
|
||||||
|
): T | Promise<T> {
|
||||||
|
if (response instanceof Promise) {
|
||||||
|
return response.then((result) => throwIfDataError(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
throw new DataFetcherError(response.error.message, response.error.code);
|
||||||
|
}
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the data from the response or null if there is an "Not found" error.
|
||||||
|
*/
|
||||||
|
export function getDataOrNull<T>(
|
||||||
|
response: DataFetcherResponse<T>,
|
||||||
|
ignoreErrors?: number[]
|
||||||
|
): T | null;
|
||||||
|
export function getDataOrNull<T>(
|
||||||
|
response: Promise<DataFetcherResponse<T>>,
|
||||||
|
ignoreErrors?: number[]
|
||||||
|
): Promise<T | null>;
|
||||||
|
export function getDataOrNull<T>(
|
||||||
|
response: DataFetcherResponse<T> | Promise<DataFetcherResponse<T>>,
|
||||||
|
ignoreErrors: number[] = [404]
|
||||||
|
): T | null | Promise<T | null> {
|
||||||
|
if (response instanceof Promise) {
|
||||||
|
return response.then((result) => getDataOrNull(result, ignoreErrors));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
if (ignoreErrors.includes(response.error.code)) return null;
|
||||||
|
throw new DataFetcherError(response.error.message, response.error.code);
|
||||||
|
}
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignore error for an API or data call.
|
||||||
|
*/
|
||||||
|
export async function ignoreDataThrownError<T>(promise: Promise<T>): Promise<T | null> {
|
||||||
|
try {
|
||||||
|
return await promise;
|
||||||
|
} catch (error) {
|
||||||
|
getExposableError(error as Error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignore all errors for an API or data call.
|
||||||
|
*/
|
||||||
|
export async function ignoreAllThrownError<T>(promise: Promise<T>): Promise<T | null> {
|
||||||
|
try {
|
||||||
|
return await promise;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Ignoring error', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap an async execution to handle errors and return a DataFetcherResponse.
|
||||||
|
*/
|
||||||
|
export async function wrapDataFetcherError<T>(
|
||||||
|
fn: () => Promise<T>
|
||||||
|
): Promise<DataFetcherResponse<T>> {
|
||||||
|
try {
|
||||||
|
return { data: await fn() };
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
error: getExposableError(error as Error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a data fetcher exposable error from a JS error.
|
||||||
|
*/
|
||||||
|
export function getExposableError(error: Error): DataFetcherErrorData {
|
||||||
|
if (error instanceof GitBookAPIError) {
|
||||||
|
if (error.code >= 500) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: error.code,
|
||||||
|
message: error.errorMessage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof DataFetcherError) {
|
||||||
|
if (error.code >= 500) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: error.code,
|
||||||
|
message: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
export * from './api';
|
export * from './api';
|
||||||
export * from './types';
|
export * from './types';
|
||||||
export * from './utils';
|
export * from './pages';
|
||||||
export * from './urls';
|
export * from './urls';
|
||||||
|
export * from './errors';
|
||||||
|
export * from './lookup';
|
||||||
|
export * from './proxy';
|
||||||
|
export * from './visitor';
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { race, tryCatch } from '@/lib/async';
|
||||||
|
import { joinPath, joinPathWithBaseURL } from '@/lib/paths';
|
||||||
|
import { trace } from '@/lib/tracing';
|
||||||
|
import type { PublishedSiteContentLookup } from '@gitbook/api';
|
||||||
|
import { apiClient } from './api';
|
||||||
|
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;
|
||||||
|
apiToken: string | null;
|
||||||
|
}): 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 = await apiClient({ apiToken: input.apiToken });
|
||||||
|
|
||||||
|
const callResult = await trace(
|
||||||
|
{
|
||||||
|
operation: 'getPublishedContentByURL',
|
||||||
|
name: alternative.url,
|
||||||
|
},
|
||||||
|
() =>
|
||||||
|
tryCatch(
|
||||||
|
api.urls.getPublishedContentByUrl(
|
||||||
|
{
|
||||||
|
url: alternative.url,
|
||||||
|
visitorAuthToken: input.visitorAuthToken ?? undefined,
|
||||||
|
redirectOnError: input.redirectOnError,
|
||||||
|
|
||||||
|
// As this endpoint is cached by our API, we version the request
|
||||||
|
// to void getting stale data with missing properties.
|
||||||
|
// this could be improved by ensuring our API cache layer is versioned
|
||||||
|
// or invalidated when needed
|
||||||
|
// @ts-expect-error - cacheVersion is not a real query param
|
||||||
|
cacheVersion: 'v2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
signal,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
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 changeRequest = data.changeRequest ?? lookup.changeRequest;
|
||||||
|
const revision = data.revision ?? lookup.revision;
|
||||||
|
|
||||||
|
const siteResult: PublishedSiteContentLookup = {
|
||||||
|
...data,
|
||||||
|
canonicalUrl: joinPathWithBaseURL(data.canonicalUrl, alternative.extraPath),
|
||||||
|
basePath: joinPath(data.basePath, lookup.basePath ?? ''),
|
||||||
|
pathname: joinPath(data.pathname, alternative.extraPath),
|
||||||
|
...(changeRequest ? { changeRequest } : {}),
|
||||||
|
...(revision ? { revision } : {}),
|
||||||
|
};
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, expect, it, mock } from 'bun:test';
|
||||||
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||||
|
import { withCacheKey, withoutConcurrentExecution } from './memoize';
|
||||||
|
|
||||||
|
describe('withoutConcurrentExecution', () => {
|
||||||
|
it('should memoize the function based on the cache key', async () => {
|
||||||
|
const fn = mock(async (_cacheKey: string, a: number, b: number) => a + b);
|
||||||
|
const memoized = withoutConcurrentExecution(() => null, fn);
|
||||||
|
|
||||||
|
const p1 = memoized('c1', 1, 2);
|
||||||
|
const p2 = memoized('c1', 1, 2);
|
||||||
|
const p3 = memoized('c3', 2, 3);
|
||||||
|
|
||||||
|
expect(await p1).toBe(await p2);
|
||||||
|
expect(await p1).not.toBe(await p3);
|
||||||
|
expect(fn.mock.calls.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should support caching per request', async () => {
|
||||||
|
const fn = mock(async () => Math.random());
|
||||||
|
|
||||||
|
const request1 = { id: 'request1' };
|
||||||
|
const request2 = { id: 'request2' };
|
||||||
|
|
||||||
|
const requestContext = new AsyncLocalStorage<{ id: string }>();
|
||||||
|
|
||||||
|
const memoized = withoutConcurrentExecution(() => requestContext.getStore(), fn);
|
||||||
|
|
||||||
|
// Both in the same request
|
||||||
|
const promise1 = requestContext.run(request1, () => memoized('c1'));
|
||||||
|
const promise2 = requestContext.run(request1, () => memoized('c1'));
|
||||||
|
|
||||||
|
// In a different request
|
||||||
|
const promise3 = requestContext.run(request2, () => memoized('c1'));
|
||||||
|
|
||||||
|
expect(await promise1).toBe(await promise2);
|
||||||
|
expect(await promise1).not.toBe(await promise3);
|
||||||
|
expect(fn.mock.calls.length).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('withCacheKey', () => {
|
||||||
|
it('should wrap the function by passing the cache key', async () => {
|
||||||
|
const fn = mock(
|
||||||
|
async (cacheKey: string, arg: { a: number; b: number }, c: number) =>
|
||||||
|
`${cacheKey}, result=${arg.a + arg.b + c}`
|
||||||
|
);
|
||||||
|
const memoized = withCacheKey(fn);
|
||||||
|
expect(await memoized({ a: 1, b: 2 }, 4)).toBe('[[["a",1],["b",2]],4], result=7');
|
||||||
|
expect(fn.mock.calls.length).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/**
|
||||||
|
* Wrap a function by preventing concurrent executions of the same function.
|
||||||
|
* With a logic to work per-request in Cloudflare Workers.
|
||||||
|
*/
|
||||||
|
export function withoutConcurrentExecution<ArgsType extends any[], ReturnType>(
|
||||||
|
getGlobalContext: () => object | null | undefined,
|
||||||
|
wrapped: (key: string, ...args: ArgsType) => Promise<ReturnType>
|
||||||
|
): (cacheKey: string, ...args: ArgsType) => Promise<ReturnType> {
|
||||||
|
const globalPromiseCache = new WeakMap<object, Map<string, Promise<ReturnType>>>();
|
||||||
|
|
||||||
|
return (key: string, ...args: ArgsType) => {
|
||||||
|
const globalContext = getGlobalContext() ?? globalThis;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache storage that is scoped to the current request when executed in Cloudflare Workers,
|
||||||
|
* to avoid "Cannot perform I/O on behalf of a different request" errors.
|
||||||
|
*/
|
||||||
|
const promiseCache =
|
||||||
|
globalPromiseCache.get(globalContext) ?? new Map<string, Promise<ReturnType>>();
|
||||||
|
globalPromiseCache.set(globalContext, promiseCache);
|
||||||
|
|
||||||
|
const concurrent = promiseCache.get(key);
|
||||||
|
if (concurrent) {
|
||||||
|
return concurrent;
|
||||||
|
}
|
||||||
|
|
||||||
|
const promise = (async () => {
|
||||||
|
try {
|
||||||
|
const result = await wrapped(key, ...args);
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
promiseCache.delete(key);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
promiseCache.set(key, promise);
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a function by passing it a cache key that is computed from the function arguments.
|
||||||
|
*/
|
||||||
|
export function withCacheKey<ArgsType extends any[], ReturnType>(
|
||||||
|
wrapped: (cacheKey: string, ...args: ArgsType) => Promise<ReturnType>
|
||||||
|
): (...args: ArgsType) => Promise<ReturnType> {
|
||||||
|
return (...args: ArgsType) => {
|
||||||
|
const cacheKey = getCacheKey(args);
|
||||||
|
return wrapped(cacheKey, ...args);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute a cache key from the function arguments.
|
||||||
|
*/
|
||||||
|
function getCacheKey(args: any[]) {
|
||||||
|
return JSON.stringify(deepSortValue(args));
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepSortValue(value: unknown): unknown {
|
||||||
|
if (
|
||||||
|
typeof value === 'string' ||
|
||||||
|
typeof value === 'number' ||
|
||||||
|
typeof value === 'boolean' ||
|
||||||
|
value === null ||
|
||||||
|
value === undefined
|
||||||
|
) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map(deepSortValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
return Object.entries(value)
|
||||||
|
.map(([key, subValue]) => {
|
||||||
|
return [key, deepSortValue(subValue)] as const;
|
||||||
|
})
|
||||||
|
.sort((a, b) => {
|
||||||
|
return a[0].localeCompare(b[0]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { JSONDocument, RevisionPageDocument, Space } from '@gitbook/api';
|
||||||
|
import { getDataOrNull } from './errors';
|
||||||
|
import type { GitBookDataFetcher } from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the document for a page.
|
||||||
|
*/
|
||||||
|
export async function getPageDocument(
|
||||||
|
dataFetcher: GitBookDataFetcher,
|
||||||
|
space: Space,
|
||||||
|
page: RevisionPageDocument
|
||||||
|
): Promise<JSONDocument | null> {
|
||||||
|
if (page.documentId) {
|
||||||
|
return getDataOrNull(
|
||||||
|
dataFetcher.getDocument({ spaceId: space.id, documentId: page.documentId })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if ('computed' in page && page.computed) {
|
||||||
|
return getDataOrNull(
|
||||||
|
dataFetcher.getComputedDocument({
|
||||||
|
organizationId: space.organization,
|
||||||
|
spaceId: space.id,
|
||||||
|
source: page.computed,
|
||||||
|
seed: page.computedSeed,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test';
|
||||||
|
import { getProxyRequestIdentifier, isProxyRequest } from './proxy';
|
||||||
|
|
||||||
|
describe('isProxyRequest', () => {
|
||||||
|
it('should return true for proxy requests', () => {
|
||||||
|
const proxyRequestURL = new URL('https://proxy.gitbook.site/sites/site_foo/hello/world');
|
||||||
|
expect(isProxyRequest(proxyRequestURL)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false for non-proxy requests', () => {
|
||||||
|
const nonProxyRequestURL = new URL('https://example.com/docs/foo/hello/world');
|
||||||
|
expect(isProxyRequest(nonProxyRequestURL)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getProxyRequestIdentifier', () => {
|
||||||
|
it('should return the correct identifier for proxy requests', () => {
|
||||||
|
const proxyRequestURL = new URL('https://proxy.gitbook.site/sites/site_foo/hello/world');
|
||||||
|
expect(getProxyRequestIdentifier(proxyRequestURL)).toBe('sites/site_foo');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* Check if the request to the site was through a proxy.
|
||||||
|
*/
|
||||||
|
export function isProxyRequest(requestURL: URL): boolean {
|
||||||
|
return (
|
||||||
|
requestURL.host === 'proxy.gitbook.site' || requestURL.host === 'proxy.gitbook-staging.site'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getProxyRequestIdentifier(requestURL: URL): string {
|
||||||
|
// For proxy requests, we extract the site ID from the pathname
|
||||||
|
// e.g. https://proxy.gitbook.site/site/siteId/...
|
||||||
|
const pathname = requestURL.pathname.slice(1).split('/');
|
||||||
|
return pathname.slice(0, 2).join('/');
|
||||||
|
}
|
||||||
@@ -1,28 +1,41 @@
|
|||||||
import type * as api from '@gitbook/api';
|
import type * as api from '@gitbook/api';
|
||||||
|
|
||||||
|
export type DataFetcherErrorData = {
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DataFetcherResponse<T> =
|
||||||
|
| {
|
||||||
|
data: T;
|
||||||
|
error?: undefined;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
error: DataFetcherErrorData;
|
||||||
|
data?: undefined;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generic fetcher for GitBook data.
|
* Generic fetcher for GitBook data.
|
||||||
* It is used between v1 and v2.
|
* It is used between v1 and v2.
|
||||||
*/
|
*/
|
||||||
export interface GitBookDataFetcher {
|
export interface GitBookDataFetcher {
|
||||||
/**
|
/**
|
||||||
* Endpoint of the API.
|
* Get an API client for the current context.
|
||||||
*/
|
*/
|
||||||
apiEndpoint: string;
|
api(): Promise<api.GitBookAPI>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a data fetcher authenticated with a specific token.
|
||||||
|
*/
|
||||||
|
withToken(input: {
|
||||||
|
apiToken: string;
|
||||||
|
}): GitBookDataFetcher;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a user by its ID.
|
* Get a user by its ID.
|
||||||
*/
|
*/
|
||||||
getUserById(userId: string): Promise<api.User | null>;
|
getUserById(userId: string): Promise<DataFetcherResponse<api.User>>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a published content by its URL.
|
|
||||||
*/
|
|
||||||
getPublishedContentByUrl(params: {
|
|
||||||
url: string;
|
|
||||||
visitorAuthToken: string | null;
|
|
||||||
redirectOnError: boolean;
|
|
||||||
}): Promise<api.PublishedSiteContentLookup>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a published content site by its organization ID and site ID.
|
* Get a published content site by its organization ID and site ID.
|
||||||
@@ -31,12 +44,14 @@ export interface GitBookDataFetcher {
|
|||||||
organizationId: string;
|
organizationId: string;
|
||||||
siteId: string;
|
siteId: string;
|
||||||
siteShareKey: string | undefined;
|
siteShareKey: string | undefined;
|
||||||
}): Promise<api.PublishedContentSite>;
|
}): Promise<DataFetcherResponse<api.PublishedContentSite>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a space by its ID.
|
* Get a space by its ID.
|
||||||
*/
|
*/
|
||||||
getSpace(params: { spaceId: string; shareKey: string | undefined }): Promise<api.Space>;
|
getSpace(params: { spaceId: string; shareKey: string | undefined }): Promise<
|
||||||
|
DataFetcherResponse<api.Space>
|
||||||
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a change request by its space ID and change request ID.
|
* Get a change request by its space ID and change request ID.
|
||||||
@@ -44,7 +59,7 @@ export interface GitBookDataFetcher {
|
|||||||
getChangeRequest(params: {
|
getChangeRequest(params: {
|
||||||
spaceId: string;
|
spaceId: string;
|
||||||
changeRequestId: string;
|
changeRequestId: string;
|
||||||
}): Promise<api.ChangeRequest | null>;
|
}): Promise<DataFetcherResponse<api.ChangeRequest>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the revision by its space ID and revision ID.
|
* Get the revision by its space ID and revision ID.
|
||||||
@@ -53,7 +68,7 @@ export interface GitBookDataFetcher {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
revisionId: string;
|
revisionId: string;
|
||||||
metadata: boolean;
|
metadata: boolean;
|
||||||
}): Promise<api.Revision>;
|
}): Promise<DataFetcherResponse<api.Revision>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the revision pages by its space ID and revision ID.
|
* Get the revision pages by its space ID and revision ID.
|
||||||
@@ -62,7 +77,7 @@ export interface GitBookDataFetcher {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
revisionId: string;
|
revisionId: string;
|
||||||
metadata: boolean;
|
metadata: boolean;
|
||||||
}): Promise<api.RevisionPage[]>;
|
}): Promise<DataFetcherResponse<api.RevisionPage[]>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a revision file by its space ID, revision ID and file ID.
|
* Get a revision file by its space ID, revision ID and file ID.
|
||||||
@@ -71,7 +86,7 @@ export interface GitBookDataFetcher {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
revisionId: string;
|
revisionId: string;
|
||||||
fileId: string;
|
fileId: string;
|
||||||
}): Promise<api.RevisionFile | null>;
|
}): Promise<DataFetcherResponse<api.RevisionFile>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a revision page by its path.
|
* Get a revision page by its path.
|
||||||
@@ -80,20 +95,33 @@ export interface GitBookDataFetcher {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
revisionId: string;
|
revisionId: string;
|
||||||
path: string;
|
path: string;
|
||||||
}): Promise<api.RevisionPageDocument | api.RevisionPageGroup | null>;
|
}): Promise<DataFetcherResponse<api.RevisionPageDocument | api.RevisionPageGroup>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the markdown content of a page by its path.
|
||||||
|
*/
|
||||||
|
getRevisionPageMarkdown(params: {
|
||||||
|
spaceId: string;
|
||||||
|
revisionId: string;
|
||||||
|
pageId: string;
|
||||||
|
}): Promise<DataFetcherResponse<string>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a document by its space ID and document ID.
|
* Get a document by its space ID and document ID.
|
||||||
*/
|
*/
|
||||||
getDocument(params: { spaceId: string; documentId: string }): Promise<api.JSONDocument>;
|
getDocument(params: { spaceId: string; documentId: string }): Promise<
|
||||||
|
DataFetcherResponse<api.JSONDocument>
|
||||||
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a computed document by its space ID and computed source.
|
* Get a computed document by its space ID and computed source.
|
||||||
*/
|
*/
|
||||||
getComputedDocument(params: {
|
getComputedDocument(params: {
|
||||||
|
organizationId: string;
|
||||||
spaceId: string;
|
spaceId: string;
|
||||||
source: api.ComputedContentSource;
|
source: api.ComputedContentSource;
|
||||||
}): Promise<api.JSONDocument>;
|
seed: string;
|
||||||
|
}): Promise<DataFetcherResponse<api.JSONDocument>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a reusable content by its space ID, revision ID and reusable content ID.
|
* Get a reusable content by its space ID, revision ID and reusable content ID.
|
||||||
@@ -102,7 +130,7 @@ export interface GitBookDataFetcher {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
revisionId: string;
|
revisionId: string;
|
||||||
reusableContentId: string;
|
reusableContentId: string;
|
||||||
}): Promise<api.RevisionReusableContent | null>;
|
}): Promise<DataFetcherResponse<api.RevisionReusableContent>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the latest OpenAPI spec version content by its organization ID and slug.
|
* Get the latest OpenAPI spec version content by its organization ID and slug.
|
||||||
@@ -110,7 +138,7 @@ export interface GitBookDataFetcher {
|
|||||||
getLatestOpenAPISpecVersionContent(params: {
|
getLatestOpenAPISpecVersionContent(params: {
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
}): Promise<api.OpenAPISpecContent | null>;
|
}): Promise<DataFetcherResponse<api.OpenAPISpecContent>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a site redirect by its source path.
|
* Get a site redirect by its source path.
|
||||||
@@ -120,10 +148,46 @@ export interface GitBookDataFetcher {
|
|||||||
siteId: string;
|
siteId: string;
|
||||||
siteShareKey: string | undefined;
|
siteShareKey: string | undefined;
|
||||||
source: string;
|
source: string;
|
||||||
}): Promise<{ redirect: api.SiteRedirect | null; target: string } | null>;
|
}): Promise<DataFetcherResponse<{ redirect: api.SiteRedirect | null; target: string }>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an embed by its URL.
|
* Get an embed by its URL.
|
||||||
*/
|
*/
|
||||||
getEmbedByUrl(params: { url: string; spaceId: string }): Promise<api.Embed>;
|
getEmbedByUrl(params: { url: string; spaceId: string }): Promise<
|
||||||
|
DataFetcherResponse<api.Embed>
|
||||||
|
>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search content in a site.
|
||||||
|
*/
|
||||||
|
searchSiteContent(params: {
|
||||||
|
organizationId: string;
|
||||||
|
siteId: string;
|
||||||
|
query: string;
|
||||||
|
scope:
|
||||||
|
| { mode: 'all' }
|
||||||
|
| { mode: 'current'; siteSpaceId: string }
|
||||||
|
| { mode: 'specific'; siteSpaceIds: string[] };
|
||||||
|
/** Cache bust to ensure the search results are fresh when the space is updated. */
|
||||||
|
cacheBust?: string;
|
||||||
|
}): Promise<DataFetcherResponse<api.SearchSpaceResult[]>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render an integration UI.
|
||||||
|
*/
|
||||||
|
renderIntegrationUi(params: {
|
||||||
|
integrationName: string;
|
||||||
|
request: api.RenderIntegrationUI;
|
||||||
|
}): Promise<DataFetcherResponse<api.ContentKitRenderOutput>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stream an AI response.
|
||||||
|
*/
|
||||||
|
streamAIResponse(params: {
|
||||||
|
organizationId: string;
|
||||||
|
siteId: string;
|
||||||
|
input: api.AIMessageInput[];
|
||||||
|
output: api.AIOutputFormat;
|
||||||
|
model: api.AIModel;
|
||||||
|
}): AsyncGenerator<api.AIStreamResponse, void, unknown>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import type { RevisionPageDocument } from '@gitbook/api';
|
|
||||||
import type { GitBookDataFetcher } from './types';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the document for a page.
|
|
||||||
*/
|
|
||||||
export async function getPageDocument(
|
|
||||||
dataFetcher: GitBookDataFetcher,
|
|
||||||
spaceId: string,
|
|
||||||
page: RevisionPageDocument
|
|
||||||
) {
|
|
||||||
if (page.documentId) {
|
|
||||||
return dataFetcher.getDocument({ spaceId, documentId: page.documentId });
|
|
||||||
}
|
|
||||||
if (page.computed) {
|
|
||||||
return dataFetcher.getComputedDocument({ spaceId, source: page.computed });
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test';
|
||||||
|
import { getVisitorAuthBasePath } from './visitor';
|
||||||
|
|
||||||
|
describe('getVisitorAuthBasePath', () => {
|
||||||
|
it('should return the correct base path for proxy requests', () => {
|
||||||
|
expect(
|
||||||
|
getVisitorAuthBasePath(
|
||||||
|
new URL('https://proxy.gitbook.site/sites/site_foo/hello/world'),
|
||||||
|
{
|
||||||
|
site: 'site_foo',
|
||||||
|
siteSpace: 'sitesp_foo',
|
||||||
|
basePath: '/foo',
|
||||||
|
siteBasePath: '/foo',
|
||||||
|
organization: 'org_foo',
|
||||||
|
space: 'space_foo',
|
||||||
|
pathname: '/hello/world',
|
||||||
|
complete: false,
|
||||||
|
apiToken: 'api_token_foo',
|
||||||
|
canonicalUrl: 'https://example.com/docs/foo/hello/world',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
).toBe('/sites/site_foo/');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return the correct base path for non-proxy requests', () => {
|
||||||
|
expect(
|
||||||
|
getVisitorAuthBasePath(new URL('https://example.com/docs/foo/hello/world'), {
|
||||||
|
site: 'site_foo',
|
||||||
|
siteSpace: 'sitesp_foo',
|
||||||
|
basePath: '/foo/',
|
||||||
|
siteBasePath: '/foo/',
|
||||||
|
organization: 'org_foo',
|
||||||
|
space: 'space_foo',
|
||||||
|
pathname: '/hello/world',
|
||||||
|
complete: false,
|
||||||
|
apiToken: 'api_token_foo',
|
||||||
|
canonicalUrl: 'https://example.com/docs/foo/hello/world',
|
||||||
|
})
|
||||||
|
).toBe('/foo/');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { withLeadingSlash, withTrailingSlash } from '@/lib/paths';
|
||||||
|
import type { PublishedSiteContent } from '@gitbook/api';
|
||||||
|
import { getProxyRequestIdentifier, isProxyRequest } from './proxy';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the appropriate base path for the visitor authentication cookie.
|
||||||
|
*/
|
||||||
|
export function getVisitorAuthBasePath(
|
||||||
|
siteRequestURL: URL,
|
||||||
|
siteURLData: PublishedSiteContent
|
||||||
|
): string {
|
||||||
|
// The siteRequestURL for proxy requests is of the form `https://proxy.gitbook.com/site/siteId/...`
|
||||||
|
// In such cases, we should not use the resolved siteBasePath for the cookie because for subsequent requests
|
||||||
|
// we will not have the siteBasePath in the request URL in order to retrieve the cookie. So we use the
|
||||||
|
// proxy identifier instead.
|
||||||
|
return isProxyRequest(siteRequestURL)
|
||||||
|
? withLeadingSlash(withTrailingSlash(getProxyRequestIdentifier(siteRequestURL)))
|
||||||
|
: siteURLData.siteBasePath;
|
||||||
|
}
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
/**
|
|
||||||
* Main host on which GitBook is running.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_URL =
|
|
||||||
process.env.NODE_ENV === 'development'
|
|
||||||
? 'http://localhost:3000'
|
|
||||||
: ((process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : undefined) ??
|
|
||||||
process.env.GITBOOK_URL ??
|
|
||||||
'');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* URL at which static assets are served.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_ASSETS_URL =
|
|
||||||
process.env.NODE_ENV === 'development'
|
|
||||||
? 'http://localhost:3000'
|
|
||||||
: (process.env.GITBOOK_ASSETS_PREFIX ?? GITBOOK_URL);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GitBook app URL.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_APP_URL = process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? 'https://app.gitbook.com';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default GitBook API URL endpoint.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_API_URL = process.env.GITBOOK_API_URL ?? 'https://api.gitbook.com';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default GitBook API token.
|
|
||||||
* It can be use to avoid rate-limiting.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_API_TOKEN = process.env.GITBOOK_API_TOKEN ?? null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* User agent to use for API requests.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_USER_AGENT = process.env.GITBOOK_USER_AGENT ?? 'GitBook-Open/2.0.0';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether to disable tracking of events into site insights.
|
|
||||||
* This is used to disable tracking in development mode.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_DISABLE_TRACKING = Boolean(
|
|
||||||
!!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production'
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hostname serving the integrations.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_INTEGRATIONS_HOST =
|
|
||||||
process.env.GITBOOK_INTEGRATIONS_HOST ?? 'integrations.gitbook.com';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Endpoint to use for resizing images.
|
|
||||||
* It should be a Cloudflare domain with image resizing enabled.
|
|
||||||
*/
|
|
||||||
export const GITBOOK_IMAGE_RESIZE_URL = process.env.GITBOOK_IMAGE_RESIZE_URL ?? null;
|
|
||||||
export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
|
|
||||||
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null;
|
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime environment.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_RUNTIME = (process.env.GITBOOK_RUNTIME ?? 'unknown') as
|
||||||
|
| 'vercel'
|
||||||
|
| 'cloudflare'
|
||||||
|
| 'unknown';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main host on which GitBook is running.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_URL =
|
||||||
|
process.env.NODE_ENV === 'development'
|
||||||
|
? 'http://localhost:3000'
|
||||||
|
: (process.env.GITBOOK_URL ??
|
||||||
|
(process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : undefined) ??
|
||||||
|
'');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL at which static assets are served.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_ASSETS_URL =
|
||||||
|
process.env.NODE_ENV === 'development'
|
||||||
|
? 'http://localhost:3000'
|
||||||
|
: process.env.GITBOOK_ASSETS_PREFIX;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitBook app URL.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_APP_URL = process.env.GITBOOK_APP_URL || 'https://app.gitbook.com';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default GitBook API URL endpoint.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_API_URL = process.env.GITBOOK_API_URL || 'https://api.gitbook.com';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default GitBook API URL endpoint, to be shared with the client.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_API_PUBLIC_URL = process.env.GITBOOK_API_PUBLIC_URL || GITBOOK_API_URL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default GitBook API token.
|
||||||
|
* It can be use to avoid rate-limiting.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_API_TOKEN = process.env.GITBOOK_API_TOKEN || null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User agent to use for API requests.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_USER_AGENT = process.env.GITBOOK_USER_AGENT || 'GitBook-Open/2.0.0';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether to disable tracking of events into site insights.
|
||||||
|
* This is used to disable tracking in development mode.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_DISABLE_TRACKING = Boolean(
|
||||||
|
!!process.env.GITBOOK_DISABLE_TRACKING || process.env.NODE_ENV !== 'production'
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hostname serving the integrations.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_INTEGRATIONS_HOST =
|
||||||
|
process.env.GITBOOK_INTEGRATIONS_HOST || 'integrations.gitbook.com';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hostname for fonts.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_FONTS_URL = process.env.GITBOOK_FONTS_URL || 'https://fonts.gitbook.com';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Endpoint to use for resizing images.
|
||||||
|
* It should be a Cloudflare domain with image resizing enabled.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_IMAGE_RESIZE_URL = process.env.GITBOOK_IMAGE_RESIZE_URL ?? null;
|
||||||
|
export const GITBOOK_IMAGE_RESIZE_SIGNING_KEY =
|
||||||
|
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY ?? null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode used for resizing images.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_IMAGE_RESIZE_MODE = enforceEnum(
|
||||||
|
'GITBOOK_IMAGE_RESIZE_MODE',
|
||||||
|
process.env.GITBOOK_IMAGE_RESIZE_MODE || 'cdn-cgi',
|
||||||
|
['cdn-cgi', 'cf-fetch']
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
export const GITBOOK_SECRET = process.env.GITBOOK_SECRET ?? null;
|
||||||
|
|
||||||
|
function enforceEnum<T extends string>(key: string, value: string, enumValues: T[]): T {
|
||||||
|
if (!enumValues.includes(value as T)) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid value for ${key}: "${value}", expected one of: ${enumValues.join(', ')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value as T;
|
||||||
|
}
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './globals';
|
||||||
|
export * from './urls';
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
import { GITBOOK_ASSETS_URL, GITBOOK_URL } from './globals';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the URL is a GitBook host URL.
|
||||||
|
*/
|
||||||
|
export function isGitBookHostURL(input: URL | string): boolean {
|
||||||
|
const url = typeof input === 'string' ? new URL(input) : input;
|
||||||
|
|
||||||
|
if (!GITBOOK_URL) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const gitbookHost = new URL(GITBOOK_URL).host;
|
||||||
|
|
||||||
|
if (url.host === gitbookHost) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle the Cloudflare preview URLs that are prefixed with a random hash
|
||||||
|
// https://developers.cloudflare.com/workers/configuration/previews/
|
||||||
|
if (url.host.endsWith(`-${gitbookHost}`)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the URL is a GitBook assets host URL.
|
||||||
|
*/
|
||||||
|
export function isGitBookAssetsHostURL(input: URL | string): boolean {
|
||||||
|
const url = typeof input === 'string' ? new URL(input) : input;
|
||||||
|
|
||||||
|
if (!GITBOOK_ASSETS_URL) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const gitbookAssetsHost = new URL(GITBOOK_ASSETS_URL).host;
|
||||||
|
|
||||||
|
if (url.host === gitbookAssetsHost) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { checkIsHttpURL } from '@/lib/urls';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if an image URL is resizable.
|
||||||
|
* Skip it for non-http(s) URLs (data, etc).
|
||||||
|
* Skip it for SVGs.
|
||||||
|
* Skip it for GitBook images (to avoid recursion).
|
||||||
|
*/
|
||||||
|
export function checkIsSizableImageURL(input: string): boolean {
|
||||||
|
if (!URL.canParse(input)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.includes('/~gitbook/image')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = new URL(input);
|
||||||
|
if (parsed.pathname.endsWith('.svg') || parsed.pathname.endsWith('.avif')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!checkIsHttpURL(parsed)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -1,45 +1,22 @@
|
|||||||
import 'server-only';
|
import 'server-only';
|
||||||
|
|
||||||
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env';
|
import { GITBOOK_IMAGE_RESIZE_SIGNING_KEY, GITBOOK_IMAGE_RESIZE_URL } from '../env';
|
||||||
import type { GitBookSpaceLinker } from '../links';
|
import type { GitBookLinker } from '../links';
|
||||||
|
import { checkIsSizableImageURL } from './checkIsSizableImageURL';
|
||||||
|
import { getImageSize } from './resizer';
|
||||||
import { type SignatureVersion, generateImageSignature } from './signatures';
|
import { type SignatureVersion, generateImageSignature } from './signatures';
|
||||||
import type { ImageResizer } from './types';
|
import type { ImageResizer } from './types';
|
||||||
|
|
||||||
interface CloudflareImageJsonFormat {
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
original: {
|
|
||||||
file_size: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
format: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* https://developers.cloudflare.com/images/image-resizing/resize-with-workers/
|
|
||||||
*/
|
|
||||||
export interface CloudflareImageOptions {
|
|
||||||
format?: 'webp' | 'avif' | 'json' | 'jpeg';
|
|
||||||
fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad';
|
|
||||||
width?: number;
|
|
||||||
height?: number;
|
|
||||||
dpr?: number;
|
|
||||||
anim?: boolean;
|
|
||||||
quality?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an image resizer for a rendering context.
|
* Create an image resizer for a rendering context.
|
||||||
*/
|
*/
|
||||||
export function createImageResizer({
|
export function createImageResizer({
|
||||||
host,
|
imagesContextId,
|
||||||
linker,
|
linker,
|
||||||
}: {
|
}: {
|
||||||
/** The linker to use to create URLs. */
|
/** The linker to use to create URLs. */
|
||||||
linker: GitBookSpaceLinker;
|
linker: GitBookLinker;
|
||||||
/** The host name of the current site. */
|
/** The site identifier to use for verifying the image signature. */
|
||||||
host: string;
|
imagesContextId: string;
|
||||||
}): ImageResizer {
|
}): ImageResizer {
|
||||||
if (!GITBOOK_IMAGE_RESIZE_URL || !GITBOOK_IMAGE_RESIZE_SIGNING_KEY) {
|
if (!GITBOOK_IMAGE_RESIZE_URL || !GITBOOK_IMAGE_RESIZE_SIGNING_KEY) {
|
||||||
return createNoopImageResizer();
|
return createNoopImageResizer();
|
||||||
@@ -58,32 +35,31 @@ export function createImageResizer({
|
|||||||
|
|
||||||
return async (options) => {
|
return async (options) => {
|
||||||
cachedSignature ??= await generateImageSignature({
|
cachedSignature ??= await generateImageSignature({
|
||||||
host,
|
imagesContextId,
|
||||||
url: urlInput,
|
url: urlInput,
|
||||||
});
|
});
|
||||||
|
|
||||||
const url = new URL(
|
const url = linker.toAbsoluteURL(linker.toPathInSite('/~gitbook/image'));
|
||||||
linker.toAbsoluteURL(linker.toPathInContent('/~gitbook/image'))
|
const searchParams = new URLSearchParams();
|
||||||
);
|
searchParams.set('url', getImageAPIUrl(urlInput));
|
||||||
url.searchParams.set('url', getImageAPIUrl(urlInput));
|
|
||||||
|
|
||||||
if (options.width) {
|
if (options.width) {
|
||||||
url.searchParams.set('width', options.width.toString());
|
searchParams.set('width', options.width.toString());
|
||||||
}
|
}
|
||||||
if (options.height) {
|
if (options.height) {
|
||||||
url.searchParams.set('height', options.height.toString());
|
searchParams.set('height', options.height.toString());
|
||||||
}
|
}
|
||||||
if (options.dpr) {
|
if (options.dpr) {
|
||||||
url.searchParams.set('dpr', options.dpr.toString());
|
searchParams.set('dpr', options.dpr.toString());
|
||||||
}
|
}
|
||||||
if (options.quality) {
|
if (options.quality) {
|
||||||
url.searchParams.set('quality', options.quality.toString());
|
searchParams.set('quality', options.quality.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
url.searchParams.set('sign', cachedSignature.signature);
|
searchParams.set('sign', cachedSignature.signature);
|
||||||
url.searchParams.set('sv', cachedSignature.version);
|
searchParams.set('sv', cachedSignature.version);
|
||||||
|
|
||||||
return url.toString();
|
return `${url}?${searchParams.toString()}`;
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -107,124 +83,6 @@ export function createNoopImageResizer(): ImageResizer {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a URL is an HTTP URL.
|
|
||||||
*/
|
|
||||||
export function checkIsHttpURL(input: string | URL): boolean {
|
|
||||||
if (!URL.canParse(input)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const parsed = new URL(input);
|
|
||||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if an image URL is resizable.
|
|
||||||
* Skip it for non-http(s) URLs (data, etc).
|
|
||||||
* Skip it for SVGs.
|
|
||||||
* Skip it for GitBook images (to avoid recursion).
|
|
||||||
*/
|
|
||||||
export function checkIsSizableImageURL(input: string): boolean {
|
|
||||||
if (!URL.canParse(input)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.includes('/~gitbook/image')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsed = new URL(input);
|
|
||||||
if (parsed.pathname.endsWith('.svg') || parsed.pathname.endsWith('.avif')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!checkIsHttpURL(parsed)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the size of an image.
|
|
||||||
*/
|
|
||||||
export async function getImageSize(
|
|
||||||
input: string,
|
|
||||||
defaultSize: Partial<CloudflareImageOptions> = {}
|
|
||||||
): Promise<{ width: number; height: number } | null> {
|
|
||||||
if (!checkIsSizableImageURL(input)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await resizeImage(input, {
|
|
||||||
// Abort the request after 2 seconds to avoid blocking rendering for too long
|
|
||||||
signal: AbortSignal.timeout(2000),
|
|
||||||
// Measure size and resize it to the most common size
|
|
||||||
// to optimize caching
|
|
||||||
...defaultSize,
|
|
||||||
format: 'json',
|
|
||||||
anim: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const json = (await response.json()) as CloudflareImageJsonFormat;
|
|
||||||
return {
|
|
||||||
width: json.original.width,
|
|
||||||
height: json.original.height,
|
|
||||||
};
|
|
||||||
} catch (_error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute a Cloudflare Image Resize operation on an image.
|
|
||||||
*/
|
|
||||||
export async function resizeImage(
|
|
||||||
input: string,
|
|
||||||
options: CloudflareImageOptions & {
|
|
||||||
signal?: AbortSignal;
|
|
||||||
}
|
|
||||||
): Promise<Response> {
|
|
||||||
const { signal, ...resizeOptions } = options;
|
|
||||||
|
|
||||||
const parsed = new URL(input);
|
|
||||||
if (parsed.protocol === 'data:') {
|
|
||||||
throw new Error('Cannot resize data: URLs');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsed.hostname === 'localhost') {
|
|
||||||
throw new Error('Cannot resize localhost URLs');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Since Cloudflare Images options on fetch are not supported on Cloudflare Pages,
|
|
||||||
// we need to use the Cloudflare Image Resize API directly.
|
|
||||||
if (!GITBOOK_IMAGE_RESIZE_URL) {
|
|
||||||
throw new Error('GITBOOK_IMAGE_RESIZE_URL is not set');
|
|
||||||
}
|
|
||||||
|
|
||||||
return await fetch(
|
|
||||||
`${GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions(
|
|
||||||
resizeOptions
|
|
||||||
)}/${encodeURIComponent(input)}`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
// Pass the `Accept` header, as Cloudflare uses this to validate the format.
|
|
||||||
Accept:
|
|
||||||
resizeOptions.format === 'json'
|
|
||||||
? 'application/json'
|
|
||||||
: `image/${resizeOptions.format || 'jpeg'}`,
|
|
||||||
},
|
|
||||||
signal,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function stringifyOptions(options: CloudflareImageOptions): string {
|
|
||||||
return Object.entries({ ...options }).reduce((rest, [key, value]) => {
|
|
||||||
return `${rest}${rest ? ',' : ''}${key}=${value}`;
|
|
||||||
}, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Because of a bug in Cloudflare, 127.0.0.1 is replaced by localhost.
|
* Because of a bug in Cloudflare, 127.0.0.1 is replaced by localhost.
|
||||||
* We protect against it by converting to a special token, and then parsing
|
* We protect against it by converting to a special token, and then parsing
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { getProxyRequestIdentifier, isProxyRequest } from '../data';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the site identifier to use for image resizing for an incoming request.
|
||||||
|
* This identifier can be obtained before resolving the request URL.
|
||||||
|
*/
|
||||||
|
export function getImageResizingContextId(url: URL): string {
|
||||||
|
if (isProxyRequest(url)) {
|
||||||
|
return getProxyRequestIdentifier(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
return url.host;
|
||||||
|
}
|
||||||
@@ -2,3 +2,6 @@ export * from './types';
|
|||||||
export * from './createImageResizer';
|
export * from './createImageResizer';
|
||||||
export * from './signatures';
|
export * from './signatures';
|
||||||
export * from './utils';
|
export * from './utils';
|
||||||
|
export * from './getImageResizingContextId';
|
||||||
|
export * from './resizer';
|
||||||
|
export * from './checkIsSizableImageURL';
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { GITBOOK_IMAGE_RESIZE_URL } from '@v2/lib/env';
|
||||||
|
import type { CloudflareImageOptions } from './types';
|
||||||
|
import { copyImageResponse } from './utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resize an image by doing a request to a /cdn/cgi/ endpoint.
|
||||||
|
* https://developers.cloudflare.com/images/transform-images/transform-via-url/
|
||||||
|
*/
|
||||||
|
export async function resizeImageWithCDNCgi(
|
||||||
|
input: string,
|
||||||
|
options: CloudflareImageOptions & {
|
||||||
|
signal?: AbortSignal;
|
||||||
|
}
|
||||||
|
): Promise<Response> {
|
||||||
|
const { signal, ...resizeOptions } = options;
|
||||||
|
|
||||||
|
// Since Cloudflare Images options on fetch are not supported on Cloudflare Pages,
|
||||||
|
// we need to use the Cloudflare Image Resize API directly.
|
||||||
|
if (!GITBOOK_IMAGE_RESIZE_URL) {
|
||||||
|
throw new Error('GITBOOK_IMAGE_RESIZE_URL is not set for cdn-cgi image resize mode');
|
||||||
|
}
|
||||||
|
|
||||||
|
const resizeURL = `${GITBOOK_IMAGE_RESIZE_URL}${stringifyOptions(
|
||||||
|
resizeOptions
|
||||||
|
)}/${encodeURIComponent(input)}`;
|
||||||
|
|
||||||
|
// biome-ignore lint/suspicious/noConsole: this log is useful for debugging
|
||||||
|
console.log(`resize image using cdn-cgi: ${resizeURL}`);
|
||||||
|
|
||||||
|
return copyImageResponse(
|
||||||
|
await fetch(resizeURL, {
|
||||||
|
headers: {
|
||||||
|
// Pass the `Accept` header, as Cloudflare uses this to validate the format.
|
||||||
|
Accept:
|
||||||
|
resizeOptions.format === 'json'
|
||||||
|
? 'application/json'
|
||||||
|
: `image/${resizeOptions.format || 'jpeg'}`,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stringifyOptions(options: CloudflareImageOptions): string {
|
||||||
|
return Object.entries({ ...options }).reduce((rest, [key, value]) => {
|
||||||
|
return `${rest}${rest ? ',' : ''}${key}=${value}`;
|
||||||
|
}, '');
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { CloudflareImageOptions } from './types';
|
||||||
|
import { copyImageResponse } from './utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resize an image by doing a request to the image itself using the Cloudflare fetch.
|
||||||
|
* https://developers.cloudflare.com/images/transform-images/transform-via-workers/
|
||||||
|
*
|
||||||
|
* This method doesn't work in Cloudflare Pages and is only supported in workers.
|
||||||
|
*/
|
||||||
|
export async function resizeImageWithCFFetch(
|
||||||
|
input: string,
|
||||||
|
options: CloudflareImageOptions & {
|
||||||
|
signal?: AbortSignal;
|
||||||
|
}
|
||||||
|
): Promise<Response> {
|
||||||
|
const { signal, ...resizeOptions } = options;
|
||||||
|
|
||||||
|
// biome-ignore lint/suspicious/noConsole: this log is useful for debugging
|
||||||
|
console.log(`resize image using cf-fetch: ${input}`);
|
||||||
|
|
||||||
|
return copyImageResponse(
|
||||||
|
await fetch(input, {
|
||||||
|
headers: {
|
||||||
|
// Pass the `Accept` header, as Cloudflare uses this to validate the format.
|
||||||
|
Accept:
|
||||||
|
resizeOptions.format === 'json'
|
||||||
|
? 'application/json'
|
||||||
|
: `image/${resizeOptions.format || 'jpeg'}`,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
cf: { image: resizeOptions },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './types';
|
||||||
|
export * from './resizeImage';
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import 'server-only';
|
||||||
|
import assertNever from 'assert-never';
|
||||||
|
import { GITBOOK_IMAGE_RESIZE_MODE } from '../../env';
|
||||||
|
import { checkIsSizableImageURL } from '../checkIsSizableImageURL';
|
||||||
|
import { resizeImageWithCDNCgi } from './cdn-cgi';
|
||||||
|
import { resizeImageWithCFFetch } from './cf-fetch';
|
||||||
|
import type { CloudflareImageJsonFormat, CloudflareImageOptions } from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the size of an image.
|
||||||
|
*/
|
||||||
|
export async function getImageSize(
|
||||||
|
input: string,
|
||||||
|
defaultSize: Partial<CloudflareImageOptions> = {}
|
||||||
|
): Promise<{ width: number; height: number } | null> {
|
||||||
|
if (!checkIsSizableImageURL(input)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await resizeImage(input, {
|
||||||
|
// Abort the request after 2 seconds to avoid blocking rendering for too long
|
||||||
|
signal: AbortSignal.timeout(2000),
|
||||||
|
// Measure size and resize it to the most common size
|
||||||
|
// to optimize caching
|
||||||
|
...defaultSize,
|
||||||
|
format: 'json',
|
||||||
|
anim: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const json = (await response.json()) as CloudflareImageJsonFormat;
|
||||||
|
return {
|
||||||
|
width: json.original.width,
|
||||||
|
height: json.original.height,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Error getting image size for ${input}:`, error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a Cloudflare Image Resize operation on an image.
|
||||||
|
*/
|
||||||
|
export async function resizeImage(
|
||||||
|
input: string,
|
||||||
|
options: CloudflareImageOptions & {
|
||||||
|
signal?: AbortSignal;
|
||||||
|
}
|
||||||
|
): Promise<Response> {
|
||||||
|
const parsed = new URL(input);
|
||||||
|
if (parsed.protocol === 'data:') {
|
||||||
|
throw new Error('Cannot resize data: URLs');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.hostname === 'localhost') {
|
||||||
|
throw new Error('Cannot resize localhost URLs');
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (GITBOOK_IMAGE_RESIZE_MODE) {
|
||||||
|
case 'cdn-cgi':
|
||||||
|
return resizeImageWithCDNCgi(input, options);
|
||||||
|
case 'cf-fetch':
|
||||||
|
return resizeImageWithCFFetch(input, options);
|
||||||
|
default:
|
||||||
|
assertNever(GITBOOK_IMAGE_RESIZE_MODE);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
export interface CloudflareImageJsonFormat {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
original: {
|
||||||
|
file_size: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
format: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* https://developers.cloudflare.com/images/image-resizing/resize-with-workers/
|
||||||
|
*/
|
||||||
|
export interface CloudflareImageOptions {
|
||||||
|
format?: 'webp' | 'avif' | 'json' | 'jpeg';
|
||||||
|
fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad';
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
dpr?: number;
|
||||||
|
anim?: boolean;
|
||||||
|
quality?: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* Copy a response to make sure it can be mutated by the rest of the middleware.
|
||||||
|
* To avoid errors "Can't modify immutable headers".
|
||||||
|
*/
|
||||||
|
export function copyImageResponse(response: Response) {
|
||||||
|
return new Response(response.body, response);
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ export const CURRENT_SIGNATURE_VERSION: SignatureVersion = '2';
|
|||||||
|
|
||||||
type SignFnInput = {
|
type SignFnInput = {
|
||||||
url: string;
|
url: string;
|
||||||
host: string;
|
imagesContextId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type SignFn = (input: SignFnInput) => MaybePromise<string>;
|
type SignFn = (input: SignFnInput) => MaybePromise<string>;
|
||||||
@@ -32,6 +32,11 @@ export async function verifyImageSignature(
|
|||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const generator = IMAGE_SIGNATURE_FUNCTIONS[version];
|
const generator = IMAGE_SIGNATURE_FUNCTIONS[version];
|
||||||
const generated = await generator(input);
|
const generated = await generator(input);
|
||||||
|
|
||||||
|
// biome-ignore lint/suspicious/noConsole: we want to log the signature comparison
|
||||||
|
console.log(
|
||||||
|
`comparing image signature for "${input.url}" on identifier "${input.imagesContextId}": "${generated}" (expected) === "${signature}" (actual)`
|
||||||
|
);
|
||||||
return generated === signature;
|
return generated === signature;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,12 +65,14 @@ const generateSignatureV2: SignFn = async (input) => {
|
|||||||
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
|
assert(GITBOOK_IMAGE_RESIZE_SIGNING_KEY, 'GITBOOK_IMAGE_RESIZE_SIGNING_KEY is not set');
|
||||||
const all = [
|
const all = [
|
||||||
input.url,
|
input.url,
|
||||||
input.host, // The hostname is used to avoid serving images from other sites on the same domain
|
input.imagesContextId, // The hostname is used to avoid serving images from other sites on the same domain
|
||||||
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(':');
|
.join(':');
|
||||||
return fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16);
|
|
||||||
|
const signature = fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16);
|
||||||
|
return signature;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reused buffer for FNV-1a hashing in the v1 algorithm
|
// Reused buffer for FNV-1a hashing in the v1 algorithm
|
||||||
|
|||||||
@@ -1,25 +1,51 @@
|
|||||||
import { describe, expect, it } from 'bun:test';
|
import { describe, expect, it } from 'bun:test';
|
||||||
import { appendBasePathToLinker, createLinker } from './links';
|
import { createLinker } from './links';
|
||||||
|
|
||||||
const root = createLinker({
|
const root = createLinker({
|
||||||
host: 'docs.company.com',
|
host: 'docs.company.com',
|
||||||
pathname: '/',
|
spaceBasePath: '/',
|
||||||
|
siteBasePath: '/',
|
||||||
});
|
});
|
||||||
|
|
||||||
const variantInSection = createLinker({
|
const variantInSection = createLinker({
|
||||||
host: 'docs.company.com',
|
host: 'docs.company.com',
|
||||||
pathname: '/section/variant',
|
spaceBasePath: '/section/variant',
|
||||||
|
siteBasePath: '/',
|
||||||
|
});
|
||||||
|
|
||||||
|
const siteGitBookIO = createLinker({
|
||||||
|
host: 'org.gitbook.io',
|
||||||
|
spaceBasePath: '/sitename/variant/',
|
||||||
|
siteBasePath: '/sitename/',
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('toPathInContent', () => {
|
describe('toPathInContent', () => {
|
||||||
it('should return the correct path', () => {
|
it('should return the correct path', () => {
|
||||||
expect(root.toPathInContent('some/path')).toBe('/some/path');
|
expect(root.toPathInSpace('some/path')).toBe('/some/path');
|
||||||
expect(variantInSection.toPathInContent('some/path')).toBe('/section/variant/some/path');
|
expect(variantInSection.toPathInSpace('some/path')).toBe('/section/variant/some/path');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle leading slash', () => {
|
it('should handle leading slash', () => {
|
||||||
expect(root.toPathInContent('/some/path')).toBe('/some/path');
|
expect(root.toPathInSpace('/some/path')).toBe('/some/path');
|
||||||
expect(variantInSection.toPathInContent('/some/path')).toBe('/section/variant/some/path');
|
expect(variantInSection.toPathInSpace('/some/path')).toBe('/section/variant/some/path');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('toPathInSite', () => {
|
||||||
|
it('should return the correct path', () => {
|
||||||
|
expect(root.toPathInSite('some/path')).toBe('/some/path');
|
||||||
|
expect(siteGitBookIO.toPathInSite('some/path')).toBe('/sitename/some/path');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('toRelativePathInSite', () => {
|
||||||
|
it('should return the correct path', () => {
|
||||||
|
expect(root.toRelativePathInSite('/some/path')).toBe('some/path');
|
||||||
|
expect(siteGitBookIO.toRelativePathInSite('/sitename/some/path')).toBe('some/path');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should preserve absolute paths outside of the site', () => {
|
||||||
|
expect(siteGitBookIO.toRelativePathInSite('/outside/some/path')).toBe('/outside/some/path');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -32,27 +58,17 @@ describe('toAbsoluteURL', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('appendBasePathToLinker', () => {
|
describe('toLinkForContent', () => {
|
||||||
const prefixedRoot = appendBasePathToLinker(root, '/section/variant');
|
it('should return the correct path', () => {
|
||||||
const prefixedVariantInSection = appendBasePathToLinker(variantInSection, '/base');
|
expect(root.toLinkForContent('https://docs.company.com/some/path')).toBe('/some/path');
|
||||||
|
expect(siteGitBookIO.toLinkForContent('https://org.gitbook.io/sitename/some/path')).toBe(
|
||||||
describe('toPathInContent', () => {
|
'/sitename/some/path'
|
||||||
it('should return the correct path', () => {
|
);
|
||||||
expect(prefixedRoot.toPathInContent('some/path')).toBe('/section/variant/some/path');
|
|
||||||
expect(prefixedVariantInSection.toPathInContent('some/path')).toBe(
|
|
||||||
'/section/variant/base/some/path'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('toAbsoluteURL', () => {
|
it('should preserve an absolute URL if the site is not the same', () => {
|
||||||
it('should return the correct path', () => {
|
expect(siteGitBookIO.toLinkForContent('https://org.gitbook.io/anothersite/some/path')).toBe(
|
||||||
expect(prefixedRoot.toAbsoluteURL('some/path')).toBe(
|
'https://org.gitbook.io/anothersite/some/path'
|
||||||
'https://docs.company.com/some/path'
|
);
|
||||||
);
|
|
||||||
expect(prefixedVariantInSection.toAbsoluteURL('some/path')).toBe(
|
|
||||||
'https://docs.company.com/some/path'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,22 +1,35 @@
|
|||||||
import { getPagePath } from '@/lib/pages';
|
import { getPagePath } from '@/lib/pages';
|
||||||
|
import { withLeadingSlash, withTrailingSlash } from '@/lib/paths';
|
||||||
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
||||||
|
import warnOnce from 'warn-once';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generic interface to generate links based on a given context.
|
* Generic interface to generate links based on a given context.
|
||||||
*
|
*
|
||||||
* URL levels:
|
* URL levels:
|
||||||
*
|
*
|
||||||
* https://docs.company.com/section/variant/page
|
* https://docs.company.com/basename/section/variant/page
|
||||||
*
|
*
|
||||||
* toPathInContent('some/path') => /section/variant/some/path
|
* toPathInSpace('some/path') => /basename/section/variant/some/path
|
||||||
* toPathForPage({ pages, page }) => /section/variant/some/path
|
* toPathInSite('some/path') => /basename/some/path
|
||||||
|
* toPathForPage({ pages, page }) => /basename/section/variant/some/path
|
||||||
* toAbsoluteURL('some/path') => https://docs.company.com/some/path
|
* toAbsoluteURL('some/path') => https://docs.company.com/some/path
|
||||||
*/
|
*/
|
||||||
export interface GitBookSpaceLinker {
|
export interface GitBookLinker {
|
||||||
/**
|
/**
|
||||||
* Generate an absolute path for a relative path to the current content.
|
* Generate an absolute path for a relative path to the current content.
|
||||||
*/
|
*/
|
||||||
toPathInContent(relativePath: string): string;
|
toPathInSpace(relativePath: string): string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate an absolute path for a relative path to the current site.
|
||||||
|
*/
|
||||||
|
toPathInSite(relativePath: string): string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform an absolute path in a site, to a relative path from the root of the site.
|
||||||
|
*/
|
||||||
|
toRelativePathInSite(absolutePath: string): string;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate an absolute path for a page in the current content.
|
* Generate an absolute path for a page in the current content.
|
||||||
@@ -46,66 +59,67 @@ export function createLinker(
|
|||||||
/** Where the top of the space is served on */
|
/** Where the top of the space is served on */
|
||||||
servedOn: {
|
servedOn: {
|
||||||
protocol?: string;
|
protocol?: string;
|
||||||
host: string;
|
host?: string;
|
||||||
pathname: string;
|
|
||||||
}
|
|
||||||
): GitBookSpaceLinker {
|
|
||||||
if (servedOn.host.includes('/')) {
|
|
||||||
throw new Error('Host cannot include a slash');
|
|
||||||
}
|
|
||||||
|
|
||||||
const linker: GitBookSpaceLinker = {
|
/** The base path of the space */
|
||||||
toPathInContent(relativePath: string): string {
|
spaceBasePath: string;
|
||||||
return joinPaths(servedOn.pathname, relativePath);
|
|
||||||
|
/** The base path of the site */
|
||||||
|
siteBasePath: string;
|
||||||
|
}
|
||||||
|
): GitBookLinker {
|
||||||
|
warnOnce(!servedOn.host, 'No host provided to createLinker. It can lead to issues with links.');
|
||||||
|
|
||||||
|
const siteBasePath = withTrailingSlash(withLeadingSlash(servedOn.siteBasePath));
|
||||||
|
const spaceBasePath = withTrailingSlash(withLeadingSlash(servedOn.spaceBasePath));
|
||||||
|
|
||||||
|
const linker: GitBookLinker = {
|
||||||
|
toPathInSpace(relativePath: string): string {
|
||||||
|
return joinPaths(spaceBasePath, relativePath);
|
||||||
|
},
|
||||||
|
|
||||||
|
toPathInSite(relativePath: string): string {
|
||||||
|
return joinPaths(siteBasePath, relativePath);
|
||||||
|
},
|
||||||
|
|
||||||
|
toRelativePathInSite(absolutePath: string): string {
|
||||||
|
const normalizedPath = withLeadingSlash(absolutePath);
|
||||||
|
|
||||||
|
if (!normalizedPath.startsWith(servedOn.siteBasePath)) {
|
||||||
|
return normalizedPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizedPath.slice(servedOn.siteBasePath.length);
|
||||||
},
|
},
|
||||||
|
|
||||||
toAbsoluteURL(absolutePath: string): string {
|
toAbsoluteURL(absolutePath: string): string {
|
||||||
|
if (!servedOn.host) {
|
||||||
|
return absolutePath;
|
||||||
|
}
|
||||||
|
|
||||||
return `${servedOn.protocol ?? 'https:'}//${joinPaths(servedOn.host, absolutePath)}`;
|
return `${servedOn.protocol ?? 'https:'}//${joinPaths(servedOn.host, absolutePath)}`;
|
||||||
},
|
},
|
||||||
|
|
||||||
toPathForPage({ pages, page, anchor }) {
|
toPathForPage({ pages, page, anchor }) {
|
||||||
return linker.toPathInContent(getPagePath(pages, page)) + (anchor ? `#${anchor}` : '');
|
return linker.toPathInSpace(getPagePath(pages, page)) + (anchor ? `#${anchor}` : '');
|
||||||
},
|
},
|
||||||
|
|
||||||
toLinkForContent(url: string): string {
|
toLinkForContent(rawURL: string): string {
|
||||||
return url;
|
const url = new URL(rawURL);
|
||||||
|
|
||||||
|
// If the link points to a content in the same site, we return an absolute path
|
||||||
|
// instead of a full URL; it makes it possible to use router navigation
|
||||||
|
if (url.hostname === servedOn.host && url.pathname.startsWith(servedOn.siteBasePath)) {
|
||||||
|
return url.pathname;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rawURL;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return linker;
|
return linker;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Append a prefix to a linker.
|
|
||||||
*/
|
|
||||||
export function appendBasePathToLinker(
|
|
||||||
linker: GitBookSpaceLinker,
|
|
||||||
basePath: string
|
|
||||||
): GitBookSpaceLinker {
|
|
||||||
const linkerWithPrefix: GitBookSpaceLinker = {
|
|
||||||
toPathInContent(relativePath: string): string {
|
|
||||||
return linker.toPathInContent(joinPaths(basePath, relativePath));
|
|
||||||
},
|
|
||||||
|
|
||||||
toAbsoluteURL(absolutePath: string): string {
|
|
||||||
return linker.toAbsoluteURL(absolutePath);
|
|
||||||
},
|
|
||||||
|
|
||||||
toPathForPage({ pages, page, anchor }) {
|
|
||||||
return (
|
|
||||||
linkerWithPrefix.toPathInContent(getPagePath(pages, page)) +
|
|
||||||
(anchor ? `#${anchor}` : '')
|
|
||||||
);
|
|
||||||
},
|
|
||||||
|
|
||||||
toLinkForContent(url: string): string {
|
|
||||||
return linker.toLinkForContent(url);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
return linkerWithPrefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
function joinPaths(prefix: string, path: string): string {
|
function joinPaths(prefix: string, path: string): string {
|
||||||
const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`;
|
const prefixPath = prefix.endsWith('/') ? prefix : `${prefix}/`;
|
||||||
const suffixPath = path.startsWith('/') ? path.slice(1) : path;
|
const suffixPath = path.startsWith('/') ? path.slice(1) : path;
|
||||||
|
|||||||
@@ -1,14 +1,48 @@
|
|||||||
import { CustomizationThemeMode } from '@gitbook/api';
|
import { CustomizationThemeMode } from '@gitbook/api';
|
||||||
import { headers } from 'next/headers';
|
import { headers } from 'next/headers';
|
||||||
|
import type { SiteURLData } from './context';
|
||||||
|
|
||||||
export enum MiddlewareHeaders {
|
export enum MiddlewareHeaders {
|
||||||
|
/**
|
||||||
|
* Type of the route (static or dynamic)
|
||||||
|
*/
|
||||||
|
RouteType = 'x-gitbook-route-type',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The URL of the site (without the pathname)
|
||||||
|
*/
|
||||||
|
SiteURL = 'x-gitbook-site-url',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data associated with the URL.
|
||||||
|
*/
|
||||||
|
SiteURLData = 'x-gitbook-site-url-data',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mode of the URL (url or url-host)
|
||||||
|
*/
|
||||||
URLMode = 'x-gitbook-url-mode',
|
URLMode = 'x-gitbook-url-mode',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The theme of the page (light or dark)
|
||||||
|
*/
|
||||||
Theme = 'x-gitbook-theme',
|
Theme = 'x-gitbook-theme',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The customization override to apply.
|
||||||
|
*/
|
||||||
Customization = 'x-gitbook-customization',
|
Customization = 'x-gitbook-customization',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The API token used to fetch the content.
|
||||||
|
* This should only be passed for non-site dynamic routes.
|
||||||
|
*/
|
||||||
|
APIToken = 'x-gitbook-api-token',
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the URL mode from the middleware headers.
|
* Get the URL mode from the middleware headers.
|
||||||
|
* This function should only be called in a server action or a dynamic route.
|
||||||
*/
|
*/
|
||||||
export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> {
|
export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> {
|
||||||
const headersList = await headers();
|
const headersList = await headers();
|
||||||
@@ -20,8 +54,40 @@ export async function getURLModeFromMiddleware(): Promise<'url' | 'url-host'> {
|
|||||||
return mode as 'url' | 'url-host';
|
return mode as 'url' | 'url-host';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the site URL data from the middleware headers.
|
||||||
|
* This function should only be called in a server action or a dynamic route.
|
||||||
|
*/
|
||||||
|
export async function getSiteURLDataFromMiddleware(): Promise<SiteURLData> {
|
||||||
|
const headersList = await headers();
|
||||||
|
const siteURLData = headersList.get(MiddlewareHeaders.SiteURLData);
|
||||||
|
|
||||||
|
if (!siteURLData) {
|
||||||
|
throw new Error(
|
||||||
|
'Site URL data is not set by the middleware. This should only be called in a server action or a dynamic route.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.parse(siteURLData);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the URL from the middleware headers.
|
||||||
|
* This function should only be called in a server action or a dynamic route.
|
||||||
|
*/
|
||||||
|
export async function getSiteURLFromMiddleware(): Promise<string> {
|
||||||
|
const headersList = await headers();
|
||||||
|
const siteURL = headersList.get(MiddlewareHeaders.SiteURL);
|
||||||
|
if (!siteURL) {
|
||||||
|
throw new Error('URL mode is not set by the middleware');
|
||||||
|
}
|
||||||
|
|
||||||
|
return siteURL;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* For preview, the theme can be set via query string (?theme=light).
|
* For preview, the theme can be set via query string (?theme=light).
|
||||||
|
* This function should only be called in a dynamic route.
|
||||||
*/
|
*/
|
||||||
export async function getThemeFromMiddleware() {
|
export async function getThemeFromMiddleware() {
|
||||||
const headersList = await headers();
|
const headersList = await headers();
|
||||||
@@ -34,3 +100,17 @@ export async function getThemeFromMiddleware() {
|
|||||||
? CustomizationThemeMode.Light
|
? CustomizationThemeMode.Light
|
||||||
: CustomizationThemeMode.Dark;
|
: CustomizationThemeMode.Dark;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GITBOOK_SECRET } from './env';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify the signature of the request and call the function with the body.
|
||||||
|
*/
|
||||||
|
export async function withVerifySignature<T>(
|
||||||
|
request: Request,
|
||||||
|
fn: (body: T) => Promise<NextResponse>
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const rawBody = await request.text();
|
||||||
|
const body = JSON.parse(rawBody) as T;
|
||||||
|
|
||||||
|
if (GITBOOK_SECRET) {
|
||||||
|
// Retrieve the signature header from the request
|
||||||
|
const incomingSignature = request.headers.get('x-gitbook-signature');
|
||||||
|
if (!incomingSignature) {
|
||||||
|
return NextResponse.json({ error: 'Missing signature header' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const computedSignature = crypto
|
||||||
|
.createHmac('sha256', GITBOOK_SECRET)
|
||||||
|
.update(rawBody)
|
||||||
|
.digest('hex');
|
||||||
|
|
||||||
|
// Compare incoming signature to computed signature
|
||||||
|
if (incomingSignature !== computedSignature) {
|
||||||
|
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return await fn(body);
|
||||||
|
} catch (_error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Invalid request or unable to parse JSON' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { type GitBookBaseContext, fetchSiteContextByURLLookup, getBaseContext } from './context';
|
||||||
|
import {
|
||||||
|
getSiteURLDataFromMiddleware,
|
||||||
|
getSiteURLFromMiddleware,
|
||||||
|
getURLModeFromMiddleware,
|
||||||
|
} from './middleware';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the base context for a server action.
|
||||||
|
* This function should only be called in a server action.
|
||||||
|
*/
|
||||||
|
export async function getServerActionBaseContext() {
|
||||||
|
const siteURL = await getSiteURLFromMiddleware();
|
||||||
|
const siteURLData = await getSiteURLDataFromMiddleware();
|
||||||
|
const urlMode = await getURLModeFromMiddleware();
|
||||||
|
|
||||||
|
return getBaseContext({
|
||||||
|
siteURL,
|
||||||
|
siteURLData,
|
||||||
|
urlMode,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the context for a site in a server action.
|
||||||
|
* The server action is always dynamic and the request is passed through the middleware.
|
||||||
|
*/
|
||||||
|
export async function fetchServerActionSiteContext(baseContext: GitBookBaseContext) {
|
||||||
|
const siteURLData = await getSiteURLDataFromMiddleware();
|
||||||
|
return fetchSiteContextByURLLookup(baseContext, siteURLData);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user