doccupine 0.0.158 → 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.
- package/README.md +51 -1
- package/dist/generator/app-scaffolder.js +11 -3
- package/dist/generator/generated-page-publisher.d.ts +6 -6
- package/dist/generator/generated-page-publisher.js +7 -5
- package/dist/generator/mdx-pass-builder.d.ts +4 -4
- package/dist/generator/mdx-pass-builder.js +8 -1
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
- package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
- package/dist/generator/page-catalog.d.ts +2 -4
- package/dist/generator/page-catalog.js +7 -2
- package/dist/generator/page-renderer.d.ts +15 -5
- package/dist/generator/page-renderer.js +38 -11
- package/dist/generator/project-config-repository.d.ts +4 -1
- package/dist/generator/project-config-repository.js +26 -0
- package/dist/generator/public-asset-manager.d.ts +10 -0
- package/dist/generator/public-asset-manager.js +63 -3
- package/dist/generator/section-index-generator.d.ts +10 -1
- package/dist/generator/section-index-generator.js +43 -15
- package/dist/generator/section-resolver.d.ts +8 -0
- package/dist/generator/site-artifacts.d.ts +4 -3
- package/dist/generator/site-artifacts.js +94 -9
- package/dist/generator/watch-coordinator.js +6 -1
- package/dist/lib/generated-artifacts.d.ts +3 -0
- package/dist/lib/generated-artifacts.js +36 -0
- package/dist/lib/layout.d.ts +6 -3
- package/dist/lib/layout.js +107 -4
- package/dist/lib/metadata.d.ts +7 -0
- package/dist/lib/metadata.js +33 -10
- package/dist/lib/structures.js +20 -0
- package/dist/lib/types.d.ts +28 -0
- package/dist/lib/ui-strings.d.ts +44 -0
- package/dist/lib/ui-strings.js +48 -0
- package/dist/lib/variants.d.ts +91 -0
- package/dist/lib/variants.js +411 -0
- package/dist/mdx-to-nextjs-generator.d.ts +22 -5
- package/dist/mdx-to-nextjs-generator.js +89 -10
- package/dist/templates/app/api/mcp/route.d.ts +1 -1
- package/dist/templates/app/api/mcp/route.js +14 -1
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +13 -2
- package/dist/templates/app/api/search/route.d.ts +1 -1
- package/dist/templates/app/api/search/route.js +16 -1
- package/dist/templates/app/sitemap.d.ts +2 -0
- package/dist/templates/app/sitemap.js +48 -3
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +40 -12
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +5 -2
- package/dist/templates/components/DocsSideBar.d.ts +1 -1
- package/dist/templates/components/DocsSideBar.js +3 -1
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +17 -3
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +22 -14
- package/dist/templates/components/SectionNavProvider.d.ts +1 -1
- package/dist/templates/components/SectionNavProvider.js +32 -20
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +26 -12
- package/dist/templates/components/layout/ActionBar.d.ts +1 -1
- package/dist/templates/components/layout/ActionBar.js +9 -7
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +6 -3
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +38 -5
- package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
- package/dist/templates/components/layout/DocsNavigation.js +4 -2
- package/dist/templates/components/layout/Dropdown.d.ts +1 -0
- package/dist/templates/components/layout/Dropdown.js +308 -0
- package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
- package/dist/templates/components/layout/FocusModeToggle.js +7 -4
- package/dist/templates/components/layout/Footer.d.ts +1 -1
- package/dist/templates/components/layout/Footer.js +4 -2
- package/dist/templates/components/layout/Header.d.ts +1 -1
- package/dist/templates/components/layout/Header.js +18 -8
- package/dist/templates/components/layout/SectionBar.d.ts +1 -1
- package/dist/templates/components/layout/SectionBar.js +16 -10
- package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
- package/dist/templates/components/layout/VariantSwitchers.js +313 -0
- package/dist/templates/components/useStrings.d.ts +1 -0
- package/dist/templates/components/useStrings.js +10 -0
- package/dist/templates/components/useVariant.d.ts +1 -0
- package/dist/templates/components/useVariant.js +13 -0
- package/dist/templates/llms/llmsIndex.d.ts +13 -0
- package/dist/templates/llms/llmsIndex.js +18 -3
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +2 -0
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +2 -0
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +1 -1
- package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
- package/dist/templates/mdx/fonts.mdx.js +1 -1
- package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
- package/dist/templates/mdx/footer-links.mdx.js +1 -1
- package/dist/templates/mdx/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/index.mdx.js +2 -0
- package/dist/templates/mdx/languages.mdx.d.ts +1 -0
- package/dist/templates/mdx/languages.mdx.js +94 -0
- package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
- package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
- package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
- package/dist/templates/mdx/navigation.mdx.js +2 -0
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
- package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
- package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/index.mdx.js +1 -1
- package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/languages.mdx.js +50 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
- package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
- package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/versions.mdx.js +33 -0
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +1 -1
- package/dist/templates/mdx/theme.mdx.d.ts +1 -1
- package/dist/templates/mdx/theme.mdx.js +1 -1
- package/dist/templates/mdx/versions.mdx.d.ts +1 -0
- package/dist/templates/mdx/versions.mdx.js +78 -0
- package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
- package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +2 -0
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +54 -10
- package/dist/templates/services/mcp/tools.d.ts +1 -1
- package/dist/templates/services/mcp/tools.js +81 -6
- package/dist/templates/services/mcp/types.d.ts +1 -1
- package/dist/templates/services/mcp/types.js +10 -0
- package/dist/templates/services/search.d.ts +1 -1
- package/dist/templates/services/search.js +34 -4
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +2 -0
- package/dist/templates/utils/strings.d.ts +1 -0
- package/dist/templates/utils/strings.js +27 -0
- package/dist/templates/utils/variants.d.ts +1 -0
- package/dist/templates/utils/variants.js +170 -0
- package/package.json +1 -1
|
@@ -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({
|
|
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
|
-
.
|
|
384
|
-
|
|
385
|
-
|
|
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(
|
|
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
|
-
|
|
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) => ({
|
|
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
|
|
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
|
-
*
|
|
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
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
|
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 {
|
|
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 {
|
|
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
|
-
|
|
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
|
|
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";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const stringsUtilTemplate: string;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { DEFAULT_UI_STRINGS } from "../../lib/ui-strings.js";
|
|
2
|
+
const defaults = Object.entries(DEFAULT_UI_STRINGS)
|
|
3
|
+
.map(([key, value]) => ` ${key}: ${JSON.stringify(value)},`)
|
|
4
|
+
.join("\n");
|
|
5
|
+
export const stringsUtilTemplate = `import { languages } from "@/utils/variants";
|
|
6
|
+
|
|
7
|
+
// The site's own chrome strings. A languages.json entry overrides them for
|
|
8
|
+
// its language through its \`strings\` object; anything it leaves out keeps
|
|
9
|
+
// the default below.
|
|
10
|
+
export const DEFAULT_STRINGS = {
|
|
11
|
+
${defaults}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type UiStrings = { [K in keyof typeof DEFAULT_STRINGS]: string };
|
|
15
|
+
|
|
16
|
+
export function getStrings(locale?: string): UiStrings {
|
|
17
|
+
const overrides = languages?.find(
|
|
18
|
+
(language) => language.code === locale,
|
|
19
|
+
)?.strings;
|
|
20
|
+
return overrides ? { ...DEFAULT_STRINGS, ...overrides } : DEFAULT_STRINGS;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Fills a \`{count}\` placeholder in a string. */
|
|
24
|
+
export function withCount(template: string, count: number): string {
|
|
25
|
+
return template.replace("{count}", String(count));
|
|
26
|
+
}
|
|
27
|
+
`;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const variantsUtilTemplate = "import rawLanguages from \"@/languages.json\";\nimport rawVersions from \"@/versions.json\";\n\n// Languages (languages.json) and versions (versions.json) of this site. A\n// variant's folder is its URL prefix - \"de\", \"v1\", \"de/v1\" - and the default\n// language and version live at the docs root with no prefix. The CLI\n// validated both files when it generated this app, so this module only has to\n// read them. The resolver mirrors the CLI's src/lib/variants.ts; keep the two\n// in step.\n\nexport interface LanguageConfig {\n code: string;\n label: string;\n default?: boolean;\n strings?: Record<string, string>;\n}\n\nexport interface VersionConfig {\n /** URL prefix and folder name; \"\" for the default version at the docs root. */\n slug: string;\n label: string;\n default?: boolean;\n}\n\nexport interface VariantResolution {\n /** Language code; undefined when languages.json is not configured. */\n locale?: string;\n /** Version slug (\"\" for the default); undefined when not configured. */\n version?: string;\n /** URL prefix: \"\", \"de\", \"v1\", or \"de/v1\". */\n prefix: string;\n /** The slug with the variant prefix removed. */\n rest: string;\n}\n\nfunction readLanguages(raw: unknown): LanguageConfig[] | null {\n if (!Array.isArray(raw) || raw.length === 0) return null;\n return raw as LanguageConfig[];\n}\n\nfunction readVersions(raw: unknown): VersionConfig[] | null {\n if (!Array.isArray(raw) || raw.length === 0) return null;\n return (raw as Partial<VersionConfig>[]).map((entry) => ({\n slug: entry.default ? \"\" : (entry.slug ?? \"\"),\n label: entry.label ?? \"\",\n default: entry.default === true,\n }));\n}\n\nexport const languages = readLanguages(rawLanguages);\nexport const versions = readVersions(rawVersions);\n\nexport function isVariantsConfigured(): boolean {\n return languages !== null || versions !== null;\n}\n\nexport function defaultLanguage(): LanguageConfig | null {\n return languages?.find((language) => language.default) ?? null;\n}\n\nexport function defaultVersion(): VersionConfig | null {\n return versions?.find((version) => version.default) ?? null;\n}\n\nexport function joinVariantSlug(prefix: string, slug: string): string {\n if (!prefix) return slug;\n if (slug === \"\") return prefix;\n return prefix + \"/\" + slug;\n}\n\n/**\n * Resolves the variant of a URL slug: a leading declared language folder is\n * consumed first, then a declared version folder. \"de\" alone is the German\n * home, \"de/v1\" the German v1 home.\n */\nexport function resolveVariantFromSlug(slug: string): VariantResolution {\n const normalized = slug.replace(/^\\/+|\\/+$/g, \"\");\n const segments = normalized === \"\" ? [] : normalized.split(\"/\");\n let locale = languages ? (defaultLanguage()?.code ?? \"\") : undefined;\n let version = versions ? \"\" : undefined;\n let consumed = 0;\n const prefix: string[] = [];\n\n const language = languages?.find(\n (entry) => !entry.default && entry.code === segments[0],\n );\n if (language) {\n locale = language.code;\n prefix.push(language.code);\n consumed = 1;\n }\n const versionEntry = versions?.find(\n (entry) => !entry.default && entry.slug === segments[consumed],\n );\n if (versionEntry) {\n version = versionEntry.slug;\n prefix.push(versionEntry.slug);\n consumed += 1;\n }\n\n return {\n ...(locale !== undefined ? { locale } : {}),\n ...(version !== undefined ? { version } : {}),\n prefix: prefix.join(\"/\"),\n rest: segments.slice(consumed).join(\"/\"),\n };\n}\n\n/** Key of a navigation.json object entry: the URL prefix of the scope. */\nexport function navigationScopeKey(\n prefix: string,\n sectionSlug: string,\n): string {\n return [prefix, sectionSlug].filter(Boolean).join(\"/\");\n}\n\n/** URL prefix of a language/version pair; the default of either is \"\". */\nexport function variantPrefix(\n locale: string | undefined,\n version: string | undefined,\n): string {\n const language =\n languages && locale !== undefined\n ? languages.find((entry) => entry.code === locale)\n : undefined;\n const versionEntry =\n versions && version !== undefined\n ? versions.find((entry) => entry.slug === version)\n : undefined;\n return joinVariantSlug(\n language && !language.default ? language.code : \"\",\n versionEntry && !versionEntry.default ? versionEntry.slug : \"\",\n );\n}\n\nexport function pageVariantPrefix(page: {\n locale?: string;\n version?: string;\n}): string {\n return variantPrefix(page.locale, page.version);\n}\n\n/** The slug without its language prefix: the same page in every language. */\nexport function stripLanguagePrefix(\n slug: string,\n locale: string | undefined,\n): string {\n if (!languages || locale === undefined) return slug;\n const language = languages.find((entry) => entry.code === locale);\n if (!language || language.default) return slug;\n if (slug === language.code) return \"\";\n if (slug.startsWith(language.code + \"/\")) {\n return slug.slice(language.code.length + 1);\n }\n return slug;\n}\n\n/** The slug without its whole variant prefix: the same page in every variant. */\nexport function stripVariantPrefix(\n slug: string,\n locale: string | undefined,\n version: string | undefined,\n): string {\n const prefix = variantPrefix(locale, version);\n if (!prefix) return slug;\n if (slug === prefix) return \"\";\n if (slug.startsWith(prefix + \"/\")) return slug.slice(prefix.length + 1);\n return slug;\n}\n";
|