doccupine 0.0.158 → 0.0.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +56 -4
  2. package/dist/generator/app-scaffolder.js +11 -3
  3. package/dist/generator/generated-page-publisher.d.ts +6 -6
  4. package/dist/generator/generated-page-publisher.js +7 -5
  5. package/dist/generator/mdx-pass-builder.d.ts +4 -4
  6. package/dist/generator/mdx-pass-builder.js +8 -1
  7. package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
  8. package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
  9. package/dist/generator/page-catalog.d.ts +2 -4
  10. package/dist/generator/page-catalog.js +7 -2
  11. package/dist/generator/page-renderer.d.ts +15 -5
  12. package/dist/generator/page-renderer.js +38 -11
  13. package/dist/generator/project-config-repository.d.ts +4 -1
  14. package/dist/generator/project-config-repository.js +26 -0
  15. package/dist/generator/public-asset-manager.d.ts +10 -0
  16. package/dist/generator/public-asset-manager.js +63 -3
  17. package/dist/generator/section-index-generator.d.ts +10 -1
  18. package/dist/generator/section-index-generator.js +43 -15
  19. package/dist/generator/section-resolver.d.ts +8 -0
  20. package/dist/generator/site-artifacts.d.ts +4 -3
  21. package/dist/generator/site-artifacts.js +94 -9
  22. package/dist/generator/watch-coordinator.js +6 -1
  23. package/dist/lib/generated-artifacts.d.ts +3 -0
  24. package/dist/lib/generated-artifacts.js +36 -0
  25. package/dist/lib/layout.d.ts +6 -3
  26. package/dist/lib/layout.js +107 -4
  27. package/dist/lib/metadata.d.ts +7 -0
  28. package/dist/lib/metadata.js +33 -10
  29. package/dist/lib/structures.js +20 -0
  30. package/dist/lib/types.d.ts +28 -0
  31. package/dist/lib/ui-strings.d.ts +44 -0
  32. package/dist/lib/ui-strings.js +48 -0
  33. package/dist/lib/variants.d.ts +91 -0
  34. package/dist/lib/variants.js +411 -0
  35. package/dist/mdx-to-nextjs-generator.d.ts +22 -5
  36. package/dist/mdx-to-nextjs-generator.js +89 -10
  37. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  38. package/dist/templates/app/api/mcp/route.js +14 -1
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +13 -2
  41. package/dist/templates/app/api/search/route.d.ts +1 -1
  42. package/dist/templates/app/api/search/route.js +16 -1
  43. package/dist/templates/app/sitemap.d.ts +2 -0
  44. package/dist/templates/app/sitemap.js +48 -3
  45. package/dist/templates/components/Chat.d.ts +1 -1
  46. package/dist/templates/components/Chat.js +40 -12
  47. package/dist/templates/components/Docs.d.ts +1 -1
  48. package/dist/templates/components/Docs.js +5 -2
  49. package/dist/templates/components/DocsSideBar.d.ts +1 -1
  50. package/dist/templates/components/DocsSideBar.js +3 -1
  51. package/dist/templates/components/SearchDocs.d.ts +1 -1
  52. package/dist/templates/components/SearchDocs.js +17 -3
  53. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  54. package/dist/templates/components/SearchModalContent.js +22 -14
  55. package/dist/templates/components/SectionNavProvider.d.ts +1 -1
  56. package/dist/templates/components/SectionNavProvider.js +32 -20
  57. package/dist/templates/components/SideBar.d.ts +1 -1
  58. package/dist/templates/components/SideBar.js +26 -12
  59. package/dist/templates/components/layout/ActionBar.d.ts +1 -1
  60. package/dist/templates/components/layout/ActionBar.js +9 -7
  61. package/dist/templates/components/layout/Code.d.ts +1 -1
  62. package/dist/templates/components/layout/Code.js +6 -3
  63. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  64. package/dist/templates/components/layout/DocsComponents.js +38 -5
  65. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  66. package/dist/templates/components/layout/DocsNavigation.js +4 -2
  67. package/dist/templates/components/layout/Dropdown.d.ts +1 -0
  68. package/dist/templates/components/layout/Dropdown.js +308 -0
  69. package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
  70. package/dist/templates/components/layout/FocusModeToggle.js +7 -4
  71. package/dist/templates/components/layout/Footer.d.ts +1 -1
  72. package/dist/templates/components/layout/Footer.js +4 -2
  73. package/dist/templates/components/layout/Header.d.ts +1 -1
  74. package/dist/templates/components/layout/Header.js +18 -8
  75. package/dist/templates/components/layout/SectionBar.d.ts +1 -1
  76. package/dist/templates/components/layout/SectionBar.js +16 -10
  77. package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
  78. package/dist/templates/components/layout/VariantSwitchers.js +313 -0
  79. package/dist/templates/components/useStrings.d.ts +1 -0
  80. package/dist/templates/components/useStrings.js +10 -0
  81. package/dist/templates/components/useVariant.d.ts +1 -0
  82. package/dist/templates/components/useVariant.js +13 -0
  83. package/dist/templates/env.example.d.ts +1 -1
  84. package/dist/templates/env.example.js +2 -1
  85. package/dist/templates/llms/llmsIndex.d.ts +13 -0
  86. package/dist/templates/llms/llmsIndex.js +18 -3
  87. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  88. package/dist/templates/mdx/ai-assistant.mdx.js +9 -3
  89. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  90. package/dist/templates/mdx/api-playground.mdx.js +2 -0
  91. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  92. package/dist/templates/mdx/commands.mdx.js +1 -1
  93. package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
  94. package/dist/templates/mdx/fonts.mdx.js +1 -1
  95. package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
  96. package/dist/templates/mdx/footer-links.mdx.js +1 -1
  97. package/dist/templates/mdx/index.mdx.d.ts +1 -1
  98. package/dist/templates/mdx/index.mdx.js +2 -0
  99. package/dist/templates/mdx/languages.mdx.d.ts +1 -0
  100. package/dist/templates/mdx/languages.mdx.js +94 -0
  101. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  102. package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
  103. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  104. package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
  105. package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
  106. package/dist/templates/mdx/navigation.mdx.js +2 -0
  107. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  108. package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
  109. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  110. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
  111. package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
  112. package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
  113. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  114. package/dist/templates/mdx/platform/index.mdx.js +1 -1
  115. package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
  116. package/dist/templates/mdx/platform/languages.mdx.js +50 -0
  117. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  118. package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
  119. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  120. package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
  121. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  122. package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
  123. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  124. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
  125. package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
  126. package/dist/templates/mdx/platform/versions.mdx.js +33 -0
  127. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  128. package/dist/templates/mdx/sections.mdx.js +1 -1
  129. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  130. package/dist/templates/mdx/theme.mdx.js +1 -1
  131. package/dist/templates/mdx/versions.mdx.d.ts +1 -0
  132. package/dist/templates/mdx/versions.mdx.js +78 -0
  133. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  134. package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
  135. package/dist/templates/package.js +20 -20
  136. package/dist/templates/prettierignore.d.ts +1 -1
  137. package/dist/templates/prettierignore.js +2 -0
  138. package/dist/templates/services/llm/config.d.ts +1 -1
  139. package/dist/templates/services/llm/config.js +50 -3
  140. package/dist/templates/services/llm/factory.d.ts +1 -1
  141. package/dist/templates/services/llm/factory.js +6 -3
  142. package/dist/templates/services/llm/types.d.ts +1 -1
  143. package/dist/templates/services/llm/types.js +2 -1
  144. package/dist/templates/services/mcp/server.d.ts +1 -1
  145. package/dist/templates/services/mcp/server.js +54 -10
  146. package/dist/templates/services/mcp/tools.d.ts +1 -1
  147. package/dist/templates/services/mcp/tools.js +81 -6
  148. package/dist/templates/services/mcp/types.d.ts +1 -1
  149. package/dist/templates/services/mcp/types.js +10 -0
  150. package/dist/templates/services/search.d.ts +1 -1
  151. package/dist/templates/services/search.js +34 -4
  152. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  153. package/dist/templates/utils/orderNavItems.js +2 -0
  154. package/dist/templates/utils/strings.d.ts +1 -0
  155. package/dist/templates/utils/strings.js +27 -0
  156. package/dist/templates/utils/variants.d.ts +1 -0
  157. package/dist/templates/utils/variants.js +170 -0
  158. package/package.json +11 -11
@@ -1 +1 @@
1
- export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({ directory: parsed.data.directory });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleMCPRequest(req);\n}\n";
1
+ export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n resolveDocsFilter,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n resolveDocsFilter({\n language: parsed.data.language,\n version: parsed.data.version,\n }),\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...(chunk.locale !== undefined ? { language: chunk.locale } : {}),\n ...(chunk.version !== undefined ? { version: chunk.version } : {}),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({\n directory: parsed.data.directory,\n language: parsed.data.language,\n version: parsed.data.version,\n });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleMCPRequest(req);\n}\n";
@@ -12,6 +12,7 @@ import {
12
12
  searchDocsArgsSchema,
13
13
  getDocArgsSchema,
14
14
  listDocsArgsSchema,
15
+ resolveDocsFilter,
15
16
  serializeMCPResult,
16
17
  } from "@/services/mcp";
17
18
  import type { MCPToolName } from "@/services/mcp";
@@ -159,11 +160,17 @@ async function handleRESTRequest(req: Request, body: ToolCallRequest) {
159
160
  parsed.data.query,
160
161
  parsed.data.limit ?? 6,
161
162
  req.signal,
163
+ resolveDocsFilter({
164
+ language: parsed.data.language,
165
+ version: parsed.data.version,
166
+ }),
162
167
  );
163
168
  return toolResponse({
164
169
  content: results.map(({ chunk, score }) => ({
165
170
  path: chunk.path,
166
171
  uri: chunk.uri,
172
+ ...(chunk.locale !== undefined ? { language: chunk.locale } : {}),
173
+ ...(chunk.version !== undefined ? { version: chunk.version } : {}),
167
174
  score: score.toFixed(3),
168
175
  text: chunk.text,
169
176
  })),
@@ -199,13 +206,19 @@ async function handleRESTRequest(req: Request, body: ToolCallRequest) {
199
206
  );
200
207
  }
201
208
  req.signal.throwIfAborted();
202
- const docs = await listDocs({ directory: parsed.data.directory });
209
+ const docs = await listDocs({
210
+ directory: parsed.data.directory,
211
+ language: parsed.data.language,
212
+ version: parsed.data.version,
213
+ });
203
214
  req.signal.throwIfAborted();
204
215
  return toolResponse({
205
216
  content: docs.map((doc) => ({
206
217
  name: doc.name,
207
218
  path: doc.path,
208
219
  uri: doc.uri,
220
+ ...(doc.locale !== undefined ? { language: doc.locale } : {}),
221
+ ...(doc.version !== undefined ? { version: doc.version } : {}),
209
222
  })),
210
223
  });
211
224
  }
@@ -1 +1 @@
1
- export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
1
+ export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
@@ -6,6 +6,7 @@ import {
6
6
  ensureDocsIndex,
7
7
  getIndexStatus,
8
8
  } from "@/services/mcp/server";
9
+ import { resolveDocsFilter } from "@/services/mcp/tools";
9
10
  import { rateLimit } from "@/utils/rateLimit";
10
11
  import { config } from "@/utils/config";
11
12
  import { isSiteRequestAuthorized } from "@/lib/access";
@@ -22,10 +23,18 @@ const messageSchema = z
22
23
  })
23
24
  .strict();
24
25
 
26
+ // A language code or version slug is a lowercase URL segment.
27
+ const variantTokenSchema = z
28
+ .string()
29
+ .regex(/^[a-z0-9-]{1,32}$/)
30
+ .optional();
31
+
25
32
  const ragSchema = z
26
33
  .object({
27
34
  question: z.string().min(1).max(2000),
28
35
  history: z.array(messageSchema).max(20).optional(),
36
+ locale: variantTokenSchema,
37
+ version: variantTokenSchema,
29
38
  })
30
39
  .strict();
31
40
 
@@ -139,7 +148,9 @@ export async function POST(req: Request) {
139
148
  { status: 400 },
140
149
  );
141
150
  }
142
- const { question, history } = parsed.data;
151
+ const { question, history, locale, version } = parsed.data;
152
+ // Retrieval stays inside the language/version the reader is looking at.
153
+ const docsFilter = resolveDocsFilter({ language: locale, version });
143
154
 
144
155
  let llmConfig;
145
156
  try {
@@ -194,7 +205,7 @@ export async function POST(req: Request) {
194
205
  signal.throwIfAborted();
195
206
 
196
207
  // Use MCP search_docs tool to find relevant documentation
197
- const searchResults = await searchDocs(question, 6, signal);
208
+ const searchResults = await searchDocs(question, 6, signal, docsFilter);
198
209
  signal.throwIfAborted();
199
210
 
200
211
  // Build context from search results
@@ -1 +1 @@
1
- export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n});\n\nexport async function GET(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10);\n return NextResponse.json({ results });\n}\n";
1
+ export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n});\n\nexport async function GET(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const localeParam = url.searchParams.get(\"locale\");\n const versionParam = url.searchParams.get(\"version\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n ...(localeParam != null && { locale: localeParam }),\n ...(versionParam != null && { version: versionParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10, {\n locale: parsed.data.locale,\n version: parsed.data.version,\n });\n return NextResponse.json({ results });\n}\n";
@@ -3,9 +3,17 @@ import { z } from "zod";
3
3
  import { searchContent } from "@/services/search";
4
4
  import { isSiteRequestAuthorized } from "@/lib/access";
5
5
 
6
+ // A language code or version slug is a lowercase URL segment.
7
+ const variantTokenSchema = z
8
+ .string()
9
+ .regex(/^[a-z0-9-]{1,32}$/)
10
+ .optional();
11
+
6
12
  const searchSchema = z.object({
7
13
  q: z.string().min(1).max(200),
8
14
  limit: z.coerce.number().int().min(1).max(30).optional(),
15
+ locale: variantTokenSchema,
16
+ version: variantTokenSchema,
9
17
  });
10
18
 
11
19
  export async function GET(req: Request) {
@@ -15,9 +23,13 @@ export async function GET(req: Request) {
15
23
 
16
24
  const url = new URL(req.url);
17
25
  const limitParam = url.searchParams.get("limit");
26
+ const localeParam = url.searchParams.get("locale");
27
+ const versionParam = url.searchParams.get("version");
18
28
  const parsed = searchSchema.safeParse({
19
29
  q: url.searchParams.get("q"),
20
30
  ...(limitParam != null && { limit: limitParam }),
31
+ ...(localeParam != null && { locale: localeParam }),
32
+ ...(versionParam != null && { version: versionParam }),
21
33
  });
22
34
 
23
35
  if (!parsed.success) {
@@ -27,7 +39,10 @@ export async function GET(req: Request) {
27
39
  );
28
40
  }
29
41
 
30
- const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10);
42
+ const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10, {
43
+ locale: parsed.data.locale,
44
+ version: parsed.data.version,
45
+ });
31
46
  return NextResponse.json({ results });
32
47
  }
33
48
  `;
@@ -3,5 +3,7 @@ export interface SitemapEntry {
3
3
  lastModified?: string;
4
4
  changeFrequency: "weekly";
5
5
  priority: number;
6
+ /** hreflang -> slug of the same page in that language (languages.json). */
7
+ alternates?: Record<string, string>;
6
8
  }
7
9
  export declare const sitemapTemplate: (entries: SitemapEntry[]) => string;
@@ -1,3 +1,16 @@
1
+ function formatAlternates(alternates) {
2
+ const entries = Object.entries(alternates).map(([lang, slug]) => {
3
+ const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(lang)
4
+ ? lang
5
+ : JSON.stringify(lang);
6
+ return `${key}: ${JSON.stringify(slug)}`;
7
+ });
8
+ const inline = ` alternates: { ${entries.join(", ")} }`;
9
+ // The caller appends a comma, which Prettier counts against the width.
10
+ if (inline.length + 1 <= 80)
11
+ return inline;
12
+ return ` alternates: {\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
13
+ }
1
14
  function formatEntries(entries) {
2
15
  const lines = entries.map((entry) => {
3
16
  const parts = [
@@ -7,6 +20,7 @@ function formatEntries(entries) {
7
20
  : null,
8
21
  ` changeFrequency: ${JSON.stringify(entry.changeFrequency)}`,
9
22
  ` priority: ${entry.priority}`,
23
+ entry.alternates ? formatAlternates(entry.alternates) : null,
10
24
  ].filter(Boolean);
11
25
  return ` {\n${parts.join(",\n")},\n }`;
12
26
  });
@@ -14,6 +28,37 @@ function formatEntries(entries) {
14
28
  }
15
29
  export const sitemapTemplate = (entries) => {
16
30
  const entriesLiteral = formatEntries(entries);
31
+ const hasAlternates = entries.some((entry) => entry.alternates);
32
+ // The hreflang mapping is emitted only for sites with translated pages, so
33
+ // every other site's sitemap.ts is unchanged.
34
+ const alternatesField = hasAlternates
35
+ ? `
36
+ alternates?: Record<string, string>;`
37
+ : "";
38
+ const alternatesHelper = hasAlternates
39
+ ? `
40
+ function languageAlternates(
41
+ base: string,
42
+ alternates: Record<string, string>,
43
+ ): Record<string, string> {
44
+ const languages: Record<string, string> = {};
45
+ for (const [lang, slug] of Object.entries(alternates)) {
46
+ languages[lang] = slug === "" ? base : \`\${base}/\${slug}\`;
47
+ }
48
+ return languages;
49
+ }
50
+ `
51
+ : "";
52
+ const alternatesSpread = hasAlternates
53
+ ? `
54
+ ...(entry.alternates
55
+ ? {
56
+ alternates: {
57
+ languages: languageAlternates(base, entry.alternates),
58
+ },
59
+ }
60
+ : {}),`
61
+ : "";
17
62
  return `import type { MetadataRoute } from "next";
18
63
  import { config } from "@/utils/config";
19
64
 
@@ -24,7 +69,7 @@ interface Entry {
24
69
  slug: string;
25
70
  lastModified?: string;
26
71
  changeFrequency: ChangeFrequency;
27
- priority: number;
72
+ priority: number;${alternatesField}
28
73
  }
29
74
 
30
75
  const ENTRIES: Entry[] = ${entriesLiteral};
@@ -34,7 +79,7 @@ function resolveBaseUrl(): string | null {
34
79
  if (!raw) return null;
35
80
  return raw.replace(/\\/$/, "");
36
81
  }
37
-
82
+ ${alternatesHelper}
38
83
  export default function sitemap(): MetadataRoute.Sitemap {
39
84
  const base = resolveBaseUrl();
40
85
  if (!base) return [];
@@ -43,7 +88,7 @@ export default function sitemap(): MetadataRoute.Sitemap {
43
88
  url: entry.slug === "" ? base : \`\${base}/\${entry.slug}\`,
44
89
  lastModified: entry.lastModified ? new Date(entry.lastModified) : undefined,
45
90
  changeFrequency: entry.changeFrequency,
46
- priority: entry.priority,
91
+ priority: entry.priority,${alternatesSpread}
47
92
  }));
48
93
  }
49
94
  `;
@@ -1 +1 @@
1
- export declare const chatTemplate = "\"use client\";\nimport React, { createContext, useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n ChatInput,\n ChatMessage,\n ChatMessageList,\n ChatPanel,\n ChatProvider,\n ChatSource,\n ChatSources,\n ChatTyping,\n IconButton,\n Prose,\n useBelowBreakpoint,\n useChat,\n type ChatSendContext,\n type ChatSourceData,\n} from \"cherry-styled-components\";\nimport { RotateCcw } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\n\nconst mdxComponents = getMDXComponents({});\n\ntype RagSource = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\n// Map a retrieval hit onto the chip the transcript renders: docs://<slug>\n// becomes an app-relative href, and the slug's last segment becomes a\n// title-cased label.\nfunction toSourceChip(src: RagSource): ChatSourceData {\n const slug = src.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return { id: src.id, label, href };\n}\n\n// Cherry's ChatProvider owns the transcript, panel state, and streaming\n// bookkeeping; this handler owns the transport: POST the question to\n// /api/rag, stream the SSE frames, and patch the assistant bubble as tokens\n// arrive. The provider bounds `history` to the RAG contract (20 entries,\n// 4000 chars each), swallows aborts, and surfaces thrown errors as `error`.\nasync function sendToAssistant(\n question: string,\n { signal, history, setAssistant }: ChatSendContext,\n) {\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question, history }),\n signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: ChatSourceData[] = [];\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop so it lands\n // in the provider's error state instead of dying in a parse-error\n // log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: RagSource[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources\n .filter((s) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n })\n .map(toSourceChip);\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n setAssistant(streamedContent, { text: streamedContent, sources });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAssistant(\n mdxSource ? (\n <MDXRemote {...mdxSource} components={mdxComponents} />\n ) : (\n streamedContent\n ),\n { text: streamedContent, sources },\n );\n }\n }\n }\n}\n\nfunction ChatSourceLink({ source }: { source: ChatSourceData }) {\n const { close } = useChat();\n const isMobileChat = useBelowBreakpoint(\"lg\");\n const router = useRouter();\n\n return (\n <ChatSource\n href={source.href}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // ChatSource renders a plain anchor, so route unmodified left clicks\n // client-side to keep the transcript alive; below lg the panel is a\n // fullscreen dialog, so close it to reveal the navigated page.\n event.preventDefault();\n if (isMobileChat) close();\n router.push(source.href);\n }}\n >\n {source.label}\n </ChatSource>\n );\n}\n\nfunction ChatTranscript() {\n const { messages, loading, error } = useChat();\n const lastMessage = messages[messages.length - 1];\n\n return (\n <ChatMessageList>\n {messages.map((message) => (\n <ChatMessage key={message.id} $role={message.role}>\n {message.role === \"assistant\" ? (\n // The docs' typographic context lives on the docs page wrapper,\n // so a rendered MDX answer would arrive margin-less here. Prose\n // $compact is Cherry's document styling for chat replies: a 10px\n // rhythm between elements, inline-code chips, lists, and tables.\n <Prose $compact>{message.content}</Prose>\n ) : (\n message.content\n )}\n {message.role === \"assistant\" &&\n message.sources &&\n message.sources.length > 0 && (\n <ChatSources>\n {message.sources.map((source) => (\n <ChatSourceLink key={source.id} source={source} />\n ))}\n </ChatSources>\n )}\n </ChatMessage>\n ))}\n {loading && lastMessage?.role !== \"assistant\" && <ChatTyping />}\n {error && (\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n )}\n </ChatMessageList>\n );\n}\n\nfunction ChatActions() {\n const { reset } = useChat();\n\n return (\n <IconButton\n onClick={reset}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n );\n}\n\nfunction Chat() {\n return (\n <ChatPanel $title=\"AI Assistant\" $actions={<ChatActions />}>\n <ChatTranscript />\n <ChatInput $glow />\n </ChatPanel>\n );\n}\n\n// App-level chat context: only whether the AI assistant is enabled (an LLM\n// provider is configured). Panel state, the transcript, and streaming all\n// live in Cherry's ChatProvider - read those with useChat() from\n// \"cherry-styled-components\".\nconst ChatContext = createContext<{ isChatActive: boolean }>({\n isChatActive: false,\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const value = useMemo(() => ({ isChatActive }), [isChatActive]);\n\n return (\n <ChatContext.Provider value={value}>\n <ChatProvider\n onSend={sendToAssistant}\n shortcut={isChatActive ? \"i\" : null}\n >\n {children}\n </ChatProvider>\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext };\n";
1
+ export declare const chatTemplate = "\"use client\";\nimport React, { createContext, useCallback, useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n ChatInput,\n ChatMessage,\n ChatMessageList,\n ChatPanel,\n ChatProvider,\n ChatSource,\n ChatSources,\n ChatTyping,\n IconButton,\n Prose,\n useBelowBreakpoint,\n useChat,\n type ChatSendContext,\n type ChatSourceData,\n} from \"cherry-styled-components\";\nimport { RotateCcw } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\nimport { useStrings } from \"@/components/useStrings\";\nimport { useVariant } from \"@/components/useVariant\";\n\nconst mdxComponents = getMDXComponents({});\n\n/** The language/version the reader is looking at; retrieval stays inside it. */\ninterface ChatScope {\n locale?: string;\n version?: string;\n}\n\ntype RagSource = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\n// Map a retrieval hit onto the chip the transcript renders: docs://<slug>\n// becomes an app-relative href, and the slug's last segment becomes a\n// title-cased label.\nfunction toSourceChip(src: RagSource): ChatSourceData {\n const slug = src.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return { id: src.id, label, href };\n}\n\n// Cherry's ChatProvider owns the transcript, panel state, and streaming\n// bookkeeping; this handler owns the transport: POST the question to\n// /api/rag, stream the SSE frames, and patch the assistant bubble as tokens\n// arrive. The provider bounds `history` to the RAG contract (20 entries,\n// 4000 chars each), swallows aborts, and surfaces thrown errors as `error`.\nasync function sendToAssistant(\n question: string,\n { signal, history, setAssistant }: ChatSendContext,\n scope: ChatScope,\n) {\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n question,\n history,\n ...(scope.locale ? { locale: scope.locale } : {}),\n ...(scope.version ? { version: scope.version } : {}),\n }),\n signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: ChatSourceData[] = [];\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop so it lands\n // in the provider's error state instead of dying in a parse-error\n // log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: RagSource[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources\n .filter((s) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n })\n .map(toSourceChip);\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n setAssistant(streamedContent, { text: streamedContent, sources });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAssistant(\n mdxSource ? (\n <MDXRemote {...mdxSource} components={mdxComponents} />\n ) : (\n streamedContent\n ),\n { text: streamedContent, sources },\n );\n }\n }\n }\n}\n\nfunction ChatSourceLink({ source }: { source: ChatSourceData }) {\n const { close } = useChat();\n const isMobileChat = useBelowBreakpoint(\"lg\");\n const router = useRouter();\n\n return (\n <ChatSource\n href={source.href}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // ChatSource renders a plain anchor, so route unmodified left clicks\n // client-side to keep the transcript alive; below lg the panel is a\n // fullscreen dialog, so close it to reveal the navigated page.\n event.preventDefault();\n if (isMobileChat) close();\n router.push(source.href);\n }}\n >\n {source.label}\n </ChatSource>\n );\n}\n\nfunction ChatTranscript() {\n const { messages, loading, error } = useChat();\n const lastMessage = messages[messages.length - 1];\n const t = useStrings();\n\n return (\n <ChatMessageList>\n {messages.map((message) => (\n <ChatMessage key={message.id} $role={message.role}>\n {message.role === \"assistant\" ? (\n // The docs' typographic context lives on the docs page wrapper,\n // so a rendered MDX answer would arrive margin-less here. Prose\n // $compact is Cherry's document styling for chat replies: a 10px\n // rhythm between elements, inline-code chips, lists, and tables.\n <Prose $compact>{message.content}</Prose>\n ) : (\n message.content\n )}\n {message.role === \"assistant\" &&\n message.sources &&\n message.sources.length > 0 && (\n <ChatSources>\n {message.sources.map((source) => (\n <ChatSourceLink key={source.id} source={source} />\n ))}\n </ChatSources>\n )}\n </ChatMessage>\n ))}\n {loading && lastMessage?.role !== \"assistant\" && (\n <ChatTyping>{t.chatAnswering}</ChatTyping>\n )}\n {error && (\n <Callout type=\"danger\">\n <p>\n <strong>{t.chatError}</strong> {error}\n </p>\n </Callout>\n )}\n </ChatMessageList>\n );\n}\n\nfunction ChatActions() {\n const { reset } = useChat();\n const t = useStrings();\n\n return (\n <IconButton onClick={reset} aria-label={t.resetChat} title={t.resetChat}>\n <RotateCcw />\n </IconButton>\n );\n}\n\nfunction Chat() {\n const t = useStrings();\n\n return (\n <ChatPanel $title={t.aiAssistant} $actions={<ChatActions />}>\n <ChatTranscript />\n <ChatInput\n $glow\n placeholder={t.chatPlaceholder}\n aria-label={t.chatInputLabel}\n />\n </ChatPanel>\n );\n}\n\n// App-level chat context: only whether the AI assistant is enabled (an LLM\n// provider is configured). Panel state, the transcript, and streaming all\n// live in Cherry's ChatProvider - read those with useChat() from\n// \"cherry-styled-components\".\nconst ChatContext = createContext<{ isChatActive: boolean }>({\n isChatActive: false,\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const value = useMemo(() => ({ isChatActive }), [isChatActive]);\n const { locale, version } = useVariant();\n const t = useStrings();\n const onSend = useCallback(\n (question: string, context: ChatSendContext) =>\n sendToAssistant(question, context, { locale, version }),\n [locale, version],\n );\n\n return (\n <ChatContext.Provider value={value}>\n <ChatProvider\n onSend={onSend}\n greeting={t.chatGreeting}\n shortcut={isChatActive ? \"i\" : null}\n >\n {children}\n </ChatProvider>\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext };\n";
@@ -1,5 +1,5 @@
1
1
  export const chatTemplate = `"use client";
2
- import React, { createContext, useMemo } from "react";
2
+ import React, { createContext, useCallback, useMemo } from "react";
3
3
  import { useRouter } from "next/navigation";
4
4
  import {
5
5
  ChatInput,
@@ -24,9 +24,17 @@ import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
24
24
  import { serialize } from "next-mdx-remote/serialize";
25
25
  import { Callout } from "@/components/layout/Callout";
26
26
  import { useMDXComponents as getMDXComponents } from "@/components/MDXComponents";
27
+ import { useStrings } from "@/components/useStrings";
28
+ import { useVariant } from "@/components/useVariant";
27
29
 
28
30
  const mdxComponents = getMDXComponents({});
29
31
 
32
+ /** The language/version the reader is looking at; retrieval stays inside it. */
33
+ interface ChatScope {
34
+ locale?: string;
35
+ version?: string;
36
+ }
37
+
30
38
  type RagSource = {
31
39
  id: string;
32
40
  path: string;
@@ -58,11 +66,17 @@ function toSourceChip(src: RagSource): ChatSourceData {
58
66
  async function sendToAssistant(
59
67
  question: string,
60
68
  { signal, history, setAssistant }: ChatSendContext,
69
+ scope: ChatScope,
61
70
  ) {
62
71
  const res = await fetch("/api/rag", {
63
72
  method: "POST",
64
73
  headers: { "Content-Type": "application/json" },
65
- body: JSON.stringify({ question, history }),
74
+ body: JSON.stringify({
75
+ question,
76
+ history,
77
+ ...(scope.locale ? { locale: scope.locale } : {}),
78
+ ...(scope.version ? { version: scope.version } : {}),
79
+ }),
66
80
  signal,
67
81
  });
68
82
 
@@ -198,6 +212,7 @@ function ChatSourceLink({ source }: { source: ChatSourceData }) {
198
212
  function ChatTranscript() {
199
213
  const { messages, loading, error } = useChat();
200
214
  const lastMessage = messages[messages.length - 1];
215
+ const t = useStrings();
201
216
 
202
217
  return (
203
218
  <ChatMessageList>
@@ -223,11 +238,13 @@ function ChatTranscript() {
223
238
  )}
224
239
  </ChatMessage>
225
240
  ))}
226
- {loading && lastMessage?.role !== "assistant" && <ChatTyping />}
241
+ {loading && lastMessage?.role !== "assistant" && (
242
+ <ChatTyping>{t.chatAnswering}</ChatTyping>
243
+ )}
227
244
  {error && (
228
245
  <Callout type="danger">
229
246
  <p>
230
- <strong>Error:</strong> {error}
247
+ <strong>{t.chatError}</strong> {error}
231
248
  </p>
232
249
  </Callout>
233
250
  )}
@@ -237,23 +254,26 @@ function ChatTranscript() {
237
254
 
238
255
  function ChatActions() {
239
256
  const { reset } = useChat();
257
+ const t = useStrings();
240
258
 
241
259
  return (
242
- <IconButton
243
- onClick={reset}
244
- aria-label="Reset chat history"
245
- title="Reset chat history"
246
- >
260
+ <IconButton onClick={reset} aria-label={t.resetChat} title={t.resetChat}>
247
261
  <RotateCcw />
248
262
  </IconButton>
249
263
  );
250
264
  }
251
265
 
252
266
  function Chat() {
267
+ const t = useStrings();
268
+
253
269
  return (
254
- <ChatPanel $title="AI Assistant" $actions={<ChatActions />}>
270
+ <ChatPanel $title={t.aiAssistant} $actions={<ChatActions />}>
255
271
  <ChatTranscript />
256
- <ChatInput $glow />
272
+ <ChatInput
273
+ $glow
274
+ placeholder={t.chatPlaceholder}
275
+ aria-label={t.chatInputLabel}
276
+ />
257
277
  </ChatPanel>
258
278
  );
259
279
  }
@@ -273,11 +293,19 @@ interface ChatContextProviderProps {
273
293
 
274
294
  const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
275
295
  const value = useMemo(() => ({ isChatActive }), [isChatActive]);
296
+ const { locale, version } = useVariant();
297
+ const t = useStrings();
298
+ const onSend = useCallback(
299
+ (question: string, context: ChatSendContext) =>
300
+ sendToAssistant(question, context, { locale, version }),
301
+ [locale, version],
302
+ );
276
303
 
277
304
  return (
278
305
  <ChatContext.Provider value={value}>
279
306
  <ChatProvider
280
- onSend={sendToAssistant}
307
+ onSend={onSend}
308
+ greeting={t.chatGreeting}
281
309
  shortcut={isChatActive ? "i" : null}
282
310
  >
283
311
  {children}
@@ -1 +1 @@
1
- export declare const docsTemplate = "import React from \"react\";\nimport { Flex } from \"cherry-styled-components\";\nimport {\n DocsContainer,\n StyledMarkdownContainer,\n} from \"@/components/layout/DocsComponents\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { compileMDX } from \"next-mdx-remote/rsc\";\nimport remarkGfm from \"remark-gfm\";\nimport { useMDXComponents } from \"@/components/MDXComponents\";\nimport { createMermaidPre } from \"@/components/MermaidPre\";\nimport { DocsSideBar } from \"@/components/DocsSideBar\";\nimport { ActionBar } from \"@/components/layout/ActionBar\";\nimport { ApiPlaygroundDemo } from \"@/components/layout/ApiPlaygroundDemo\";\nimport { createSlugger } from \"@/components/layout/Slug\";\nimport { rehypeCodeMeta } from \"@/utils/rehypeCodeMeta\";\n\ninterface DocsProps {\n content: string;\n sourcePath?: string;\n // Path of this page's RSS feed; when set, the action bar shows an RSS\n // button linking to it.\n rssHref?: string;\n // Extra content rendered inside the markdown column, after the MDX body.\n // Used to place generated widgets (e.g. the API playground) inside the docs\n // content area rather than outside its layout.\n children?: React.ReactNode;\n}\n\ninterface Heading {\n id: string;\n text: string;\n level: number;\n}\n\nfunction extractHeadings(content: string): Heading[] {\n const contentWithoutCodeBlocks = content.replace(/```[\\s\\S]*?```/g, \"\");\n const entries: { text: string; level: number; position: number }[] = [];\n let match;\n\n // Markdown headings (# .. ######)\n const headingRegex = /^(#{1,6})\\s+(.+)$/gm;\n while ((match = headingRegex.exec(contentWithoutCodeBlocks)) !== null) {\n const level = match[1].length;\n const text = match[2].trim();\n entries.push({ text, level, position: match.index });\n }\n\n // <Update label=\"...\"> blocks surface their label as a top-level entry\n const updateRegex = /<Update\\b[^>]*?\\blabel=[\"']([^\"']+)[\"'][^>]*>/g;\n while ((match = updateRegex.exec(contentWithoutCodeBlocks)) !== null) {\n entries.push({ text: match[1].trim(), level: 1, position: match.index });\n }\n\n // Assign ids in document order with a shared slugger so repeated heading\n // text produces unique anchors (\"setup\", \"setup-1\", ...) that stay in sync\n // with the ids rendered by MDXComponents/Update.\n const slug = createSlugger();\n return entries\n .sort((a, b) => a.position - b.position)\n .map(({ text, level }) => ({ id: slug(text), text, level }));\n}\n\nfunction extractComponentNames(source: string): string[] {\n const stripped = source\n .replace(/```[\\s\\S]*?```/g, \"\")\n .replace(/`[^`]*`/g, \"\");\n const tagRegex = /<([A-Z][a-zA-Z0-9]*)/g;\n const names = new Set<string>();\n let match;\n while ((match = tagRegex.exec(stripped)) !== null) {\n names.add(match[1]);\n }\n return Array.from(names);\n}\n\nfunction MissingComponent({\n componentName,\n children: _children,\n}: {\n componentName: string;\n children?: React.ReactNode;\n}) {\n return (\n <Callout type=\"danger\">\n <p>Missing component: &lt;{componentName} /&gt;</p>\n </Callout>\n );\n}\n\ninterface MdxBodyProps {\n source: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: Record<string, React.ComponentType<any>>;\n sourcePath?: string;\n}\n\n// Compiles the MDX body inside a try/catch so an authoring mistake (an\n// orphaned closing tag, a stray {expression}) renders an inline error panel\n// instead of throwing during static prerender - a broken page must never\n// fail `next build` for the rest of the site.\nasync function MdxBody({ source, components, sourcePath }: MdxBodyProps) {\n try {\n const { content } = await compileMDX({\n source,\n options: {\n blockJS: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeCodeMeta],\n },\n },\n components,\n });\n // JS expressions in the body only run when the compiled component\n // renders, which would escape this try/catch and still fail the build.\n // The compiled component is a plain sync function, so invoke it once\n // here to surface those errors (a {placeholder} typo, for example).\n if (typeof content.type === \"function\") {\n await (content.type as React.FC<unknown>)(content.props);\n }\n return content;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const where = sourcePath ? ` in ${sourcePath}` : \"\";\n console.error(`[doccupine] MDX error${where}:`, message);\n return (\n <Callout type=\"danger\">\n <p>\n <strong>This page has an MDX error{where}.</strong> The rest of the\n site still builds and renders. Fix the syntax below and save the file\n to rebuild this page.\n </p>\n <pre>{message}</pre>\n </Callout>\n );\n }\n}\n\nfunction Docs({ content, sourcePath, rssHref, children }: DocsProps) {\n const components = useMDXComponents({\n pre: createMermaidPre(sourcePath),\n ApiPlaygroundDemo,\n });\n\n const knownNames = Object.keys(components);\n const usedNames = extractComponentNames(content);\n const missingNames = usedNames.filter((name) => !knownNames.includes(name));\n\n // A <SidePanel> takes over the right rail, so the table of contents that\n // normally lives there is dropped for that page. extractComponentNames\n // ignores code blocks, so a panel shown only as a code sample never counts.\n const hasSidePanel = usedNames.includes(\"SidePanel\");\n const headings = hasSidePanel ? [] : extractHeadings(content);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stubs: Record<string, React.ComponentType<any>> = {};\n for (const name of missingNames) {\n stubs[name] = ({ children }: { children?: React.ReactNode }) => (\n <MissingComponent componentName={name}>{children}</MissingComponent>\n );\n }\n\n const allComponents = { ...components, ...stubs };\n\n return (\n <>\n <DocsContainer>\n <ActionBar content={content} rssHref={rssHref}>\n <Flex $gap={20}>\n <StyledMarkdownContainer>\n {children}\n {content && (\n <MdxBody\n source={content}\n components={allComponents}\n sourcePath={sourcePath}\n />\n )}\n </StyledMarkdownContainer>\n </Flex>\n </ActionBar>\n </DocsContainer>\n {!hasSidePanel && <DocsSideBar headings={headings} />}\n </>\n );\n}\n\nexport { Docs };\n";
1
+ export declare const docsTemplate = "import React from \"react\";\nimport { Flex } from \"cherry-styled-components\";\nimport {\n DocsContainer,\n StyledMarkdownContainer,\n} from \"@/components/layout/DocsComponents\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { compileMDX } from \"next-mdx-remote/rsc\";\nimport remarkGfm from \"remark-gfm\";\nimport { useMDXComponents } from \"@/components/MDXComponents\";\nimport { createMermaidPre } from \"@/components/MermaidPre\";\nimport { DocsSideBar } from \"@/components/DocsSideBar\";\nimport { ActionBar } from \"@/components/layout/ActionBar\";\nimport { ApiPlaygroundDemo } from \"@/components/layout/ApiPlaygroundDemo\";\nimport { createSlugger } from \"@/components/layout/Slug\";\nimport { rehypeCodeMeta } from \"@/utils/rehypeCodeMeta\";\n\ninterface DocsProps {\n content: string;\n sourcePath?: string;\n // Path of this page's RSS feed; when set, the action bar shows an RSS\n // button linking to it.\n rssHref?: string;\n // Language of the page content (languages.json); set on the <main> element\n // so the article's language is correct server-side whatever <html lang> is.\n lang?: string;\n // Extra content rendered inside the markdown column, after the MDX body.\n // Used to place generated widgets (e.g. the API playground) inside the docs\n // content area rather than outside its layout.\n children?: React.ReactNode;\n}\n\ninterface Heading {\n id: string;\n text: string;\n level: number;\n}\n\nfunction extractHeadings(content: string): Heading[] {\n const contentWithoutCodeBlocks = content.replace(/```[\\s\\S]*?```/g, \"\");\n const entries: { text: string; level: number; position: number }[] = [];\n let match;\n\n // Markdown headings (# .. ######)\n const headingRegex = /^(#{1,6})\\s+(.+)$/gm;\n while ((match = headingRegex.exec(contentWithoutCodeBlocks)) !== null) {\n const level = match[1].length;\n const text = match[2].trim();\n entries.push({ text, level, position: match.index });\n }\n\n // <Update label=\"...\"> blocks surface their label as a top-level entry\n const updateRegex = /<Update\\b[^>]*?\\blabel=[\"']([^\"']+)[\"'][^>]*>/g;\n while ((match = updateRegex.exec(contentWithoutCodeBlocks)) !== null) {\n entries.push({ text: match[1].trim(), level: 1, position: match.index });\n }\n\n // Assign ids in document order with a shared slugger so repeated heading\n // text produces unique anchors (\"setup\", \"setup-1\", ...) that stay in sync\n // with the ids rendered by MDXComponents/Update.\n const slug = createSlugger();\n return entries\n .sort((a, b) => a.position - b.position)\n .map(({ text, level }) => ({ id: slug(text), text, level }));\n}\n\nfunction extractComponentNames(source: string): string[] {\n const stripped = source\n .replace(/```[\\s\\S]*?```/g, \"\")\n .replace(/`[^`]*`/g, \"\");\n const tagRegex = /<([A-Z][a-zA-Z0-9]*)/g;\n const names = new Set<string>();\n let match;\n while ((match = tagRegex.exec(stripped)) !== null) {\n names.add(match[1]);\n }\n return Array.from(names);\n}\n\nfunction MissingComponent({\n componentName,\n children: _children,\n}: {\n componentName: string;\n children?: React.ReactNode;\n}) {\n return (\n <Callout type=\"danger\">\n <p>Missing component: &lt;{componentName} /&gt;</p>\n </Callout>\n );\n}\n\ninterface MdxBodyProps {\n source: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: Record<string, React.ComponentType<any>>;\n sourcePath?: string;\n}\n\n// Compiles the MDX body inside a try/catch so an authoring mistake (an\n// orphaned closing tag, a stray {expression}) renders an inline error panel\n// instead of throwing during static prerender - a broken page must never\n// fail `next build` for the rest of the site.\nasync function MdxBody({ source, components, sourcePath }: MdxBodyProps) {\n try {\n const { content } = await compileMDX({\n source,\n options: {\n blockJS: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeCodeMeta],\n },\n },\n components,\n });\n // JS expressions in the body only run when the compiled component\n // renders, which would escape this try/catch and still fail the build.\n // The compiled component is a plain sync function, so invoke it once\n // here to surface those errors (a {placeholder} typo, for example).\n if (typeof content.type === \"function\") {\n await (content.type as React.FC<unknown>)(content.props);\n }\n return content;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const where = sourcePath ? ` in ${sourcePath}` : \"\";\n console.error(`[doccupine] MDX error${where}:`, message);\n return (\n <Callout type=\"danger\">\n <p>\n <strong>This page has an MDX error{where}.</strong> The rest of the\n site still builds and renders. Fix the syntax below and save the file\n to rebuild this page.\n </p>\n <pre>{message}</pre>\n </Callout>\n );\n }\n}\n\nfunction Docs({ content, sourcePath, rssHref, lang, children }: DocsProps) {\n const components = useMDXComponents({\n pre: createMermaidPre(sourcePath),\n ApiPlaygroundDemo,\n });\n\n const knownNames = Object.keys(components);\n const usedNames = extractComponentNames(content);\n const missingNames = usedNames.filter((name) => !knownNames.includes(name));\n\n // A <SidePanel> takes over the right rail, so the table of contents that\n // normally lives there is dropped for that page. extractComponentNames\n // ignores code blocks, so a panel shown only as a code sample never counts.\n const hasSidePanel = usedNames.includes(\"SidePanel\");\n const headings = hasSidePanel ? [] : extractHeadings(content);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stubs: Record<string, React.ComponentType<any>> = {};\n for (const name of missingNames) {\n stubs[name] = ({ children }: { children?: React.ReactNode }) => (\n <MissingComponent componentName={name}>{children}</MissingComponent>\n );\n }\n\n const allComponents = { ...components, ...stubs };\n\n return (\n <>\n <DocsContainer lang={lang}>\n <ActionBar content={content} rssHref={rssHref}>\n <Flex $gap={20}>\n <StyledMarkdownContainer>\n {children}\n {content && (\n <MdxBody\n source={content}\n components={allComponents}\n sourcePath={sourcePath}\n />\n )}\n </StyledMarkdownContainer>\n </Flex>\n </ActionBar>\n </DocsContainer>\n {!hasSidePanel && <DocsSideBar headings={headings} />}\n </>\n );\n}\n\nexport { Docs };\n";
@@ -21,6 +21,9 @@ interface DocsProps {
21
21
  // Path of this page's RSS feed; when set, the action bar shows an RSS
22
22
  // button linking to it.
23
23
  rssHref?: string;
24
+ // Language of the page content (languages.json); set on the <main> element
25
+ // so the article's language is correct server-side whatever <html lang> is.
26
+ lang?: string;
24
27
  // Extra content rendered inside the markdown column, after the MDX body.
25
28
  // Used to place generated widgets (e.g. the API playground) inside the docs
26
29
  // content area rather than outside its layout.
@@ -137,7 +140,7 @@ async function MdxBody({ source, components, sourcePath }: MdxBodyProps) {
137
140
  }
138
141
  }
139
142
 
140
- function Docs({ content, sourcePath, rssHref, children }: DocsProps) {
143
+ function Docs({ content, sourcePath, rssHref, lang, children }: DocsProps) {
141
144
  const components = useMDXComponents({
142
145
  pre: createMermaidPre(sourcePath),
143
146
  ApiPlaygroundDemo,
@@ -165,7 +168,7 @@ function Docs({ content, sourcePath, rssHref, children }: DocsProps) {
165
168
 
166
169
  return (
167
170
  <>
168
- <DocsContainer>
171
+ <DocsContainer lang={lang}>
169
172
  <ActionBar content={content} rssHref={rssHref}>
170
173
  <Flex $gap={20}>
171
174
  <StyledMarkdownContainer>
@@ -1 +1 @@
1
- export declare const docsSideBarTemplate = "\"use client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Space } from \"cherry-styled-components\";\nimport {\n StyledIndexSidebar,\n StyledIndexSidebarLink,\n StyledIndexSidebarLabel,\n StyledIndexSidebarLi,\n} from \"@/components/layout/DocsComponents\";\n\ninterface Heading {\n id: string;\n text: string;\n level: number;\n}\n\nconst FALLBACK_OFFSET = 60;\n\nfunction getOffset() {\n const header = document.getElementById(\"header\");\n return (header ? header.offsetHeight : FALLBACK_OFFSET) + 20;\n}\n\nexport function DocsSideBar({ headings }: { headings: Heading[] }) {\n const [activeId, setActiveId] = useState<string>(\"\");\n const activeRef = useRef<HTMLLIElement>(null);\n\n const handleScroll = useCallback(() => {\n if (headings.length === 0) return;\n\n const headingElements = headings\n .map((heading) => document.getElementById(heading.id))\n .filter((el): el is HTMLElement => el !== null);\n\n if (headingElements.length === 0) return;\n\n const windowHeight = window.innerHeight;\n\n const visibleHeadings = headingElements.filter((element) => {\n const rect = element.getBoundingClientRect();\n const elementTop = rect.top;\n const elementBottom = rect.bottom;\n return elementTop < windowHeight && elementBottom > -50;\n });\n\n if (visibleHeadings.length > 0) {\n let closestHeading = visibleHeadings[0];\n let closestDistance = Math.abs(\n closestHeading.getBoundingClientRect().top - getOffset(),\n );\n for (const heading of visibleHeadings) {\n const distance = Math.abs(\n heading.getBoundingClientRect().top - getOffset(),\n );\n if (\n distance < closestDistance &&\n heading.getBoundingClientRect().top <= windowHeight * 0.3\n ) {\n closestDistance = distance;\n closestHeading = heading;\n }\n }\n setActiveId(closestHeading.id);\n return;\n }\n\n let currentActiveId = headings[0].id;\n for (const element of headingElements) {\n const rect = element.getBoundingClientRect();\n if (rect.top <= getOffset()) {\n currentActiveId = element.id;\n } else {\n break;\n }\n }\n setActiveId(currentActiveId);\n }, [headings]);\n\n useEffect(() => {\n if (headings.length === 0) return;\n // Set active heading from URL hash immediately on mount (deferred to next frame)\n const hashId = window.location.hash ? window.location.hash.slice(1) : null;\n // Run initial scroll check on next frame to avoid synchronous setState in effect\n const rafId = requestAnimationFrame(() => {\n if (hashId) {\n setActiveId(hashId);\n }\n handleScroll();\n });\n // Re-check after browser finishes scrolling to hash target on new page load\n const delayedId = setTimeout(handleScroll, 300);\n let timeoutId: NodeJS.Timeout;\n const throttledHandleScroll = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(handleScroll, 50);\n };\n window.addEventListener(\"scroll\", throttledHandleScroll);\n window.addEventListener(\"resize\", handleScroll);\n return () => {\n window.removeEventListener(\"scroll\", throttledHandleScroll);\n window.removeEventListener(\"resize\", handleScroll);\n cancelAnimationFrame(rafId);\n clearTimeout(delayedId);\n clearTimeout(timeoutId);\n };\n }, [handleScroll, headings]);\n\n useEffect(() => {\n const el = activeRef.current;\n const container = el?.closest(\"[data-sidebar]\") as HTMLElement | null;\n if (!el || !container) return;\n const elRect = el.getBoundingClientRect();\n const cRect = container.getBoundingClientRect();\n const pad = 140;\n // Animate the scroll, but honor users who opt out of motion.\n const behavior = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n .matches\n ? \"auto\"\n : \"smooth\";\n if (elRect.bottom + pad > cRect.bottom) {\n container.scrollBy({\n top: elRect.bottom - cRect.bottom + pad,\n behavior,\n });\n } else if (elRect.top - pad < cRect.top) {\n container.scrollBy({\n top: elRect.top - cRect.top - pad,\n behavior,\n });\n }\n }, [activeId]);\n\n const handleHeadingClick = (headingId: string) => {\n const element = document.getElementById(headingId);\n if (element) {\n const elementPosition =\n element.getBoundingClientRect().top + window.scrollY;\n window.scrollTo({\n top: elementPosition - getOffset(),\n behavior: \"smooth\",\n });\n }\n };\n\n return (\n <StyledIndexSidebar data-sidebar data-markdown-ignore>\n {headings?.length > 0 && (\n <li aria-hidden=\"true\">\n <StyledIndexSidebarLabel>On this page</StyledIndexSidebarLabel>\n <Space $size={15} />\n </li>\n )}\n {headings.map((heading, index) => (\n <StyledIndexSidebarLi\n key={index}\n ref={activeId === heading.id ? activeRef : null}\n $isActive={activeId === heading.id}\n style={{ paddingLeft: `${(heading.level - 1) * 16}px` }}\n >\n <StyledIndexSidebarLink\n href={`#${heading.id}`}\n onClick={(e) => {\n e.preventDefault();\n handleHeadingClick(heading.id);\n }}\n $isActive={activeId === heading.id}\n >\n {heading.text}\n </StyledIndexSidebarLink>\n </StyledIndexSidebarLi>\n ))}\n </StyledIndexSidebar>\n );\n}\n";
1
+ export declare const docsSideBarTemplate = "\"use client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Space } from \"cherry-styled-components\";\nimport { useStrings } from \"@/components/useStrings\";\nimport {\n StyledIndexSidebar,\n StyledIndexSidebarLink,\n StyledIndexSidebarLabel,\n StyledIndexSidebarLi,\n} from \"@/components/layout/DocsComponents\";\n\ninterface Heading {\n id: string;\n text: string;\n level: number;\n}\n\nconst FALLBACK_OFFSET = 60;\n\nfunction getOffset() {\n const header = document.getElementById(\"header\");\n return (header ? header.offsetHeight : FALLBACK_OFFSET) + 20;\n}\n\nexport function DocsSideBar({ headings }: { headings: Heading[] }) {\n const [activeId, setActiveId] = useState<string>(\"\");\n const activeRef = useRef<HTMLLIElement>(null);\n const t = useStrings();\n\n const handleScroll = useCallback(() => {\n if (headings.length === 0) return;\n\n const headingElements = headings\n .map((heading) => document.getElementById(heading.id))\n .filter((el): el is HTMLElement => el !== null);\n\n if (headingElements.length === 0) return;\n\n const windowHeight = window.innerHeight;\n\n const visibleHeadings = headingElements.filter((element) => {\n const rect = element.getBoundingClientRect();\n const elementTop = rect.top;\n const elementBottom = rect.bottom;\n return elementTop < windowHeight && elementBottom > -50;\n });\n\n if (visibleHeadings.length > 0) {\n let closestHeading = visibleHeadings[0];\n let closestDistance = Math.abs(\n closestHeading.getBoundingClientRect().top - getOffset(),\n );\n for (const heading of visibleHeadings) {\n const distance = Math.abs(\n heading.getBoundingClientRect().top - getOffset(),\n );\n if (\n distance < closestDistance &&\n heading.getBoundingClientRect().top <= windowHeight * 0.3\n ) {\n closestDistance = distance;\n closestHeading = heading;\n }\n }\n setActiveId(closestHeading.id);\n return;\n }\n\n let currentActiveId = headings[0].id;\n for (const element of headingElements) {\n const rect = element.getBoundingClientRect();\n if (rect.top <= getOffset()) {\n currentActiveId = element.id;\n } else {\n break;\n }\n }\n setActiveId(currentActiveId);\n }, [headings]);\n\n useEffect(() => {\n if (headings.length === 0) return;\n // Set active heading from URL hash immediately on mount (deferred to next frame)\n const hashId = window.location.hash ? window.location.hash.slice(1) : null;\n // Run initial scroll check on next frame to avoid synchronous setState in effect\n const rafId = requestAnimationFrame(() => {\n if (hashId) {\n setActiveId(hashId);\n }\n handleScroll();\n });\n // Re-check after browser finishes scrolling to hash target on new page load\n const delayedId = setTimeout(handleScroll, 300);\n let timeoutId: NodeJS.Timeout;\n const throttledHandleScroll = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(handleScroll, 50);\n };\n window.addEventListener(\"scroll\", throttledHandleScroll);\n window.addEventListener(\"resize\", handleScroll);\n return () => {\n window.removeEventListener(\"scroll\", throttledHandleScroll);\n window.removeEventListener(\"resize\", handleScroll);\n cancelAnimationFrame(rafId);\n clearTimeout(delayedId);\n clearTimeout(timeoutId);\n };\n }, [handleScroll, headings]);\n\n useEffect(() => {\n const el = activeRef.current;\n const container = el?.closest(\"[data-sidebar]\") as HTMLElement | null;\n if (!el || !container) return;\n const elRect = el.getBoundingClientRect();\n const cRect = container.getBoundingClientRect();\n const pad = 140;\n // Animate the scroll, but honor users who opt out of motion.\n const behavior = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n .matches\n ? \"auto\"\n : \"smooth\";\n if (elRect.bottom + pad > cRect.bottom) {\n container.scrollBy({\n top: elRect.bottom - cRect.bottom + pad,\n behavior,\n });\n } else if (elRect.top - pad < cRect.top) {\n container.scrollBy({\n top: elRect.top - cRect.top - pad,\n behavior,\n });\n }\n }, [activeId]);\n\n const handleHeadingClick = (headingId: string) => {\n const element = document.getElementById(headingId);\n if (element) {\n const elementPosition =\n element.getBoundingClientRect().top + window.scrollY;\n window.scrollTo({\n top: elementPosition - getOffset(),\n behavior: \"smooth\",\n });\n }\n };\n\n return (\n <StyledIndexSidebar data-sidebar data-markdown-ignore>\n {headings?.length > 0 && (\n <li aria-hidden=\"true\">\n <StyledIndexSidebarLabel>{t.onThisPage}</StyledIndexSidebarLabel>\n <Space $size={15} />\n </li>\n )}\n {headings.map((heading, index) => (\n <StyledIndexSidebarLi\n key={index}\n ref={activeId === heading.id ? activeRef : null}\n $isActive={activeId === heading.id}\n style={{ paddingLeft: `${(heading.level - 1) * 16}px` }}\n >\n <StyledIndexSidebarLink\n href={`#${heading.id}`}\n onClick={(e) => {\n e.preventDefault();\n handleHeadingClick(heading.id);\n }}\n $isActive={activeId === heading.id}\n >\n {heading.text}\n </StyledIndexSidebarLink>\n </StyledIndexSidebarLi>\n ))}\n </StyledIndexSidebar>\n );\n}\n";