doccupine 0.0.157 → 0.0.159

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 (153) hide show
  1. package/README.md +52 -2
  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/icon-registry-generator.d.ts +8 -5
  6. package/dist/generator/icon-registry-generator.js +19 -11
  7. package/dist/generator/mdx-pass-builder.d.ts +4 -4
  8. package/dist/generator/mdx-pass-builder.js +8 -1
  9. package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
  10. package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
  11. package/dist/generator/page-catalog.d.ts +2 -4
  12. package/dist/generator/page-catalog.js +7 -2
  13. package/dist/generator/page-renderer.d.ts +15 -5
  14. package/dist/generator/page-renderer.js +38 -11
  15. package/dist/generator/project-config-repository.d.ts +4 -1
  16. package/dist/generator/project-config-repository.js +26 -0
  17. package/dist/generator/public-asset-manager.d.ts +10 -0
  18. package/dist/generator/public-asset-manager.js +63 -3
  19. package/dist/generator/section-index-generator.d.ts +10 -1
  20. package/dist/generator/section-index-generator.js +43 -15
  21. package/dist/generator/section-resolver.d.ts +8 -0
  22. package/dist/generator/site-artifacts.d.ts +4 -3
  23. package/dist/generator/site-artifacts.js +94 -9
  24. package/dist/generator/watch-coordinator.js +6 -1
  25. package/dist/lib/generated-artifacts.d.ts +3 -0
  26. package/dist/lib/generated-artifacts.js +36 -0
  27. package/dist/lib/icon-registry.d.ts +10 -4
  28. package/dist/lib/icon-registry.js +13 -4
  29. package/dist/lib/layout.d.ts +6 -3
  30. package/dist/lib/layout.js +107 -4
  31. package/dist/lib/metadata.d.ts +7 -0
  32. package/dist/lib/metadata.js +33 -10
  33. package/dist/lib/structures.js +20 -0
  34. package/dist/lib/types.d.ts +28 -0
  35. package/dist/lib/ui-strings.d.ts +44 -0
  36. package/dist/lib/ui-strings.js +48 -0
  37. package/dist/lib/variants.d.ts +91 -0
  38. package/dist/lib/variants.js +411 -0
  39. package/dist/mdx-to-nextjs-generator.d.ts +22 -5
  40. package/dist/mdx-to-nextjs-generator.js +92 -12
  41. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  42. package/dist/templates/app/api/mcp/route.js +14 -1
  43. package/dist/templates/app/api/rag/route.d.ts +1 -1
  44. package/dist/templates/app/api/rag/route.js +13 -2
  45. package/dist/templates/app/api/search/route.d.ts +1 -1
  46. package/dist/templates/app/api/search/route.js +16 -1
  47. package/dist/templates/app/sitemap.d.ts +2 -0
  48. package/dist/templates/app/sitemap.js +48 -3
  49. package/dist/templates/components/Chat.d.ts +1 -1
  50. package/dist/templates/components/Chat.js +40 -12
  51. package/dist/templates/components/Docs.d.ts +1 -1
  52. package/dist/templates/components/Docs.js +5 -2
  53. package/dist/templates/components/DocsSideBar.d.ts +1 -1
  54. package/dist/templates/components/DocsSideBar.js +3 -1
  55. package/dist/templates/components/SearchDocs.d.ts +1 -1
  56. package/dist/templates/components/SearchDocs.js +17 -3
  57. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  58. package/dist/templates/components/SearchModalContent.js +22 -14
  59. package/dist/templates/components/SectionNavProvider.d.ts +1 -1
  60. package/dist/templates/components/SectionNavProvider.js +32 -20
  61. package/dist/templates/components/SideBar.d.ts +1 -1
  62. package/dist/templates/components/SideBar.js +26 -12
  63. package/dist/templates/components/layout/ActionBar.d.ts +1 -1
  64. package/dist/templates/components/layout/ActionBar.js +9 -7
  65. package/dist/templates/components/layout/Code.d.ts +1 -1
  66. package/dist/templates/components/layout/Code.js +6 -3
  67. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  68. package/dist/templates/components/layout/DocsComponents.js +38 -5
  69. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  70. package/dist/templates/components/layout/DocsNavigation.js +4 -2
  71. package/dist/templates/components/layout/Dropdown.d.ts +1 -0
  72. package/dist/templates/components/layout/Dropdown.js +308 -0
  73. package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
  74. package/dist/templates/components/layout/FocusModeToggle.js +7 -4
  75. package/dist/templates/components/layout/Footer.d.ts +1 -1
  76. package/dist/templates/components/layout/Footer.js +4 -2
  77. package/dist/templates/components/layout/Header.d.ts +1 -1
  78. package/dist/templates/components/layout/Header.js +18 -8
  79. package/dist/templates/components/layout/SectionBar.d.ts +1 -1
  80. package/dist/templates/components/layout/SectionBar.js +16 -10
  81. package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
  82. package/dist/templates/components/layout/VariantSwitchers.js +313 -0
  83. package/dist/templates/components/useStrings.d.ts +1 -0
  84. package/dist/templates/components/useStrings.js +10 -0
  85. package/dist/templates/components/useVariant.d.ts +1 -0
  86. package/dist/templates/components/useVariant.js +13 -0
  87. package/dist/templates/llms/llmsIndex.d.ts +13 -0
  88. package/dist/templates/llms/llmsIndex.js +18 -3
  89. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  90. package/dist/templates/mdx/ai-assistant.mdx.js +2 -0
  91. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  92. package/dist/templates/mdx/api-playground.mdx.js +2 -0
  93. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  94. package/dist/templates/mdx/commands.mdx.js +1 -1
  95. package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
  96. package/dist/templates/mdx/fonts.mdx.js +1 -1
  97. package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
  98. package/dist/templates/mdx/footer-links.mdx.js +1 -1
  99. package/dist/templates/mdx/index.mdx.d.ts +1 -1
  100. package/dist/templates/mdx/index.mdx.js +2 -0
  101. package/dist/templates/mdx/languages.mdx.d.ts +1 -0
  102. package/dist/templates/mdx/languages.mdx.js +94 -0
  103. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  104. package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
  105. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  106. package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
  107. package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
  108. package/dist/templates/mdx/navigation.mdx.js +2 -0
  109. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  110. package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
  111. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  112. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
  113. package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
  114. package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
  115. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  116. package/dist/templates/mdx/platform/index.mdx.js +1 -1
  117. package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
  118. package/dist/templates/mdx/platform/languages.mdx.js +50 -0
  119. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  120. package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
  121. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  122. package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
  123. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  124. package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
  125. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  126. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
  127. package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
  128. package/dist/templates/mdx/platform/versions.mdx.js +33 -0
  129. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  130. package/dist/templates/mdx/sections.mdx.js +1 -1
  131. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  132. package/dist/templates/mdx/theme.mdx.js +1 -1
  133. package/dist/templates/mdx/versions.mdx.d.ts +1 -0
  134. package/dist/templates/mdx/versions.mdx.js +78 -0
  135. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  136. package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
  137. package/dist/templates/prettierignore.d.ts +1 -1
  138. package/dist/templates/prettierignore.js +2 -0
  139. package/dist/templates/services/mcp/server.d.ts +1 -1
  140. package/dist/templates/services/mcp/server.js +54 -10
  141. package/dist/templates/services/mcp/tools.d.ts +1 -1
  142. package/dist/templates/services/mcp/tools.js +81 -6
  143. package/dist/templates/services/mcp/types.d.ts +1 -1
  144. package/dist/templates/services/mcp/types.js +10 -0
  145. package/dist/templates/services/search.d.ts +1 -1
  146. package/dist/templates/services/search.js +34 -4
  147. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  148. package/dist/templates/utils/orderNavItems.js +2 -0
  149. package/dist/templates/utils/strings.d.ts +1 -0
  150. package/dist/templates/utils/strings.js +27 -0
  151. package/dist/templates/utils/variants.d.ts +1 -0
  152. package/dist/templates/utils/variants.js +170 -0
  153. package/package.json +1 -1
@@ -1 +1 @@
1
- export declare const whatIsDoccupineMdxTemplate = "---\ntitle: \"What is Doccupine\"\ndescription: \"Doccupine is a CLI that turns a directory of MDX files into a complete, production-ready documentation website - no frontend work required.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 1\n---\n# What is Doccupine\n\n**Doccupine** is a CLI tool that turns a directory of MDX files into a complete Next.js documentation website. It is less of a framework you assemble and more of a tool that does the assembling for you - you bring the content, Doccupine builds the site.\n\n```bash\nnpx doccupine\n```\n\n## Philosophy\n\nDoccupine was built on a simple belief: writing documentation should feel like writing, not like building a web app. Most docs frameworks hand you a pile of libraries and configuration and expect you to wire up rendering, navigation, theming, and search yourself. Doccupine makes those decisions for you and gets out of the way, so the only thing left to do is write.\n\n## Content first\n\nYou write standard Markdown and MDX. No React, no build configuration, no component wiring. Your navigation, theming, and search are all derived from your files and a handful of JSON config files. If you can write a Markdown file, you can ship a documentation site.\n\n## Batteries included\n\nEverything you expect from a great docs site works the moment you run the command - MDX rendering, an auto-generated sidebar, dark and light themes, 14+ built-in components, full-text search, an AI chat assistant, and an MCP server. Nothing to install, nothing to opt into.\n\n<Callout type=\"info\">\n Every element on this page - this callout, the cards below, the code block above - is a live example of what your docs get out of the box, with zero setup.\n</Callout>\n\n## You control the output\n\nDoccupine generates a real Next.js 16 app that you can inspect, deploy anywhere, or fork into a separately maintained application. While you continue using Doccupine, its registered output paths remain generator-managed: every fresh run recreates `app` and may rewrite generated components, services, configuration, and manifests.\n\nKeep durable customizations in MDX, project-root JSON configuration, and `public`. If you want to modify the generated implementation directly, fork the app or stop regenerating it first.\n\n## Instant feedback\n\nRun `npx doccupine` to watch MDX, supported project-root configuration, public assets, and configured OpenAPI sources. Doccupine reconciles edits made during startup and keeps the last successful site when a watch refresh fails.\n\nFiles such as `theme.json`, `navigation.json`, `sections.json`, `fonts.json`, and `analytics.json` update live. Within `doccupine.json`, the `openapi` field updates live, while `watchDir`, `outputDir`, `port`, and `packageManager` require a restart.\n\n## AI-native\n\nDocumentation is not only read by people anymore. Doccupine ships a RAG-powered chat assistant so readers can ask questions in natural language, and an MCP server so AI tools and agents can search your documentation directly. Your content is ready for both audiences from day one.\n\n## Opinionated, on purpose\n\nDoccupine makes the boring decisions - layout, typography, color, navigation structure - so you can spend your time on the words that matter. When you are ready to customize, simple JSON files let you adjust site metadata, navigation, theme, and fonts without touching a line of code.\n\n## When to use Doccupine\n\nDoccupine is built for anyone who needs a polished documentation site without becoming a frontend engineer.\n\n- Product and API documentation\n- Developer guides and tutorials\n- Internal knowledge bases and runbooks\n- Design systems and component references\n\nThere are two ways to run it:\n\n<Columns cols={2}>\n <Card title=\"Local CLI\" icon=\"terminal\" href=\"/\">\n `npx doccupine` scaffolds and serves the site on your machine, and you self-host the generated Next.js app anywhere.\n </Card>\n <Card title=\"Doccupine Platform\" icon=\"cloud\" href=\"/platform\">\n A managed, browser-based experience with a visual editor, one-click publishing, custom domains, and team collaboration - no local setup.\n </Card>\n</Columns>";
1
+ export declare const whatIsDoccupineMdxTemplate = "---\ntitle: \"What is Doccupine\"\ndescription: \"Doccupine is a CLI that turns a directory of MDX files into a complete, production-ready documentation website - no frontend work required.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 1\n---\n# What is Doccupine\n\n**Doccupine** is a CLI tool that turns a directory of MDX files into a complete Next.js documentation website. It is less of a framework you assemble and more of a tool that does the assembling for you - you bring the content, Doccupine builds the site.\n\n```bash\nnpx doccupine\n```\n\n## Philosophy\n\nDoccupine was built on a simple belief: writing documentation should feel like writing, not like building a web app. Most docs frameworks hand you a pile of libraries and configuration and expect you to wire up rendering, navigation, theming, and search yourself. Doccupine makes those decisions for you and gets out of the way, so the only thing left to do is write.\n\n## Content first\n\nYou write standard Markdown and MDX. No React, no build configuration, no component wiring. Your navigation, theming, and search are all derived from your files and a handful of JSON config files. If you can write a Markdown file, you can ship a documentation site.\n\n## Batteries included\n\nEverything you expect from a great docs site works the moment you run the command - MDX rendering, an auto-generated sidebar, dark and light themes, 14+ built-in components, full-text search, an AI chat assistant, and an MCP server. Nothing to install, nothing to opt into.\n\n<Callout type=\"info\">\n Every element on this page - this callout, the cards below, the code block above - is a live example of what your docs get out of the box, with zero setup.\n</Callout>\n\n## You control the output\n\nDoccupine generates a real Next.js 16 app that you can inspect, deploy anywhere, or fork into a separately maintained application. While you continue using Doccupine, its registered output paths remain generator-managed: every fresh run recreates `app` and may rewrite generated components, services, configuration, and manifests.\n\nKeep durable customizations in MDX, project-root JSON configuration, and `public`. If you want to modify the generated implementation directly, fork the app or stop regenerating it first.\n\n## Instant feedback\n\nRun `npx doccupine` to watch MDX, supported project-root configuration, public assets, and configured OpenAPI sources. Doccupine reconciles edits made during startup and keeps the last successful site when a watch refresh fails.\n\nFiles such as `theme.json`, `navigation.json`, `sections.json`, `languages.json`, `versions.json`, `fonts.json`, and `analytics.json` update live. Within `doccupine.json`, the `openapi` field updates live, while `watchDir`, `outputDir`, `port`, and `packageManager` require a restart.\n\n## AI-native\n\nDocumentation is not only read by people anymore. Doccupine ships a RAG-powered chat assistant so readers can ask questions in natural language, and an MCP server so AI tools and agents can search your documentation directly. Your content is ready for both audiences from day one.\n\n## Opinionated, on purpose\n\nDoccupine makes the boring decisions - layout, typography, color, navigation structure - so you can spend your time on the words that matter. When you are ready to customize, simple JSON files let you adjust site metadata, navigation, theme, and fonts without touching a line of code.\n\n## When to use Doccupine\n\nDoccupine is built for anyone who needs a polished documentation site without becoming a frontend engineer.\n\n- Product and API documentation\n- Developer guides and tutorials\n- Internal knowledge bases and runbooks\n- Design systems and component references\n\nThere are two ways to run it:\n\n<Columns cols={2}>\n <Card title=\"Local CLI\" icon=\"terminal\" href=\"/\">\n `npx doccupine` scaffolds and serves the site on your machine, and you self-host the generated Next.js app anywhere.\n </Card>\n <Card title=\"Doccupine Platform\" icon=\"cloud\" href=\"/platform\">\n A managed, browser-based experience with a visual editor, one-click publishing, custom domains, and team collaboration - no local setup.\n </Card>\n</Columns>";
@@ -41,7 +41,7 @@ Keep durable customizations in MDX, project-root JSON configuration, and \`publi
41
41
 
42
42
  Run \`npx doccupine\` to watch MDX, supported project-root configuration, public assets, and configured OpenAPI sources. Doccupine reconciles edits made during startup and keeps the last successful site when a watch refresh fails.
43
43
 
44
- Files such as \`theme.json\`, \`navigation.json\`, \`sections.json\`, \`fonts.json\`, and \`analytics.json\` update live. Within \`doccupine.json\`, the \`openapi\` field updates live, while \`watchDir\`, \`outputDir\`, \`port\`, and \`packageManager\` require a restart.
44
+ Files such as \`theme.json\`, \`navigation.json\`, \`sections.json\`, \`languages.json\`, \`versions.json\`, \`fonts.json\`, and \`analytics.json\` update live. Within \`doccupine.json\`, the \`openapi\` field updates live, while \`watchDir\`, \`outputDir\`, \`port\`, and \`packageManager\` require a restart.
45
45
 
46
46
  ## AI-native
47
47
 
@@ -1 +1 @@
1
- export declare const prettierignoreTemplate = "node_modules\nconvex/_generated\npublic\npackage.json\npackage-lock.json\npnpm-lock.yaml\npnpm-workspace.yaml\nservices/mcp/docs-index.json\n.doccupine-*\n\n# Mirrored verbatim from the project root, so their formatting is the author's\n# choice rather than generated output. Reformatting them here would also make\n# the copy differ from the source it is fingerprinted against.\nanalytics.json\nconfig.json\nfonts.json\nlinks.json\nnavigation.json\nsections.json\ntheme.json\n";
1
+ export declare const prettierignoreTemplate = "node_modules\nconvex/_generated\npublic\npackage.json\npackage-lock.json\npnpm-lock.yaml\npnpm-workspace.yaml\nservices/mcp/docs-index.json\n.doccupine-*\n\n# Mirrored verbatim from the project root, so their formatting is the author's\n# choice rather than generated output. Reformatting them here would also make\n# the copy differ from the source it is fingerprinted against.\nanalytics.json\nconfig.json\nfonts.json\nlanguages.json\nlinks.json\nnavigation.json\nsections.json\ntheme.json\nversions.json\n";
@@ -14,8 +14,10 @@ services/mcp/docs-index.json
14
14
  analytics.json
15
15
  config.json
16
16
  fonts.json
17
+ languages.json
17
18
  links.json
18
19
  navigation.json
19
20
  sections.json
20
21
  theme.json
22
+ versions.json
21
23
  `;
@@ -1 +1 @@
1
- export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n 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\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register the documentation index as a resource\n server.registerResource(\n \"docs-list\",\n \"docs://list\",\n {\n title: \"Documentation index\",\n description:\n \"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read\",\n mimeType: \"application/json\",\n },\n async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n mimeType: \"application/json\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n },\n );\n\n // Register every documentation page as a readable docs://<route> resource.\n // `{+path}` is a reserved expansion so nested routes keep their slashes.\n // The fixed docs://list resource above is matched before this template.\n server.registerResource(\n \"doc\",\n new ResourceTemplate(\"docs://{+path}\", { list: undefined }),\n {\n title: \"Documentation page\",\n description:\n \"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index\",\n mimeType: \"text/markdown\",\n },\n async (uri, _variables, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new Error(`Document not found: ${uri.href}`);\n }\n return {\n contents: [\n { uri: doc.uri, mimeType: \"text/markdown\", text: doc.content },\n ],\n };\n },\n );\n\n return server;\n}\n";
1
+ export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listAllDocs,\n listDocs,\n getDoc,\n getAllDocsChunks,\n matchesDocsFilter,\n resolveDocsFilter,\n DOCS_TOOLS,\n type DocsFilter,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\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\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n language: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({\n directory: z.string().max(500).optional(),\n language: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\n/** The language/version fields of a doc or chunk, for tool results. */\nfunction variantFields(doc: { locale?: string; version?: string }) {\n return {\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n };\n}\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n ...(c.locale !== undefined ? { locale: c.locale } : {}),\n ...(c.version !== undefined ? { version: c.version } : {}),\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n filter: DocsFilter = resolveDocsFilter(),\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n // One index holds every language and version; the filter keeps the answer\n // inside the variant the reader is looking at.\n const scored = docsIndex.chunks\n .filter((c) => matchesDocsFilter(c, filter))\n .map(({ embedding, ...chunk }) => ({\n chunk,\n score: cosineFloatInt8(queryVector, embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit, language, version }, { signal }) => {\n const results = await searchDocs(\n query,\n limit ?? 6,\n signal,\n resolveDocsFilter({ language, version }),\n );\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...variantFields(chunk),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory, language, version }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory, language, version });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n ...variantFields(d),\n })),\n );\n },\n );\n\n // Register the documentation index as a resource\n server.registerResource(\n \"docs-list\",\n \"docs://list\",\n {\n title: \"Documentation index\",\n description:\n \"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read\",\n mimeType: \"application/json\",\n },\n async () => {\n // The index lists every language and version; each entry carries its\n // language/version so a client can pick the variant it wants to read.\n const docs = await listAllDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n mimeType: \"application/json\",\n text: resourceText(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n ...variantFields(d),\n })),\n ),\n },\n ],\n };\n },\n );\n\n // Register every documentation page as a readable docs://<route> resource.\n // `{+path}` is a reserved expansion so nested routes keep their slashes.\n // The fixed docs://list resource above is matched before this template.\n server.registerResource(\n \"doc\",\n new ResourceTemplate(\"docs://{+path}\", { list: undefined }),\n {\n title: \"Documentation page\",\n description:\n \"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index\",\n mimeType: \"text/markdown\",\n },\n async (uri, _variables, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new Error(`Document not found: ${uri.href}`);\n }\n return {\n contents: [\n { uri: doc.uri, mimeType: \"text/markdown\", text: doc.content },\n ],\n };\n },\n );\n\n return server;\n}\n";
@@ -6,10 +6,14 @@ import {
6
6
  } from "@modelcontextprotocol/sdk/server/mcp.js";
7
7
  import { z } from "zod";
8
8
  import {
9
+ listAllDocs,
9
10
  listDocs,
10
11
  getDoc,
11
12
  getAllDocsChunks,
13
+ matchesDocsFilter,
14
+ resolveDocsFilter,
12
15
  DOCS_TOOLS,
16
+ type DocsFilter,
13
17
  } from "@/services/mcp/tools";
14
18
  import { getLLMConfig, createEmbeddings } from "@/services/llm";
15
19
  import {
@@ -27,10 +31,18 @@ export const MCP_MAX_REQUEST_BYTES = 64 * 1024;
27
31
  export const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;
28
32
  export const MCP_MAX_RESULT_BYTES = 256 * 1024;
29
33
 
34
+ // A language code or version slug is a lowercase URL segment.
35
+ const variantTokenSchema = z
36
+ .string()
37
+ .regex(/^[a-z0-9-]{1,32}$/)
38
+ .optional();
39
+
30
40
  export const searchDocsArgsSchema = z
31
41
  .object({
32
42
  query: z.string().min(1).max(2000),
33
43
  limit: z.number().int().min(1).max(20).optional(),
44
+ language: variantTokenSchema,
45
+ version: variantTokenSchema,
34
46
  })
35
47
  .strict();
36
48
 
@@ -39,9 +51,21 @@ export const getDocArgsSchema = z
39
51
  .strict();
40
52
 
41
53
  export const listDocsArgsSchema = z
42
- .object({ directory: z.string().max(500).optional() })
54
+ .object({
55
+ directory: z.string().max(500).optional(),
56
+ language: variantTokenSchema,
57
+ version: variantTokenSchema,
58
+ })
43
59
  .strict();
44
60
 
61
+ /** The language/version fields of a doc or chunk, for tool results. */
62
+ function variantFields(doc: { locale?: string; version?: string }) {
63
+ return {
64
+ ...(doc.locale !== undefined ? { language: doc.locale } : {}),
65
+ ...(doc.version !== undefined ? { version: doc.version } : {}),
66
+ };
67
+ }
68
+
45
69
  export function serializeMCPResult(value: unknown): {
46
70
  text: string;
47
71
  tooLarge: boolean;
@@ -168,6 +192,8 @@ function loadPrecomputedIndex(): IndexedChunk[] | null {
168
192
  text: c.text,
169
193
  path: c.path,
170
194
  uri: c.uri,
195
+ ...(c.locale !== undefined ? { locale: c.locale } : {}),
196
+ ...(c.version !== undefined ? { version: c.version } : {}),
171
197
  embedding,
172
198
  });
173
199
  }
@@ -369,6 +395,7 @@ export async function searchDocs(
369
395
  query: string,
370
396
  limit = 6,
371
397
  signal?: AbortSignal,
398
+ filter: DocsFilter = resolveDocsFilter(),
372
399
  ): Promise<{ chunk: DocsChunk; score: number }[]> {
373
400
  await ensureDocsIndex(false, signal);
374
401
  throwIfCancelled(signal);
@@ -379,10 +406,13 @@ export async function searchDocs(
379
406
  const rawQueryVector = await embedQuery(query, signal);
380
407
  const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);
381
408
 
409
+ // One index holds every language and version; the filter keeps the answer
410
+ // inside the variant the reader is looking at.
382
411
  const scored = docsIndex.chunks
383
- .map((c) => ({
384
- chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },
385
- score: cosineFloatInt8(queryVector, c.embedding),
412
+ .filter((c) => matchesDocsFilter(c, filter))
413
+ .map(({ embedding, ...chunk }) => ({
414
+ chunk,
415
+ score: cosineFloatInt8(queryVector, embedding),
386
416
  }))
387
417
  .sort((a, b) => b.score - a.score)
388
418
  .slice(0, normalizeSearchLimit(limit));
@@ -421,12 +451,18 @@ export function createMCPServer(): McpServer {
421
451
  description: DOCS_TOOLS[0].description,
422
452
  inputSchema: searchDocsArgsSchema,
423
453
  },
424
- async ({ query, limit }, { signal }) => {
425
- const results = await searchDocs(query, limit ?? 6, signal);
454
+ async ({ query, limit, language, version }, { signal }) => {
455
+ const results = await searchDocs(
456
+ query,
457
+ limit ?? 6,
458
+ signal,
459
+ resolveDocsFilter({ language, version }),
460
+ );
426
461
  return toolResult(
427
462
  results.map(({ chunk, score }) => ({
428
463
  path: chunk.path,
429
464
  uri: chunk.uri,
465
+ ...variantFields(chunk),
430
466
  score: score.toFixed(3),
431
467
  text: chunk.text,
432
468
  })),
@@ -459,15 +495,16 @@ export function createMCPServer(): McpServer {
459
495
  description: DOCS_TOOLS[2].description,
460
496
  inputSchema: listDocsArgsSchema,
461
497
  },
462
- async ({ directory }, { signal }) => {
498
+ async ({ directory, language, version }, { signal }) => {
463
499
  signal.throwIfAborted();
464
- const docs = await listDocs({ directory });
500
+ const docs = await listDocs({ directory, language, version });
465
501
  signal.throwIfAborted();
466
502
  return toolResult(
467
503
  docs.map((d) => ({
468
504
  name: d.name,
469
505
  path: d.path,
470
506
  uri: d.uri,
507
+ ...variantFields(d),
471
508
  })),
472
509
  );
473
510
  },
@@ -484,14 +521,21 @@ export function createMCPServer(): McpServer {
484
521
  mimeType: "application/json",
485
522
  },
486
523
  async () => {
487
- const docs = await listDocs();
524
+ // The index lists every language and version; each entry carries its
525
+ // language/version so a client can pick the variant it wants to read.
526
+ const docs = await listAllDocs();
488
527
  return {
489
528
  contents: [
490
529
  {
491
530
  uri: "docs://list",
492
531
  mimeType: "application/json",
493
532
  text: resourceText(
494
- docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),
533
+ docs.map((d) => ({
534
+ name: d.name,
535
+ path: d.path,
536
+ uri: d.uri,
537
+ ...variantFields(d),
538
+ })),
495
539
  ),
496
540
  },
497
541
  ],
@@ -1 +1 @@
1
- export declare const mcpToolsTemplate = "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\n\n// Keep the corpus out of the function's JavaScript bundle. next.config.ts\n// traces this fixed file into the RAG/MCP functions, just like docs-index.json.\nconst DOCS_CONTENT_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-content.json\",\n);\n\nlet docsContentCache:\n { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;\n\nfunction loadDocsContent(): DocsResource[] {\n try {\n // Generated content changes while `next dev` stays alive. Key the cache by\n // file metadata so watch-mode updates become visible without parsing the\n // whole corpus on every tool call.\n const stat = fs.statSync(DOCS_CONTENT_FILE);\n if (\n docsContentCache?.mtimeMs === stat.mtimeMs &&\n docsContentCache.size === stat.size\n ) {\n return docsContentCache.docs;\n }\n const parsed: unknown = JSON.parse(\n fs.readFileSync(DOCS_CONTENT_FILE, \"utf8\"),\n );\n const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];\n docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };\n return docs;\n } catch {\n docsContentCache = undefined;\n return [];\n }\n}\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n },\n },\n },\n];\n\n/**\n * List all documentation resources\n */\nexport async function listDocs(\n params?: ListDocsParams,\n): Promise<DocsResource[]> {\n const docsContent = loadDocsContent();\n const filterDir = params?.directory?.replace(/\\\\/g, \"/\");\n const resources = filterDir\n ? docsContent.filter((doc) => doc.path.includes(filterDir))\n : docsContent;\n return resources.map((doc) => ({ ...doc }));\n}\n\n/**\n * Get a specific documentation page\n */\nexport async function getDoc(\n params: GetDocParams,\n): Promise<DocsResource | null> {\n const docsContent = loadDocsContent();\n const requested = params.path.trim().replace(/\\\\/g, \"/\");\n if (!requested || requested.includes(\"\\0\")) return null;\n\n const withoutScheme = requested.replace(/^docs:\\/\\//, \"\");\n const route = withoutScheme\n .replace(/^app\\/(?:\\([^/]+\\)\\/)?/, \"\")\n .replace(/(?:^|\\/)page\\.(?:tsx?|jsx?)$/, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n\n const doc = docsContent.find((candidate) => {\n const candidateRoute = candidate.uri\n .replace(/^docs:\\/\\//, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n return (\n candidate.path === requested ||\n candidate.uri === requested ||\n candidateRoute === route\n );\n });\n\n return doc ? { ...doc } : null;\n}\n\n/**\n * Chunk text for embeddings.\n * - chunkSize=800 chars balances granularity with embedding context window limits\n * - overlap=100 chars ensures continuity so searches don't miss content at chunk boundaries\n */\nfunction chunkText(text: string, chunkSize = 800, overlap = 100): string[] {\n const chunks: string[] = [];\n let i = 0;\n while (i < text.length) {\n const end = Math.min(i + chunkSize, text.length);\n chunks.push(text.slice(i, end));\n if (end === text.length) break;\n i = end - overlap;\n if (i < 0) i = 0;\n }\n return chunks;\n}\n\n/**\n * Get all documentation chunks for indexing\n */\nexport async function getAllDocsChunks(): Promise<DocsChunk[]> {\n const allChunks: DocsChunk[] = [];\n const docs = await listDocs();\n\n for (const doc of docs) {\n const cleanContent = doc.content\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n\n const textChunks = chunkText(cleanContent);\n for (let i = 0; i < textChunks.length; i++) {\n allChunks.push({\n id: `${doc.path}:${i}`,\n text: textChunks[i],\n path: doc.path,\n uri: doc.uri,\n });\n }\n }\n\n return allChunks;\n}\n";
1
+ export declare const mcpToolsTemplate = "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\nimport {\n defaultLanguage,\n isVariantsConfigured,\n languages,\n versions,\n} from \"@/utils/variants\";\n\n/** The language/version a docs query is scoped to. Empty when the site has\n * neither configured, so every page matches. */\nexport interface DocsFilter {\n locale?: string;\n version?: string;\n}\n\n/**\n * Resolve the scope of a docs query: the requested language and version, or\n * the site's default language / default version when a request names none.\n * A language or version the site does not declare matches nothing.\n */\nexport function resolveDocsFilter(params?: {\n language?: string;\n version?: string;\n}): DocsFilter {\n if (!isVariantsConfigured()) return {};\n const filter: DocsFilter = {};\n if (languages) {\n filter.locale = params?.language ?? defaultLanguage()?.code ?? \"\";\n }\n if (versions) {\n filter.version = params?.version ?? \"\";\n }\n return filter;\n}\n\nexport function matchesDocsFilter(\n doc: { locale?: string; version?: string },\n filter: DocsFilter,\n): boolean {\n return (\n (filter.locale === undefined || doc.locale === filter.locale) &&\n (filter.version === undefined || doc.version === filter.version)\n );\n}\n\n// Keep the corpus out of the function's JavaScript bundle. next.config.ts\n// traces this fixed file into the RAG/MCP functions, just like docs-index.json.\nconst DOCS_CONTENT_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-content.json\",\n);\n\nlet docsContentCache:\n { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;\n\nfunction loadDocsContent(): DocsResource[] {\n try {\n // Generated content changes while `next dev` stays alive. Key the cache by\n // file metadata so watch-mode updates become visible without parsing the\n // whole corpus on every tool call.\n const stat = fs.statSync(DOCS_CONTENT_FILE);\n if (\n docsContentCache?.mtimeMs === stat.mtimeMs &&\n docsContentCache.size === stat.size\n ) {\n return docsContentCache.docs;\n }\n const parsed: unknown = JSON.parse(\n fs.readFileSync(DOCS_CONTENT_FILE, \"utf8\"),\n );\n const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];\n docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };\n return docs;\n } catch {\n docsContentCache = undefined;\n return [];\n }\n}\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n language: {\n type: \"string\",\n description:\n \"Language code to search (e.g. 'de'); defaults to the site's default language\",\n },\n version: {\n type: \"string\",\n description:\n \"Documentation version slug to search (e.g. 'v1'); defaults to the current version\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n language: {\n type: \"string\",\n description:\n \"Language code to list (e.g. 'de'); defaults to the site's default language\",\n },\n version: {\n type: \"string\",\n description:\n \"Documentation version slug to list (e.g. 'v1'); defaults to the current version\",\n },\n },\n },\n },\n];\n\n/**\n * Every documentation resource in every language and version. Indexes are\n * built from this and filtered at query time.\n */\nexport async function listAllDocs(): Promise<DocsResource[]> {\n return loadDocsContent().map((doc) => ({ ...doc }));\n}\n\n/**\n * List the documentation resources of one language/version (the default\n * variant unless the params name another), optionally under a directory.\n */\nexport async function listDocs(\n params?: ListDocsParams,\n): Promise<DocsResource[]> {\n const docsContent = loadDocsContent();\n const filterDir = params?.directory?.replace(/\\\\/g, \"/\");\n const filter = resolveDocsFilter(params);\n return docsContent\n .filter((doc) => matchesDocsFilter(doc, filter))\n .filter((doc) => !filterDir || doc.path.includes(filterDir))\n .map((doc) => ({ ...doc }));\n}\n\n/**\n * Get a specific documentation page\n */\nexport async function getDoc(\n params: GetDocParams,\n): Promise<DocsResource | null> {\n const docsContent = loadDocsContent();\n const requested = params.path.trim().replace(/\\\\/g, \"/\");\n if (!requested || requested.includes(\"\\0\")) return null;\n\n const withoutScheme = requested.replace(/^docs:\\/\\//, \"\");\n const route = withoutScheme\n .replace(/^app\\/(?:\\([^/]+\\)\\/)?/, \"\")\n .replace(/(?:^|\\/)page\\.(?:tsx?|jsx?)$/, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n\n const doc = docsContent.find((candidate) => {\n const candidateRoute = candidate.uri\n .replace(/^docs:\\/\\//, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n return (\n candidate.path === requested ||\n candidate.uri === requested ||\n candidateRoute === route\n );\n });\n\n return doc ? { ...doc } : null;\n}\n\n/**\n * Chunk text for embeddings.\n * - chunkSize=800 chars balances granularity with embedding context window limits\n * - overlap=100 chars ensures continuity so searches don't miss content at chunk boundaries\n */\nfunction chunkText(text: string, chunkSize = 800, overlap = 100): string[] {\n const chunks: string[] = [];\n let i = 0;\n while (i < text.length) {\n const end = Math.min(i + chunkSize, text.length);\n chunks.push(text.slice(i, end));\n if (end === text.length) break;\n i = end - overlap;\n if (i < 0) i = 0;\n }\n return chunks;\n}\n\n/**\n * Get all documentation chunks for indexing\n */\nexport async function getAllDocsChunks(): Promise<DocsChunk[]> {\n const allChunks: DocsChunk[] = [];\n const docs = await listAllDocs();\n\n for (const doc of docs) {\n const cleanContent = doc.content\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n\n const textChunks = chunkText(cleanContent);\n for (let i = 0; i < textChunks.length; i++) {\n allChunks.push({\n id: `${doc.path}:${i}`,\n text: textChunks[i],\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { locale: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n });\n }\n }\n\n return allChunks;\n}\n";
@@ -7,6 +7,49 @@ import type {
7
7
  GetDocParams,
8
8
  ListDocsParams,
9
9
  } from "@/services/mcp/types";
10
+ import {
11
+ defaultLanguage,
12
+ isVariantsConfigured,
13
+ languages,
14
+ versions,
15
+ } from "@/utils/variants";
16
+
17
+ /** The language/version a docs query is scoped to. Empty when the site has
18
+ * neither configured, so every page matches. */
19
+ export interface DocsFilter {
20
+ locale?: string;
21
+ version?: string;
22
+ }
23
+
24
+ /**
25
+ * Resolve the scope of a docs query: the requested language and version, or
26
+ * the site's default language / default version when a request names none.
27
+ * A language or version the site does not declare matches nothing.
28
+ */
29
+ export function resolveDocsFilter(params?: {
30
+ language?: string;
31
+ version?: string;
32
+ }): DocsFilter {
33
+ if (!isVariantsConfigured()) return {};
34
+ const filter: DocsFilter = {};
35
+ if (languages) {
36
+ filter.locale = params?.language ?? defaultLanguage()?.code ?? "";
37
+ }
38
+ if (versions) {
39
+ filter.version = params?.version ?? "";
40
+ }
41
+ return filter;
42
+ }
43
+
44
+ export function matchesDocsFilter(
45
+ doc: { locale?: string; version?: string },
46
+ filter: DocsFilter,
47
+ ): boolean {
48
+ return (
49
+ (filter.locale === undefined || doc.locale === filter.locale) &&
50
+ (filter.version === undefined || doc.version === filter.version)
51
+ );
52
+ }
10
53
 
11
54
  // Keep the corpus out of the function's JavaScript bundle. next.config.ts
12
55
  // traces this fixed file into the RAG/MCP functions, just like docs-index.json.
@@ -63,6 +106,16 @@ export const DOCS_TOOLS: MCPToolDefinition[] = [
63
106
  type: "number",
64
107
  description: "Maximum number of results to return (default: 6)",
65
108
  },
109
+ language: {
110
+ type: "string",
111
+ description:
112
+ "Language code to search (e.g. 'de'); defaults to the site's default language",
113
+ },
114
+ version: {
115
+ type: "string",
116
+ description:
117
+ "Documentation version slug to search (e.g. 'v1'); defaults to the current version",
118
+ },
66
119
  },
67
120
  required: ["query"],
68
121
  },
@@ -95,23 +148,43 @@ export const DOCS_TOOLS: MCPToolDefinition[] = [
95
148
  description:
96
149
  "Optional directory to filter results (e.g., 'components')",
97
150
  },
151
+ language: {
152
+ type: "string",
153
+ description:
154
+ "Language code to list (e.g. 'de'); defaults to the site's default language",
155
+ },
156
+ version: {
157
+ type: "string",
158
+ description:
159
+ "Documentation version slug to list (e.g. 'v1'); defaults to the current version",
160
+ },
98
161
  },
99
162
  },
100
163
  },
101
164
  ];
102
165
 
103
166
  /**
104
- * List all documentation resources
167
+ * Every documentation resource in every language and version. Indexes are
168
+ * built from this and filtered at query time.
169
+ */
170
+ export async function listAllDocs(): Promise<DocsResource[]> {
171
+ return loadDocsContent().map((doc) => ({ ...doc }));
172
+ }
173
+
174
+ /**
175
+ * List the documentation resources of one language/version (the default
176
+ * variant unless the params name another), optionally under a directory.
105
177
  */
106
178
  export async function listDocs(
107
179
  params?: ListDocsParams,
108
180
  ): Promise<DocsResource[]> {
109
181
  const docsContent = loadDocsContent();
110
182
  const filterDir = params?.directory?.replace(/\\\\/g, "/");
111
- const resources = filterDir
112
- ? docsContent.filter((doc) => doc.path.includes(filterDir))
113
- : docsContent;
114
- return resources.map((doc) => ({ ...doc }));
183
+ const filter = resolveDocsFilter(params);
184
+ return docsContent
185
+ .filter((doc) => matchesDocsFilter(doc, filter))
186
+ .filter((doc) => !filterDir || doc.path.includes(filterDir))
187
+ .map((doc) => ({ ...doc }));
115
188
  }
116
189
 
117
190
  /**
@@ -167,7 +240,7 @@ function chunkText(text: string, chunkSize = 800, overlap = 100): string[] {
167
240
  */
168
241
  export async function getAllDocsChunks(): Promise<DocsChunk[]> {
169
242
  const allChunks: DocsChunk[] = [];
170
- const docs = await listDocs();
243
+ const docs = await listAllDocs();
171
244
 
172
245
  for (const doc of docs) {
173
246
  const cleanContent = doc.content
@@ -182,6 +255,8 @@ export async function getAllDocsChunks(): Promise<DocsChunk[]> {
182
255
  text: textChunks[i],
183
256
  path: doc.path,
184
257
  uri: doc.uri,
258
+ ...(doc.locale !== undefined ? { locale: doc.locale } : {}),
259
+ ...(doc.version !== undefined ? { version: doc.version } : {}),
185
260
  });
186
261
  }
187
262
  }
@@ -1 +1 @@
1
- export declare const mcpTypesTemplate = "export interface DocsResource {\n uri: string;\n name: string;\n path: string;\n content: string;\n}\n\nexport interface DocsChunk {\n id: string;\n text: string;\n path: string;\n uri: string;\n}\n\nexport interface GetDocParams {\n path: string;\n}\n\nexport interface ListDocsParams {\n directory?: string;\n}\n\nexport type MCPToolName = \"search_docs\" | \"get_doc\" | \"list_docs\";\n\nexport interface MCPToolDefinition {\n name: MCPToolName;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, unknown>;\n required?: string[];\n };\n}\n";
1
+ export declare const mcpTypesTemplate = "export interface DocsResource {\n uri: string;\n name: string;\n path: string;\n content: string;\n /** Language code and version slug; present only on sites that configure\n * languages.json / versions.json. */\n locale?: string;\n version?: string;\n}\n\nexport interface DocsChunk {\n id: string;\n text: string;\n path: string;\n uri: string;\n locale?: string;\n version?: string;\n}\n\nexport interface GetDocParams {\n path: string;\n}\n\nexport interface ListDocsParams {\n directory?: string;\n /** Language code and version slug to list; each defaults to the site's\n * default language / version when the site configures them. */\n language?: string;\n version?: string;\n}\n\nexport type MCPToolName = \"search_docs\" | \"get_doc\" | \"list_docs\";\n\nexport interface MCPToolDefinition {\n name: MCPToolName;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, unknown>;\n required?: string[];\n };\n}\n";
@@ -3,6 +3,10 @@ export const mcpTypesTemplate = `export interface DocsResource {
3
3
  name: string;
4
4
  path: string;
5
5
  content: string;
6
+ /** Language code and version slug; present only on sites that configure
7
+ * languages.json / versions.json. */
8
+ locale?: string;
9
+ version?: string;
6
10
  }
7
11
 
8
12
  export interface DocsChunk {
@@ -10,6 +14,8 @@ export interface DocsChunk {
10
14
  text: string;
11
15
  path: string;
12
16
  uri: string;
17
+ locale?: string;
18
+ version?: string;
13
19
  }
14
20
 
15
21
  export interface GetDocParams {
@@ -18,6 +24,10 @@ export interface GetDocParams {
18
24
 
19
25
  export interface ListDocsParams {
20
26
  directory?: string;
27
+ /** Language code and version slug to list; each defaults to the site's
28
+ * default language / version when the site configures them. */
29
+ language?: string;
30
+ version?: string;
21
31
  }
22
32
 
23
33
  export type MCPToolName = "search_docs" | "get_doc" | "list_docs";
@@ -1 +1 @@
1
- export declare const searchServiceTemplate = "import MiniSearch from \"minisearch\";\nimport { listDocs } from \"@/services/mcp/tools\";\n\ninterface IndexedDoc {\n id: string;\n slug: string;\n title: string;\n content: string;\n}\n\nexport interface SearchHit {\n slug: string;\n snippet: string;\n}\n\nlet index: MiniSearch<IndexedDoc> | null = null;\nlet docs: IndexedDoc[] = [];\nlet buildPromise: Promise<void> | null = null;\n\nconst CONTEXT_BEFORE = 60;\nconst CONTEXT_AFTER = 90;\n\n/**\n * Convert raw MDX (as extracted from the generated page templates) into plain,\n * human-readable text for search snippets: undoes the template-literal escaping\n * and strips common Markdown syntax so inline code shows as Test rather than a\n * backtick-wrapped or backslash-escaped fragment.\n */\nfunction toPlainText(text: string): string {\n return (\n text\n // Undo the template-literal escaping from the generated page files so\n // escaped backticks, dollar-braces and backslashes read as plain text.\n .replace(/\\\\([\\s\\S])/g, \"$1\")\n // Images and links -> visible text only.\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n // Bold markers.\n .replace(/\\*\\*([\\s\\S]*?)\\*\\*/g, \"$1\")\n // Line-leading markers: headings, blockquotes, list bullets.\n .replace(/^\\s{0,3}#{1,6}\\s+/gm, \"\")\n .replace(/^\\s{0,3}>\\s?/gm, \"\")\n .replace(/^\\s{0,3}[-*+]\\s+/gm, \"\")\n .replace(/^\\s{0,3}\\d+\\.\\s+/gm, \"\")\n // Inline code / escaped backticks -> plain text.\n .replace(/`/g, \"\")\n );\n}\n\nasync function ensureIndex(): Promise<MiniSearch<IndexedDoc>> {\n if (index) return index;\n if (buildPromise) {\n await buildPromise;\n return index!;\n }\n\n buildPromise = (async () => {\n const resources = await listDocs();\n\n docs = resources.map((doc) => {\n // Strip the leading \"app/\", the \"/page.ext\" suffix, and any Next.js\n // route-group segments like \"(site)\" which never appear in URLs. This\n // must match the URL slug produced by toDocPath() in mcp/tools.ts and\n // the nav slugs in the layout, otherwise content hits fail to map back\n // to a page on the client and get silently dropped.\n const slug = doc.path\n .replace(/^app\\//, \"\")\n .replace(/\\/page\\.\\w+$/, \"\")\n .split(\"/\")\n .filter((seg) => !(seg.startsWith(\"(\") && seg.endsWith(\")\")))\n .join(\"/\");\n const cleanContent = toPlainText(doc.content.replace(/\\r\\n/g, \"\\n\"))\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n return {\n id: slug || \"__index__\",\n slug,\n title: doc.name,\n content: cleanContent,\n };\n });\n\n index = new MiniSearch<IndexedDoc>({\n fields: [\"title\", \"content\"],\n storeFields: [\"slug\", \"title\", \"content\"],\n searchOptions: {\n boost: { title: 3 },\n fuzzy: 0.2,\n prefix: true,\n },\n });\n\n index.addAll(docs);\n })();\n\n await buildPromise;\n return index!;\n}\n\nfunction extractSnippet(content: string, query: string): string {\n const lower = content.toLowerCase();\n const qLower = query.toLowerCase();\n const matchIdx = lower.indexOf(qLower);\n\n if (matchIdx === -1) {\n // Fuzzy match - no exact substring. Return start of content.\n const end = Math.min(content.length, CONTEXT_BEFORE + CONTEXT_AFTER);\n const raw = content.slice(0, end).trim();\n return raw.length < content.length ? raw + \"...\" : raw;\n }\n\n let start = Math.max(0, matchIdx - CONTEXT_BEFORE);\n let end = Math.min(content.length, matchIdx + query.length + CONTEXT_AFTER);\n\n // Align to word boundaries\n if (start > 0) {\n const space = content.indexOf(\" \", start);\n if (space !== -1 && space < matchIdx) start = space + 1;\n }\n if (end < content.length) {\n const space = content.lastIndexOf(\" \", end);\n if (space > matchIdx + query.length) end = space;\n }\n\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < content.length ? \"...\" : \"\";\n const snippet = content.slice(start, end).replace(/\\n+/g, \" \").trim();\n\n return prefix + snippet + suffix;\n}\n\nexport async function searchContent(\n query: string,\n limit = 10,\n): Promise<SearchHit[]> {\n const q = query.trim();\n if (!q) return [];\n\n const idx = await ensureIndex();\n const results = idx.search(q);\n\n return results.slice(0, limit).map((result) => {\n const doc = docs.find((d) => d.id === result.id);\n const content = doc?.content || \"\";\n return {\n slug: doc?.slug || \"\",\n snippet: extractSnippet(content, q),\n };\n });\n}\n";
1
+ export declare const searchServiceTemplate = "import MiniSearch from \"minisearch\";\nimport {\n listAllDocs,\n matchesDocsFilter,\n resolveDocsFilter,\n} from \"@/services/mcp/tools\";\n\ninterface IndexedDoc {\n id: string;\n slug: string;\n title: string;\n content: string;\n locale?: string;\n version?: string;\n}\n\n/** The language/version a search is scoped to; each defaults to the site's\n * default variant when the site configures one. */\nexport interface SearchScope {\n locale?: string;\n version?: string;\n}\n\nexport interface SearchHit {\n slug: string;\n snippet: string;\n}\n\nlet index: MiniSearch<IndexedDoc> | null = null;\nlet docs: IndexedDoc[] = [];\nlet buildPromise: Promise<void> | null = null;\n\nconst CONTEXT_BEFORE = 60;\nconst CONTEXT_AFTER = 90;\n\n/**\n * Convert raw MDX (as extracted from the generated page templates) into plain,\n * human-readable text for search snippets: undoes the template-literal escaping\n * and strips common Markdown syntax so inline code shows as Test rather than a\n * backtick-wrapped or backslash-escaped fragment.\n */\nfunction toPlainText(text: string): string {\n return (\n text\n // Undo the template-literal escaping from the generated page files so\n // escaped backticks, dollar-braces and backslashes read as plain text.\n .replace(/\\\\([\\s\\S])/g, \"$1\")\n // Images and links -> visible text only.\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n // Bold markers.\n .replace(/\\*\\*([\\s\\S]*?)\\*\\*/g, \"$1\")\n // Line-leading markers: headings, blockquotes, list bullets.\n .replace(/^\\s{0,3}#{1,6}\\s+/gm, \"\")\n .replace(/^\\s{0,3}>\\s?/gm, \"\")\n .replace(/^\\s{0,3}[-*+]\\s+/gm, \"\")\n .replace(/^\\s{0,3}\\d+\\.\\s+/gm, \"\")\n // Inline code / escaped backticks -> plain text.\n .replace(/`/g, \"\")\n );\n}\n\nasync function ensureIndex(): Promise<MiniSearch<IndexedDoc>> {\n if (index) return index;\n if (buildPromise) {\n await buildPromise;\n return index!;\n }\n\n buildPromise = (async () => {\n // One index over every language and version; a search filters it down to\n // the variant the reader is looking at.\n const resources = await listAllDocs();\n\n docs = resources.map((doc) => {\n // Strip the leading \"app/\", the \"/page.ext\" suffix, and any Next.js\n // route-group segments like \"(site)\" which never appear in URLs. This\n // must match the URL slug produced by toDocPath() in mcp/tools.ts and\n // the nav slugs in the layout, otherwise content hits fail to map back\n // to a page on the client and get silently dropped.\n const slug = doc.path\n .replace(/^app\\//, \"\")\n .replace(/\\/page\\.\\w+$/, \"\")\n .split(\"/\")\n .filter((seg) => !(seg.startsWith(\"(\") && seg.endsWith(\")\")))\n .join(\"/\");\n const cleanContent = toPlainText(doc.content.replace(/\\r\\n/g, \"\\n\"))\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n return {\n id: slug || \"__index__\",\n slug,\n title: doc.name,\n content: cleanContent,\n ...(doc.locale !== undefined ? { locale: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n };\n });\n\n index = new MiniSearch<IndexedDoc>({\n fields: [\"title\", \"content\"],\n storeFields: [\"slug\", \"title\", \"content\", \"locale\", \"version\"],\n searchOptions: {\n boost: { title: 3 },\n fuzzy: 0.2,\n prefix: true,\n },\n });\n\n index.addAll(docs);\n })();\n\n await buildPromise;\n return index!;\n}\n\nfunction extractSnippet(content: string, query: string): string {\n const lower = content.toLowerCase();\n const qLower = query.toLowerCase();\n const matchIdx = lower.indexOf(qLower);\n\n if (matchIdx === -1) {\n // Fuzzy match - no exact substring. Return start of content.\n const end = Math.min(content.length, CONTEXT_BEFORE + CONTEXT_AFTER);\n const raw = content.slice(0, end).trim();\n return raw.length < content.length ? raw + \"...\" : raw;\n }\n\n let start = Math.max(0, matchIdx - CONTEXT_BEFORE);\n let end = Math.min(content.length, matchIdx + query.length + CONTEXT_AFTER);\n\n // Align to word boundaries\n if (start > 0) {\n const space = content.indexOf(\" \", start);\n if (space !== -1 && space < matchIdx) start = space + 1;\n }\n if (end < content.length) {\n const space = content.lastIndexOf(\" \", end);\n if (space > matchIdx + query.length) end = space;\n }\n\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < content.length ? \"...\" : \"\";\n const snippet = content.slice(start, end).replace(/\\n+/g, \" \").trim();\n\n return prefix + snippet + suffix;\n}\n\nexport async function searchContent(\n query: string,\n limit = 10,\n scope: SearchScope = {},\n): Promise<SearchHit[]> {\n const q = query.trim();\n if (!q) return [];\n\n const idx = await ensureIndex();\n const filter = resolveDocsFilter({\n language: scope.locale,\n version: scope.version,\n });\n const results = idx.search(q, {\n // MiniSearch types a result's stored fields loosely; they are the\n // indexed doc's own locale and version.\n filter: (result) =>\n matchesDocsFilter(\n result as unknown as Pick<IndexedDoc, \"locale\" | \"version\">,\n filter,\n ),\n });\n\n return results.slice(0, limit).map((result) => {\n const doc = docs.find((d) => d.id === result.id);\n const content = doc?.content || \"\";\n return {\n slug: doc?.slug || \"\",\n snippet: extractSnippet(content, q),\n };\n });\n}\n";
@@ -1,11 +1,24 @@
1
1
  export const searchServiceTemplate = `import MiniSearch from "minisearch";
2
- import { listDocs } from "@/services/mcp/tools";
2
+ import {
3
+ listAllDocs,
4
+ matchesDocsFilter,
5
+ resolveDocsFilter,
6
+ } from "@/services/mcp/tools";
3
7
 
4
8
  interface IndexedDoc {
5
9
  id: string;
6
10
  slug: string;
7
11
  title: string;
8
12
  content: string;
13
+ locale?: string;
14
+ version?: string;
15
+ }
16
+
17
+ /** The language/version a search is scoped to; each defaults to the site's
18
+ * default variant when the site configures one. */
19
+ export interface SearchScope {
20
+ locale?: string;
21
+ version?: string;
9
22
  }
10
23
 
11
24
  export interface SearchHit {
@@ -55,7 +68,9 @@ async function ensureIndex(): Promise<MiniSearch<IndexedDoc>> {
55
68
  }
56
69
 
57
70
  buildPromise = (async () => {
58
- const resources = await listDocs();
71
+ // One index over every language and version; a search filters it down to
72
+ // the variant the reader is looking at.
73
+ const resources = await listAllDocs();
59
74
 
60
75
  docs = resources.map((doc) => {
61
76
  // Strip the leading "app/", the "/page.ext" suffix, and any Next.js
@@ -77,12 +92,14 @@ async function ensureIndex(): Promise<MiniSearch<IndexedDoc>> {
77
92
  slug,
78
93
  title: doc.name,
79
94
  content: cleanContent,
95
+ ...(doc.locale !== undefined ? { locale: doc.locale } : {}),
96
+ ...(doc.version !== undefined ? { version: doc.version } : {}),
80
97
  };
81
98
  });
82
99
 
83
100
  index = new MiniSearch<IndexedDoc>({
84
101
  fields: ["title", "content"],
85
- storeFields: ["slug", "title", "content"],
102
+ storeFields: ["slug", "title", "content", "locale", "version"],
86
103
  searchOptions: {
87
104
  boost: { title: 3 },
88
105
  fuzzy: 0.2,
@@ -132,12 +149,25 @@ function extractSnippet(content: string, query: string): string {
132
149
  export async function searchContent(
133
150
  query: string,
134
151
  limit = 10,
152
+ scope: SearchScope = {},
135
153
  ): Promise<SearchHit[]> {
136
154
  const q = query.trim();
137
155
  if (!q) return [];
138
156
 
139
157
  const idx = await ensureIndex();
140
- const results = idx.search(q);
158
+ const filter = resolveDocsFilter({
159
+ language: scope.locale,
160
+ version: scope.version,
161
+ });
162
+ const results = idx.search(q, {
163
+ // MiniSearch types a result's stored fields loosely; they are the
164
+ // indexed doc's own locale and version.
165
+ filter: (result) =>
166
+ matchesDocsFilter(
167
+ result as unknown as Pick<IndexedDoc, "locale" | "version">,
168
+ filter,
169
+ ),
170
+ });
141
171
 
142
172
  return results.slice(0, limit).map((result) => {
143
173
  const doc = docs.find((d) => d.id === result.id);
@@ -1 +1 @@
1
- export declare const orderNavItemsTemplate = "export interface PagesProps {\n slug: string;\n title: string;\n date: string | null;\n category: string;\n description?: string;\n path?: string;\n categoryOrder?: number;\n order?: number;\n section?: string;\n navIcon?: string;\n categoryIcon?: string;\n httpMethod?: string;\n}\n\ninterface AccProps {\n [key: string]: {\n categoryOrder: number;\n icon?: string;\n pages: {\n date: string | null;\n slug: string;\n title: string;\n order: number;\n icon?: string;\n httpMethod?: string;\n }[];\n };\n}\n\nfunction transformPagesToGroupedStructure(pages: PagesProps[]) {\n const grouped = pages.reduce((acc: AccProps, page: PagesProps) => {\n const category = page.category || \"Uncategorized\";\n\n if (!acc[category]) {\n acc[category] = {\n categoryOrder: page.categoryOrder || 0,\n pages: [],\n };\n }\n\n // The first page in a category to declare a categoryIcon sets it.\n if (!acc[category].icon && page.categoryIcon) {\n acc[category].icon = page.categoryIcon;\n }\n\n acc[category].pages.push({\n date: page.date,\n slug: page.slug,\n title: page.title,\n order: page.order || 0,\n icon: page.navIcon,\n httpMethod: page.httpMethod,\n });\n\n return acc;\n }, {});\n\n return Object.entries(grouped)\n .sort(([, a], [, b]) => a.categoryOrder - b.categoryOrder)\n .map(([categoryName, categoryData], index) => ({\n slug: index === 0 ? \"\" : categoryName.toLowerCase().replace(/\\s+/g, \"-\"),\n label: categoryName,\n icon: categoryData.icon,\n links: categoryData.pages.sort((a, b) => a.order - b.order),\n }));\n}\n\nexport { transformPagesToGroupedStructure };\n";
1
+ export declare const orderNavItemsTemplate = "export interface PagesProps {\n slug: string;\n title: string;\n date: string | null;\n category: string;\n description?: string;\n path?: string;\n categoryOrder?: number;\n order?: number;\n section?: string;\n navIcon?: string;\n categoryIcon?: string;\n httpMethod?: string;\n locale?: string;\n version?: string;\n}\n\ninterface AccProps {\n [key: string]: {\n categoryOrder: number;\n icon?: string;\n pages: {\n date: string | null;\n slug: string;\n title: string;\n order: number;\n icon?: string;\n httpMethod?: string;\n }[];\n };\n}\n\nfunction transformPagesToGroupedStructure(pages: PagesProps[]) {\n const grouped = pages.reduce((acc: AccProps, page: PagesProps) => {\n const category = page.category || \"Uncategorized\";\n\n if (!acc[category]) {\n acc[category] = {\n categoryOrder: page.categoryOrder || 0,\n pages: [],\n };\n }\n\n // The first page in a category to declare a categoryIcon sets it.\n if (!acc[category].icon && page.categoryIcon) {\n acc[category].icon = page.categoryIcon;\n }\n\n acc[category].pages.push({\n date: page.date,\n slug: page.slug,\n title: page.title,\n order: page.order || 0,\n icon: page.navIcon,\n httpMethod: page.httpMethod,\n });\n\n return acc;\n }, {});\n\n return Object.entries(grouped)\n .sort(([, a], [, b]) => a.categoryOrder - b.categoryOrder)\n .map(([categoryName, categoryData], index) => ({\n slug: index === 0 ? \"\" : categoryName.toLowerCase().replace(/\\s+/g, \"-\"),\n label: categoryName,\n icon: categoryData.icon,\n links: categoryData.pages.sort((a, b) => a.order - b.order),\n }));\n}\n\nexport { transformPagesToGroupedStructure };\n";
@@ -11,6 +11,8 @@ export const orderNavItemsTemplate = `export interface PagesProps {
11
11
  navIcon?: string;
12
12
  categoryIcon?: string;
13
13
  httpMethod?: string;
14
+ locale?: string;
15
+ version?: string;
14
16
  }
15
17
 
16
18
  interface AccProps {
@@ -0,0 +1 @@
1
+ export declare const stringsUtilTemplate: string;