Compare commits

...

75 Commits

Author SHA1 Message Date
Nolann Biron 76a94b8316 Lazy-load OpenAPI and ContentKit stylesheets 2026-07-16 20:28:48 +02:00
Utku Ufuk 703e654a37 Split the default-scope site search into two parallel API requests (#4395) 2026-07-16 15:23:30 +03:00
conico974 1b571aeaa9 Fix scroll behavior for navigation (#4406) 2026-07-16 14:21:01 +02:00
Zeno Kapitein c41cf9c12a Add cover image background mode and mask (#4213)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 18:02:53 +02:00
Zeno Kapitein 3d376845d7 Add a carousel layout for cards blocks (#4393)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 16:17:00 +02:00
Nolann B. bcd4d4e980 Remove MCP test that recorded real feedback in production (#4399) 2026-07-15 10:42:20 +02:00
Addison 88b1919a45 Add centered GitBook logo to README (#4401)
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 17:31:04 +09:00
Steven H cf94386c16 fix an issue where certain keywords could cause an exception when rendering emojis (#4397) 2026-07-14 19:08:09 +00:00
Zeno Kapitein e77bf32d51 Update customer e2e test URL after redirect (#4398)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 18:24:14 +00:00
Zeno Kapitein a69a307de2 Take a near-neutral extreme tint as the exact site background (#4392) 2026-07-13 20:37:08 +02:00
Zeno Kapitein 39156ee9c3 Support button sizes in the button block (#4394)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:03:52 +02:00
spastorelli 47ac3e2c81 Only advertise OAuth PRM doc for the auth MCP endpoint on non-VA sites (#4387) 2026-07-10 15:24:33 +02:00
Zeno Kapitein e73b182925 Declare embed standalone bundle as a Turbo build output (RND-11876) (#4386)
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-10 13:51:48 +02:00
claude[bot] a9a52fee72 RND-11356: remove redundant GBO best-section re-selection (#4375)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Zeno Kapitein <zeno@gitbook.io>
2026-07-10 13:25:26 +02:00
Greg Bergé cb92754575 Add a navigate action to integration block webframes (#4362)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:24:33 +02:00
Zeno Kapitein 49d35aa026 Let visitors type a follow-up while the Assistant is answering (RND-11789) (#4377)
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-09 21:00:01 +02:00
Nolann B. 98b2df42ef Add sendFeedback MCP tool for reporting documentation findings (#4384)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-09 15:17:32 +02:00
Zeno Kapitein 6cf4278f14 Only show "Back to [space]" for table-of-contents cross-space links (#4381)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 14:32:11 +02:00
Zeno Kapitein 86c44299eb docs(agents): discourage multi-line block comments (#4382)
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-09 14:16:26 +02:00
claude[bot] 89c4a0f808 feat(mcp): add askQuestion tool to the site MCP server (#4372)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Zeno Kapitein <zeno@gitbook.io>
2026-07-09 13:11:05 +02:00
Nolann B. 8e9a49de1a Separate prompt block actions (#4379) 2026-07-08 16:11:26 +02:00
Zeno Kapitein 4e9071d1b5 Fix docs embed navigateToPage for cross-space/section deep links (#4374)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 11:02:49 +02:00
Nolann B. 597fe34d3b Sync responses selector with the Responses collapsibles (#4376) 2026-07-08 09:08:21 +02:00
claude[bot] e14609cb3e fix(theme): resolve system theme before first paint to avoid dark/light flash (RND-11643) (#4373)
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-07 20:10:02 +02:00
Zeno Kapitein 57f3077006 Keep the page outline and Ask button in view while scrolling API reference pages (#4371)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:10:55 +02:00
conico974 e24632c80b Integrate GitBook image resizing service and remove cdn-cgi mode (#4285) 2026-07-07 16:21:32 +02:00
Zeno Kapitein ad3399b42e Refine the per-paragraph ask button (shorter tooltip, hide inside cards) (#4365)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 19:27:04 +02:00
Brett Jephson f3408ed495 A11y fix: table structure (#4368) 2026-07-06 16:58:23 +01:00
Brett Jephson 8676ad19e2 RND-11788: hide unlabelled button from screen readers (#4369) 2026-07-06 16:58:02 +01:00
Samy Pessé 3a31100efe Version Packages (#4335)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-06 12:52:44 +00:00
Greg Bergé 3fedaaa08c Install eval-estree-expression from npm instead of a GitHub commit (#4367)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:31:54 +00:00
Nolann B. bcea23e886 Handle nullable expressed via anyOf/oneOf with a null member (#4366) 2026-07-06 12:33:02 +02:00
Zeno Kapitein fdea8f1c47 Show section, variant & section groups in page breadcrumbs (#4357)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 11:49:47 +02:00
Zeno Kapitein 139b897521 Improve language selector on mobile (#4361) 2026-07-06 11:03:39 +02:00
Greg Bergé 37c2dd8819 Fix flaky customer screenshots caused by the cookie banner (#4363)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 22:06:20 +02:00
Zeno Kapitein 62ca6d3ce5 Show a "Back to [space]" shortcut when a link leads to another space (#4358)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 12:36:07 +02:00
Nolann B. 6102413d6b Reuse shared AI mode helpers across AI actions and UI (#4355) 2026-07-02 23:19:07 +02:00
Zeno Kapitein eaef259a80 Refresh e2e customer list (#4360)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 19:34:09 +02:00
Zeno Kapitein 578a3a829b Fix section tab dropdowns clipping their contents during animation (#4356)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 12:06:41 +00:00
Zeno Kapitein c923c654bd Fix centered paragraphs shifting left with the paragraph ask button (#4354)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 12:19:24 +02:00
Nolann B. 65fd3cc101 Gate AI features server-actions (#4353) 2026-07-02 11:37:03 +02:00
Zeno Kapitein bb30db105d Add a margin button to ask the assistant about a paragraph (#4328) 2026-07-02 08:34:49 +02:00
Nolann B. 6146f8e183 Reduce oversized searchDocumentation MCP responses (#4352) 2026-07-01 18:00:02 +02:00
Nolann B. 7e55cd5e4c Add "Available in MCP" badge for OpenAPI operations (#4350) 2026-07-01 17:38:04 +02:00
conico974 cb2dfa76af Keep first 3 remote results pinned at the top (#4349) 2026-06-30 13:47:04 +02:00
Viktor Renkema 77efd449ae Allow quickly viewing which pages have changed in a CR/revision (#4348) 2026-06-30 12:49:31 +02:00
Zeno Kapitein af259fbe86 Scrap recommended questions from Search e2e test (#4351) 2026-06-30 12:29:21 +02:00
conico974 2b31b0213c Refactor error handling and remove unused caching logic (#4345) 2026-06-30 08:16:23 +02:00
Nolann B. f60afe1b25 Add missing MCP annotations (#4347) 2026-06-29 10:15:57 +02:00
Nolann B. b7c3b847e8 Prevent insights tracking failures from breaking MCP tool requests (#4346) 2026-06-27 09:31:20 +02:00
Zeno Kapitein 2fa65e6949 Support per-table search override (#4340)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 10:46:47 +02:00
Nolann B. c76b4fdccc Fix OpenAPI sticky preview column overflowing onto the next operation (#4341) 2026-06-25 15:10:26 +02:00
Zeno Kapitein 9f651339f0 Redesign the 404 page with related-page suggestions and a search input (#4338)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 12:30:42 +02:00
Zeno Kapitein 5ce3b1e578 Turn off search on cards (for now) (#4339) 2026-06-24 11:26:14 +02:00
Nolann B. d172684b88 Some small OpenAPI design tweaks (#4337) 2026-06-23 21:20:28 +02:00
conico974 937c8b8eb2 Remove 'remote' from cache usage in specific functions (#4312) 2026-06-23 17:59:43 +02:00
Zeno Kapitein 36dbdb48cc Support agent goal query param for markdownAsk (#4324)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:47:51 +02:00
Zeno Kapitein 2dc76a2c3c Fix empty grouped section dropdown in embedded sites (#4334)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:47:15 +02:00
Samy Pessé 0edc378c57 Version Packages (#4306)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-23 00:10:23 +02:00
Zeno Kapitein 2eb313194a Remove old PageAction checks (#4333) 2026-06-22 17:12:35 +02:00
Brett Jephson 882dfcda83 Tidy relating to prompt (#4332) 2026-06-22 15:48:58 +02:00
Brett Jephson 3ff88ba22f Adds the prompt block (#4329) 2026-06-22 11:53:25 +01:00
Nolann B. 51bd768042 Make the AI Assistant panel resizable (#4330) 2026-06-20 21:41:59 +02:00
spastorelli daadd91eba Fix NextLink prefetch side effect on unsigned claims persistance (#4325) 2026-06-19 11:39:12 +02:00
Nolann B. f4469b2df3 Support OpenAPI one-operation-per-page mode (#4314) 2026-06-19 10:35:09 +02:00
Nolann B. 91b325ca08 Add AI chat reference button on text selection (#4326) 2026-06-19 10:18:07 +02:00
Nolann B. 1616028426 Align code block action buttons vertically with the block (#4327) 2026-06-19 10:03:37 +02:00
Nolann B. 6c15d8314a Update OpenAPI border radius (#4323) 2026-06-18 23:25:19 +02:00
Zeno Kapitein 6c967c9bcc Add search and filters to table blocks (#4322)
Co-authored-by: utkuufuk <utkuufuk@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 10:41:40 +02:00
Johan Preynat c44d822fe1 Trust cookieless integration content host for WebFrames (#4321)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 18:08:25 +02:00
Zeno Kapitein af3cda1c53 Fix wide content overflowing hint blocks (#4320)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 13:32:53 +02:00
Tomek a0ad403a91 Stabilize Playwright Chrome text rendering across platforms (#4318) 2026-06-17 09:21:16 +00:00
Zeno Kapitein 0ca49523a2 Remove external link button from link tooltip hover card (#4316)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 10:52:02 +02:00
Zeno Kapitein 76550415ac Fix ⌘-C opening the Assistant on Dvorak keyboard layouts (#4311)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 10:51:20 +02:00
Nolann B. 509389c7e5 Update @gitbook/api to latest version (#4315) 2026-06-16 14:30:10 +02:00
279 changed files with 8371 additions and 1603 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Mark the AI Assistant chat as `aria-busy` while it is generating a response (including the follow-up suggestion phase), so assistive technologies are notified of the in-progress state.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the AI assistant panel overflowing its frame when rendering single/multi-choice question forms with long option text.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Assistant: group all of a turn's tool calls behind a single "Explored with N tools" expandable instead of rendering a separate single-item expandable for each client-side tool call.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Assistant: you can now send follow-up questions while an answer is still being written. Each one appears as your own message with a "Queued" badge (hover for when it will send, × to cancel), and they're sent automatically one at a time as each answer completes.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": minor
---
Add a carousel layout option to cards blocks, rendering them as a horizontally-scrolling, scroll-snapping row instead of a wrapping grid.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix the docs embed `navigateToPage` API on multi-space sites. Deep-linking to a page in a different space/section (e.g. `navigateToPage('/help-center/integrations')`) previously 404'd because the section base was not placed before `~gitbook/embed/page`. The target is now resolved to its space server-side, so pages in any space resolve correctly. The input accepts the page path, an absolute path, or the full published URL.
@@ -0,0 +1,6 @@
---
"@gitbook/colors": patch
"gitbook": patch
---
A near-white tint color (e.g. a warm `#F5F3EF`) is now taken as the exact page background, mirroring the existing behavior for near-black tints. The tint's exact lightness, hue and chroma are preserved, and the color is anchored to whichever scale step the active theme renders as the background — so it matches exactly on `muted` (which uses the second step) as well as `clean`. This applies only to near-neutral tints that are light enough to read as a background; saturated or merely light-ish colors keep their normal accent scale. The `bold` theme is unaffected: it already uses the tint for the header and stays intentionally two-tone.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Add cover image background mode and masks
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Button blocks now respect the `size` option, so you can render small, medium, or large buttons.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": minor
---
Add an `askQuestion` tool to the site MCP server. Alongside `searchDocumentation` and `getPage`, MCP clients can now ask a natural-language question and get a synthesized answer with links to the source pages, powered by the same AI search backend as the site's "ask a question" experience. The tool accepts an optional `goal` param so calling agents can attach the intent they're trying to accomplish, which tailors the answer and is tracked in analytics. The tool is only exposed on sites that have AI enabled.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Drive page actions ordering and default action from the new `pageActions.items` list, including the reorderable assistant action
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Add a page reference chip when opening the Assistant from the page action, so the assistant is informed about the page the reader is currently on.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Remove GBO's redundant re-selection of the best-scoring search section. The search API now returns a single highest-scoring section per page (and orders sections highest-score-first), so GBO no longer needs its own `getBestScoredResult` helper to pick the best section for the search and MCP previews. No user-visible change.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Sync the API reference responses selector with the "Responses" collapsibles, and keep the selected response in sync across every operation on the page (like the code sample language selector). Selecting a status code now expands the matching response section and applies to all operations at once.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix a light/dark flash on published sites configured to respect the system default (no theme toggle). Such sites forced the `system` theme, but `next-themes`' pre-paint script applies a forced value verbatim without resolving `prefers-color-scheme`, so the page painted light and only switched to dark after hydration. We now leave the theme unforced when the default is `system` (only concrete light/dark themes are forced), letting `next-themes`' existing pre-paint script resolve the system preference before first paint.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Add a `sendFeedback` MCP tool so AI agents can report documentation findings (outdated / incoherent / gap / other) as `agent_feedback` insights events. The tool only accepts finding categories, so it never records positive feedback.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Separate the prompt block actions into a primary "Open in" dropdown and a secondary "Copy prompt" button, instead of a single combined button group, and align the block's design with the expandable block (bordered frame, left disclosure chevron, and subtle elevation when expanded).
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix the docs embed widget shipping a stale script: declare the embed package's `standalone/` bundle as a Turbo build output. Because it wasn't declared, changes confined to the standalone widget (which compiles to `standalone/` but not `dist/`) didn't invalidate the downstream `generate` cache that copies it into the app, so the deployed widget could lag the source — e.g. the `clipboard-write` permission on the widget iframe never reached production, breaking the copy button in the Assistant embed.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Refine the per-paragraph AI ask button: shorten its tooltip to "Ask" (from "Ask <assistant> about this"), and hide it inside cards where it would otherwise be clipped by the card's overflow.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Split the default-scope site search into two parallel API requests — one restricted to the current site space and one for the other site spaces — rendering each result set as soon as its response arrives. All results are ranked together by score, with the current site space scores boosted.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Keep the "On this page" and "Ask" buttons pinned below the header while scrolling on desktop API reference pages, so the page outline stays reachable throughout long operations.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Hide unfocusable unlabelled button from screen readers
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Only show the "Back to [space]" shortcut for cross-space links in the table of contents, not for in-content text links or other ways of reaching another space.
-5
View File
@@ -1,5 +0,0 @@
---
"@gitbook/react-openapi": patch
---
Handle circular oneOf with discriminator and allOf in OpenAPI schemas
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
a11y screen reader fixes
+6
View File
@@ -0,0 +1,6 @@
---
"@gitbook/react-contentkit": patch
"gitbook": patch
---
Let integration block webframes navigate the reader to another page in the site by posting a `@webframe.navigate` action with a `path` (and optional `anchor`). Resolved client-side against the site base path, so navigation stays in-site and drives the standard navigation progress bar.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix an issue where certain keywords could cause an exception when rendering emojis
@@ -55,8 +55,10 @@ runs:
GITBOOK_OAUTH_SERVER_URL: ${{ inputs.opItem }}/GITBOOK_OAUTH_SERVER_URL
GITBOOK_PREVIEW_BASE_URL: ${{ inputs.opItem }}/GITBOOK_PREVIEW_BASE_URL
GITBOOK_INTEGRATIONS_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_HOST
GITBOOK_INTEGRATIONS_CONTENT_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_CONTENT_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_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL_2
GITBOOK_IMAGE_RESIZE_SALT: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SALT
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
@@ -65,6 +67,7 @@ runs:
env:
GITBOOK_RUNTIME: cloudflare
GITBOOK_BLOCK_SEARCH_INDEXATION: ${{ inputs.environment == 'preview' && 'true' || '' }}
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: ${{ inputs.environment == 'preview' && 'true' || '' }}
shell: bash
- name: Upload the DO worker
+4 -1
View File
@@ -57,8 +57,10 @@ runs:
GITBOOK_OAUTH_SERVER_URL: ${{ inputs.opItem }}/GITBOOK_OAUTH_SERVER_URL
GITBOOK_PREVIEW_BASE_URL: ${{ inputs.opItem }}/GITBOOK_PREVIEW_BASE_URL
GITBOOK_INTEGRATIONS_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_HOST
GITBOOK_INTEGRATIONS_CONTENT_HOST: ${{ inputs.opItem }}/GITBOOK_INTEGRATIONS_CONTENT_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_URL: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_URL_2
GITBOOK_IMAGE_RESIZE_SALT: ${{ inputs.opItem }}/GITBOOK_IMAGE_RESIZE_SALT
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
@@ -71,6 +73,7 @@ runs:
echo "GITBOOK_HEAD_SHA=$HEAD_SHA" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_RUNTIME=vercel" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_BLOCK_SEARCH_INDEXATION=true" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE=true" >> .vercel/.env.${{ inputs.environment }}.local
echo "--- .vercel/.env.${{ inputs.environment }}.local after inject ---"
cat .vercel/.env.${{ inputs.environment }}.local
- name: Build Project Artifacts
+2 -2
View File
@@ -168,7 +168,7 @@ jobs:
name: Visual Testing Customers v2
needs: deploy-v2-vercel
if: ${{ always() && needs.deploy-v2-vercel.result == 'success' }}
timeout-minutes: 15
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -192,7 +192,7 @@ jobs:
name: Visual Testing Customers v2 (Cloudflare)
needs: deploy-v2-cloudflare
if: ${{ always() && needs.deploy-v2-cloudflare.result == 'success' }}
timeout-minutes: 15
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v4
+4
View File
@@ -75,3 +75,7 @@ Save as `.changeset/<name>.md`, then commit it separately with message: `changes
## Formatting
Uses Biome (not ESLint/Prettier). Always run `bun run format` before committing.
## Comments
Comment to explain *why*, not *what* — the code already shows what it does. Keep comments short, ideally a single line. Avoid multi-line block comments that narrate mechanics a reader can follow from the code; they add noise and go stale. Reserve longer comments for genuinely non-obvious rationale: a subtle invariant, or a workaround and the reason it exists.
+4
View File
@@ -1,3 +1,7 @@
<p align="center">
<img src="./assets/gitbook_icon_dark.svg" alt="GitBook" width="48" />
</p>
<h1 align="center">GitBook</h1>
<p align="center">
+3
View File
@@ -0,0 +1,3 @@
<svg width="65" height="65" viewBox="0 0 65 65" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M27.3963 34.2195C30.5255 36.0255 32.09 36.9285 33.8082 36.93C35.5265 36.9315 37.0926 36.0313 40.2249 34.2308L60.1913 22.7534C61.0927 22.2353 61.6484 21.2749 61.6484 20.2352C61.6484 19.1955 61.0927 18.2351 60.1913 17.717L40.2177 6.23554C37.0888 4.43695 35.5243 3.53766 33.8078 3.53833C32.0912 3.539 30.5275 4.43951 27.4 6.24053L10.2292 16.1286C10.102 16.2019 10.0383 16.2385 9.97905 16.2732C4.11368 19.7068 0.489862 25.9754 0.441408 32.7717C0.440918 32.8404 0.440918 32.9138 0.440918 33.0607C0.440918 33.2074 0.440918 33.2807 0.441407 33.3494C0.489754 40.138 4.10549 46.4008 9.96041 49.837C10.0196 49.8718 10.0831 49.9085 10.2101 49.9818L20.9658 56.1918C27.2331 59.8104 30.3668 61.6197 33.808 61.6208C37.2493 61.622 40.3842 59.8148 46.6539 56.2005L58.008 49.6551C61.1474 47.8454 62.7171 46.9405 63.579 45.4487C64.4409 43.957 64.4409 42.1451 64.4409 38.5215V31.5212C64.4409 30.5159 63.8965 29.5895 63.0182 29.1004C62.1683 28.627 61.1325 28.6341 60.2891 29.1189L37.0074 42.5019C35.4453 43.3998 34.6643 43.8487 33.8072 43.849C32.9501 43.8493 32.1688 43.4008 30.6062 42.5038L14.8487 33.4586C14.0593 33.0055 13.6647 32.7789 13.3477 32.738C12.625 32.6448 11.9301 33.0497 11.6548 33.7244C11.534 34.0203 11.5365 34.4753 11.5414 35.3855C11.545 36.0555 11.5468 36.3905 11.6094 36.6987C11.7496 37.3887 12.1127 38.0136 12.6428 38.4771C12.8795 38.6842 13.1696 38.8516 13.7499 39.1866L30.5974 48.9103C32.164 49.8145 32.9473 50.2666 33.8075 50.2668C34.6677 50.267 35.4512 49.8154 37.0184 48.912L57.6684 37.0085C58.2037 36.7 58.4713 36.5457 58.672 36.6616C58.8727 36.7776 58.8727 37.0865 58.8727 37.7044V40.8796C58.8727 41.7855 58.8727 42.2385 58.6572 42.6114C58.4417 42.9844 58.0493 43.2106 57.2644 43.663L40.2322 53.4811C37.0966 55.2885 35.5288 56.1923 33.8078 56.1915C32.0869 56.1907 30.5199 55.2855 27.386 53.4752L11.4509 44.2701C11.4003 44.2409 11.375 44.2262 11.3514 44.2125C8.0102 42.26 5.94856 38.6882 5.92922 34.8185C5.92909 34.7911 5.92909 34.7619 5.92909 34.7035V31.7889C5.92909 29.6526 7.06686 27.678 8.9151 26.6067C10.5483 25.66 12.5628 25.6582 14.1977 26.6018L27.3963 34.2195Z" fill="#181C1F"/>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

+96 -30
View File
@@ -7,7 +7,7 @@
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@changesets/cli": "^2.31.0",
"turbo": "^2.9.18",
"turbo": "^2.10.3",
"vercel": "50.37.3",
},
},
@@ -74,14 +74,14 @@
},
"packages/expr": {
"name": "@gitbook/expr",
"version": "1.3.0",
"version": "1.3.1",
"dependencies": {
"acorn": "^8.15.0",
"acorn-loose": "^8.5.2",
"acorn-walk": "^8.3.4",
"assert-never": "catalog:",
"escodegen": "^2.1.0",
"eval-estree-expression": "github:jonschlinkert/eval-estree-expression#fb0246a",
"eval-estree-expression": "^3.0.1",
},
"devDependencies": {
"@tsconfig/node20": "catalog:",
@@ -109,7 +109,7 @@
},
"packages/gitbook": {
"name": "gitbook",
"version": "0.27.0",
"version": "0.27.2",
"dependencies": {
"@cloudflare/workers-types": "^4.20251011.0",
"@gitbook/api": "catalog:",
@@ -201,8 +201,8 @@
"zustand": "^5.0.3",
},
"devDependencies": {
"@argos-ci/playwright": "^6.4.2",
"@playwright/test": "^1.58.2",
"@argos-ci/playwright": "^7.2.0",
"@playwright/test": "^1.61.1",
"@scalar/api-client-react": "catalog:",
"@tailwindcss/postcss": "^4.1.11",
"@types/js-cookie": "^3.0.6",
@@ -253,7 +253,7 @@
},
"packages/openapi-parser": {
"name": "@gitbook/openapi-parser",
"version": "3.0.11",
"version": "3.0.12",
"dependencies": {
"@scalar/json-magic": "^0.9.4",
"@scalar/openapi-parser": "^0.24.5",
@@ -312,7 +312,7 @@
},
"packages/react-openapi": {
"name": "@gitbook/react-openapi",
"version": "1.5.13",
"version": "1.5.15",
"dependencies": {
"@gitbook/expr": "workspace:*",
"@gitbook/openapi-parser": "workspace:*",
@@ -360,7 +360,7 @@
"react-dom": "catalog:",
},
"catalog": {
"@gitbook/api": "0.183.1",
"@gitbook/api": "0.189.0",
"@scalar/api-client-react": "^1.3.46",
"@tsconfig/node20": "^20.1.6",
"@tsconfig/strictest": "^2.0.6",
@@ -392,15 +392,15 @@
"@antfu/install-pkg": ["@antfu/install-pkg@1.1.0", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="],
"@argos-ci/api-client": ["@argos-ci/api-client@0.16.0", "", { "dependencies": { "debug": "^4.4.3", "openapi-fetch": "^0.15.0" } }, "sha512-BG6g+AZABKN8W2syzfPWKhPxxrAB9Wjp2iNS11R4IskHDV6T41+qeQDpT88GOq6eUZ64Sjzoh/nXG+9EpNxtfw=="],
"@argos-ci/api-client": ["@argos-ci/api-client@0.24.0", "", { "dependencies": { "debug": "^4.4.3", "openapi-fetch": "^0.17.0", "p-retry": "^8.0.0" } }, "sha512-pWEkmqVyD2CbGGG9KsTQgufWIYRzMsZVWyLY4d3lI2pUbuTlv0W0pvvmJybmKkIk3Tcn1T5vMBjT2DYuUiZbqQ=="],
"@argos-ci/browser": ["@argos-ci/browser@5.1.2", "", {}, "sha512-eQqtM54Vh83++Dac5+7ml4YXKW/KnUHRQWjTZ+VGeXfOJdjnZa4JjfVL6fnFG6CKrXjCK5dd9gcZRmbVpbt8rA=="],
"@argos-ci/browser": ["@argos-ci/browser@6.3.0", "", {}, "sha512-quTww/Yhm2jv+Y6q6dD4xEpm9Bb/SrZNFJaXgncAnCvW8jNnCrmDE2+8zAuGUh41Wkq1JQNDYKlBCO/RpY6A8Q=="],
"@argos-ci/core": ["@argos-ci/core@5.1.1", "", { "dependencies": { "@argos-ci/api-client": "0.16.0", "@argos-ci/util": "3.2.0", "convict": "^6.2.4", "debug": "^4.4.3", "fast-glob": "^3.3.3", "mime-types": "^3.0.2", "sharp": "^0.34.5", "tmp": "^0.2.5" } }, "sha512-RI5pYb5wmWUoXzWefNCjKSqGA3BroUB2ac9awlYV3McJjSAW8nCGJUt2Eds90Shkp+i4S6KbMLnLG56slhTCsg=="],
"@argos-ci/core": ["@argos-ci/core@6.4.0", "", { "dependencies": { "@argos-ci/api-client": "0.24.0", "@argos-ci/util": "4.0.0", "convict": "^6.2.5", "debug": "^4.4.3", "fast-glob": "^3.3.3", "mime-types": "^3.0.2", "p-retry": "^8.0.0", "sharp": "^0.35.2", "tmp": "^0.2.7" } }, "sha512-YUySBUbjHpI8GZKe96n4VzgPPXl90hjw/GCHLQ3U6xbbIEZczCBCHeHB/MDjyXCHyk+9T7FUJSE0ddWnpDRI8Q=="],
"@argos-ci/playwright": ["@argos-ci/playwright@6.4.2", "", { "dependencies": { "@argos-ci/browser": "5.1.2", "@argos-ci/core": "5.1.1", "@argos-ci/util": "3.2.0", "chalk": "^5.6.2", "debug": "^4.4.3" } }, "sha512-0HE4rmgx2/znlMUi3z0Bp8OD7u7zNls9SlljL+qTVoWQRW22sDvpmRdZpjzb4pEjoe6onqPTDOqm5/f8QYHMwg=="],
"@argos-ci/playwright": ["@argos-ci/playwright@7.2.0", "", { "dependencies": { "@argos-ci/browser": "6.3.0", "@argos-ci/core": "6.4.0", "@argos-ci/util": "4.0.0", "chalk": "^5.6.2", "debug": "^4.4.3" } }, "sha512-YkZswuc+hZLC8sUUp6QPzZJSfZsxnbt+sfyZr5DWSHuz5g2XRxJ8oEsXJwFraDMYku5jwfAtqXvza1J3WUo6qA=="],
"@argos-ci/util": ["@argos-ci/util@3.2.0", "", {}, "sha512-/Bn0qCH8VsdPv5WB9TUEf3oTgsIqsTMUEjPVDopHLzKK+j7nQYGOF3MnN7VhBow82BXeStBfJCS3UiZ6cgxRlw=="],
"@argos-ci/util": ["@argos-ci/util@4.0.0", "", {}, "sha512-2yrJr81OVpa2TkvSjzGZlGv6SVqZcxF62AVk6M79aZ7nXkwWFg3tjA8awbFwn2mODI67gkP5FarAD29bzx3P3w=="],
"@ast-grep/napi": ["@ast-grep/napi@0.40.5", "", { "optionalDependencies": { "@ast-grep/napi-darwin-arm64": "0.40.5", "@ast-grep/napi-darwin-x64": "0.40.5", "@ast-grep/napi-linux-arm64-gnu": "0.40.5", "@ast-grep/napi-linux-arm64-musl": "0.40.5", "@ast-grep/napi-linux-x64-gnu": "0.40.5", "@ast-grep/napi-linux-x64-musl": "0.40.5", "@ast-grep/napi-win32-arm64-msvc": "0.40.5", "@ast-grep/napi-win32-ia32-msvc": "0.40.5", "@ast-grep/napi-win32-x64-msvc": "0.40.5" } }, "sha512-hJA62OeBKUQT68DD2gDyhOqJxZxycqg8wLxbqjgqSzYttCMSDL9tiAQ9abgekBYNHudbJosm9sWOEbmCDfpX2A=="],
@@ -756,7 +756,7 @@
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
"@gitbook/api": ["@gitbook/api@0.183.1", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-l9Bse8mLXG9rUR+jTiD/xZYMQ21t4XrxQvvaa7skaibIyBjjnIsNGo7NhVmjESUKHrA6F40ouH36Oiv2DfH+Wg=="],
"@gitbook/api": ["@gitbook/api@0.189.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-QezuW8dMScSTJ+2IL/GGixkhGEsMRFRoO/W2r80pKRjoWyI9Ebai9oZsoN/pbRZz3cTnwa7hpRDtzaqHeeOAdQ=="],
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
@@ -812,6 +812,8 @@
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],
"@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "os": "freebsd" }, "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg=="],
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.2.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="],
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.2.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="],
@@ -850,6 +852,8 @@
"@img/sharp-wasm32": ["@img/sharp-wasm32@0.34.5", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="],
"@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "cpu": "none" }, "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q=="],
"@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.34.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="],
"@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.34.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="],
@@ -1026,7 +1030,7 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@playwright/test": ["@playwright/test@1.58.2", "", { "dependencies": { "playwright": "1.58.2" }, "bin": { "playwright": "cli.js" } }, "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA=="],
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@poppinss/colors": ["@poppinss/colors@4.1.5", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-FvdDqtcRCtz6hThExcFOgW0cWX+xwSMWcRuQe5ZEb2m7cVQOAVZOIMt+/v9RxGiD9/OY16qJBXK4CVKWAPalBw=="],
@@ -1590,17 +1594,17 @@
"@tsconfig/strictest": ["@tsconfig/strictest@2.0.6", "", {}, "sha512-tPOhmDhIUcDjvpDDYyiUdssP84Eqm7n5KxJe5J3/g+s6xoDIPAf+SIn06dhw7VkhxIvLOnhDDrX7tsqMHNEhDg=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.9.18", "", { "os": "darwin", "cpu": "x64" }, "sha512-9f27peFu16ur8c0v9nUFUEyBnbKuuFsUTjHFWfmwGfzySBXbHwzU44QhZon6Mznz0cHsIr3984NQj/bVrnGSRw=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.10.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-guuiO2kKc7yUQFU2jhWyM/BrYGD/brqb0+JvJIXTQ/QI1NlWfHZ1id50kkkOWqxmBiDc8DgW2orfY85pQIc7gw=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.9.18", "", { "os": "darwin", "cpu": "arm64" }, "sha512-9A6TMRq/Ib+QnbhLlgkhOm+624wO4pzSQ/yQviQfWHOlFvaYxdnIAYmu2H6TS6y7kSVL0DvzNe04NbESTOzFVQ=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.10.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UglEDl/r1/h5Vw6oS6cEE29Jugz2sDLxHCSupNznKatj1fDMRXFqYKFcbvm8RTFhtYPI45NxkrPNo9BqNychBg=="],
"@turbo/linux-64": ["@turbo/linux-64@2.9.18", "", { "os": "linux", "cpu": "x64" }, "sha512-zCdIDtz69AnbYh913elJRRoF3QY5aa2HNnf+4rAkc7bQ+tWujiDkCNV7stazOUPggaDvhKIf2Z87qHftTeXSkw=="],
"@turbo/linux-64": ["@turbo/linux-64@2.10.3", "", { "os": "linux", "cpu": "x64" }, "sha512-KuQxaPWD7OBmwEZqO0sgijwcuXR5eMWbo7BEt2m1D2Q3RylJDj7WMcJ0Btv2VJA0QC+khzAaTAm1yWowJ0CWAw=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.9.18", "", { "os": "linux", "cpu": "arm64" }, "sha512-Va1kXI04naMgYwqv/5Dfa36dTDx8015U7oaQAjrXa45ua9OoFjSV4OmvkML4EmXvUclQHCiBRbY8bvd0jV7eAg=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.10.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-DPkIKQ+6p0sho3Cx/e/A3F+AKgXQJA+z//cHsTcyyM1YWRGSYA0UTP8NUpb4iS2tVBSniGwmjRUr73hpq8kcDg=="],
"@turbo/windows-64": ["@turbo/windows-64@2.9.18", "", { "os": "win32", "cpu": "x64" }, "sha512-m0kDhZANxSNz9ck1ybogFscHabriAsp4eDFNrN/1H5WrgTF7b3VlcPZnhuO3v2+E2KnCbeAc+UUT10BZZHdDKw=="],
"@turbo/windows-64": ["@turbo/windows-64@2.10.3", "", { "os": "win32", "cpu": "x64" }, "sha512-8NvFAze9D4PsosZAnK3aGqHz2vLzREz9lNIxLgfE0jRchq2sZQE190cwFm7WX17yg3ftPvwCvWH3rhLbG1UHCQ=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.9.18", "", { "os": "win32", "cpu": "arm64" }, "sha512-nUdR8WqoomUys9iIQmG45TMiizJ+5BV8egSeLLZba/AWblyp3fVBcIH1kSE58OtK4g2YzbMJEth6Ttv9w5rqMA=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.10.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-AqjqV5cHbFa0YRaQ+Dyw6lSm6as4h/Uf8LcZ7VN8i+Odr23ShFD5SUvVAR1d3rZqibFVs9c0VdtXdfQfkdcs3A=="],
"@tusbar/cache-control": ["@tusbar/cache-control@1.0.2", "", {}, "sha512-PXfjYTYBVvMPYCLDWj+xIOA9ITFbbhWCHzLcqUCJ5TPGm4JO4cxpGb7x3K8Q1K1ADgNgfBxLsDcTMVRydtZB9A=="],
@@ -2024,7 +2028,7 @@
"convert-hrtime": ["convert-hrtime@3.0.0", "", {}, "sha512-7V+KqSvMiHp8yWDuwfww06XleMWVVB9b9tURBx+G7UTADuo5hYPuowKloz4OzOqbPezxgo+fdQ1522WzPG4OeA=="],
"convict": ["convict@6.2.4", "", { "dependencies": { "lodash.clonedeep": "^4.5.0", "yargs-parser": "^20.2.7" } }, "sha512-qN60BAwdMVdofckX7AlohVJ2x9UvjTNoKVXCL2LxFk1l7757EJqf1nySdMkPQer0bt8kQ5lQiyZ9/2NvrFBuwQ=="],
"convict": ["convict@6.2.5", "", { "dependencies": { "lodash.clonedeep": "^4.5.0", "yargs-parser": "^20.2.7" } }, "sha512-JtXpxqDqJ8P0UwEHwhxLzCIXQy97vlYBZR222Sbzb1q1Erex9ASrztJ29SyhWFQjod1AeFBaPzEEC8YvtZMIYg=="],
"cookie": ["cookie@1.0.2", "", {}, "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA=="],
@@ -2270,7 +2274,7 @@
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eval-estree-expression": ["eval-estree-expression@github:jonschlinkert/eval-estree-expression#fb0246a", {}, "jonschlinkert-eval-estree-expression-fb0246a"],
"eval-estree-expression": ["eval-estree-expression@3.0.1", "", {}, "sha512-zTLKGbiVdQYp4rQkSoXPibrFf5ZoPn6jzExegRLEQ13F+FSxu5iLgaRH6hlDs2kWSUa6vp8yD20cdJi0me6pEw=="],
"event-emitter": ["event-emitter@0.3.5", "", { "dependencies": { "d": "1", "es5-ext": "~0.10.14" } }, "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA=="],
@@ -2908,11 +2912,11 @@
"oniguruma-to-es": ["oniguruma-to-es@4.3.4", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.0.1", "regex-recursion": "^6.0.2" } }, "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA=="],
"openapi-fetch": ["openapi-fetch@0.15.2", "", { "dependencies": { "openapi-typescript-helpers": "^0.0.15" } }, "sha512-rdYTzUmSsJevmNqg7fwUVGuKc2Gfb9h6ph74EVPkPfIGJaZTfqdIbJahtbJ3qg1LKinln30hqZniLnKpH0RJBg=="],
"openapi-fetch": ["openapi-fetch@0.17.0", "", { "dependencies": { "openapi-typescript-helpers": "^0.1.0" } }, "sha512-PsbZR1wAPcG91eEthKhN+Zn92FMHxv+/faECIwjXdxfTODGSGegYv0sc1Olz+HYPvKOuoXfp+0pA2XVt2cI0Ig=="],
"openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
"openapi-typescript-helpers": ["openapi-typescript-helpers@0.0.15", "", {}, "sha512-opyTPaunsklCBpTK8JGef6mfPhLSnyy5a0IN9vKtx3+4aExf+KxEqYwIy3hqkedXIB97u357uLMJsOnm3GVjsw=="],
"openapi-typescript-helpers": ["openapi-typescript-helpers@0.1.0", "", {}, "sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw=="],
"os-paths": ["os-paths@4.4.0", "", {}, "sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg=="],
@@ -3322,7 +3326,7 @@
"tldts-core": ["tldts-core@7.0.30", "", {}, "sha512-uiHN8PIB1VmWyS98eZYja4xzlYqeFZVjb4OuYlJQnZAuJhMw4PbKQOKgHKhBdJR3FE/t5mUQ1Kd80++B+qhD1Q=="],
"tmp": ["tmp@0.2.5", "", {}, "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow=="],
"tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
"to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
@@ -3356,7 +3360,7 @@
"tsx": ["tsx@4.21.0", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"turbo": ["turbo@2.9.18", "", { "optionalDependencies": { "@turbo/darwin-64": "2.9.18", "@turbo/darwin-arm64": "2.9.18", "@turbo/linux-64": "2.9.18", "@turbo/linux-arm64": "2.9.18", "@turbo/windows-64": "2.9.18", "@turbo/windows-arm64": "2.9.18" }, "bin": { "turbo": "bin/turbo" } }, "sha512-bwabv6PupzeavybzEoArBAkwq5fnzwf8OFnRtpHwnviFWuwJPFxtyH+aVp36TmIqK3aYYgtTJ3J0m2ysxxSzQg=="],
"turbo": ["turbo@2.10.3", "", { "optionalDependencies": { "@turbo/darwin-64": "2.10.3", "@turbo/darwin-arm64": "2.10.3", "@turbo/linux-64": "2.10.3", "@turbo/linux-arm64": "2.10.3", "@turbo/windows-64": "2.10.3", "@turbo/windows-arm64": "2.10.3" }, "bin": { "turbo": "bin/turbo" } }, "sha512-uZIqzfgtWbyqu1Tqwdd0giRnPGgL0ejbcdF8eZLJhtTTVSrOgArZGzYeXTD6XNcc7ANgdhqex11Y9bHBeyiQLQ=="],
"type": ["type@2.7.3", "", {}, "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ=="],
@@ -3538,6 +3542,8 @@
"@argos-ci/core/mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"@argos-ci/core/sharp": ["sharp@0.35.3", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.3", "@img/sharp-darwin-x64": "0.35.3", "@img/sharp-freebsd-wasm32": "0.35.3", "@img/sharp-libvips-darwin-arm64": "1.3.2", "@img/sharp-libvips-darwin-x64": "1.3.2", "@img/sharp-libvips-linux-arm": "1.3.2", "@img/sharp-libvips-linux-arm64": "1.3.2", "@img/sharp-libvips-linux-ppc64": "1.3.2", "@img/sharp-libvips-linux-riscv64": "1.3.2", "@img/sharp-libvips-linux-s390x": "1.3.2", "@img/sharp-libvips-linux-x64": "1.3.2", "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", "@img/sharp-libvips-linuxmusl-x64": "1.3.2", "@img/sharp-linux-arm": "0.35.3", "@img/sharp-linux-arm64": "0.35.3", "@img/sharp-linux-ppc64": "0.35.3", "@img/sharp-linux-riscv64": "0.35.3", "@img/sharp-linux-s390x": "0.35.3", "@img/sharp-linux-x64": "0.35.3", "@img/sharp-linuxmusl-arm64": "0.35.3", "@img/sharp-linuxmusl-x64": "0.35.3", "@img/sharp-webcontainers-wasm32": "0.35.3", "@img/sharp-win32-arm64": "0.35.3", "@img/sharp-win32-ia32": "0.35.3", "@img/sharp-win32-x64": "0.35.3" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q=="],
"@aws-crypto/crc32/@aws-sdk/types": ["@aws-sdk/types@3.734.0", "", { "dependencies": { "@smithy/types": "^4.1.0", "tslib": "^2.6.2" } }, "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg=="],
"@aws-crypto/crc32c/@aws-sdk/types": ["@aws-sdk/types@3.734.0", "", { "dependencies": { "@smithy/types": "^4.1.0", "tslib": "^2.6.2" } }, "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg=="],
@@ -3630,6 +3636,10 @@
"@hyperjump/json-schema/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
"@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.3", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w=="],
"@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.3", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w=="],
"@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"@isaacs/cliui/strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="],
@@ -3682,7 +3692,7 @@
"@oxc-transform/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.1", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
"@playwright/test/playwright": ["playwright@1.58.2", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
"@playwright/test/playwright": ["playwright@1.61.1", "", { "dependencies": { "playwright-core": "1.61.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ=="],
"@poppinss/dumper/supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
@@ -4288,6 +4298,58 @@
"@argos-ci/core/mime-types/mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"@argos-ci/core/sharp/@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
"@argos-ci/core/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.2" }, "os": "darwin", "cpu": "arm64" }, "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg=="],
"@argos-ci/core/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.2" }, "os": "darwin", "cpu": "x64" }, "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w=="],
"@argos-ci/core/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg=="],
"@argos-ci/core/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.2", "", { "os": "linux", "cpu": "arm" }, "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.2", "", { "os": "linux", "cpu": "none" }, "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw=="],
"@argos-ci/core/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ=="],
"@argos-ci/core/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.2" }, "os": "linux", "cpu": "arm" }, "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA=="],
"@argos-ci/core/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ=="],
"@argos-ci/core/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.2" }, "os": "linux", "cpu": "ppc64" }, "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA=="],
"@argos-ci/core/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.2" }, "os": "linux", "cpu": "none" }, "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ=="],
"@argos-ci/core/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.2" }, "os": "linux", "cpu": "s390x" }, "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw=="],
"@argos-ci/core/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA=="],
"@argos-ci/core/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w=="],
"@argos-ci/core/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg=="],
"@argos-ci/core/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w=="],
"@argos-ci/core/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw=="],
"@argos-ci/core/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.3", "", { "os": "win32", "cpu": "x64" }, "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA=="],
"@argos-ci/core/sharp/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"@argos-ci/core/sharp/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"@aws-crypto/crc32/@aws-sdk/types/@smithy/types": ["@smithy/types@4.1.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw=="],
"@aws-crypto/crc32c/@aws-sdk/types/@smithy/types": ["@smithy/types@4.1.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw=="],
@@ -4332,6 +4394,10 @@
"@headlessui/react/@floating-ui/react/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.7", "", { "dependencies": { "@floating-ui/dom": "^1.7.5" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-0tLRojf/1Go2JgEVm+3Frg9A3IW8bJgKgdO0BN5RkF//ufuz2joZM63Npau2ff3J6lUVYgDSNzNkR+aH3IVfjg=="],
"@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="],
"@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="],
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="],
@@ -4370,7 +4436,7 @@
"@playwright/test/playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"@playwright/test/playwright/playwright-core": ["playwright-core@1.58.2", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
"@playwright/test/playwright/playwright-core": ["playwright-core@1.61.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg=="],
"@radix-ui/react-arrow/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
+2 -2
View File
@@ -7,7 +7,7 @@
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@changesets/cli": "^2.31.0",
"turbo": "^2.9.18",
"turbo": "^2.10.3",
"vercel": "50.37.3"
},
"packageManager": "bun@1.3.7",
@@ -43,7 +43,7 @@
"catalog": {
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@gitbook/api": "0.183.1",
"@gitbook/api": "0.189.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+1
View File
@@ -17,6 +17,7 @@
"scripts": {
"build": "tsdown",
"typecheck": "tsc --noEmit",
"unit": "bun test",
"dev": "bun run build -- --watch ./src",
"publish-to-npm": "../../scripts/publish-if-new.sh"
},
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'bun:test';
import { colorScale } from './transformations';
describe('colorScale exact base', () => {
it('takes a very light tint as the exact background on step 1 (clean/bold)', () => {
const scale = colorScale('#F5F3EF', { baseStep: 1 });
expect(scale[0]).toBe('#F5F3EF');
});
it('anchors a very light tint to step 2 when the theme uses the subtle step (muted)', () => {
const scale = colorScale('#F5F3EF', { baseStep: 2 });
expect(scale[1]).toBe('#F5F3EF');
// Step 1 sits just above the exact base, toward white.
expect(scale[0]).not.toBe('#F5F3EF');
expect(scale[0]).not.toBe('#ffffff');
});
it('takes a darker-than-dark tint as the exact background, preserving hue and chroma', () => {
const scale = colorScale('#0B0F19', { darkMode: true, baseStep: 1 });
expect(scale[0]).toBe('#0B0F19');
});
it('does not trigger for a normal mid-lightness tint', () => {
const scale = colorScale('#787878', { baseStep: 2 });
// The default white background is kept; the tint only colors the scale.
expect(scale[0]).toBe('#ffffff');
expect(scale[1]).not.toBe('#787878');
});
it('does not trigger for a saturated light color, keeping the normal accent ramp', () => {
// Light enough (L≈0.93) to pass the lightness bound, but too chromatic to read as a
// background — emitting it verbatim would leave a vivid step 1 above a near-gray scale.
const scale = colorScale('#FFEB3B', { baseStep: 1 });
expect(scale[0]).toBe('#ffffff');
expect(scale[0]).not.toBe('#FFEB3B');
});
it('respects a custom light background instead of overriding it with the tint', () => {
// The color is darker than the requested background, so it is not the extreme end and the
// supplied base must be preserved rather than overwritten.
const scale = colorScale('#eeeeee', { baseStep: 1, background: '#f8f8f8' });
expect(scale[0]).not.toBe('#eeeeee');
});
it('anchors an exact base even when a neutral mix is supplied (tint === primary)', () => {
// getTintMixColor blends neutral into the tint when it equals the primary color; that must
// not darken a near-white tint out of the exact-base path.
const scale = colorScale('#F5F3EF', {
baseStep: 1,
mix: { color: '#787878', ratio: 0.4 },
});
expect(scale[0]).toBe('#F5F3EF');
});
it('does not trigger for a light accent color below the near-white threshold', () => {
// #D8DEEC (light blue-gray, L≈0.90) is a UI accent, not a background, so it must not anchor.
const scale = colorScale('#D8DEEC', { baseStep: 1 });
expect(scale[0]).toBe('#ffffff');
expect(scale[0]).not.toBe('#D8DEEC');
});
it('never anchors when no baseStep is given (accent scales and the bold theme)', () => {
// A scale that does not define the page background opts out of the exact base entirely.
const scale = colorScale('#F5F3EF', {});
expect(scale[0]).toBe('#ffffff');
expect(scale[0]).not.toBe('#F5F3EF');
});
});
+58 -10
View File
@@ -82,6 +82,22 @@ export const colorMixMapping = {
dark: [0, 0.03, 0.08, 0.1, 0.13, 0.15, 0.2, 0.25, 0.5, 0.55, 0.75, 1],
};
/**
* Light mode has no equivalent to the dark base bound (nothing is lighter than white), so a tint
* at or above this lightness is treated as an explicit, near-white background (e.g. a warm `#F5F3EF`
* at L≈0.96). Kept high so light UI accent colors (around L≈0.90) aren't mistaken for backgrounds.
*/
const EXACT_BASE_LIGHT_THRESHOLD = 0.95;
/**
* Only a near-neutral tint reads as a background. A saturated color would keep the exact hue at the
* anchored step while the rest of the low scale stays ~gray, so those keep the normal accent ramp.
*/
const EXACT_BASE_NEUTRAL_CHROMA = 0.05;
/** Lightness of the default white light background (≈0.99999, not exactly 1). */
const LIGHT_BASE_L = rgbToOklch(hexToRgbArray(LIGHT_BASE)).L;
/**
* Convert a hex color to an RGB color.
*/
@@ -159,6 +175,14 @@ export type ColorScaleOptions = {
/** Define a custom foreground color to use. If left undefined, the global `light`/`dark` values (in `colors.ts`) will be used. */
foreground?: string;
/**
* The 1-indexed scale step this scale renders as the page background (1 = `tint-base` for
* `clean`, 2 = `tint-subtle` for `muted`). When set, an extreme near-neutral tint is taken as
* the exact background, anchored to this step so it matches exactly. Omit for scales that don't
* define the page background (accents, or the two-tone `bold` theme) — they never anchor.
*/
baseStep?: number;
mix?: {
/** If set to a hex code, this color will be additionally mixed into the generated scale according to `mix.ratio`. */
color: string;
@@ -179,6 +203,7 @@ export function colorScale(
darkMode = false,
background = darkMode ? DARK_BASE : LIGHT_BASE,
foreground = darkMode ? LIGHT_BASE : DARK_BASE,
baseStep,
mix,
}: ColorScaleOptions = {}
) {
@@ -188,31 +213,51 @@ export function colorScale(
const backgroundColor = rgbToOklch(hexToRgbArray(background));
let mapping = darkMode ? colorMixMapping.dark : colorMixMapping.light;
if (mixColor && mix?.ratio && mix.ratio > 0) {
// If defined, we mix in a (tiny) bit of the mix color with the base color.
// A near-neutral tint at the extreme end of the scale is taken as the exact page background
// rather than tinting pure black/white with it — letting brands set an exact background such as
// a warm `#F5F3EF`. Only scales that define the page background opt in (via `baseStep`). In light
// mode the base is pure white by default, so a near-white tint also qualifies (nothing is lighter
// than white); a custom, lower background is respected instead. Decided on the raw color so a
// neutral mix (below) can't darken a tint out of the exact base.
const isExtremeBase = darkMode
? baseColor.L < backgroundColor.L
: backgroundColor.L >= LIGHT_BASE_L
? baseColor.L > EXACT_BASE_LIGHT_THRESHOLD
: baseColor.L > backgroundColor.L;
const isExactBase =
baseStep !== undefined && isExtremeBase && baseColor.C < EXACT_BASE_NEUTRAL_CHROMA;
const exactBaseIndex = (baseStep ?? 1) - 1;
if (mixColor && mix?.ratio && mix.ratio > 0 && !isExactBase) {
// Mix a little of the mix color into the base — but not when the tint is the exact base,
// where it must stay true to the supplied color (and match `--header-background`).
baseColor.L = mixColor.L * mix.ratio + baseColor.L * (1 - mix.ratio);
baseColor.C = mixColor.C * mix.ratio + baseColor.C * (1 - mix.ratio);
baseColor.H = mix.color === DEFAULT_TINT_COLOR ? baseColor.H : mixColor.H;
}
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.
if (isExactBase) {
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
);
// Anchor the supplied color to the step the theme renders as the background, solving the
// background lightness so neighbouring steps stay continuous with it.
const baseMix = mapping[exactBaseIndex]!;
backgroundColor.L = (baseColor.L - foregroundColor.L * baseMix) / (1 - baseMix);
}
const result = [];
for (let index = 0; index < mapping.length; index++) {
if (isExactBase && index === exactBaseIndex) {
result.push(hex);
continue;
}
const step = mapping[index]!;
const targetL = foregroundColor.L * step + backgroundColor.L * (1 - step);
@@ -238,7 +283,10 @@ export function colorScale(
case 11:
return 0.1;
default:
return index * 0.05;
// When the tint is the exact base, hold the steps from the base toward the
// accents at its chroma so the background stays tinted; steps lighter than the
// base (e.g. cards in `muted`) keep desaturating toward white.
return isExactBase && index >= exactBaseIndex ? 1 : index * 0.05;
}
})();
+2 -2
View File
@@ -187,7 +187,7 @@ function MyComponent() {
- `GitBook('open')` - Open widget window
- `GitBook('close')` - Close widget window
- `GitBook('toggle')` - Toggle widget window
- `GitBook('navigateToPage', path: string)` - Navigate to page
- `GitBook('navigateToPage', path: string)` - Navigate to page (accepts the page path within the site, an absolute path, or the full published URL; resolves pages in any space/section)
- `GitBook('navigateToAssistant')` - Navigate to assistant tab
- `GitBook('postUserMessage', message: string)` - Post message to chat
- `GitBook('clearChat')` - Clear chat history
@@ -202,7 +202,7 @@ function MyComponent() {
- `client.createFrame(iframe: HTMLIFrameElement)``GitBookFrameClient`
**Frame Client:**
- `frame.navigateToPage(path: string)``void`
- `frame.navigateToPage(path: string)``void` (accepts the page path within the site, an absolute path, or the full published URL; resolves pages in any space/section)
- `frame.navigateToAssistant()``void`
- `frame.postUserMessage(message: string)``void`
- `frame.clearChat()``void`
@@ -7,7 +7,12 @@ import type {
export type GitBookFrameClient = {
/**
* Navigate to a page by its path.
* Navigate to a page in the docs tab.
*
* Accepts the page's path within the site (e.g. `getting-started/quickstart`),
* an absolute path (e.g. `/help-center/integrations`), or its full published URL.
* The target page may live in any space/section of the site — including one other
* than the embed is currently showing — and is resolved to the right space.
*/
navigateToPage: (path: string) => void;
+8
View File
@@ -0,0 +1,8 @@
{
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["dist/**", "standalone/**"]
}
}
}
+6
View File
@@ -1,5 +1,11 @@
# @gitbook/expr
## 1.3.1
### Patch Changes
- 3fedaaa: Depend on `eval-estree-expression` from the npm registry (`^3.0.1`) instead of a pinned GitHub commit. The published `3.0.1` release is built from the exact commit the package was pinned to, so the code is unchanged — this only removes the fragile git/tarball dependency so consumers install it from npm like any other package.
## 1.3.0
### Minor Changes
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@gitbook/expr",
"description": "Safely evaluate & parse user-defined GitBook expressions.",
"version": "1.3.0",
"version": "1.3.1",
"type": "module",
"exports": {
".": {
@@ -16,7 +16,7 @@
"acorn-walk": "^8.3.4",
"assert-never": "catalog:",
"escodegen": "^2.1.0",
"eval-estree-expression": "github:jonschlinkert/eval-estree-expression#fb0246a"
"eval-estree-expression": "^3.0.1"
},
"devDependencies": {
"@tsconfig/strictest": "catalog:",
+48
View File
@@ -1,5 +1,53 @@
# gitbook
## 0.27.2
### Patch Changes
- bb30db1: Add a hover affordance in the document margin to ask the AI Assistant about a paragraph. On devices with a fine pointer, hovering a top-level paragraph reveals a small button that stages the paragraph's text as context and opens the assistant — making the existing text-selection "Ask" flow more discoverable.
- 62ca6d3: Show a "Back to [space]" shortcut at the top of the table of contents when a reader follows a link into a different space, so they don't lose track of where they were browsing from.
- fdea8f1: Show where a page lives in the site at the start of the page breadcrumbs: its section (including any enclosing section groups) and variant. Hovering any breadcrumb item reveals a dropdown to switch to its siblings at the same level — other section groups, sections, variants, page groups or pages — computed on the server from already-available data (no extra request). Language variants are left to the dedicated language picker rather than shown as a crumb. Also restyles the breadcrumbs to normal casing (matching search results).
- 37c2dd8: Navigate customer visual tests with `domcontentloaded` to avoid `load`-event hangs on external sites.
- c923c65: Fix center- and end-aligned paragraphs shifting left on wide/no-TOC pages when the AI Assistant is enabled, caused by the per-paragraph ask-button wrapper not inheriting the block alignment.
- 37c2dd8: Fix flaky customer e2e screenshots by waiting for the built-in cookie banner before capturing.
- 37c2dd8: Add a `data-testid` to the admin toolbar so e2e tests can assert its presence while hiding it from visual screenshots (it animates open, causing flaky diffs).
- 36dbdb4: Support an optional `goal` query parameter on the markdown ask interface (`?ask=…&goal=…`), letting agents describe the broader end goal they are working towards so the answer can be steered towards it.
- 7e55cd5: Add an "Available in MCP" badge on OpenAPI operations marked with `x-gitbook-mcp: true`. When `x-gitbook-mcp-url` is set (on the operation, path, or root — most specific wins), the badge becomes a button that copies the MCP server URL to the clipboard.
- 6146f8e: Reduce the size of `searchDocumentation` MCP responses by returning only the best-matching section per page instead of concatenating every section body.
- 37c2dd8: Disable the content max-width transition under reduced motion, matching the surrounding layout transitions.
- 37c2dd8: Reset cross-space navigation state between e2e navigations so the "Back to <space>" shortcut can't leak in and cause flaky screenshots.
- bcea23e: Render `anyOf`/`oneOf` with a `null` member as a nullable schema instead of a `null` union branch.
- 77efd44: Show changed pages in preview toolbars for change requests and revisions.
- 578a3a8: Fix site section dropdowns not being bounded by their container during the open/resize animation, causing the contents to visually clip.
- 2dc76a2: Fix grouped top-nav section dropdowns rendering empty when the site is embedded in an iframe (visitor-auth embeds, editor preview) or shown in the embeddable view. The dropdown viewport is composited and animated, and a clipped composited layer fails to rasterize its text in Chromium when painted inside a sub compositing root; the rounded-corner clipping is now done on an inner wrapper so the viewport itself is no longer clipped.
- 9f65133: Improve the 404 page: remove the table of contents sidebar and center the content, suggest related pages (ranked from the already-cached search index, so no extra request per 404), show a search or assistant input depending on the site's AI configuration, and move "Go to homepage" to the bottom as a last resort.
- Updated dependencies [3fedaaa]
- Updated dependencies [7e55cd5]
- @gitbook/expr@1.3.1
- @gitbook/openapi-parser@3.0.12
- @gitbook/react-openapi@1.5.15
## 0.27.1
### Patch Changes
- acf2719: Mark the AI Assistant chat as `aria-busy` while it is generating a response (including the follow-up suggestion phase), so assistive technologies are notified of the in-progress state.
- 72a1596: Fix the AI assistant panel overflowing its frame when rendering single/multi-choice question forms with long option text.
- 77c717c: Assistant: group all of a turn's tool calls behind a single "Explored with N tools" expandable instead of rendering a separate single-item expandable for each client-side tool call.
- c44d822: Trust an optional cookieless integration content host (`GITBOOK_INTEGRATIONS_CONTENT_HOST`) for WebFrame postMessage, in preparation for isolating integration-rendered content onto a separate origin. Defaults to `GITBOOK_INTEGRATIONS_HOST`, so behavior is unchanged until the content host is configured.
- 7655041: Match keyboard shortcuts by the logical character typed instead of the physical key position, so that ⌘-C no longer opens the Assistant on the Dvorak layout (and other non-QWERTY layouts).
- af3cda1: Fix wide content (such as code blocks and tables) overflowing the edges of hint blocks instead of scrolling within them.
- 0ca4952: Remove the external link button from the link tooltip hover card, as its arrow read as clickable even though the preview card isn't interactive.
- 3ff88ba: Add a Prompt block
- 251630c: Drive page actions ordering and default action from the new `pageActions.items` list, including the reorderable assistant action
- ddba803: Add a page reference chip when opening the Assistant from the page action, so the assistant is informed about the page the reader is currently on.
- f4469b2: Support OpenAPI one-operation-per-page mode
- 6c967c9: Add a client-side search field to table blocks, with per-column filters for select and checkbox columns
- 882dfcd: Tidy prompt and add e2e test
- Updated dependencies [f4469b2]
- Updated dependencies [88b94b5]
- @gitbook/react-openapi@1.5.14
## 0.27.0
### Minor Changes
+417 -62
View File
@@ -40,11 +40,6 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://asiksupport-stg.dto.kemkes.go.id',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'jasons-tutorials.gitbook.io',
contentBaseURL: 'https://jasons-tutorials.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'faq.deltaemulator.com',
contentBaseURL: 'https://faq.deltaemulator.com',
@@ -70,16 +65,12 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://docs.gmgn.ai',
tests: [{ name: 'Home', url: '/' }],
},
// Removed, an AI widget, makes it flaky.
// {
// name: 'docs.spicychat.ai',
// contentBaseURL: 'https://docs.spicychat.ai',
// tests: [{ name: 'Home', url: '/' }],
// name: 'docs.portainer.io',
// contentBaseURL: 'https://docs.portainer.io',
// tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
// },
{
name: 'docs.portainer.io',
contentBaseURL: 'https://docs.portainer.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.chirptoken.io',
contentBaseURL: 'https://docs.chirptoken.io',
@@ -110,27 +101,11 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://docs.midas.app',
tests: [{ name: 'Home', url: '/' }],
},
// Disabling for now, one of the image is making the tests timeout
// {
// name: 'docs.keeper.io',
// contentBaseURL: 'https://docs.keeper.io',
// tests: [{ name: 'Home', url: '/en', run: waitForCookiesDialog }],
// },
{
name: 'adiblar.gitbook.io',
contentBaseURL: 'https://adiblar.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
// {
// name: 'docs.gradient.network',
// contentBaseURL: 'https://docs.gradient.network',
// tests: [{ name: 'Home', url: '/' }],
// },
// {
// name: 'mygate-network.gitbook.io',
// contentBaseURL: 'https://mygate-network.gitbook.io',
// tests: [{ name: 'Home', url: '/' }],
// },
{
name: 'treasurenft.gitbook.io',
contentBaseURL: 'https://treasurenft.gitbook.io',
@@ -159,23 +134,13 @@ const testCases: TestsCase[] = [
{
name: 'docs.tickettool.xyz',
contentBaseURL: 'https://docs.tickettool.xyz',
tests: [{ name: 'Home', url: '/' }],
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'wiki.redmodding.org',
contentBaseURL: 'https://wiki.redmodding.org',
tests: [{ name: 'Home', url: '/' }],
},
// {
// name: 'docs.cherry-ai.com',
// contentBaseURL: 'https://docs.cherry-ai.com',
// tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
// },
{
name: 'docs.snyk.io',
contentBaseURL: 'https://docs.snyk.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.realapp.link',
contentBaseURL: 'https://docs.realapp.link',
@@ -203,16 +168,6 @@ const testCases: TestsCase[] = [
},
],
},
{
name: 'sosovalue-white-paper.gitbook.io',
contentBaseURL: 'https://sosovalue-white-paper.gitbook.io',
tests: [{ name: 'Home', url: '/' }],
},
// {
// name: 'docs.revrobotics.com',
// contentBaseURL: 'https://docs.revrobotics.com',
// tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
// },
{
name: 'chartschool.stockcharts.com',
contentBaseURL: 'https://chartschool.stockcharts.com',
@@ -221,24 +176,13 @@ const testCases: TestsCase[] = [
{
name: 'docs.soniclabs.com',
contentBaseURL: 'https://docs.soniclabs.com',
tests: [{ name: 'Home', url: '/' }],
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
// This one redirects to binance now
// {
// name: 'docs.meshchain.ai',
// contentBaseURL: 'https://docs.meshchain.ai',
// tests: [{ name: 'Home', url: '/' }],
// },
{
name: 'docs.thousandeyes.com',
contentBaseURL: 'https://docs.thousandeyes.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.raydium.io',
contentBaseURL: 'https://docs.raydium.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.fluentbit.io',
contentBaseURL: 'https://docs.fluentbit.io',
@@ -256,6 +200,417 @@ const testCases: TestsCase[] = [
{ name: 'OG Image', url: '/~gitbook/ogimage/h17zQIFwy3MaafVNmItO', mode: 'image' },
],
},
// Additional customer docs sites.
{
name: 'unsloth.ai/docs',
contentBaseURL: 'https://unsloth.ai',
tests: [{ name: 'Home', url: '/docs', run: waitForCookiesDialog }],
},
{
name: 'mariadb.com/docs',
contentBaseURL: 'https://mariadb.com',
tests: [{ name: 'Home', url: '/docs', run: waitForCookiesDialog }],
},
{
name: 'docs.n8n.io',
contentBaseURL: 'https://docs.n8n.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.cherryai.com.cn',
contentBaseURL: 'https://docs.cherryai.com.cn',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'library.zoom.com',
contentBaseURL: 'https://library.zoom.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'help.verkada.com',
contentBaseURL: 'https://help.verkada.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.overleaf.com',
contentBaseURL: 'https://docs.overleaf.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'wiki.tiltedphoques.com/tilted-online',
contentBaseURL: 'https://wiki.tiltedphoques.com',
tests: [{ name: 'Home', url: '/tilted-online' }],
},
{
name: 'handbook.musescore.org',
contentBaseURL: 'https://handbook.musescore.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'kakaobusiness.gitbook.io/main',
contentBaseURL: 'https://kakaobusiness.gitbook.io',
tests: [{ name: 'Home', url: '/main', run: waitForCookiesDialog }],
},
{
name: 'docs.maestro.dev',
contentBaseURL: 'https://docs.maestro.dev',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'developers.oxylabs.io',
contentBaseURL: 'https://developers.oxylabs.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.parallels.com/landing',
contentBaseURL: 'https://docs.parallels.com',
tests: [{ name: 'Home', url: '/landing', run: waitForCookiesDialog }],
},
{
name: 'help.impact.com',
contentBaseURL: 'https://help.impact.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.9proxy.com',
contentBaseURL: 'https://docs.9proxy.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'vimeo.com/legal',
contentBaseURL: 'https://vimeo.com',
tests: [{ name: 'Home', url: '/legal' }],
},
{
name: 'help.platipomiru.com',
contentBaseURL: 'https://help.platipomiru.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'help.aikido.dev',
contentBaseURL: 'https://help.aikido.dev',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'doc.demarche.numerique.gouv.fr',
contentBaseURL: 'https://doc.demarche.numerique.gouv.fr',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.adapta.org',
contentBaseURL: 'https://docs.adapta.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'www.xabuxa.com',
contentBaseURL: 'https://www.xabuxa.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.triumpharcade.com',
contentBaseURL: 'https://docs.triumpharcade.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.nats.io',
contentBaseURL: 'https://docs.nats.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'help.glpi-project.org',
contentBaseURL: 'https://help.glpi-project.org',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.waydro.id',
contentBaseURL: 'https://docs.waydro.id',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'bellingcat.gitbook.io/toolkit',
contentBaseURL: 'https://bellingcat.gitbook.io',
tests: [{ name: 'Home', url: '/toolkit' }],
},
{
name: 'wiki.project-fika.com',
contentBaseURL: 'https://wiki.project-fika.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.pinot.apache.org',
contentBaseURL: 'https://docs.pinot.apache.org',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.devolutions.net',
contentBaseURL: 'https://docs.devolutions.net',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'guides.gresb.com',
contentBaseURL: 'https://guides.gresb.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.prestashop-project.org/welcome',
contentBaseURL: 'https://docs.prestashop-project.org',
tests: [{ name: 'Home', url: '/welcome', run: waitForCookiesDialog }],
},
{
name: 'help.researchgate.net',
contentBaseURL: 'https://help.researchgate.net',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.verifone.com',
contentBaseURL: 'https://docs.verifone.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
// Deactivate it because of a custom Ask AI that causes flakiness.
// {
// name: 'docs.roboflow.com',
// contentBaseURL: 'https://docs.roboflow.com',
// tests: [{ name: 'Home', url: '/' }],
// },
{
name: 'www.netexec.wiki',
contentBaseURL: 'https://www.netexec.wiki',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'guide.strikepack.com',
contentBaseURL: 'https://guide.strikepack.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'gitbook.com/docs',
contentBaseURL: 'https://gitbook.com',
tests: [
{ name: 'Home', url: '/docs', run: waitForCookiesDialog },
{
name: 'OpenAPI',
url: '/docs/developers/gitbook-api/api-reference/docs-sites/site-ai-ask',
run: waitForCookiesDialog,
},
],
},
{
name: 'documentation.gravitee.io',
contentBaseURL: 'https://documentation.gravitee.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'faq.wanttopay.net/wanttopay-app',
contentBaseURL: 'https://faq.wanttopay.net',
tests: [{ name: 'Home', url: '/wanttopay-app', run: waitForCookiesDialog }],
},
{
name: 'guide.prismlive.com',
contentBaseURL: 'https://guide.prismlive.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.ionos.com/cloud',
contentBaseURL: 'https://docs.ionos.com',
tests: [{ name: 'Home', url: '/cloud', run: waitForCookiesDialog }],
},
{
name: 'support.evite.com',
contentBaseURL: 'https://support.evite.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'knowledge.illumina.com',
contentBaseURL: 'https://knowledge.illumina.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'wiki.retrobat.org',
contentBaseURL: 'https://wiki.retrobat.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'wiki.polymaker.com',
contentBaseURL: 'https://wiki.polymaker.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.ducks-services.com',
contentBaseURL: 'https://docs.ducks-services.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.hex-rays.com',
contentBaseURL: 'https://docs.hex-rays.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'whitepaper.interlinklabs.ai',
contentBaseURL: 'https://whitepaper.interlinklabs.ai',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'help.openloyalty.io',
contentBaseURL: 'https://help.openloyalty.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'retrozia.gitbook.io/retrozia',
contentBaseURL: 'https://retrozia.gitbook.io',
tests: [{ name: 'Home', url: '/retrozia' }],
},
{
name: 'helpcenter.channable.com',
contentBaseURL: 'https://helpcenter.channable.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'developerdocs.instructure.com',
contentBaseURL: 'https://developerdocs.instructure.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'legal.jagex.com',
contentBaseURL: 'https://legal.jagex.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'manual.edgetx.org',
contentBaseURL: 'https://manual.edgetx.org',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.cortex.io',
contentBaseURL: 'https://docs.cortex.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
// Flaky because of the GIF
// {
// name: 'docs.mufy.ai',
// contentBaseURL: 'https://docs.mufy.ai',
// tests: [{ name: 'Home', url: '/' }],
// },
{
name: 'docs.ndi.video/all',
contentBaseURL: 'https://docs.ndi.video',
tests: [{ name: 'Home', url: '/all', run: waitForCookiesDialog }],
},
{
name: 'docs.sevenpens.com/drawtab',
contentBaseURL: 'https://docs.sevenpens.com',
tests: [{ name: 'Home', url: '/drawtab' }],
},
{
name: 'manuals.i-reporter.jp',
contentBaseURL: 'https://manuals.i-reporter.jp',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.holybro.com',
contentBaseURL: 'https://docs.holybro.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'help.tokenpocket.pro/en',
contentBaseURL: 'https://help.tokenpocket.pro',
tests: [{ name: 'Home', url: '/en' }],
},
{
name: 'docs.bullmq.io',
contentBaseURL: 'https://docs.bullmq.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'tools.osintnewsletter.com',
contentBaseURL: 'https://tools.osintnewsletter.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'wiki.mmorealms.gg',
contentBaseURL: 'https://wiki.mmorealms.gg',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.vectra.ai',
contentBaseURL: 'https://docs.vectra.ai',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.cipp.app',
contentBaseURL: 'https://docs.cipp.app',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'sinfa-com-co.gitbook.io/manual-de-usuario',
contentBaseURL: 'https://sinfa-com-co.gitbook.io',
tests: [{ name: 'Home', url: '/manual-de-usuario' }],
},
{
name: 'support.skylum.com',
contentBaseURL: 'https://support.skylum.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.jgscripts.com',
contentBaseURL: 'https://docs.jgscripts.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.patchmypc.com',
contentBaseURL: 'https://docs.patchmypc.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'guide.cryosparc.com',
contentBaseURL: 'https://guide.cryosparc.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'guides.stellaraio.com/stellar',
contentBaseURL: 'https://guides.stellaraio.com',
tests: [{ name: 'Home', url: '/stellar', run: waitForCookiesDialog }],
},
{
name: 'docs.iyzico.com',
contentBaseURL: 'https://docs.iyzico.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'help.wotnot.io',
contentBaseURL: 'https://help.wotnot.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.sportmonks.com/v3',
contentBaseURL: 'https://docs.sportmonks.com',
tests: [{ name: 'Home', url: '/v3', run: waitForCookiesDialog }],
},
{
name: 'docs.payments.thalescloud.io',
contentBaseURL: 'https://docs.payments.thalescloud.io',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'doc.anytype.io/anytype-docs',
contentBaseURL: 'https://doc.anytype.io',
tests: [{ name: 'Home', url: '/anytype-docs', run: waitForCookiesDialog }],
},
{
name: 'help.blotato.com',
contentBaseURL: 'https://help.blotato.com',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'docs.cartographer3d.com',
contentBaseURL: 'https://docs.cartographer3d.com',
tests: [{ name: 'Home', url: '/' }],
},
{
name: 'docs.acestudio.ai',
contentBaseURL: 'https://docs.acestudio.ai',
tests: [{ name: 'Home', url: '/' }],
},
];
runTestCases(testCases);
+22 -23
View File
@@ -32,6 +32,7 @@ import {
runTestCases,
setTimeToMorning,
waitForAIChatResponse,
waitForAdminToolbar,
waitForCookiesDialog,
waitForCoverImages,
waitForNotFound,
@@ -185,17 +186,8 @@ const searchTestCases: Test[] = [
await waitForCookiesDialog(page);
const searchInput = page.locator('css=[data-testid="search-input"]');
// Focus search input, expecting recommended questions
await searchInput.focus();
await expect(page.getByTestId('search-results')).toBeVisible({
timeout: 30_000,
});
const recommendedQuestions = await page
.getByTestId('search-recommended-question')
.all();
await expect(recommendedQuestions.length).toBeGreaterThanOrEqual(1); // Expect at least 1 question
// Fill search input, expecting AI search option
await searchInput.focus();
await searchInput.fill(AI_PROMPT);
const aiSearchResult = page.getByTestId('search-ask-question');
await expect(aiSearchResult).toBeVisible();
@@ -621,21 +613,19 @@ const testCases: TestsCase[] = [
name: 'Site with sections and section groups',
url: '',
},
{
name: 'Section group dropdown',
url: '',
run: async (page) => {
await page.getByRole('button', { name: 'Test Section Group 1' }).hover();
await expect(page.getByRole('link', { name: /Section B/ })).toBeVisible();
},
},
{
name: 'Section group link',
url: '',
screenshot: false,
run: async (page) => {
const sectionGroupDropdown = await page.getByText('Test Section Group 1');
await sectionGroupDropdown.hover();
const trigger = page.getByRole('button', { name: 'Test Section Group 1' });
// Radix NavigationMenu opens the dropdown on a `pointermove`. A single
// synthetic hover can land before hydration and be lost, so re-hover
// until the dropdown content actually appears.
await expect(async () => {
await trigger.hover();
await expect(page.getByText('Section B')).toBeVisible({ timeout: 1000 });
}).toPass({ timeout: 15000 });
await page.getByText('Section B').click();
await page.waitForURL((url) => url.pathname.includes('/sections/sections-4'));
},
@@ -665,7 +655,12 @@ const testCases: TestsCase[] = [
{
name: 'Revision',
url: '~/revisions/S55pwsEr5UVoroaOiWnP/blocks/headings',
run: waitForCookiesDialog,
run: async (page) => {
await waitForCookiesDialog(page);
// Viewing a past revision shows the admin toolbar; assert it is
// present (it is hidden from the screenshot as it animates open).
await waitForAdminToolbar(page);
},
},
{
name: 'Invalid revision',
@@ -1113,6 +1108,11 @@ const testCases: TestsCase[] = [
url: 'blocks/mermaid',
run: waitForCookiesDialog,
},
{
name: 'Prompt',
url: 'blocks/prompt',
run: waitForCookiesDialog,
},
],
},
{
@@ -1359,8 +1359,7 @@ const testCases: TestsCase[] = [
name: 'Without page actions',
url: getCustomizationURL({
pageActions: {
markdown: false,
externalAI: false,
items: [],
},
}),
run: waitForCookiesDialog,
+45 -10
View File
@@ -13,6 +13,7 @@ import {
CustomizationIconsStyle,
CustomizationLinksStyle,
CustomizationLocale,
CustomizationPageActionType,
CustomizationSearchStyle,
CustomizationSidebarBackgroundStyle,
CustomizationSidebarListStyle,
@@ -171,6 +172,19 @@ export async function waitForCookiesDialog(page: Page) {
});
}
/**
* Wait for the GitBook admin toolbar to be present.
*
* The toolbar only renders when signed in to GitBook. It is hidden from
* screenshots (see `argosCSS`) because it auto-expands with an animation, so
* use this to assert it is rendered without capturing its flaky visual state.
*/
export async function waitForAdminToolbar(page: Page) {
await expect(page.getByTestId('admin-toolbar')).toBeVisible({
timeout: 10_000,
});
}
export async function waitForNotFound(_page: Page, response: Response | null) {
expect(response).not.toBeNull();
expect(response?.status()).toBe(404);
@@ -247,6 +261,19 @@ export function runTestCases(testCases: TestsCase[]) {
);
}
// Reset the cross-space navigation state on every document load so the
// "Back to <space>" shortcut never leaks between navigations/tests. It is
// detected client-side from this sessionStorage, and a stale value (e.g.
// after a retry or a cross-space redirect) makes it appear or not
// non-deterministically, causing flaky screenshots.
await page.addInitScript(() => {
try {
sessionStorage.removeItem('gitbook-space-navigation:last');
sessionStorage.removeItem('gitbook-space-navigation:back');
sessionStorage.removeItem('gitbook-space-navigation:from-picker');
} catch {}
});
// Set the header to disable the Vercel toolbar
// But only on the main document as it'd cause CORS issues on other resources
await page.route('**/*', async (route, request) => {
@@ -262,7 +289,11 @@ export function runTestCases(testCases: TestsCase[]) {
}
});
const response = await page.goto(url);
// Wait only for `domcontentloaded` rather than the default `load`: these
// are real customer sites whose third-party subresources can hang and
// never fire `load`, aborting the navigation. Argos stabilization (run in
// `beforeScreenshot`) still waits for images/fonts before capturing.
const response = await page.goto(url, { waitUntil: 'domcontentloaded' });
if (testEntry.run) {
await testEntry.run(page, response);
}
@@ -282,6 +313,12 @@ export function runTestCases(testCases: TestsCase[]) {
/* Hide Intercom */
.intercom-lightweight-app {
display: none !important;
}
/* Hide the GitBook admin toolbar: it auto-expands with an
animation, so its state at capture time is non-deterministic.
Its presence is asserted separately via waitForAdminToolbar. */
[data-testid="admin-toolbar"] {
display: none !important;
}
`,
threshold: screenshotOptions?.threshold ?? undefined,
@@ -389,9 +426,6 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
default: CustomizationDefaultThemeMode.System,
toggeable: true,
},
pdf: {
enabled: true,
},
feedback: {
enabled: false,
},
@@ -404,16 +438,17 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
advancedCustomization: {
enabled: true,
},
git: {
showEditLink: false,
},
pagination: {
enabled: true,
},
pageActions: {
externalAI: true,
markdown: true,
mcp: true,
items: [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
],
},
trademark: {
enabled: true,
+3
View File
@@ -48,7 +48,9 @@ const nextConfig = {
GITBOOK_OAUTH_SERVER_URL: process.env.GITBOOK_OAUTH_SERVER_URL,
GITBOOK_PREVIEW_BASE_URL: process.env.GITBOOK_PREVIEW_BASE_URL,
GITBOOK_INTEGRATIONS_HOST: process.env.GITBOOK_INTEGRATIONS_HOST,
GITBOOK_INTEGRATIONS_CONTENT_HOST: process.env.GITBOOK_INTEGRATIONS_CONTENT_HOST,
GITBOOK_IMAGE_RESIZE_URL: process.env.GITBOOK_IMAGE_RESIZE_URL,
GITBOOK_IMAGE_RESIZE_SALT: process.env.GITBOOK_IMAGE_RESIZE_SALT,
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
GITBOOK_URL: process.env.GITBOOK_URL,
@@ -60,6 +62,7 @@ const nextConfig = {
GITBOOK_FONTS_URL: process.env.GITBOOK_FONTS_URL,
GITBOOK_RUNTIME: process.env.GITBOOK_RUNTIME,
GITBOOK_BLOCK_SEARCH_INDEXATION: process.env.GITBOOK_BLOCK_SEARCH_INDEXATION,
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: process.env.GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE,
// Next.js envs
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "0.27.0",
"version": "0.27.2",
"private": true,
"dependencies": {
"@cloudflare/workers-types": "^4.20251011.0",
@@ -93,8 +93,8 @@
"zustand": "^5.0.3"
},
"devDependencies": {
"@argos-ci/playwright": "^6.4.2",
"@playwright/test": "^1.58.2",
"@argos-ci/playwright": "^7.2.0",
"@playwright/test": "^1.61.1",
"@scalar/api-client-react": "catalog:",
"@tailwindcss/postcss": "^4.1.11",
"@types/js-cookie": "^3.0.6",
+10
View File
@@ -18,6 +18,16 @@ export default defineConfig({
use: {
...devices['Desktop Chrome'],
channel: 'chrome',
launchOptions: {
args: [
// Disable subpixel (LCD) text so glyphs always render with
// grayscale antialiasing — removes the red/blue edge fringing
// that varies between macOS (local) and Linux (CI) runs.
'--disable-lcd-text',
// Disable font hinting so glyph rasterization is platform-independent.
'--font-render-hinting=none',
],
},
},
},
],
@@ -1,7 +1,7 @@
import type { RouteLayoutParams } from '@/app/utils';
import { EmbeddableAssistantPage } from '@/components/Embeddable';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getEmbeddableDynamicContext } from '@/lib/embeddable';
import { CustomizationAIMode } from '@gitbook/api';
import { redirect } from 'next/navigation';
type PageProps = {
@@ -15,7 +15,7 @@ export default async function Page(props: PageProps) {
const { context } = await getEmbeddableDynamicContext(params);
// If the assistant is not enabled, redirect to the docs
if (context.customization.ai.mode !== CustomizationAIMode.Assistant) {
if (!isAIChatEnabled(context.customization.ai.mode)) {
redirect(`${context.linker.toPathInSite('~gitbook/embed/page/')}`);
}
@@ -1,6 +1,6 @@
import type { RouteLayoutParams } from '@/app/utils';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getEmbeddableDynamicContext } from '@/lib/embeddable';
import { CustomizationAIMode } from '@gitbook/api';
import { redirect } from 'next/navigation';
type PageProps = {
@@ -13,7 +13,7 @@ export default async function Page(props: PageProps) {
const baseURL = context.linker.toPathInSite('~gitbook/embed/');
// If assistant is enabled, redirect to assistant, otherwise to docs
if (context.customization.ai.mode === CustomizationAIMode.Assistant) {
if (isAIChatEnabled(context.customization.ai.mode)) {
redirect(`${baseURL}/assistant`);
} else {
redirect(`${baseURL}/page/`);
@@ -1,8 +1,14 @@
import { SiteInsightsDisplayContext } from '@gitbook/api';
import {
CustomizationPageActionType,
SiteFindingType,
SiteInsightsDisplayContext,
} from '@gitbook/api';
import { type RouteLayoutParams, getDynamicSiteContext } from '@/app/utils';
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask';
import { getExposableError, throwIfDataError } from '@/lib/data';
import { getMarkdownForPageInSpace } from '@/lib/markdownPage';
import { fromPageMarkdown, getMarkdownForPageInSpace, toPageMarkdown } from '@/lib/markdownPage';
import { resolvePagePath } from '@/lib/pages';
import { joinPathWithBaseURL } from '@/lib/paths';
import { findSiteSpaceBy, findSiteSpaceByUrl } from '@/lib/sites';
@@ -12,6 +18,18 @@ import { createMcpHandler } from 'mcp-handler';
import type { NextRequest } from 'next/server';
import { z } from 'zod';
/**
* Fire-and-forget insights tracking for the MCP endpoint. A tracking failure (e.g. a 422 from the
* insights API) must never reject into the request lifecycle, or it surfaces as an MCP transport error.
*/
function trackMcpEvent(args: Parameters<typeof trackServerInsightsEvents>[0]) {
waitUntil(
trackServerInsightsEvents(args).catch((error) => {
console.error('Failed to track MCP insights event:', error);
})
);
}
export async function handleMcpRequest(
rawRequest: NextRequest,
params: RouteLayoutParams,
@@ -20,7 +38,9 @@ export async function handleMcpRequest(
const { context } = await getDynamicSiteContext(params);
const { dataFetcher, linker, site } = context;
if (!context.customization.pageActions.mcp) {
const { pageActions } = context.customization;
const isMcpEnabled = pageActions.items.includes(CustomizationPageActionType.Mcp);
if (!isMcpEnabled) {
return new Response('Not Found', { status: 404 });
}
@@ -29,21 +49,19 @@ export async function handleMcpRequest(
requestURL.search = rawRequest.nextUrl.search;
const request = new Request(requestURL, rawRequest);
waitUntil(
trackServerInsightsEvents({
organizationId: context.organizationId,
siteId: context.site.id,
events: [
{
type: 'mcp_request',
location: {
displayContext: SiteInsightsDisplayContext.Server,
},
trackMcpEvent({
organizationId: context.organizationId,
siteId: context.site.id,
events: [
{
type: 'mcp_request',
location: {
displayContext: SiteInsightsDisplayContext.Server,
},
],
request,
})
);
},
],
request,
});
const mcpHandler = createMcpHandler(
(server) => {
@@ -53,6 +71,13 @@ export async function handleMcpRequest(
{
query: z.string(),
},
{
title: 'Search documentation',
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
async ({ query }) => {
const results = await throwIfDataError(
dataFetcher.searchSiteContent({
@@ -63,22 +88,20 @@ export async function handleMcpRequest(
})
);
waitUntil(
trackServerInsightsEvents({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'search_type_query',
query,
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
},
trackMcpEvent({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'search_type_query',
query,
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
},
],
request,
})
);
},
],
request,
});
return {
content: results.flatMap((result) => {
@@ -111,9 +134,11 @@ export async function handleMcpRequest(
)
);
const body = pageResult.sections
?.map((section) => section.body)
.join('\n');
// The search API returns sections ordered highest-score-first, so
// the first section with a body is the best-scoring preview.
const body = (pageResult.sections ?? []).find(
(section) => section.body
)?.body;
return {
type: 'text',
@@ -153,6 +178,13 @@ export async function handleMcpRequest(
return z.NEVER;
}),
},
{
title: 'Get page content',
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
async ({ url }) => {
try {
const match = findSiteSpaceByUrl(context.structure, url);
@@ -184,26 +216,246 @@ export async function handleMcpRequest(
resolved.page
);
waitUntil(
trackServerInsightsEvents({
trackMcpEvent({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'page_view',
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
page: resolved.page.id,
space: match.siteSpace.space.id,
revision: match.siteSpace.space.revision,
},
},
],
request,
});
return { content: [{ type: 'text', text: markdown }] };
} catch (error) {
const exposable = getExposableError(error);
return {
content: [{ type: 'text', text: exposable.message }],
isError: true,
};
}
}
);
// Only expose the answer tool when the site has AI enabled, since it relies on
// the same AI search backend that powers the site's "ask a question" experience.
if (isAIEnabled(context.customization.ai.mode)) {
server.tool(
'askQuestion',
`Ask a natural-language question about ${site.title} and get a synthesized answer, with links to the source pages. Prefer this over \`searchDocumentation\` when you want a direct answer to a question rather than a list of matching pages; use \`searchDocumentation\`/\`getPage\` when you need to browse or read full pages yourself.`,
{
question: z
.string()
.describe(
`The natural-language question to answer about ${site.title}.`
),
goal: z
.string()
.optional()
.describe(
'The broader end goal you are ultimately trying to accomplish (as/on behalf of the user). Used to tailor the answer to be most useful for your goal. Optional.'
),
},
{
title: 'Ask a question',
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
async ({ question, goal }) => {
try {
const trimmedQuestion = question.trim();
if (!trimmedQuestion) {
return {
content: [
{
type: 'text',
text: 'Please provide a question to answer.',
},
],
isError: true,
};
}
const trimmedGoal = goal?.trim() || undefined;
const answer = await streamSiteAskAnswer(context, trimmedQuestion, {
goal: trimmedGoal,
});
trackMcpEvent({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'page_view',
type: 'ask_question',
query: trimmedQuestion,
...(trimmedGoal ? { goal: trimmedGoal } : {}),
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
page: resolved.page.id,
space: match.siteSpace.space.id,
revision: match.siteSpace.space.revision,
},
},
],
request,
})
);
});
return { content: [{ type: 'text', text: markdown }] };
if (!answer || !answer.answer || !('markdown' in answer.answer)) {
return {
content: [
{
type: 'text',
text: "We couldn't answer this question.",
},
],
};
}
const answerMarkdown = toPageMarkdown(
await fromPageMarkdown(context, {
markdown: answer.answer.markdown,
pagePath: '',
})
);
const sourcesMarkdown = await renderAskSourcesMarkdown(
context,
answer.sources ?? []
);
let text = answerMarkdown.trim();
if (sourcesMarkdown) {
text += `\n\n# Sources\n\n${sourcesMarkdown}`;
}
return { content: [{ type: 'text', text }] };
} catch (error) {
const exposable = getExposableError(error);
return {
content: [{ type: 'text', text: exposable.message }],
isError: true,
};
}
}
);
}
server.tool(
'sendFeedback',
`Report an issue in the documentation of ${site.title} so the team can fix it. Use it whenever, while helping a user, you come across content that is outdated, contradictory, missing information, or otherwise unhelpful. Also use it when the user themselves reports a problem with the docs, even if you could not verify it yourself. If it's your own observation, do a quick sanity check that the issue is real before reporting — no need to exhaustively re-read the page. Send one call per distinct issue and do not report the same issue twice in a conversation. Do not use this tool to confirm that a page is accurate; it is for reporting problems only.`,
{
category: z
.nativeEnum(SiteFindingType)
.describe(
'The kind of issue. "content-outdated": the content was correct at some point but no longer matches the current product or reality. "incoherence": the content contradicts itself or another page. "content-gap": information the reader needs is missing entirely, whether or not it was ever documented. "other": only as a last resort when none of the above fits.'
),
content: z
.string()
.min(1)
.max(2048)
.describe(
'Explain the issue in full, as if writing to a documentation maintainer who never saw this conversation. Describe what is wrong, where on the page it appears (quote the exact sentence or section title when possible), what the user was trying to do, and, when relevant, what the correct or expected information should be. Write a few clear, specific sentences in English. Never include personal or confidential information from the conversation. Up to 2048 characters.'
),
pageUrl: z
.string()
.describe(
`The full URL of the page the issue is about (e.g. ${siteUrl}/getting-started). Provide it whenever you can so the finding is linked to the exact page.`
)
.transform((value, ctx) => {
const candidate = URL.canParse(value)
? new URL(value)
: URL.canParse(value, siteUrl)
? new URL(value, siteUrl)
: null;
if (
!candidate ||
(candidate.protocol !== 'https:' && candidate.protocol !== 'http:')
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `"${value}" is not a valid URL on this site. Expected a full URL like ${siteUrl}/getting-started`,
});
return z.NEVER;
}
return candidate.toString();
})
.optional(),
},
{
title: 'Send feedback',
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
async ({ category, content, pageUrl }) => {
try {
let pageLocation:
| { page: string; space: string; revision: string }
| undefined;
if (pageUrl) {
const match = findSiteSpaceByUrl(context.structure, pageUrl);
if (!match) {
return {
content: [
{ type: 'text', text: `Page not found: "${pageUrl}"` },
],
isError: true,
};
}
const revision = await throwIfDataError(
dataFetcher.getRevision({
spaceId: match.siteSpace.space.id,
revisionId: match.siteSpace.space.revision,
})
);
const resolved = resolvePagePath(revision.pages, match.pagePath ?? '');
if (!resolved) {
return {
content: [
{ type: 'text', text: `Page not found: "${pageUrl}"` },
],
isError: true,
};
}
pageLocation = {
page: resolved.page.id,
space: match.siteSpace.space.id,
revision: match.siteSpace.space.revision,
};
}
trackMcpEvent({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'agent_feedback',
feedback: { content, category },
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
...pageLocation,
},
},
],
request,
});
return {
content: [{ type: 'text', text: 'Feedback recorded. Thank you.' }],
};
} catch (error) {
const exposable = getExposableError(error);
return {
@@ -186,11 +186,9 @@ function transformSitePageResult(args: {
};
}) ?? [];
// Find the best-scoring section to use as a body preview on the page result.
const bestSection = pageSections.reduce<ComputedSectionResult | undefined>(
(best, section) => (!best || section.score > best.score ? section : best),
undefined
);
// The search API returns each page's sections ordered highest-score-first and caps them at one
// per page, so the first section is the best-scoring one to use as a body preview.
const bestSection = pageSections[0];
if (bestSection) {
page.bestSection = {
href: bestSection.href,
@@ -1,7 +1,7 @@
import type { RouteParams } from '@/app/utils';
import { EmbeddableAssistantPage } from '@/components/Embeddable';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getEmbeddableStaticContext } from '@/lib/embeddable';
import { CustomizationAIMode } from '@gitbook/api';
import { redirect } from 'next/navigation';
export const dynamic = 'force-static';
@@ -15,7 +15,7 @@ export default async function Page(props: PageProps) {
const { context } = await getEmbeddableStaticContext(params);
// If the assistant is not enabled, redirect to the docs
if (context.customization.ai.mode !== CustomizationAIMode.Assistant) {
if (!isAIChatEnabled(context.customization.ai.mode)) {
redirect(`${context.linker.toPathInSite('~gitbook/embed/page/')}`);
}
@@ -1,6 +1,6 @@
import type { RouteLayoutParams } from '@/app/utils';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getEmbeddableStaticContext } from '@/lib/embeddable';
import { CustomizationAIMode } from '@gitbook/api';
import { redirect } from 'next/navigation';
export const dynamic = 'force-static';
@@ -15,7 +15,7 @@ export default async function Page(props: PageProps) {
const baseURL = context.linker.toPathInSite('~gitbook/embed/');
// If assistant is enabled, redirect to assistant, otherwise to docs
if (context.customization.ai.mode === CustomizationAIMode.Assistant) {
if (isAIChatEnabled(context.customization.ai.mode)) {
redirect(`${baseURL}/assistant`);
} else {
redirect(`${baseURL}/page/`);
@@ -0,0 +1,24 @@
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
import { serveAskMarkdown } from '@/routes/markdownAsk';
import type { NextRequest } from 'next/server';
export const dynamic = 'force-static';
/**
* Serve an AI answer as markdown for a page, steered by the end goal ("goal")
* the calling agent provided via the `?goal=` search parameter.
*
* The goal is encoded as a path segment (rather than read from the query) because
* this route is statically rendered, mirroring how the question itself is handled.
*/
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams & { question: string; goal: string }> }
) {
const { question: encodedQuestion, goal: encodedGoal } = await params;
const { context } = await getStaticSiteContext(await params);
const question = decodeURIComponent(encodedQuestion);
const goal = decodeURIComponent(encodedGoal);
return serveAskMarkdown(context, question, { goal });
}
+2
View File
@@ -10,6 +10,7 @@ import {
GITBOOK_FONTS_URL,
GITBOOK_ICONS_URL,
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
GITBOOK_INTEGRATIONS_CONTENT_HOST,
GITBOOK_INTEGRATIONS_HOST,
GITBOOK_OAUTH_SERVER_URL,
GITBOOK_SECRET,
@@ -32,6 +33,7 @@ export async function GET(_req: NextRequest) {
GITBOOK_ICONS_URL,
GITBOOK_USER_AGENT,
GITBOOK_INTEGRATIONS_HOST,
GITBOOK_INTEGRATIONS_CONTENT_HOST,
GITBOOK_DISABLE_TRACKING,
// Secret envs
@@ -19,7 +19,13 @@ export type PageReference = BaseAIChatReference & {
href?: string;
};
export type AIChatReference = CodeBlockReference | PageReference;
export type TextReference = BaseAIChatReference & {
type: 'text';
/** The selected text content. */
content: string;
};
export type AIChatReference = CodeBlockReference | PageReference | TextReference;
/**
* Serialize the staged references into a preamble prepended to the user's message,
@@ -42,6 +48,11 @@ export function serializeReferences(refs: AIChatReference[]): string {
sections.push(serializeCodeBlockReferences(codeRefs));
}
const textRefs = refs.filter((ref): ref is TextReference => ref.type === 'text');
if (textRefs.length > 0) {
sections.push(serializeTextReferences(textRefs));
}
if (sections.length === 0) {
return '';
}
@@ -66,6 +77,19 @@ function serializeCodeBlockReferences(refs: CodeBlockReference[]): string {
return `The user is referring to the following code block${plural ? 's' : ''} from the page they are reading. Answer their question about ${plural ? 'them' : 'it'}:\n\n${blocks}`;
}
function serializeTextReferences(refs: TextReference[]): string {
const plural = refs.length > 1;
const blocks = refs.map((ref) => quoteText(ref.content)).join('\n\n');
return `The user is referring to the following excerpt${plural ? 's' : ''} from the page they are reading. Answer their question about ${plural ? 'them' : 'it'}:\n\n${blocks}`;
}
function quoteText(content: string): string {
return content
.split('\n')
.map((line) => `> ${line}`)
.join('\n');
}
function buildCodeBlockFence(ref: CodeBlockReference): string {
const { label, content, syntax } = ref;
let max = 2;
@@ -1,6 +1,7 @@
'use server';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import { traceErrorOnly } from '@/lib/tracing';
import {
type AIMessageContext,
@@ -39,6 +40,11 @@ export async function* streamAIChatResponse({
isEmbeddable: options?.asEmbeddable,
});
const siteContext = await fetchServerActionSiteContext(context);
if (!isAIChatEnabled(siteContext.customization.ai.mode)) {
throw new Error('The AI Assistant is not enabled for this site.');
}
const siteURLData = await getSiteURLDataFromMiddleware();
const api = await context.dataFetcher.api();
+4 -3
View File
@@ -1,10 +1,11 @@
'use client';
import { CustomizationAIMode } from '@gitbook/api';
import type { CustomizationAIMode } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import * as React from 'react';
import type { ReactNode } from 'react';
import { isAIChatEnabled, isAISearchEnabled } from '@/components/utils/isAIChatEnabled';
import { tString, useLanguage } from '@/intl/client';
import type { GitBookAssistant } from '@gitbook/browser-types';
import { useAIChatController, useAIChatState } from '.';
@@ -89,7 +90,7 @@ export function useAI(): AIContext {
const assistants: Assistant[] = [];
if (config.aiMode === CustomizationAIMode.Assistant) {
if (isAIChatEnabled(config.aiMode)) {
assistants.push({
id: 'gitbook-assistant',
label: config.assistantName ?? getAIChatName(language, config.trademark),
@@ -110,7 +111,7 @@ export function useAI(): AIContext {
ui: true,
mode: 'sidebar',
});
} else if (config.aiMode === CustomizationAIMode.Search) {
} else if (isAISearchEnabled(config.aiMode)) {
assistants.push({
id: 'gitbook-ai-search',
label: tString(language, 'ai_chat_context_badge'),
@@ -117,6 +117,20 @@ export type AIChatState = {
* References staged on the next user message.
*/
references: AIChatReference[];
/**
* Draft text to pre-fill the chat input with, without sending it. The chat input consumes
* this value (seeding its editable content) and then clears it back to an empty string.
*/
draft: string;
/**
* Follow-ups the visitor submitted while a previous turn was still streaming. They are held
* here and sent automatically, one at a time in submission order, as each answer finishes
* (see the flush in `streamResponse`), so submitting mid-stream isn't lost. Empty when
* nothing is queued.
*/
queuedMessages: string[];
};
export type AIChatEvent =
@@ -150,6 +164,10 @@ export type AIChatController = {
clearReferences: () => void;
/** Focus the chat input */
focus: () => void;
/** Pre-fill the chat input with draft text, without sending it. */
setDraft: (draft: string) => void;
/** Remove a follow-up queued to send after the current answer finishes, by its queue index. */
cancelQueuedMessage: (index: number) => void;
/** Register an event listener */
on: <T extends AIChatEvent['type']>(
event: T,
@@ -173,6 +191,8 @@ const globalState = zustand.create<AIChatState>(() => {
error: false,
initialQuery: null,
references: [],
draft: '',
queuedMessages: [],
};
});
@@ -248,6 +268,9 @@ export function AIChatProvider(props: {
notify(eventsRef.current.get('close'), {});
}, [setSearchState]);
// Lets `streamResponse` flush a queued follow-up via `onPostMessage`, which is defined later.
const postMessageRef = React.useRef<((input: { message: string }) => void) | null>(null);
// Stream a message with the AI backend
const streamResponse = React.useCallback(
async (input: {
@@ -503,6 +526,15 @@ export function AIChatProvider(props: {
loading: false,
error: false,
}));
// Turn settled: send the next queued follow-up (oldest first). Held back while a
// control is pending, since posting would throw; it flushes after that resolves.
const { queuedMessages, control: activeControl } = globalState.getState();
const [next, ...rest] = queuedMessages;
if (next !== undefined && !activeControl) {
globalState.setState((state) => ({ ...state, queuedMessages: rest }));
postMessageRef.current?.({ message: next });
}
}
} catch (error) {
console.error('Error streaming AI response', error);
@@ -536,8 +568,12 @@ export function AIChatProvider(props: {
throw new Error("We can't post a message when a control is active");
}
// Ignore duplicates while a previous turn is still streaming
// Still streaming: queue this follow-up instead of dropping it (flushed in order in `streamResponse`).
if (responding) {
globalState.setState((state) => ({
...state,
queuedMessages: [...state.queuedMessages, input.message],
}));
return;
}
@@ -598,6 +634,21 @@ export function AIChatProvider(props: {
[setSearchState, siteSpaceId, trackEvent, streamResponse]
);
// Keep the ref current so `streamResponse` can flush a queued follow-up via the latest callback.
postMessageRef.current = onPostMessage;
// Remove a follow-up queued while the assistant is still answering (the × on the affordance).
const onCancelQueuedMessage = React.useCallback((index: number) => {
globalState.setState((state) =>
index < 0 || index >= state.queuedMessages.length
? state
: {
...state,
queuedMessages: state.queuedMessages.filter((_, i) => i !== index),
}
);
}, []);
// Clear the conversation and reset ask parameter
const onClear = React.useCallback(() => {
globalState.setState((state) => ({
@@ -612,6 +663,7 @@ export function AIChatProvider(props: {
error: false,
initialQuery: null,
references: [],
queuedMessages: [],
}));
// Reset ask parameter to empty string (keeps chat open but clears content)
@@ -661,6 +713,10 @@ export function AIChatProvider(props: {
notify(eventsRef.current.get('focus'), {});
}, []);
const onSetDraft = React.useCallback((draft: string) => {
globalState.setState({ draft });
}, []);
const onEvent = React.useCallback(
<T extends AIChatEvent['type']>(
event: T,
@@ -690,6 +746,8 @@ export function AIChatProvider(props: {
removeReference: onRemoveReference,
clearReferences: onClearReferences,
focus: onFocus,
setDraft: onSetDraft,
cancelQueuedMessage: onCancelQueuedMessage,
on: onEvent,
};
}, [
@@ -701,6 +759,8 @@ export function AIChatProvider(props: {
onRemoveReference,
onClearReferences,
onFocus,
onSetDraft,
onCancelQueuedMessage,
onEvent,
]);
@@ -31,9 +31,12 @@ import { ScrollContainer } from '../primitives/ScrollContainer';
import { SideSheet } from '../primitives/SideSheet';
import { AIChatControl } from './AIChatControl';
import { AIChatControlButton } from './AIChatControlButton';
import { AIChatExpandButton } from './AIChatExpandButton';
import { AIChatIcon } from './AIChatIcon';
import { AIChatInput } from './AIChatInput';
import { AIChatMessages } from './AIChatMessages';
import { AIChatQueuedMessage } from './AIChatQueuedMessage';
import { AIChatResizeHandle } from './AIChatResizeHandle';
import AIChatSuggestedQuestions from './AIChatSuggestedQuestions';
export function AIChat() {
@@ -85,9 +88,10 @@ export function AIChat() {
withOverlay={true}
data-ai-chat
className={tcls(
'ai-chat mx-auto ml-8 not-hydrated:hidden w-96 transition-[width] duration-300 ease-quint lg:max-xl:w-80'
'ai-chat mx-auto ml-8 not-hydrated:hidden w-96 transition-[width] duration-300 ease-quint lg:w-(--ai-chat-width)'
)}
>
<AIChatResizeHandle />
<EmbeddableFrame className="relative w-full shrink-0 border-tint-subtle border-l to-tint-base">
<EmbeddableFrameMain data-testid="ai-chat" aria-busy={chat.loading}>
<EmbeddableFrameHeader className="not-embed:px-4">
@@ -100,6 +104,7 @@ export function AIChat() {
</EmbeddableFrameHeaderMain>
<EmbeddableFrameButtons>
<AIChatControlButton />
<AIChatExpandButton />
<Button
onClick={() => chatController.close()}
iconOnly
@@ -115,6 +120,7 @@ export function AIChat() {
chat={chat}
suggestions={config.suggestions}
trademark={config.trademark}
assistantName={config.assistantName}
/>
</EmbeddableFrameBody>
</EmbeddableFrameMain>
@@ -203,14 +209,17 @@ export function AIChatBody(props: {
welcomeMessage?: string;
suggestions?: string[];
trademark?: boolean;
/** Custom assistant name override; falls back to the branded/unbranded default name. */
assistantName?: string;
greeting?: {
title: string;
subtitle: string;
};
}) {
const { chatController, chat, suggestions, greeting, trademark } = props;
const { chatController, chat, suggestions, greeting, trademark, assistantName } = props;
const language = useLanguage();
const resolvedAssistantName = assistantName ?? getAIChatName(language, trademark ?? true);
const now = useNow(60 * 60 * 1000); // Refresh every hour for greeting
const isEmpty = !chat.messages.length;
@@ -276,13 +285,24 @@ export function AIChatBody(props: {
</ScrollContainer>
<div className="flex max-h-3/4 min-h-0 flex-col gap-2 not-embed:px-4 pb-4">
{!chat.error &&
chat.queuedMessages.map((message, index) => (
<AIChatQueuedMessage
// Queue order is stable and items carry no local state, so the index is a
// safe key here.
key={index}
message={message}
assistantName={resolvedAssistantName}
onRemove={() => chatController.cancelQueuedMessage(index)}
/>
))}
{/* Display an error banner when something went wrong. */}
{chat.error ? <AIChatError chatController={chatController} /> : null}
{chat.control ? <AIChatControl control={chat.control} /> : null}
<AIChatInput
responding={chat.responding}
disabled={chat.responding || chat.error}
disabled={chat.error}
onSubmit={(value) => {
chatController.postMessage({ message: value });
}}
@@ -0,0 +1,35 @@
'use client';
import { tString, useLanguage } from '@/intl/client';
import { Icon } from '@gitbook/icons';
import { Button } from '../primitives';
import { useAIChatWidthStore, useIsAIChatMaxWidth } from './useAIChatWidthStore';
export function AIChatExpandButton() {
const language = useLanguage();
const toggleWidth = useAIChatWidthStore((state) => state.toggleWidth);
const isMaxWidth = useIsAIChatMaxWidth();
return (
<Button
onClick={toggleWidth}
iconOnly
icon={
<Icon
icon={
isMaxWidth
? 'arrow-down-left-and-arrow-up-right-to-center'
: 'arrow-up-right-and-arrow-down-left-from-center'
}
className="scale-90"
/>
}
label={tString(
language,
isMaxWidth ? 'ai_chat_collapse_panel' : 'ai_chat_expand_panel'
)}
variant="blank"
className="max-lg:hidden"
/>
);
}
@@ -1,7 +1,7 @@
import { t, tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
import { Icon } from '@gitbook/icons';
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { useAIChatController, useAIChatState } from '../AI/useAIChat';
import { HoverCard, HoverCardRoot, HoverCardTrigger } from '../primitives';
@@ -11,7 +11,8 @@ import { AIChatReferenceChips } from './AIChatReferenceChips';
export function AIChatInput(props: {
disabled?: boolean;
/**
* When true, the input is disabled
* When true, the assistant is streaming an answer. The field stays editable and submitting a
* follow-up queues it (sent automatically once the answer finishes) rather than being blocked.
*/
responding: boolean;
onSubmit: (value: string) => void;
@@ -24,6 +25,29 @@ export function AIChatInput(props: {
const inputRef = useRef<HTMLTextAreaElement>(null);
// Controlled value so a pre-filled draft can be injected without sending it.
const [value, setValue] = useState('');
// Consume a draft staged via the controller (e.g. the per-paragraph "Ask" button): seed the
// input, focus it with the cursor at the end, then clear the pending draft so it is applied
// once and not re-injected on a later mount.
useEffect(() => {
if (!chat.draft) {
return;
}
setValue(chat.draft);
chatController.setDraft('');
const raf = requestAnimationFrame(() => {
const el = inputRef.current;
if (el) {
el.focus();
const end = el.value.length;
el.setSelectionRange(end, end);
}
});
return () => cancelAnimationFrame(raf);
}, [chat.draft, chatController]);
useEffect(() => {
if (chat.opened && !disabled && !responding) {
// Add a small delay to ensure the input is rendered before focusing
@@ -51,6 +75,9 @@ export function AIChatInput(props: {
},
{
enableOnFormTags: true,
// Match the logical character so Dvorak ⌘-C (physical "I" key) copies
// instead of focusing the Assistant input. RND-11340.
ignoreEventWhen: (e) => e.key.toLowerCase() !== 'i',
}
);
@@ -63,6 +90,8 @@ export function AIChatInput(props: {
sizing="large"
label="Assistant chat input"
placeholder={tString(language, 'ai_chat_input_placeholder')}
value={value}
onValueChange={setValue}
onSubmit={(val) => onSubmit(val as string)}
submitButton={{
size: 'small',
@@ -82,7 +111,7 @@ export function AIChatInput(props: {
}
: undefined
}
disabled={disabled || responding || chat.control !== null}
disabled={disabled || chat.control !== null}
aria-busy={responding}
ref={inputRef}
header={
@@ -0,0 +1,44 @@
import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
import { Icon } from '@gitbook/icons';
import { Button, Tooltip } from '../primitives';
/**
* Shows a follow-up the visitor submitted while the assistant was still answering. It mirrors a
* sent user message a right-aligned, tinted bubble so it reads as "theirs", with a clock icon
* marking it as pending and a tooltip (on the whole bubble) explaining it will be sent once the
* current answer finishes. The × beside the bubble drops it from the queue.
*/
export function AIChatQueuedMessage(props: {
message: string;
assistantName: string;
onRemove: () => void;
}) {
const { message, assistantName, onRemove } = props;
const language = useLanguage();
return (
<div className="flex max-w-[80%] origin-top-right animate-scale-in items-center gap-1 self-end">
<Tooltip label={t(language, 'ai_chat_queued_message', assistantName)}>
<div
className={tcls(
'flex min-w-0 items-center gap-2 circular-corners:rounded-2xl rounded-corners:rounded-md',
'bg-primary-solid/1 px-4 py-2 text-tint'
)}
>
<Icon icon="clock" className="size-3.5 shrink-0 text-tint" />
<span className="min-w-0 break-words">{message}</span>
</div>
</Tooltip>
<Button
variant="blank"
size="small"
iconOnly
icon="xmark"
label={t(language, 'clear')}
onClick={onRemove}
className="shrink-0 text-tint"
/>
</div>
);
}
@@ -33,7 +33,7 @@ export function AIChatReferenceChips(props: {
ref.type === 'code-block' && 'font-mono'
)}
>
{ref.label}
{ref.type === 'text' ? ref.content : ref.label}
</span>
</>
);
@@ -55,6 +55,10 @@ export function AIChatReferenceChips(props: {
>
{content}
</Link>
) : ref.type === 'text' ? (
// A text selection has no persistent DOM anchor to navigate to, so the
// excerpt is shown as plain (non-interactive) content.
<span className={triggerClassName}>{content}</span>
) : (
<button
type="button"
@@ -94,6 +98,8 @@ function getReferenceIcon(ref: AIChatReference): IconName {
return 'code';
case 'page':
return 'memo';
case 'text':
return 'quote-left';
default:
assertNever(ref);
}
@@ -0,0 +1,83 @@
'use client';
import { tcls } from '@/lib/tailwind';
import React from 'react';
import { useAIChatWidthStore } from './useAIChatWidthStore';
function setResizing(active: boolean) {
document.documentElement.dataset.aiChatResizing = String(active);
}
export function AIChatResizeHandle() {
const setWidth = useAIChatWidthStore((state) => state.setWidth);
const frameRef = React.useRef<number | null>(null);
const widthRef = React.useRef(0);
React.useEffect(() => {
const onResize = () => useAIChatWidthStore.getState().syncWidth();
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current);
}
setResizing(false);
};
}, []);
const stopResizing = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current);
frameRef.current = null;
}
setResizing(false);
};
const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
widthRef.current = useAIChatWidthStore.getState().width;
setResizing(true);
};
const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) {
return;
}
// Panel is right-anchored, so its width is the distance from the cursor to the right edge.
widthRef.current = window.innerWidth - event.clientX;
if (frameRef.current === null) {
frameRef.current = requestAnimationFrame(() => {
frameRef.current = null;
widthRef.current = setWidth(widthRef.current);
});
}
};
const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) {
return;
}
setWidth(widthRef.current);
stopResizing(event);
};
return (
<div
aria-hidden="true"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={stopResizing}
className={tcls(
'group -translate-x-1/2 absolute inset-y-0 left-0 z-10 hidden w-3 cursor-col-resize touch-none lg:flex',
'items-stretch justify-center'
)}
>
<span className="h-full w-px rounded-full bg-transparent transition-all duration-150 ease-out group-hover:w-0.5 group-hover:bg-primary-solid/40 group-active:w-0.5 group-active:bg-primary-solid" />
</div>
);
}
@@ -0,0 +1,79 @@
'use client';
import fnv1a from '@sindresorhus/fnv1a';
import { useAIChatController, useAIConfig } from '@/components/AI';
import { Button } from '@/components/primitives';
import { t, tString, useLanguage } from '@/intl/client';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { AIChatIcon } from '../AIChatIcon';
/**
* A small icon button revealed in the left margin of a top-level paragraph when it is hovered (on
* devices with a fine pointer). Clicking it stages the paragraph's text as a reference and opens
* the AI chat a more discoverable variant of the text-selection "Ask" affordance.
*
* The button is absolutely positioned so it never affects the document flow, and its visibility is
* driven purely by the `group/ask-ai` hover state of its paragraph wrapper.
*/
export function AskAIParagraphButton(props: { content: string; className?: ClassValue }) {
const { content, className } = props;
const config = useAIConfig();
const language = useLanguage();
const chatController = useAIChatController();
const onClick = () => {
const text = content.trim();
if (!text) {
return;
}
chatController.addReference({
type: 'text',
id: `text-${fnv1a(text, { size: 32 })}`,
content: text,
});
chatController.open();
chatController.setDraft(tString(language, 'ai_chat_paragraph_draft'));
chatController.focus();
};
return (
<div
className={tcls(
// Sit in the left margin, flush against the paragraph so there is no hover gap.
'absolute top-0 right-full z-10 pr-1',
// Per-block nudges: `in-[…]` matches an ancestor (tag or class) with no markup
// changes elsewhere — add a self-contained rule per block type to clear its gutter.
'in-[.hint]:-top-0.5 in-[.hint]:pr-2',
'in-[li]:-left-14',
'in-[blockquote]:pr-0',
// Hover affordance only: hidden until the paragraph (or the button) is hovered.
'invisible opacity-0 transition-opacity duration-150',
'hover:visible hover:opacity-100 group-hover/ask-ai:visible group-hover/ask-ai:opacity-100',
// Never shown on touch / hover-less contexts.
'not-pointer-fine:hidden',
// Hidden where an overflow-clipped ancestor would cut it off (tables, record cards).
'in-[[role=table]]:hidden',
'in-[[data-card]]:hidden',
className
)}
>
<Button
variant="blank"
size="xsmall"
iconOnly
icon={<AIChatIcon state="default" trademark={config.trademark} />}
label={t(language, 'ask')}
onClick={onClick}
// Don't steal focus (and shift the scroll position) when clicked with the mouse.
onMouseDown={(event) => event.preventDefault()}
className={tcls(
'bg-tint-base',
'in-[.hint.bg-danger]:bg-danger in-[.hint.bg-info]:bg-info in-[.hint.bg-success]:bg-success in-[.hint.bg-warning]:bg-warning'
)}
/>
</div>
);
}
@@ -0,0 +1 @@
export * from './AskAIParagraphButton';
@@ -0,0 +1,129 @@
'use client';
import fnv1a from '@sindresorhus/fnv1a';
import { AnimatePresence, motion } from 'motion/react';
import * as React from 'react';
import { createPortal } from 'react-dom';
import { useAIChatController, useAIConfig } from '@/components/AI';
import { useIsMobile } from '@/components/hooks/useIsMobile';
import { useIsMounted } from '@/components/hooks/useIsMounted';
import { Button } from '@/components/primitives';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { t, useLanguage } from '@/intl/client';
import { AIChatIcon } from '../AIChatIcon';
import { useStableTextSelection } from './useStableTextSelection';
/** Gap between the selection and the button. */
const GAP = 8;
/** Minimum distance to the viewport edges. */
const MARGIN = 8;
/**
* Floating "Ask" button anchored above a text selection. Clicking it stages the selection as a
* reference and opens the AI chat. Only rendered in Assistant mode, on non-touch devices.
*/
export function AskAITextSelection() {
const config = useAIConfig();
const language = useLanguage();
const chatController = useAIChatController();
const isMobile = useIsMobile();
const isMounted = useIsMounted();
const enabled = isAIChatEnabled(config.aiMode) && !isMobile;
const toolbarRef = React.useRef<HTMLDivElement>(null);
const { selection, clear } = useStableTextSelection({
rootSelector: '[data-content-ref-root]',
enabled,
ignoreRef: toolbarRef,
});
const [coords, setCoords] = React.useState<{ top: number; left: number } | null>(null);
// Position once the button has been measured, so it can be centered and clamped to the viewport.
React.useLayoutEffect(() => {
if (!selection) {
return;
}
const el = toolbarRef.current;
if (!el) {
return;
}
const width = el.offsetWidth;
const height = el.offsetHeight;
const { anchor } = selection;
let top = anchor.top - GAP - height;
if (top < MARGIN) {
// Not enough room above the selection: drop below it.
top = anchor.bottom + GAP;
}
top = Math.min(top, window.innerHeight - height - MARGIN);
const left = Math.min(
Math.max(anchor.centerX - width / 2, MARGIN),
window.innerWidth - width - MARGIN
);
setCoords({ top, left });
}, [selection]);
const onClick = () => {
if (!selection) {
return;
}
const content = selection.text;
if (!content.trim()) {
return;
}
chatController.addReference({
type: 'text',
id: `text-${fnv1a(content, { size: 32 })}`,
content,
});
chatController.open();
chatController.focus();
clear();
};
if (!enabled || !isMounted) {
return null;
}
return createPortal(
<AnimatePresence>
{selection ? (
<motion.div
ref={toolbarRef}
initial={{ opacity: 0, scale: 0.92 }}
animate={{ opacity: coords ? 1 : 0, scale: 1 }}
exit={{ opacity: 0, scale: 0.92 }}
transition={{ duration: 0.12, ease: 'easeOut' }}
style={{
position: 'fixed',
top: coords?.top ?? 0,
left: coords?.left ?? 0,
zIndex: 40,
}}
// Keep the selection alive: prevent the button from stealing focus on click.
onMouseDown={(event) => event.preventDefault()}
>
<Button
size="small"
variant="primary"
icon={<AIChatIcon state="default" trademark={config.trademark} />}
onClick={onClick}
className="shadow-sm"
>
{t(language, 'ask')}
</Button>
</motion.div>
) : null}
</AnimatePresence>,
document.body
);
}
@@ -0,0 +1 @@
export * from './AskAITextSelection';
@@ -0,0 +1,202 @@
'use client';
import * as React from 'react';
type SelectionAnchor = {
top: number;
bottom: number;
centerX: number;
};
export type StableTextSelection = {
anchor: SelectionAnchor;
text: string;
};
type Options = {
/** Selector of the content root; both selection endpoints must be inside it. */
rootSelector: string;
enabled: boolean;
/** Pointer events inside this element are ignored, so clicking the UI keeps the selection. */
ignoreRef: React.RefObject<HTMLElement | null>;
};
const KEYBOARD_DEBOUNCE_MS = 250;
const SCROLL_SETTLE_MS = 200;
// Coalesces the rapid down/up bursts of a double/triple-click into a single, non-flashing show.
const POINTER_SETTLE_MS = 120;
/**
* Track a stable text selection within `rootSelector`, debounced so the floating UI it powers
* doesn't flicker mid-gesture. The selection is dropped on collapse, window blur, scroll, and
* when a new gesture starts.
*/
export function useStableTextSelection(options: Options): {
selection: StableTextSelection | null;
clear: () => void;
} {
const { rootSelector, enabled, ignoreRef } = options;
const [selection, setSelection] = React.useState<StableTextSelection | null>(null);
const clear = React.useCallback(() => {
window.getSelection()?.removeAllRanges();
setSelection(null);
}, []);
React.useEffect(() => {
if (!enabled) {
setSelection(null);
return;
}
let pointerDown = false;
let keyboardTimer: ReturnType<typeof setTimeout> | null = null;
let scrollTimer: ReturnType<typeof setTimeout> | null = null;
let finalizeTimer: ReturnType<typeof setTimeout> | null = null;
const clearKeyboardTimer = () => {
if (keyboardTimer) {
clearTimeout(keyboardTimer);
keyboardTimer = null;
}
};
const clearFinalizeTimer = () => {
if (finalizeTimer) {
clearTimeout(finalizeTimer);
finalizeTimer = null;
}
};
const finalize = () => {
// A new gesture started; it will reschedule its own finalize.
if (pointerDown) {
return;
}
setSelection(readStableSelection(rootSelector));
};
const schedulePointerFinalize = () => {
clearKeyboardTimer();
clearFinalizeTimer();
finalizeTimer = setTimeout(() => {
finalizeTimer = null;
finalize();
}, POINTER_SETTLE_MS);
};
const isIgnored = (target: EventTarget | null) =>
target instanceof Node && !!ignoreRef.current?.contains(target);
const onSelectionChange = () => {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || sel.rangeCount === 0 || !sel.toString().trim()) {
clearKeyboardTimer();
setSelection(null);
return;
}
// Mid-drag, or a pointer finalize is already queued: let the gesture settle first.
if (pointerDown || finalizeTimer) {
return;
}
clearKeyboardTimer();
keyboardTimer = setTimeout(finalize, KEYBOARD_DEBOUNCE_MS);
};
const onPointerDown = (event: PointerEvent) => {
if (isIgnored(event.target)) {
return;
}
// New gesture: hide and cancel a pending show so it can't fire mid double-click.
pointerDown = true;
clearFinalizeTimer();
setSelection(null);
};
const onPointerUp = (event: PointerEvent) => {
if (isIgnored(event.target)) {
return;
}
pointerDown = false;
schedulePointerFinalize();
};
// pointercancel replaces pointerup when a gesture is interrupted (OS gesture, scroll handoff).
const onPointerCancel = () => {
pointerDown = false;
schedulePointerFinalize();
};
const onScroll = () => {
setSelection(null);
if (scrollTimer) {
clearTimeout(scrollTimer);
}
scrollTimer = setTimeout(() => {
if (!pointerDown) {
finalize();
}
}, SCROLL_SETTLE_MS);
};
const onWindowBlur = () => {
clearKeyboardTimer();
setSelection(null);
};
document.addEventListener('selectionchange', onSelectionChange);
document.addEventListener('pointerdown', onPointerDown, true);
document.addEventListener('pointerup', onPointerUp, true);
document.addEventListener('pointercancel', onPointerCancel, true);
window.addEventListener('scroll', onScroll, true);
window.addEventListener('blur', onWindowBlur);
return () => {
document.removeEventListener('selectionchange', onSelectionChange);
document.removeEventListener('pointerdown', onPointerDown, true);
document.removeEventListener('pointerup', onPointerUp, true);
document.removeEventListener('pointercancel', onPointerCancel, true);
window.removeEventListener('scroll', onScroll, true);
window.removeEventListener('blur', onWindowBlur);
clearKeyboardTimer();
clearFinalizeTimer();
if (scrollTimer) {
clearTimeout(scrollTimer);
}
};
}, [enabled, rootSelector, ignoreRef]);
return { selection, clear };
}
function readStableSelection(rootSelector: string): StableTextSelection | null {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || sel.rangeCount === 0) {
return null;
}
const text = sel.toString().trim();
if (!text) {
return null;
}
const root = document.querySelector(rootSelector);
if (!root || !root.contains(sel.anchorNode) || !root.contains(sel.focusNode)) {
return null;
}
const anchor = getSelectionAnchor(sel);
return anchor ? { anchor, text } : null;
}
/** Box centered above the whole selection, or null if it has no size or is scrolled out of view. */
function getSelectionAnchor(sel: Selection): SelectionAnchor | null {
const rect = sel.getRangeAt(0).getBoundingClientRect();
if (!rect.width && !rect.height) {
return null;
}
if (rect.bottom < 0 || rect.top > window.innerHeight) {
return null;
}
return { top: rect.top, bottom: rect.bottom, centerX: rect.left + rect.width / 2 };
}
@@ -3,3 +3,5 @@ export * from './AIChatButton';
export * from './AIChatIcon';
export * from './AIResponseFeedback';
export * from './AIChatControlButton';
export * from './AskAITextSelection';
export * from './AskAIParagraphButton';
@@ -0,0 +1,78 @@
'use client';
import {
getLocalStorageItem,
removeLocalStorageItem,
setLocalStorageItem,
} from '@/lib/browser/local-storage';
import { create } from 'zustand';
import { type StorageValue, persist } from 'zustand/middleware';
const AI_CHAT_MIN_WIDTH = 384;
const AI_CHAT_MAX_WIDTH = 640;
const MIN_CONTENT_WIDTH = 720;
type AIChatWidthStore = {
width: number;
toggleWidth: () => void;
setWidth: (width: number) => number;
syncWidth: () => void;
};
type PersistedState = Pick<AIChatWidthStore, 'width'>;
export const useAIChatWidthStore = create<AIChatWidthStore>()(
persist(
(set, get) => ({
width: AI_CHAT_MIN_WIDTH,
toggleWidth: () =>
get().setWidth(
get().width >= AI_CHAT_MAX_WIDTH ? AI_CHAT_MIN_WIDTH : AI_CHAT_MAX_WIDTH
),
setWidth: (width) => {
const clamped = clampWidth(width);
if (get().width !== clamped) {
set({ width: clamped });
}
setWidthOnViewport(clamped);
return clamped;
},
syncWidth: () => setWidthOnViewport(get().width),
}),
{
name: '@gitbook/ai-chat-width',
storage: {
getItem: (name) =>
getLocalStorageItem<StorageValue<PersistedState> | null>(name, null),
setItem: (name, value) => setLocalStorageItem(name, value),
removeItem: (name) => removeLocalStorageItem(name),
},
partialize: (state) => ({ width: state.width }),
onRehydrateStorage: () => (state) => state?.syncWidth(),
}
)
);
/**
* Whether the panel is at its maximum width.
*/
export const useIsAIChatMaxWidth = () =>
useAIChatWidthStore((state) => state.width >= AI_CHAT_MAX_WIDTH);
// Hoisted so the synchronous persist rehydrate (during create() above) can call them before this point.
function setWidthOnViewport(width: number) {
if (typeof document !== 'undefined') {
document.documentElement.style.setProperty('--ai-chat-width', `${capToViewport(width)}px`);
}
}
function clampWidth(width: number) {
return Math.min(AI_CHAT_MAX_WIDTH, Math.max(AI_CHAT_MIN_WIDTH, Math.round(width)));
}
// Cap a width so the remaining content keeps a usable minimum at the current viewport.
function capToViewport(width: number) {
return typeof window === 'undefined'
? width
: Math.min(width, Math.max(AI_CHAT_MIN_WIDTH, window.innerWidth - MIN_CONTENT_WIDTH));
}
@@ -1,5 +1,6 @@
import type { GitBookSiteContext } from '@/lib/context';
import { AdminToolbarClient } from './AdminToolbarClient';
import { getToolbarChangedPages } from './changedPages';
import type { AdminToolbarContext } from './types';
export interface AdminToolbarProps {
@@ -11,6 +12,7 @@ export interface AdminToolbarProps {
*/
export async function AdminToolbar(props: AdminToolbarProps) {
const { context } = props;
const changedPages = await getToolbarChangedPages(context);
// Create a minimal context to avoid serializing and passing too many data to the client
const minimalContext: AdminToolbarContext = {
@@ -57,6 +59,7 @@ export async function AdminToolbar(props: AdminToolbarProps) {
published: context.site.urls.published,
},
},
changedPages,
};
return <AdminToolbarClient context={minimalContext} />;
@@ -4,6 +4,7 @@ import { MotionConfig, motion } from 'motion/react';
import { useCheckForContentUpdate } from '../AutoRefreshContent';
import { useVisitor } from '../Insights';
import { useCurrentPagePath } from '../hooks';
import { ChangedPagesButton } from './ChangedPagesButton';
import { HideToolbarButton } from './HideToolbarButton';
import { IframeWrapper } from './IframeWrapper';
import { RefreshContentButton } from './RefreshContentButton';
@@ -150,6 +151,8 @@ function ChangeRequestToolbar(props: ToolbarViewProps) {
<ToolbarActions>
{/* Refresh to retrieve latest changes */}
{updated ? <RefreshContentButton refreshForUpdates={refreshForUpdates} /> : null}
{/* View a popover with quick links to the changed pages */}
<ChangedPagesButton changedPages={context.changedPages} />
{/* Edit in GitBook */}
<EditPageButton href={changeRequest.urls.app} siteId={site.id} />
@@ -211,6 +214,9 @@ function RevisionToolbar(props: ToolbarViewProps) {
<ToolbarSubtitle subtitle={<ToolbarDate value={revision.createdAt} />} />
</ToolbarBody>
<ToolbarActions>
{/* View a popover with quick links to the changed pages */}
<ChangedPagesButton changedPages={context.changedPages} />
{/* Open commit in Git client */}
<ToolbarButton
title={
@@ -0,0 +1,172 @@
'use client';
import { tcls } from '@/lib/tailwind';
import { Icon, type IconName, IconStyle } from '@gitbook/icons';
import { motion, useReducedMotion } from 'motion/react';
import type { SVGProps } from 'react';
import { DropdownMenu, DropdownMenuItem, DropdownMenuSeparator } from '../primitives';
import type { ToolbarButtonProps } from './Toolbar';
import type { MinimalChangedPage, MinimalChangedPages } from './types';
const STATUS_ICON_STYLES: Record<
MinimalChangedPage['status'],
{ chip: string; icon: IconName; iconClassName: string; iconStyle?: IconStyle }
> = {
created: {
chip: 'border-green-200 bg-green-50',
icon: 'plus',
iconClassName: 'size-3.5 text-green-600',
},
edited: {
chip: 'border-blue-200 bg-blue-50',
icon: 'pencil',
iconClassName: 'size-3 text-blue-600',
iconStyle: IconStyle.Regular,
},
moved: {
chip: 'border-blue-200 bg-blue-50',
icon: 'arrow-right',
iconClassName: 'size-3 text-blue-600',
},
deleted: {
chip: 'border-red-200 bg-red-50',
icon: 'minus',
iconClassName: 'size-3 text-red-600',
},
};
const STATUS_ICON_CHIP_CLASS = 'flex size-5 shrink-0 items-center justify-center rounded-md border';
/**
* A button that opens a popover with quick links to the _changed_ pages.
*/
export function ChangedPagesButton(props: {
changedPages: MinimalChangedPages | null;
motionValues?: ToolbarButtonProps['motionValues'];
}) {
const { changedPages, motionValues } = props;
const reduceMotion = useReducedMotion();
if (!changedPages?.pages.length) {
return null;
}
const changedPagesCount = changedPages.pages.length + changedPages.more;
const changedPagesLabel = `${changedPagesCount} changed ${
changedPagesCount === 1 ? 'page' : 'pages'
}`;
const trigger = (
<button
type="button"
aria-label="View changed pages"
className="relative size-8 cursor-pointer border-0 bg-transparent p-0"
>
<motion.span
aria-hidden="true"
style={
reduceMotion
? undefined
: {
scale: motionValues?.scale,
x: motionValues?.x,
transformOrigin: 'bottom center',
zIndex: motionValues?.scale ? 10 : 'auto',
}
}
transition={{
type: 'spring',
stiffness: 400,
damping: 30,
}}
className={tcls(
'toolbar-button',
'relative flex size-8 items-center justify-center gap-1 truncate rounded-full text-sm transition-colors',
'text-tint-7 hover:text-tint-1',
'dark:text-tint-12',
'bg-[var(--toolbar-bg)]',
'hover:bg-[color-mix(in_srgb,var(--toolbar-bg)_90%,white)]'
)}
>
<DiffIcon className="size-4 shrink-0" />
</motion.span>
</button>
);
return (
<DropdownMenu
button={trigger}
buttonTooltip="View changed pages"
side="top"
align="end"
sideOffset={12}
className="w-80 max-w-[calc(100vw-2rem)] gap-0 overflow-hidden p-0"
>
<div className="px-3 py-2 font-medium text-sm text-tint">{changedPagesLabel}</div>
<DropdownMenuSeparator className="m-0" />
<div className="flex max-h-80 flex-col overflow-y-auto">
{changedPages.pages.map((page) => (
<ChangedPageMenuItem key={page.id} page={page} />
))}
</div>
{changedPages.more > 0 ? (
<>
<DropdownMenuSeparator />
<div className="px-3 py-1 text-tint-subtle text-xs">
{changedPages.more} more changes not shown
</div>
</>
) : null}
</DropdownMenu>
);
}
function ChangedPageMenuItem(props: { page: MinimalChangedPage }) {
const { page } = props;
const actionLabel = page.action === 'editor' ? 'Open in editor' : 'Open';
return (
<DropdownMenuItem
href={page.href}
className="group/changed-page relative w-full min-w-0 items-center rounded-none px-3 py-1.5"
>
<span className="flex min-w-0 flex-1 items-center gap-2">
<ChangedPageStatusIcon status={page.status} />
<span className="min-w-0 flex-1 transition-[padding] group-hover/changed-page:pr-24 group-focus-visible/changed-page:pr-24 group-data-[highlighted]/changed-page:pr-24">
<span className="block truncate font-medium text-sm leading-4">
{page.title}
</span>
<span className="block truncate text-tint-subtle text-xs leading-4">
/{page.path || ''}
</span>
</span>
<span className="pointer-events-none absolute right-2 flex items-center gap-0.5 bg-tint-hover pl-3 text-tint-subtle text-xs opacity-0 transition-opacity group-hover/changed-page:opacity-100 group-focus-visible/changed-page:opacity-100 group-data-[highlighted]/changed-page:opacity-100">
{actionLabel}
<Icon icon="chevron-right" className="size-3 shrink-0" />
</span>
</span>
</DropdownMenuItem>
);
}
function ChangedPageStatusIcon(props: { status: MinimalChangedPage['status'] }) {
const { status } = props;
const style = STATUS_ICON_STYLES[status];
return (
<span className={tcls(STATUS_ICON_CHIP_CLASS, style.chip)}>
<Icon icon={style.icon} iconStyle={style.iconStyle} className={style.iconClassName} />
</span>
);
}
function DiffIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg fill="none" viewBox="0 0 16 16" aria-hidden="true" {...props}>
<path
fill="currentColor"
d="M8 2.4a.6.6 0 0 1 .6.6v2.9h2.9a.6.6 0 1 1 0 1.2H8.6V10a.6.6 0 1 1-1.2 0V7.1H4.5a.6.6 0 0 1 0-1.2h2.9V3a.6.6 0 0 1 .6-.6M4.5 12.4a.6.6 0 1 0 0 1.2h7a.6.6 0 1 0 0-1.2z"
/>
</svg>
);
}
@@ -105,7 +105,10 @@ export function Toolbar(props: ToolbarProps) {
}
return (
<motion.div className="-translate-x-1/2 fixed bottom-5 left-1/2 z-40 w-auto max-w-xl transform px-4">
<motion.div
data-testid="admin-toolbar"
className="-translate-x-1/2 fixed bottom-5 left-1/2 z-40 w-auto max-w-xl transform px-4"
>
<ToolbarVisibilityHint show={showHint} />
<AnimatePresence mode="wait">
@@ -0,0 +1,57 @@
import type { GitBookSiteContext } from '@/lib/context';
import { getDataOrNull, ignoreAllThrownError } from '@/lib/data';
import { getToolbarChangedPagesFromChanges } from './changedPagesMapper';
import type { MinimalChangedPages } from './types';
export const TOOLBAR_CHANGED_PAGES_LIMIT = 100;
/**
* Fetch and reduce semantic changes to the minimal list needed by the toolbar client.
*/
export async function getToolbarChangedPages(
context: GitBookSiteContext
): Promise<MinimalChangedPages | null> {
// The changed-pages list is a non-critical toolbar enhancement. Any failure to fetch or
// reduce the changes should simply hide the button, never break rendering of the site page.
return ignoreAllThrownError(fetchToolbarChangedPages(context));
}
async function fetchToolbarChangedPages(
context: GitBookSiteContext
): Promise<MinimalChangedPages | null> {
const changes = context.changeRequest
? await getDataOrNull(
context.dataFetcher.getChangeRequestChanges({
spaceId: context.space.id,
changeRequestId: context.changeRequest.id,
limit: TOOLBAR_CHANGED_PAGES_LIMIT,
})
)
: context.revisionId !== context.space.revision
? await getDataOrNull(
context.dataFetcher.getRevisionSemanticChanges({
spaceId: context.space.id,
revisionId: context.revisionId,
limit: TOOLBAR_CHANGED_PAGES_LIMIT,
})
)
: null;
if (!changes) {
return null;
}
const pages = getToolbarChangedPagesFromChanges({
changes: changes.changes,
editorBaseURL: context.changeRequest?.urls.app ?? context.revision.urls.app,
linker: context.linker,
pages: context.revision.pages,
});
return pages.length > 0
? {
pages,
more: changes.more ?? 0,
}
: null;
}
@@ -0,0 +1,114 @@
import type { GitBookLinker } from '@/lib/links';
import { getPagePath, resolvePageId } from '@/lib/pages';
import { joinPathWithBaseURL } from '@/lib/paths';
import {
type ChangedRevisionPage,
type Revision,
RevisionPageType,
type RevisionSemanticChange,
} from '@gitbook/api';
import type { MinimalChangedPage } from './types';
// When one page has multiple semantic changes, show the label that best summarizes its final state.
const CHANGE_STATUS_SUMMARY_ORDER: Array<MinimalChangedPage['status']> = [
'edited',
'moved',
'created',
'deleted',
];
export function getToolbarChangedPagesFromChanges(input: {
changes: RevisionSemanticChange[];
linker: Pick<GitBookLinker, 'toPathForPage'>;
pages: Revision['pages'];
editorBaseURL: string;
}): MinimalChangedPage[] {
const changedPages = new Map<string, MinimalChangedPage>();
for (const change of input.changes) {
// Only real document page changes can become toolbar rows; computed/link/group pages are ignored.
const pageChange = getChangedPageChange(change);
if (!pageChange || pageChange.page.type !== RevisionPageType.Document) {
continue;
}
// Resolve against the current revision so preview links use the current title and path.
const resolved = resolvePageId(input.pages, pageChange.page.id);
const isDeleted = pageChange.status === 'deleted';
const currentPage = resolved?.page;
const path = currentPage ? getPagePath(input.pages, currentPage) : pageChange.page.path;
if (!path && !currentPage) {
continue;
}
// Missing non-deleted pages cannot be linked reliably from the preview.
if (!currentPage && !isDeleted) {
continue;
}
// Deleted pages may no longer exist in the preview, so link to their editor change.
if (!currentPage) {
changedPages.set(pageChange.page.id, {
id: pageChange.page.id,
title: pageChange.page.title,
path: path ?? '',
href: joinPathWithBaseURL(input.editorBaseURL, path ?? ''),
status: pageChange.status,
action: 'editor',
});
continue;
}
const pageId = currentPage.id;
const existing = changedPages.get(pageId);
// The API can return multiple changes for one page; keep the clearest one-row summary.
if (existing && shouldKeepExistingPageChange(existing.status, pageChange.status)) {
continue;
}
changedPages.set(pageId, {
id: pageId,
title: currentPage.title,
path: path ?? '',
href: isDeleted
? joinPathWithBaseURL(input.editorBaseURL, path ?? '')
: input.linker.toPathForPage({
pages: input.pages,
page: currentPage,
}),
status: pageChange.status,
action: isDeleted ? 'editor' : 'preview',
});
}
return Array.from(changedPages.values());
}
function getChangedPageChange(
change: RevisionSemanticChange
): { page: ChangedRevisionPage; status: MinimalChangedPage['status'] } | null {
switch (change.type) {
case 'page_created':
return { page: change.page, status: 'created' };
case 'page_edited':
return { page: change.page, status: 'edited' };
case 'page_moved':
return { page: change.page, status: 'moved' };
case 'page_deleted':
return { page: change.page, status: 'deleted' };
default:
return null;
}
}
function shouldKeepExistingPageChange(
existing: MinimalChangedPage['status'],
next: MinimalChangedPage['status']
) {
return getChangeStatusSummaryIndex(existing) >= getChangeStatusSummaryIndex(next);
}
function getChangeStatusSummaryIndex(status: MinimalChangedPage['status']) {
return CHANGE_STATUS_SUMMARY_ORDER.indexOf(status);
}
@@ -43,6 +43,20 @@ export type MinimalSite = {
};
};
export type MinimalChangedPage = {
id: string;
title: string;
path: string;
href: string;
status: 'created' | 'edited' | 'moved' | 'deleted';
action: 'preview' | 'editor';
};
export type MinimalChangedPages = {
pages: MinimalChangedPage[];
more: number;
};
export type AdminToolbarContext = {
organizationId: string;
revisionId: string;
@@ -50,6 +64,7 @@ export type AdminToolbarContext = {
changeRequest: MinimalChangeRequest | null;
revision: MinimalRevision;
site: MinimalSite;
changedPages: MinimalChangedPages | null;
};
export interface AdminToolbarClientProps {
@@ -42,7 +42,7 @@ export function AnnouncementBanner(props: {
className="theme-bold:bg-header-background pt-4 pb-2"
data-nosnippet=""
>
<div className="transition-all duration-300 motion-reduce:transition-none lg:chat-open:pr-80 xl:chat-open:pr-96">
<div className="transition-all duration-300 motion-reduce:transition-none lg:chat-open:pr-(--ai-chat-width)">
<div className={tcls('relative', CONTAINER_STYLE)}>
<Tag
href={contentRef?.href ?? ''}
@@ -80,8 +80,7 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
'max-w-md',
'text-balance',
'sm:left-auto',
'lg:chat-open:mr-80',
'xl:chat-open:mr-100',
'lg:chat-open:mr-(--ai-chat-width)',
'transition-all',
'motion-reduce:transition-none',
'duration-300',
@@ -28,6 +28,7 @@ import { ListItem } from './ListItem';
import { BlockMath } from './Math';
import { OpenAPIOperation, OpenAPISchemas, OpenAPIWebhook } from './OpenAPI';
import { Paragraph } from './Paragraph';
import { Prompt } from './Prompt';
import { Quote } from './Quote';
import { ReusableContent } from './ReusableContent';
import { Stepper } from './Stepper';
@@ -111,6 +112,8 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
return <Updates {...props} block={block} />;
case 'update':
return <Update {...props} block={block} />;
case 'prompt':
return <Prompt {...props} block={block} />;
case 'if':
// If block should be processed by the API.
return null;
@@ -151,6 +154,7 @@ export function BlockSkeleton(props: { block: DocumentBlock; style: ClassValue }
case 'hint':
case 'tabs':
case 'stepper-step':
case 'prompt':
case 'if':
return <SkeletonParagraph id={id} className={style} />;
case 'expandable':
@@ -1,10 +1,9 @@
'use client';
import { CustomizationAIMode } from '@gitbook/api';
import { useAIChatController, useAIConfig } from '@/components/AI';
import { AIChatIcon } from '@/components/AIChat';
import { Button } from '@/components/primitives';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { t, useLanguage } from '@/intl/client';
import { type ClassValue, tcls } from '@/lib/tailwind';
@@ -22,7 +21,7 @@ export function AskAICodeButton(props: {
const config = useAIConfig();
const chatController = useAIChatController();
if (config.aiMode !== CustomizationAIMode.Assistant) {
if (!isAIChatEnabled(config.aiMode)) {
return null;
}
@@ -33,6 +33,7 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
const withLineNumbers = Boolean(block.data.lineNumbers) && block.nodes.length > 1;
const withWrap = block.data.overflow === 'wrap';
const title = block.data.title;
const isSingleLine = theme.lines.length <= 1 && !withWrap;
const id = useId();
const codeId = props.id || id;
@@ -79,7 +80,12 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
) : null}
</div>
<div className="relative flex min-h-0 flex-col">
<div className="absolute top-2 right-2 z-2 flex items-start gap-1.5 font-sans leading-none opacity-0 group-hover/codeblock:opacity-11 has-[button:focus-visible]:opacity-11">
<div
className={tcls(
'absolute right-2 z-2 flex items-center gap-1.5 font-sans leading-none opacity-0 group-hover/codeblock:opacity-11 has-[button:focus-visible]:opacity-11',
isSingleLine ? 'inset-y-0' : 'top-2'
)}
>
{!isPrint ? (
<AskAICodeButton
codeId={codeId}
@@ -92,7 +98,7 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
</div>
<pre
className={tcls(
'relative overflow-auto border border-tint-subtle bg-tint-subtle theme-bold-tint:bg-tint-base theme-muted:bg-tint-base py-2 text-tint-strong contrast-more:border-tint contrast-more:bg-tint-base print:overflow-visible',
'relative overflow-auto border border-tint-subtle bg-tint-subtle theme-bold-tint:bg-tint-base theme-muted:bg-tint-base py-2.5 text-tint-strong contrast-more:border-tint contrast-more:bg-tint-base print:overflow-visible',
'circular-corners:rounded-2xl rounded-corners:rounded-xl straight-corners:rounded-xs depth-subtle:shadow-xs',
title && 'rounded-ss-none!'
)}
@@ -36,6 +36,14 @@ export interface DocumentContext {
* @default false
*/
withLinkPreviews?: boolean;
/**
* True when this document is the main page body the only place a background page cover is
* shown behind the content. Cover-aware text styling (contrast over the cover) is scoped to it
* so auxiliary documents (search answers, AI chat, PDF export) don't inherit the cover colors.
* @default false
*/
isPageBody?: boolean;
}
export interface DocumentContextProps {
@@ -59,6 +59,9 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
'justify-self-start',
'max-w-full',
'break-words',
// Cover-aware contrast text applies only to the page body, not to documents
// rendered in overlays (search answers, AI chat) on a background-cover page.
context.isPageBody && 'page-cover-background:text-contrast-cover',
getTextAlignment(block.data.align),
textStyle.lineHeight
)}
@@ -92,6 +92,11 @@ export async function Hint({
'empty:p-0',
'-row-end-1',
'-col-end-1',
// Allow the grid track to shrink below its content's min-content size so wide
// nested blocks (e.g. code blocks, tables) scroll internally instead of
// overflowing the hint. Without this, the `1fr` column keeps its default
// `min-width: auto` and grows past the hint's width.
'min-w-0',
'space-y-3',
'[&_.hint]:border',
'[&_pre]:border',
@@ -4,6 +4,14 @@ import { useAI, useAIChatController, useAIChatState } from '../AI';
import { useSetSearchState } from '../Search';
import { Button, type ButtonProps, Input } from '../primitives';
// The Input primitive has no `xsmall`; otherwise it shares the button's size scale.
const INPUT_SIZE_MAP: Record<NonNullable<ButtonProps['size']>, 'small' | 'medium' | 'large'> = {
xsmall: 'small',
small: 'small',
medium: 'medium',
large: 'large',
};
export function InlineActionButton(
props: { action: 'ask' | 'search'; query?: string } & { buttonProps: ButtonProps } // TODO: Type this properly: Pick<api.DocumentInlineButton, 'action' | 'query'> & { buttonProps: ButtonProps }
) {
@@ -42,7 +50,7 @@ export function InlineActionButton(
<Input
inline
label={buttonProps.label as string}
sizing="medium"
sizing={INPUT_SIZE_MAP[buttonProps.size ?? 'medium']}
className="inline-flex max-w-full grow"
submitButton={{
label: tString(language, action === 'ask' ? 'send' : 'search'),
@@ -9,6 +9,16 @@ import type { InlineProps } from './Inline';
import { InlineActionButton } from './InlineActionButton';
import { NotFoundRefHoverCard } from './NotFoundRefHoverCard';
// Editor button sizes render one step smaller here; the editor default (`large`) keeps the previous `medium`.
const BUTTON_SIZE_MAP: Record<
NonNullable<api.DocumentInlineButton['data']['size']>,
ButtonProps['size']
> = {
small: 'xsmall',
medium: 'small',
large: 'medium',
};
export function InlineButton(props: InlineProps<api.DocumentInlineButton>) {
const { inline, context } = props;
@@ -16,7 +26,7 @@ export function InlineButton(props: InlineProps<api.DocumentInlineButton>) {
label: inline.data.label,
variant: inline.data.kind,
icon: inline.data.icon as IconName | undefined,
size: 'medium',
size: BUTTON_SIZE_MAP[inline.data.size ?? 'large'],
};
const ButtonImplementation = () => {
@@ -151,10 +151,7 @@ function InlineLinkTooltipWrapper(props: {
<InlineLinkTooltip
breadcrumbs={breadcrumbs}
isExternal={isExternal}
isSamePage={isSamePage}
openInNewTabLabel={tString(language, 'open_in_new_tab')}
target={{
href: resolved.href,
text: resolved.text,
subText: resolved.subText,
icon: resolved.icon,
@@ -2,91 +2,69 @@
import { tcls } from '@/lib/tailwind';
import { Icon } from '@gitbook/icons';
import { Fragment } from 'react';
import { Button, HoverCard, HoverCardRoot, HoverCardTrigger, StyledLink } from '../../primitives';
import { HoverCard, HoverCardRoot, HoverCardTrigger, StyledLink } from '../../primitives';
export function InlineLinkTooltip(props: {
isSamePage: boolean;
isExternal: boolean;
breadcrumbs: Array<{ href?: string; label: string; icon?: React.ReactNode }>;
target: {
href: string;
text: string;
subText?: string;
icon?: React.ReactNode;
};
openInNewTabLabel: string;
children: React.ReactNode;
}) {
const { isSamePage, isExternal, openInNewTabLabel, target, breadcrumbs, children } = props;
const { isExternal, target, breadcrumbs, children } = props;
return (
<HoverCardRoot>
<HoverCardTrigger>{children}</HoverCardTrigger>
<HoverCard className="p-4">
<div className="flex items-start gap-4">
<div className="flex flex-col">
{breadcrumbs && breadcrumbs.length > 0 ? (
<div className="mb-1 flex grow flex-wrap items-center gap-x-2 gap-y-0.5 font-semibold text-tint text-xs uppercase leading-tight tracking-wide">
{breadcrumbs.map((crumb, index) => {
const Tag = crumb.href ? StyledLink : 'div';
<div className="flex flex-col">
{breadcrumbs && breadcrumbs.length > 0 ? (
<div className="mb-1 flex grow flex-wrap items-center gap-x-2 gap-y-0.5 font-semibold text-tint text-xs uppercase leading-tight tracking-wide">
{breadcrumbs.map((crumb, index) => {
const Tag = crumb.href ? StyledLink : 'div';
return (
<Fragment key={crumb.label}>
{index !== 0 ? (
<Icon
icon="chevron-right"
className="size-3 text-tint-subtle"
/>
return (
<Fragment key={crumb.label}>
{index !== 0 ? (
<Icon
icon="chevron-right"
className="size-3 text-tint-subtle"
/>
) : null}
<Tag
className={tcls(
'flex gap-1',
crumb.href &&
'links-default:text-tint no-underline hover:underline contrast-more:underline contrast-more:decoration-current'
)}
href={crumb.href ?? '#'}
>
{crumb.icon ? (
<span className="mt-0.5 text-tint-subtle empty:hidden">
{crumb.icon}
</span>
) : null}
<Tag
className={tcls(
'flex gap-1',
crumb.href &&
'links-default:text-tint no-underline hover:underline contrast-more:underline contrast-more:decoration-current'
)}
href={crumb.href ?? '#'}
>
{crumb.icon ? (
<span className="mt-0.5 text-tint-subtle empty:hidden">
{crumb.icon}
</span>
) : null}
{crumb.label}
</Tag>
</Fragment>
);
})}
</div>
) : null}
<div
className={tcls(
'flex gap-2 leading-snug',
isExternal && 'wrap-anywhere text-sm'
)}
>
{target.icon ? (
<div className="mt-1 text-tint-subtle empty:hidden">
{target.icon}
</div>
) : null}
<h5 className="font-semibold">{target.text}</h5>
{crumb.label}
</Tag>
</Fragment>
);
})}
</div>
</div>
{!isSamePage && target.href ? (
<Button
className={tcls(
'-mx-2 -my-2 ml-auto',
breadcrumbs?.length === 0 ? 'place-self-center' : null
)}
variant="blank"
href={target.href}
target="_blank"
label={openInNewTabLabel}
size="small"
icon="arrow-up-right-from-square"
iconOnly={true}
/>
) : null}
<div
className={tcls(
'flex gap-2 leading-snug',
isExternal && 'wrap-anywhere text-sm'
)}
>
{target.icon ? (
<div className="mt-1 text-tint-subtle empty:hidden">{target.icon}</div>
) : null}
<h5 className="font-semibold">{target.text}</h5>
</div>
</div>
{target.subText ? <p className="mt-1 text-sm text-tint">{target.subText}</p> : null}
</HoverCard>
@@ -0,0 +1,9 @@
'use client';
import { createLazyStylesheet } from '../createLazyStylesheet';
/**
* Lazy-loads the ContentKit stylesheet so it only downloads on pages that actually render
* an integration block, instead of shipping in every page's CSS chunk.
*/
export default createLazyStylesheet(() => import('./contentkit.css'));
@@ -1,28 +0,0 @@
'use client';
import { useAdaptiveVisitor } from '@/components/Adaptive';
import { ContentKit, type ContentKitClientContextData } from '@gitbook/react-contentkit/client';
import React from 'react';
type ContentKitProps<RenderContext> = React.ComponentProps<typeof ContentKit<RenderContext>>;
/**
* ContentKit wrapper for integration blocks that need client-only adaptive context.
*/
export function ContentKitWithAdaptiveVisitorContext<RenderContext>(
props: ContentKitProps<RenderContext>
) {
const getAdaptiveVisitorClaims = useAdaptiveVisitor();
const visitorClaims = getAdaptiveVisitorClaims();
const clientContext = React.useMemo<ContentKitClientContextData>(
() => ({
getVisitorContext: () => ({
visitor: visitorClaims?.visitor ?? null,
}),
}),
[visitorClaims]
);
return <ContentKit {...props} clientContext={clientContext} />;
}
@@ -0,0 +1,70 @@
'use client';
import { useAdaptiveVisitor } from '@/components/Adaptive';
import { NavigationStatusContext } from '@/components/hooks';
import { type GitBookLinker, createLinker } from '@/lib/links';
import { ContentKit, type ContentKitClientContextData } from '@gitbook/react-contentkit/client';
import { useRouter } from 'next/navigation';
import React from 'react';
type ContentKitProps<RenderContext> = React.ComponentProps<typeof ContentKit<RenderContext>>;
/** Serializable inputs to rebuild the tested linker on the client (functions can't cross the RSC boundary). */
export type WebframeLinkerData = Pick<
Parameters<typeof createLinker>[0],
'host' | 'protocol' | 'siteBasePath' | 'spaceBasePath'
>;
/**
* ContentKit wrapper for integration blocks that expose client-only capabilities to webframes:
* navigation to other pages, and adaptive visitor claims (only when the integration is allowed to
* access them).
*/
export function ContentKitWithClientContext<RenderContext>(
props: ContentKitProps<RenderContext> & {
/** Whether visitor claims may be exposed to the webframe (integration scope gated). */
canAccessVisitorClaims: boolean;
/** Data to rebuild the site linker, used to resolve webframe navigation requests. */
linkerData: WebframeLinkerData;
}
) {
const { canAccessVisitorClaims, linkerData, ...contentKitProps } = props;
const router = useRouter();
const { onNavigationClick } = React.useContext(NavigationStatusContext);
const getAdaptiveVisitorClaims = useAdaptiveVisitor();
// Rebuild the (tested) linker on the client so navigation resolves paths exactly like the rest
// of the app, instead of duplicating the join logic here.
const linker = React.useMemo<GitBookLinker>(() => createLinker(linkerData), [linkerData]);
// Navigate to an in-site href, driving the same navigation progress bar as a regular link so
// the reader gets feedback while the destination page loads.
const navigateTo = React.useCallback(
(href: string) => {
onNavigationClick(href);
router.push(href);
},
[onNavigationClick, router]
);
// Read during render (Suspense) only when the integration is allowed visitor claims, so that
// webframes that don't use visitor claims don't suspend on the visitor-claims fetch.
const visitorClaims = canAccessVisitorClaims ? getAdaptiveVisitorClaims() : null;
const clientContext = React.useMemo<ContentKitClientContextData>(
() => ({
getVisitorContext: canAccessVisitorClaims
? () => ({ visitor: visitorClaims?.visitor ?? null })
: undefined,
navigate: ({ path, anchor }) => {
// Resolve the requested path relative to the site root so a webframe can navigate
// to any section or space within the site (and nowhere outside it).
const suffix = anchor ? `#${anchor}` : '';
navigateTo(linker.toPathInSite(path) + suffix);
},
}),
[canAccessVisitorClaims, visitorClaims, linker, navigateTo]
);
return <ContentKit {...contentKitProps} clientContext={clientContext} />;
}
@@ -1,16 +1,23 @@
import { GITBOOK_INTEGRATIONS_HOST } from '@/lib/env';
import { GITBOOK_INTEGRATIONS_CONTENT_HOST, GITBOOK_INTEGRATIONS_HOST } from '@/lib/env';
import { tcls } from '@/lib/tailwind';
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { ContentKit, ContentKitOutput } from '@gitbook/react-contentkit';
import React from 'react';
import type { GitBookLinker } from '@/lib/links';
import type { BlockProps } from '../Block';
import './contentkit.css';
import { ContentKitWithAdaptiveVisitorContext } from './ContentKitWithAdaptiveVisitorContext';
import { shouldRenderIntegrationBlockWithAdaptiveVisitorContext } from './adaptive';
import {
ContentKitWithClientContext,
type WebframeLinkerData,
} from './ContentKitWithClientContext';
import { integrationBlockContainsWebframe } from './adaptive';
import { contentKitServerContext } from './contentkit';
import { fetchSafeIntegrationUI } from './render';
import { renderIntegrationUi } from './server-actions';
// Lazy so the ContentKit CSS is only fetched on pages that render an integration block.
const ContentKitStyles = React.lazy(() => import('./ContentKitStyles'));
export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegration>) {
const { block, context, style } = props;
@@ -70,25 +77,71 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
return null;
}
const ContentKitComponent = shouldRenderIntegrationBlockWithAdaptiveVisitorContext(
initialOutput
)
? ContentKitWithAdaptiveVisitorContext
: ContentKit;
const containsWebframe = integrationBlockContainsWebframe(initialOutput);
const canAccessVisitorClaims = initialOutput.canAccessVisitorClaims === true;
// Any webframe uses the client-context wrapper: it enables navigation to other pages, plus
// visitor claims when the integration is allowed them.
const useClientContext = containsWebframe;
const contentKitProps = {
renderContext: {
integrationName: block.data.integration,
},
security: {
// Trust both the integrations host and the (cookieless) content host that
// serves rendered WebFrames. `ElementWebframe` gates inbound and outbound
// postMessage on this list, so a WebFrame served from the content host would
// break (no resize/ready/actions) if the content host weren't trusted.
// The hosts are identical until a distinct content origin is configured.
firstPartyDomains: [
...new Set([GITBOOK_INTEGRATIONS_HOST, GITBOOK_INTEGRATIONS_CONTENT_HOST]),
],
},
initialInput,
initialOutput,
render: renderIntegrationUi,
};
return (
<div className={tcls(style)}>
<ContentKitComponent
renderContext={{
integrationName: block.data.integration,
}}
security={{ firstPartyDomains: [GITBOOK_INTEGRATIONS_HOST] }}
initialInput={initialInput}
initialOutput={initialOutput}
render={renderIntegrationUi}
>
<ContentKitOutput output={initialOutput} context={contentKitServerContext} />
</ContentKitComponent>
<ContentKitStyles />
{useClientContext ? (
<ContentKitWithClientContext
{...contentKitProps}
canAccessVisitorClaims={canAccessVisitorClaims}
linkerData={getWebframeLinkerData(context.contentContext.linker)}
>
<ContentKitOutput output={initialOutput} context={contentKitServerContext} />
</ContentKitWithClientContext>
) : (
<ContentKit {...contentKitProps}>
<ContentKitOutput output={initialOutput} context={contentKitServerContext} />
</ContentKit>
)}
</div>
);
}
/**
* Extract the serializable data needed to rebuild the site linker on the client, so webframe
* navigation resolves paths through the same (tested) linker as the rest of the app.
*/
function getWebframeLinkerData(linker: GitBookLinker): WebframeLinkerData {
const data: WebframeLinkerData = {
siteBasePath: linker.siteBasePath,
spaceBasePath: linker.spaceBasePath,
};
// `host`/`protocol` are only used to build absolute URLs, which webframe navigation never does.
// Carry them along when available so the rebuilt linker is complete (and avoids a dev warning).
try {
const url = new URL(linker.toAbsoluteURL('/'));
data.host = url.host;
data.protocol = url.protocol;
} catch {
// No usable host (e.g. tests): the linker still resolves in-site paths without it.
}
return data;
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'bun:test';
import type { ContentKitRenderOutput, ContentKitWebFrame } from '@gitbook/api';
import { integrationBlockContainsWebframe } from './adaptive';
const webframe: ContentKitWebFrame = {
type: 'webframe',
source: { url: 'https://integrations.gitbook.com/frame' },
};
function elementOutput(element: unknown): ContentKitRenderOutput {
return {
type: 'element',
element,
state: {},
props: {},
} as ContentKitRenderOutput;
}
describe('integrationBlockContainsWebframe', () => {
it('returns false for a completed output', () => {
expect(integrationBlockContainsWebframe({ type: 'complete' })).toBe(false);
});
it('returns false when there is no webframe in the tree', () => {
const output = elementOutput({
type: 'block',
children: [{ type: 'text', text: 'hello' }],
} as never);
expect(integrationBlockContainsWebframe(output)).toBe(false);
});
it('returns true when a webframe is nested in the tree', () => {
const output = elementOutput({
type: 'block',
children: [{ type: 'vstack', children: [webframe] }],
} as never);
expect(integrationBlockContainsWebframe(output)).toBe(true);
});
});
@@ -8,19 +8,15 @@ import type {
type ContentKitElement = ContentKitRootElement | ContentKitDescendantElement | ContentKitStepper;
/**
* Decide whether an integration block should expose Adaptive visitor context to webframes.
* Whether an integration block's output contains a webframe that can consume client-only context
* (navigation and/or visitor claims).
*/
export function shouldRenderIntegrationBlockWithAdaptiveVisitorContext(
output: ContentKitRenderOutput
) {
export function integrationBlockContainsWebframe(output: ContentKitRenderOutput): boolean {
if (output.type === 'complete') {
return false;
}
return (
output.canAccessVisitorClaims === true &&
doesContentKitElementContainWebframe(output.element)
);
return doesContentKitElementContainWebframe(output.element);
}
/**

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