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.
- package/README.md +52 -2
- 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/icon-registry-generator.d.ts +8 -5
- package/dist/generator/icon-registry-generator.js +19 -11
- 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/icon-registry.d.ts +10 -4
- package/dist/lib/icon-registry.js +13 -4
- 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 +92 -12
- 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
|
@@ -2,12 +2,14 @@ import fs from "fs-extra";
|
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import path from "path";
|
|
4
4
|
import chalk from "chalk";
|
|
5
|
+
import { ICON_CONFIG_FILES } from "./lib/icon-registry.js";
|
|
5
6
|
import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
|
|
6
7
|
import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
|
|
7
8
|
import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
|
|
8
9
|
import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
|
|
9
10
|
import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
|
|
10
11
|
import { safeMatter, writeFileAtomic } from "./lib/utils.js";
|
|
12
|
+
import { assertVariantsDisjoint, buildLanguageAlternates, defaultLanguage, resolveVariant, VARIANT_CONFIG_FILES, } from "./lib/variants.js";
|
|
11
13
|
import { nextConfigTemplate } from "./templates/next.config.js";
|
|
12
14
|
import { proxyTemplate } from "./templates/proxy.js";
|
|
13
15
|
import { SecureSourceFs } from "./generator/secure-source-fs.js";
|
|
@@ -36,11 +38,15 @@ export class MDXToNextJSGenerator {
|
|
|
36
38
|
"config.json",
|
|
37
39
|
"links.json",
|
|
38
40
|
"sections.json",
|
|
41
|
+
"languages.json",
|
|
42
|
+
"versions.json",
|
|
39
43
|
];
|
|
40
44
|
fontConfigFile = "fonts.json";
|
|
41
45
|
analyticsConfigFile = "analytics.json";
|
|
42
46
|
analyticsConfig = null;
|
|
43
47
|
sectionsConfig = null;
|
|
48
|
+
languagesConfig = null;
|
|
49
|
+
versionsConfig = null;
|
|
44
50
|
/** Guards against recursive reprocessing when maybeUpdateSections() triggers processAllMDXFiles() */
|
|
45
51
|
isReprocessing = false;
|
|
46
52
|
/** OpenAPI specs (build config) that drive the generated API reference. */
|
|
@@ -85,6 +91,7 @@ export class MDXToNextJSGenerator {
|
|
|
85
91
|
loadSectionsConfig: () => this.loadSectionsConfig(),
|
|
86
92
|
withApiReferenceSection: (sections) => this.withApiReferenceSection(sections),
|
|
87
93
|
determineSectionForFile: (filePath, frontmatter, sections) => this.determineSectionForFile(filePath, frontmatter, sections),
|
|
94
|
+
getVariants: () => this.variants,
|
|
88
95
|
lookupOpenApi: (reference) => this.apiRegistry.lookup(reference),
|
|
89
96
|
isOpenApiRegistryEmpty: () => this.apiRegistry.isEmpty,
|
|
90
97
|
syntheticOpenApiPages: () => this.apiRegistry.syntheticPages(),
|
|
@@ -92,7 +99,7 @@ export class MDXToNextJSGenerator {
|
|
|
92
99
|
getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
|
|
93
100
|
replaceMdxRoutes: (routes) => this.artifacts.replaceRoutesAndSave("mdx", routes),
|
|
94
101
|
generatePageFromMdx: (mdxFile, options) => this.generatePageFromMDX(mdxFile, options),
|
|
95
|
-
updateSectionIndex: (
|
|
102
|
+
updateSectionIndex: (routeSlug, frontmatter, content, sourcePath, options) => this.updateSectionIndex(routeSlug, frontmatter, content, sourcePath, options),
|
|
96
103
|
writeApiPages: (realPages) => this.writeApiPages(realPages),
|
|
97
104
|
updatePagesIndex: (pages) => this.updatePagesIndex(pages),
|
|
98
105
|
updateRootLayout: (pages) => this.updateRootLayout(pages),
|
|
@@ -196,10 +203,12 @@ export class MDXToNextJSGenerator {
|
|
|
196
203
|
await this.createStartingDocs();
|
|
197
204
|
const doccupineSourceState = await this.refreshInitialDoccupineConfig();
|
|
198
205
|
await this.loadOpenApiRegistry();
|
|
206
|
+
await this.loadVariantsConfig();
|
|
199
207
|
await this.watchCoordinator.establishSourceSnapshot(this.projectConfigRepository.sourceSnapshotStates(), this.apiRegistry.sourceFingerprint, doccupineSourceState);
|
|
200
208
|
// Resolve sections after loading OpenAPI so the generated reference is
|
|
201
209
|
// present in the first layout, sitemap, and LLMS pass.
|
|
202
210
|
this.sectionsConfig = await this.resolveSections();
|
|
211
|
+
assertVariantsDisjoint(this.languagesConfig, this.versionsConfig, this.sectionsConfig);
|
|
203
212
|
this.analyticsConfig = await this.loadAnalyticsConfig();
|
|
204
213
|
if (this.analyticsConfig) {
|
|
205
214
|
console.log(chalk.blue(`📊 Analytics enabled: ${this.analyticsConfig.provider}`));
|
|
@@ -256,6 +265,51 @@ export class MDXToNextJSGenerator {
|
|
|
256
265
|
async loadSectionsConfig() {
|
|
257
266
|
return this.projectConfigRepository.loadSectionsConfig();
|
|
258
267
|
}
|
|
268
|
+
get variants() {
|
|
269
|
+
return { languages: this.languagesConfig, versions: this.versionsConfig };
|
|
270
|
+
}
|
|
271
|
+
/** `null` when neither languages.json nor versions.json is configured, so
|
|
272
|
+
* every template keeps its single-tree code path. */
|
|
273
|
+
get configuredVariants() {
|
|
274
|
+
return this.languagesConfig || this.versionsConfig ? this.variants : null;
|
|
275
|
+
}
|
|
276
|
+
/** Loads languages.json and versions.json; an invalid file throws. */
|
|
277
|
+
async loadVariantsConfig() {
|
|
278
|
+
this.languagesConfig =
|
|
279
|
+
await this.projectConfigRepository.loadLanguagesConfig();
|
|
280
|
+
this.versionsConfig =
|
|
281
|
+
await this.projectConfigRepository.loadVersionsConfig();
|
|
282
|
+
if (this.languagesConfig) {
|
|
283
|
+
console.log(chalk.blue(`🌐 Languages: ${this.languagesConfig
|
|
284
|
+
.map((l) => (l.default ? `${l.code} (default)` : l.code))
|
|
285
|
+
.join(", ")}`));
|
|
286
|
+
}
|
|
287
|
+
if (this.versionsConfig) {
|
|
288
|
+
console.log(chalk.blue(`🏷️ Versions: ${this.versionsConfig
|
|
289
|
+
.map((v) => (v.default ? `${v.label} (default)` : v.slug))
|
|
290
|
+
.join(", ")}`));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Watch-mode reload of the variant files. An invalid file keeps the
|
|
295
|
+
* previous configuration (like a half-written doccupine.json), so the
|
|
296
|
+
* site never silently degrades to unscoped pages mid-session.
|
|
297
|
+
*/
|
|
298
|
+
async reloadVariants(fileName) {
|
|
299
|
+
console.log(chalk.cyan(`🌐 ${fileName} changed`));
|
|
300
|
+
const previous = this.variants;
|
|
301
|
+
try {
|
|
302
|
+
await this.loadVariantsConfig();
|
|
303
|
+
assertVariantsDisjoint(this.languagesConfig, this.versionsConfig, this.sectionsConfig);
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
this.languagesConfig = previous.languages;
|
|
307
|
+
this.versionsConfig = previous.versions;
|
|
308
|
+
console.error(chalk.red(`❌ ${fileName} was not applied; keeping the previous configuration:`), error);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
await this.processAllMDXFiles();
|
|
312
|
+
}
|
|
259
313
|
async discoverSectionsFromFrontmatter() {
|
|
260
314
|
const files = await this.getAllMDXFiles();
|
|
261
315
|
const documents = [];
|
|
@@ -313,8 +367,19 @@ export class MDXToNextJSGenerator {
|
|
|
313
367
|
async reconcileMdxSources() {
|
|
314
368
|
await this.processAllMDXFiles();
|
|
315
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* A page's route: the language/version folder comes off first (it is the
|
|
372
|
+
* URL prefix), then the section resolves against the remaining path, so
|
|
373
|
+
* `sections.json` directories and section slugs apply inside every variant.
|
|
374
|
+
*/
|
|
316
375
|
determineSectionForFile(filePath, frontmatter, sections = this.sectionsConfig) {
|
|
317
|
-
|
|
376
|
+
const variant = resolveVariant(filePath, this.languagesConfig, this.versionsConfig);
|
|
377
|
+
return {
|
|
378
|
+
...determineSectionRoute(variant.rest, frontmatter, sections),
|
|
379
|
+
prefix: variant.prefix,
|
|
380
|
+
...(variant.locale !== undefined ? { locale: variant.locale } : {}),
|
|
381
|
+
...(variant.version !== undefined ? { version: variant.version } : {}),
|
|
382
|
+
};
|
|
318
383
|
}
|
|
319
384
|
async handleConfigFileChange(filePath) {
|
|
320
385
|
const fileName = path.basename(filePath);
|
|
@@ -325,12 +390,15 @@ export class MDXToNextJSGenerator {
|
|
|
325
390
|
if (fileName === "sections.json") {
|
|
326
391
|
await this.reloadSections();
|
|
327
392
|
}
|
|
393
|
+
if (VARIANT_CONFIG_FILES.includes(fileName)) {
|
|
394
|
+
await this.reloadVariants(fileName);
|
|
395
|
+
}
|
|
328
396
|
if (fileName === "config.json") {
|
|
329
397
|
await this.updateSitemap();
|
|
330
398
|
await this.updateRobots();
|
|
331
399
|
await this.updateLlmsFiles();
|
|
332
400
|
}
|
|
333
|
-
if (fileName
|
|
401
|
+
if (ICON_CONFIG_FILES.includes(fileName)) {
|
|
334
402
|
await this.iconRegistryGenerator.refresh();
|
|
335
403
|
}
|
|
336
404
|
}
|
|
@@ -348,12 +416,15 @@ export class MDXToNextJSGenerator {
|
|
|
348
416
|
if (fileName === "sections.json") {
|
|
349
417
|
await this.reloadSections();
|
|
350
418
|
}
|
|
419
|
+
if (VARIANT_CONFIG_FILES.includes(fileName)) {
|
|
420
|
+
await this.reloadVariants(fileName);
|
|
421
|
+
}
|
|
351
422
|
if (fileName === "config.json") {
|
|
352
423
|
await this.updateSitemap();
|
|
353
424
|
await this.updateRobots();
|
|
354
425
|
await this.updateLlmsFiles();
|
|
355
426
|
}
|
|
356
|
-
if (fileName
|
|
427
|
+
if (ICON_CONFIG_FILES.includes(fileName)) {
|
|
357
428
|
await this.iconRegistryGenerator.refresh();
|
|
358
429
|
}
|
|
359
430
|
}
|
|
@@ -467,15 +538,15 @@ export class MDXToNextJSGenerator {
|
|
|
467
538
|
async generateRootLayout() {
|
|
468
539
|
const fontConfig = await this.loadFontConfig();
|
|
469
540
|
const analyticsEnabled = this.analyticsConfig !== null;
|
|
470
|
-
return rootLayoutTemplate(fontConfig, analyticsEnabled);
|
|
541
|
+
return rootLayoutTemplate(fontConfig, analyticsEnabled, this.languagesConfig);
|
|
471
542
|
}
|
|
472
543
|
async generateSiteLayout(pages) {
|
|
473
544
|
const resolvedPages = pages ?? (await this.buildAllPagesMeta());
|
|
474
|
-
return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
|
|
545
|
+
return siteLayoutTemplate(resolvedPages, this.sectionsConfig, this.configuredVariants);
|
|
475
546
|
}
|
|
476
547
|
async generateSectionIndexPages(pages, declaredSlugs) {
|
|
477
548
|
const resolvedPages = pages ?? (await this.buildAllPagesMeta());
|
|
478
|
-
return this.sectionIndexGenerator.generate(resolvedPages, this.sectionsConfig, declaredSlugs, (slug, target) => this.writeSectionIndexRedirect(slug, target));
|
|
549
|
+
return this.sectionIndexGenerator.generate(resolvedPages, this.sectionsConfig, declaredSlugs, (slug, target) => this.writeSectionIndexRedirect(slug, target), this.configuredVariants);
|
|
479
550
|
}
|
|
480
551
|
async writeSectionIndexRedirect(slug, target) {
|
|
481
552
|
const content = `import { redirect } from "next/navigation";
|
|
@@ -551,10 +622,19 @@ export default function SectionIndex() {
|
|
|
551
622
|
console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
|
|
552
623
|
}
|
|
553
624
|
}
|
|
554
|
-
|
|
625
|
+
// The homepage is the default language's; its translations are the
|
|
626
|
+
// `index.mdx` of each language folder (slug "de").
|
|
627
|
+
const locale = defaultLanguage(this.languagesConfig)?.code;
|
|
628
|
+
const alternateLanguages = pages
|
|
629
|
+
? buildLanguageAlternates(pages, this.languagesConfig).get("")
|
|
630
|
+
: undefined;
|
|
631
|
+
await this.generatedPagePublisher.updateHomepage(indexMDX, apiOperation, {
|
|
632
|
+
...(locale !== undefined ? { locale } : {}),
|
|
633
|
+
...(alternateLanguages ? { alternateLanguages } : {}),
|
|
634
|
+
});
|
|
555
635
|
}
|
|
556
|
-
async updateSectionIndex(
|
|
557
|
-
return this.generatedPagePublisher.updateSectionIndex(
|
|
636
|
+
async updateSectionIndex(routeSlug, frontmatter, mdxContent, sourcePath, options) {
|
|
637
|
+
return this.generatedPagePublisher.updateSectionIndex(routeSlug, frontmatter, mdxContent, sourcePath, options);
|
|
558
638
|
}
|
|
559
639
|
async updateRootLayout(pages) {
|
|
560
640
|
await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
|
|
@@ -566,13 +646,13 @@ export default function SectionIndex() {
|
|
|
566
646
|
return loadSiteUrlArtifact(() => this.projectConfigRepository.readConfigFile());
|
|
567
647
|
}
|
|
568
648
|
async updateSitemap(pages) {
|
|
569
|
-
return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl());
|
|
649
|
+
return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl(), this.configuredVariants);
|
|
570
650
|
}
|
|
571
651
|
async updateRobots() {
|
|
572
652
|
return writeRobots(this.outputDir, () => this.loadSiteUrl());
|
|
573
653
|
}
|
|
574
654
|
async updateLlmsFiles(pages) {
|
|
575
|
-
return writeLlmsFiles(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), (filePath) => this.readAggregateMdxSource(filePath), (slug) => this.apiRegistry.bodyForSlug(slug), () => loadSiteMetadata(() => this.projectConfigRepository.readConfigFile()), this.publicAssetManager);
|
|
655
|
+
return writeLlmsFiles(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), (filePath) => this.readAggregateMdxSource(filePath), (slug) => this.apiRegistry.bodyForSlug(slug), () => loadSiteMetadata(() => this.projectConfigRepository.readConfigFile()), this.publicAssetManager, this.configuredVariants);
|
|
576
656
|
}
|
|
577
657
|
async stop() {
|
|
578
658
|
return this.watchCoordinator.stop();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({
|
|
1
|
+
export declare const mcpRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n createMCPServer,\n searchDocs,\n getIndexStatus,\n DOCS_TOOLS,\n listDocs,\n getDoc,\n MCP_MAX_REQUEST_BYTES,\n MCP_MAX_TOOL_ARGUMENT_BYTES,\n searchDocsArgsSchema,\n getDocArgsSchema,\n listDocsArgsSchema,\n resolveDocsFilter,\n serializeMCPResult,\n} from \"@/services/mcp\";\nimport type { MCPToolName } from \"@/services/mcp\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { isMcpRequestAuthorized } from \"@/lib/access\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_PROTOCOL_MESSAGES = 20;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction jsonByteLength(value: unknown): number {\n return new TextEncoder().encode(JSON.stringify(value) ?? \"null\").byteLength;\n}\n\nfunction protocolToolCallError(body: unknown): string | null {\n const messages = Array.isArray(body) ? body : [body];\n if (messages.length === 0 || messages.length > MAX_PROTOCOL_MESSAGES) {\n return \"Invalid protocol batch\";\n }\n\n let toolCallCount = 0;\n for (const message of messages) {\n if (!isRecord(message) || message.method !== \"tools/call\") continue;\n toolCallCount++;\n if (toolCallCount > 1) {\n return \"Only one tools/call is allowed per request\";\n }\n if (!isRecord(message.params) || typeof message.params.name !== \"string\") {\n return \"Invalid tool call\";\n }\n\n const args = message.params.arguments ?? {};\n if (jsonByteLength(args) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return \"Tool arguments exceed the maximum size\";\n }\n\n let valid = true;\n switch (message.params.name) {\n case \"search_docs\":\n valid = searchDocsArgsSchema.safeParse(args).success;\n break;\n case \"get_doc\":\n valid = getDocArgsSchema.safeParse(args).success;\n break;\n case \"list_docs\":\n valid = listDocsArgsSchema.safeParse(args).success;\n break;\n }\n if (!valid) return \"Invalid tool arguments\";\n }\n return null;\n}\n\nfunction protocolError(message: string, status = 400): Response {\n return Response.json(\n {\n jsonrpc: \"2.0\",\n error: { code: status === 500 ? -32603 : -32602, message },\n id: null,\n },\n { status },\n );\n}\n\nfunction createTransport() {\n return new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n}\n\nasync function handleMCPRequest(req: Request, parsedBody?: unknown) {\n const transport = createTransport();\n const server = createMCPServer();\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n void Promise.allSettled([transport.close(), server.close()]);\n };\n req.signal.addEventListener(\"abort\", close, { once: true });\n\n try {\n await server.connect(transport);\n const response = await transport.handleRequest(\n req,\n parsedBody === undefined ? undefined : { parsedBody },\n );\n\n const body = response.clone().body;\n if (body) {\n void body\n .pipeTo(new WritableStream())\n .catch(() => {})\n .finally(close);\n } else {\n close();\n }\n return response;\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP protocol request failed:\", error);\n close();\n return protocolError(\"Internal server error\", 500);\n }\n}\n\ninterface ToolCallRequest {\n tool: MCPToolName;\n params: unknown;\n}\n\nfunction toolResponse(value: unknown): Response {\n const result = serializeMCPResult(value);\n if (result.tooLarge) {\n return NextResponse.json(\n { error: \"Tool result exceeds the maximum response size\" },\n { status: 413 },\n );\n }\n return new Response(result.text, {\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nasync function handleRESTRequest(req: Request, body: ToolCallRequest) {\n try {\n const { tool, params } = body;\n\n switch (tool) {\n case \"search_docs\": {\n const parsed = searchDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n const results = await searchDocs(\n parsed.data.query,\n parsed.data.limit ?? 6,\n req.signal,\n resolveDocsFilter({\n language: parsed.data.language,\n version: parsed.data.version,\n }),\n );\n return toolResponse({\n content: results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n ...(chunk.locale !== undefined ? { language: chunk.locale } : {}),\n ...(chunk.version !== undefined ? { version: chunk.version } : {}),\n score: score.toFixed(3),\n text: chunk.text,\n })),\n });\n }\n\n case \"get_doc\": {\n const parsed = getDocArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const doc = await getDoc({ path: parsed.data.path });\n req.signal.throwIfAborted();\n if (!doc) {\n return NextResponse.json(\n { error: \"Document not found\" },\n { status: 404 },\n );\n }\n return toolResponse({ content: doc });\n }\n\n case \"list_docs\": {\n const parsed = listDocsArgsSchema.safeParse(params);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid params\" },\n { status: 400 },\n );\n }\n req.signal.throwIfAborted();\n const docs = await listDocs({\n directory: parsed.data.directory,\n language: parsed.data.language,\n version: parsed.data.version,\n });\n req.signal.throwIfAborted();\n return toolResponse({\n content: docs.map((doc) => ({\n name: doc.name,\n path: doc.path,\n uri: doc.uri,\n ...(doc.locale !== undefined ? { language: doc.locale } : {}),\n ...(doc.version !== undefined ? { version: doc.version } : {}),\n })),\n });\n }\n\n default:\n return NextResponse.json({ error: \"Unknown tool\" }, { status: 400 });\n }\n } catch (error: unknown) {\n console.error(\"[doccupine] MCP REST tool failed:\", error);\n return NextResponse.json(\n { error: \"Internal server error\" },\n { status: 500 },\n );\n }\n}\n\nexport async function POST(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n let body: unknown;\n try {\n body = await readJsonBody(req, MCP_MAX_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n if (Array.isArray(body) || (isRecord(body) && \"jsonrpc\" in body)) {\n const validationError = protocolToolCallError(body);\n if (validationError) return protocolError(validationError);\n return handleMCPRequest(req, body);\n }\n\n if (isRecord(body) && typeof body.tool === \"string\") {\n if (jsonByteLength(body.params ?? {}) > MCP_MAX_TOOL_ARGUMENT_BYTES) {\n return NextResponse.json(\n { error: \"Tool arguments exceed the maximum size\" },\n { status: 413 },\n );\n }\n return handleRESTRequest(req, {\n tool: body.tool as MCPToolName,\n params: body.params ?? {},\n });\n }\n\n return NextResponse.json(\n { error: \"Invalid request format\" },\n { status: 400 },\n );\n}\n\nexport async function GET(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n tools: DOCS_TOOLS,\n index: { ready: status.ready, chunkCount: status.chunkCount },\n });\n}\n\nexport async function DELETE(req: Request) {\n if (!(await isMcpRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n return handleMCPRequest(req);\n}\n";
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
searchDocsArgsSchema,
|
|
13
13
|
getDocArgsSchema,
|
|
14
14
|
listDocsArgsSchema,
|
|
15
|
+
resolveDocsFilter,
|
|
15
16
|
serializeMCPResult,
|
|
16
17
|
} from "@/services/mcp";
|
|
17
18
|
import type { MCPToolName } from "@/services/mcp";
|
|
@@ -159,11 +160,17 @@ async function handleRESTRequest(req: Request, body: ToolCallRequest) {
|
|
|
159
160
|
parsed.data.query,
|
|
160
161
|
parsed.data.limit ?? 6,
|
|
161
162
|
req.signal,
|
|
163
|
+
resolveDocsFilter({
|
|
164
|
+
language: parsed.data.language,
|
|
165
|
+
version: parsed.data.version,
|
|
166
|
+
}),
|
|
162
167
|
);
|
|
163
168
|
return toolResponse({
|
|
164
169
|
content: results.map(({ chunk, score }) => ({
|
|
165
170
|
path: chunk.path,
|
|
166
171
|
uri: chunk.uri,
|
|
172
|
+
...(chunk.locale !== undefined ? { language: chunk.locale } : {}),
|
|
173
|
+
...(chunk.version !== undefined ? { version: chunk.version } : {}),
|
|
167
174
|
score: score.toFixed(3),
|
|
168
175
|
text: chunk.text,
|
|
169
176
|
})),
|
|
@@ -199,13 +206,19 @@ async function handleRESTRequest(req: Request, body: ToolCallRequest) {
|
|
|
199
206
|
);
|
|
200
207
|
}
|
|
201
208
|
req.signal.throwIfAborted();
|
|
202
|
-
const docs = await listDocs({
|
|
209
|
+
const docs = await listDocs({
|
|
210
|
+
directory: parsed.data.directory,
|
|
211
|
+
language: parsed.data.language,
|
|
212
|
+
version: parsed.data.version,
|
|
213
|
+
});
|
|
203
214
|
req.signal.throwIfAborted();
|
|
204
215
|
return toolResponse({
|
|
205
216
|
content: docs.map((doc) => ({
|
|
206
217
|
name: doc.name,
|
|
207
218
|
path: doc.path,
|
|
208
219
|
uri: doc.uri,
|
|
220
|
+
...(doc.locale !== undefined ? { language: doc.locale } : {}),
|
|
221
|
+
...(doc.version !== undefined ? { version: doc.version } : {}),
|
|
209
222
|
})),
|
|
210
223
|
});
|
|
211
224
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
|
|
1
|
+
export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
ensureDocsIndex,
|
|
7
7
|
getIndexStatus,
|
|
8
8
|
} from "@/services/mcp/server";
|
|
9
|
+
import { resolveDocsFilter } from "@/services/mcp/tools";
|
|
9
10
|
import { rateLimit } from "@/utils/rateLimit";
|
|
10
11
|
import { config } from "@/utils/config";
|
|
11
12
|
import { isSiteRequestAuthorized } from "@/lib/access";
|
|
@@ -22,10 +23,18 @@ const messageSchema = z
|
|
|
22
23
|
})
|
|
23
24
|
.strict();
|
|
24
25
|
|
|
26
|
+
// A language code or version slug is a lowercase URL segment.
|
|
27
|
+
const variantTokenSchema = z
|
|
28
|
+
.string()
|
|
29
|
+
.regex(/^[a-z0-9-]{1,32}$/)
|
|
30
|
+
.optional();
|
|
31
|
+
|
|
25
32
|
const ragSchema = z
|
|
26
33
|
.object({
|
|
27
34
|
question: z.string().min(1).max(2000),
|
|
28
35
|
history: z.array(messageSchema).max(20).optional(),
|
|
36
|
+
locale: variantTokenSchema,
|
|
37
|
+
version: variantTokenSchema,
|
|
29
38
|
})
|
|
30
39
|
.strict();
|
|
31
40
|
|
|
@@ -139,7 +148,9 @@ export async function POST(req: Request) {
|
|
|
139
148
|
{ status: 400 },
|
|
140
149
|
);
|
|
141
150
|
}
|
|
142
|
-
const { question, history } = parsed.data;
|
|
151
|
+
const { question, history, locale, version } = parsed.data;
|
|
152
|
+
// Retrieval stays inside the language/version the reader is looking at.
|
|
153
|
+
const docsFilter = resolveDocsFilter({ language: locale, version });
|
|
143
154
|
|
|
144
155
|
let llmConfig;
|
|
145
156
|
try {
|
|
@@ -194,7 +205,7 @@ export async function POST(req: Request) {
|
|
|
194
205
|
signal.throwIfAborted();
|
|
195
206
|
|
|
196
207
|
// Use MCP search_docs tool to find relevant documentation
|
|
197
|
-
const searchResults = await searchDocs(question, 6, signal);
|
|
208
|
+
const searchResults = await searchDocs(question, 6, signal, docsFilter);
|
|
198
209
|
signal.throwIfAborted();
|
|
199
210
|
|
|
200
211
|
// Build context from search results
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n});\n\nexport async function GET(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10);\n return NextResponse.json({ results });\n}\n";
|
|
1
|
+
export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n});\n\nexport async function GET(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const localeParam = url.searchParams.get(\"locale\");\n const versionParam = url.searchParams.get(\"version\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n ...(localeParam != null && { locale: localeParam }),\n ...(versionParam != null && { version: versionParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10, {\n locale: parsed.data.locale,\n version: parsed.data.version,\n });\n return NextResponse.json({ results });\n}\n";
|
|
@@ -3,9 +3,17 @@ import { z } from "zod";
|
|
|
3
3
|
import { searchContent } from "@/services/search";
|
|
4
4
|
import { isSiteRequestAuthorized } from "@/lib/access";
|
|
5
5
|
|
|
6
|
+
// A language code or version slug is a lowercase URL segment.
|
|
7
|
+
const variantTokenSchema = z
|
|
8
|
+
.string()
|
|
9
|
+
.regex(/^[a-z0-9-]{1,32}$/)
|
|
10
|
+
.optional();
|
|
11
|
+
|
|
6
12
|
const searchSchema = z.object({
|
|
7
13
|
q: z.string().min(1).max(200),
|
|
8
14
|
limit: z.coerce.number().int().min(1).max(30).optional(),
|
|
15
|
+
locale: variantTokenSchema,
|
|
16
|
+
version: variantTokenSchema,
|
|
9
17
|
});
|
|
10
18
|
|
|
11
19
|
export async function GET(req: Request) {
|
|
@@ -15,9 +23,13 @@ export async function GET(req: Request) {
|
|
|
15
23
|
|
|
16
24
|
const url = new URL(req.url);
|
|
17
25
|
const limitParam = url.searchParams.get("limit");
|
|
26
|
+
const localeParam = url.searchParams.get("locale");
|
|
27
|
+
const versionParam = url.searchParams.get("version");
|
|
18
28
|
const parsed = searchSchema.safeParse({
|
|
19
29
|
q: url.searchParams.get("q"),
|
|
20
30
|
...(limitParam != null && { limit: limitParam }),
|
|
31
|
+
...(localeParam != null && { locale: localeParam }),
|
|
32
|
+
...(versionParam != null && { version: versionParam }),
|
|
21
33
|
});
|
|
22
34
|
|
|
23
35
|
if (!parsed.success) {
|
|
@@ -27,7 +39,10 @@ export async function GET(req: Request) {
|
|
|
27
39
|
);
|
|
28
40
|
}
|
|
29
41
|
|
|
30
|
-
const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10
|
|
42
|
+
const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10, {
|
|
43
|
+
locale: parsed.data.locale,
|
|
44
|
+
version: parsed.data.version,
|
|
45
|
+
});
|
|
31
46
|
return NextResponse.json({ results });
|
|
32
47
|
}
|
|
33
48
|
`;
|
|
@@ -3,5 +3,7 @@ export interface SitemapEntry {
|
|
|
3
3
|
lastModified?: string;
|
|
4
4
|
changeFrequency: "weekly";
|
|
5
5
|
priority: number;
|
|
6
|
+
/** hreflang -> slug of the same page in that language (languages.json). */
|
|
7
|
+
alternates?: Record<string, string>;
|
|
6
8
|
}
|
|
7
9
|
export declare const sitemapTemplate: (entries: SitemapEntry[]) => string;
|
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
function formatAlternates(alternates) {
|
|
2
|
+
const entries = Object.entries(alternates).map(([lang, slug]) => {
|
|
3
|
+
const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(lang)
|
|
4
|
+
? lang
|
|
5
|
+
: JSON.stringify(lang);
|
|
6
|
+
return `${key}: ${JSON.stringify(slug)}`;
|
|
7
|
+
});
|
|
8
|
+
const inline = ` alternates: { ${entries.join(", ")} }`;
|
|
9
|
+
// The caller appends a comma, which Prettier counts against the width.
|
|
10
|
+
if (inline.length + 1 <= 80)
|
|
11
|
+
return inline;
|
|
12
|
+
return ` alternates: {\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
|
|
13
|
+
}
|
|
1
14
|
function formatEntries(entries) {
|
|
2
15
|
const lines = entries.map((entry) => {
|
|
3
16
|
const parts = [
|
|
@@ -7,6 +20,7 @@ function formatEntries(entries) {
|
|
|
7
20
|
: null,
|
|
8
21
|
` changeFrequency: ${JSON.stringify(entry.changeFrequency)}`,
|
|
9
22
|
` priority: ${entry.priority}`,
|
|
23
|
+
entry.alternates ? formatAlternates(entry.alternates) : null,
|
|
10
24
|
].filter(Boolean);
|
|
11
25
|
return ` {\n${parts.join(",\n")},\n }`;
|
|
12
26
|
});
|
|
@@ -14,6 +28,37 @@ function formatEntries(entries) {
|
|
|
14
28
|
}
|
|
15
29
|
export const sitemapTemplate = (entries) => {
|
|
16
30
|
const entriesLiteral = formatEntries(entries);
|
|
31
|
+
const hasAlternates = entries.some((entry) => entry.alternates);
|
|
32
|
+
// The hreflang mapping is emitted only for sites with translated pages, so
|
|
33
|
+
// every other site's sitemap.ts is unchanged.
|
|
34
|
+
const alternatesField = hasAlternates
|
|
35
|
+
? `
|
|
36
|
+
alternates?: Record<string, string>;`
|
|
37
|
+
: "";
|
|
38
|
+
const alternatesHelper = hasAlternates
|
|
39
|
+
? `
|
|
40
|
+
function languageAlternates(
|
|
41
|
+
base: string,
|
|
42
|
+
alternates: Record<string, string>,
|
|
43
|
+
): Record<string, string> {
|
|
44
|
+
const languages: Record<string, string> = {};
|
|
45
|
+
for (const [lang, slug] of Object.entries(alternates)) {
|
|
46
|
+
languages[lang] = slug === "" ? base : \`\${base}/\${slug}\`;
|
|
47
|
+
}
|
|
48
|
+
return languages;
|
|
49
|
+
}
|
|
50
|
+
`
|
|
51
|
+
: "";
|
|
52
|
+
const alternatesSpread = hasAlternates
|
|
53
|
+
? `
|
|
54
|
+
...(entry.alternates
|
|
55
|
+
? {
|
|
56
|
+
alternates: {
|
|
57
|
+
languages: languageAlternates(base, entry.alternates),
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
: {}),`
|
|
61
|
+
: "";
|
|
17
62
|
return `import type { MetadataRoute } from "next";
|
|
18
63
|
import { config } from "@/utils/config";
|
|
19
64
|
|
|
@@ -24,7 +69,7 @@ interface Entry {
|
|
|
24
69
|
slug: string;
|
|
25
70
|
lastModified?: string;
|
|
26
71
|
changeFrequency: ChangeFrequency;
|
|
27
|
-
priority: number
|
|
72
|
+
priority: number;${alternatesField}
|
|
28
73
|
}
|
|
29
74
|
|
|
30
75
|
const ENTRIES: Entry[] = ${entriesLiteral};
|
|
@@ -34,7 +79,7 @@ function resolveBaseUrl(): string | null {
|
|
|
34
79
|
if (!raw) return null;
|
|
35
80
|
return raw.replace(/\\/$/, "");
|
|
36
81
|
}
|
|
37
|
-
|
|
82
|
+
${alternatesHelper}
|
|
38
83
|
export default function sitemap(): MetadataRoute.Sitemap {
|
|
39
84
|
const base = resolveBaseUrl();
|
|
40
85
|
if (!base) return [];
|
|
@@ -43,7 +88,7 @@ export default function sitemap(): MetadataRoute.Sitemap {
|
|
|
43
88
|
url: entry.slug === "" ? base : \`\${base}/\${entry.slug}\`,
|
|
44
89
|
lastModified: entry.lastModified ? new Date(entry.lastModified) : undefined,
|
|
45
90
|
changeFrequency: entry.changeFrequency,
|
|
46
|
-
priority: entry.priority
|
|
91
|
+
priority: entry.priority,${alternatesSpread}
|
|
47
92
|
}));
|
|
48
93
|
}
|
|
49
94
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const chatTemplate = "\"use client\";\nimport React, { createContext, useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n ChatInput,\n ChatMessage,\n ChatMessageList,\n ChatPanel,\n ChatProvider,\n ChatSource,\n ChatSources,\n ChatTyping,\n IconButton,\n Prose,\n useBelowBreakpoint,\n useChat,\n type ChatSendContext,\n type ChatSourceData,\n} from \"cherry-styled-components\";\nimport { RotateCcw } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\n\nconst mdxComponents = getMDXComponents({});\n\ntype RagSource = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\n// Map a retrieval hit onto the chip the transcript renders: docs://<slug>\n// becomes an app-relative href, and the slug's last segment becomes a\n// title-cased label.\nfunction toSourceChip(src: RagSource): ChatSourceData {\n const slug = src.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return { id: src.id, label, href };\n}\n\n// Cherry's ChatProvider owns the transcript, panel state, and streaming\n// bookkeeping; this handler owns the transport: POST the question to\n// /api/rag, stream the SSE frames, and patch the assistant bubble as tokens\n// arrive. The provider bounds `history` to the RAG contract (20 entries,\n// 4000 chars each), swallows aborts, and surfaces thrown errors as `error`.\nasync function sendToAssistant(\n question: string,\n { signal, history, setAssistant }: ChatSendContext,\n) {\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question, history }),\n signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: ChatSourceData[] = [];\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop so it lands\n // in the provider's error state instead of dying in a parse-error\n // log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: RagSource[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources\n .filter((s) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n })\n .map(toSourceChip);\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n setAssistant(streamedContent, { text: streamedContent, sources });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAssistant(\n mdxSource ? (\n <MDXRemote {...mdxSource} components={mdxComponents} />\n ) : (\n streamedContent\n ),\n { text: streamedContent, sources },\n );\n }\n }\n }\n}\n\nfunction ChatSourceLink({ source }: { source: ChatSourceData }) {\n const { close } = useChat();\n const isMobileChat = useBelowBreakpoint(\"lg\");\n const router = useRouter();\n\n return (\n <ChatSource\n href={source.href}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // ChatSource renders a plain anchor, so route unmodified left clicks\n // client-side to keep the transcript alive; below lg the panel is a\n // fullscreen dialog, so close it to reveal the navigated page.\n event.preventDefault();\n if (isMobileChat) close();\n router.push(source.href);\n }}\n >\n {source.label}\n </ChatSource>\n );\n}\n\nfunction ChatTranscript() {\n const { messages, loading, error } = useChat();\n const lastMessage = messages[messages.length - 1];\n\n return (\n <ChatMessageList>\n {messages.map((message) => (\n <ChatMessage key={message.id} $role={message.role}>\n {message.role === \"assistant\" ? (\n // The docs' typographic context lives on the docs page wrapper,\n // so a rendered MDX answer would arrive margin-less here. Prose\n // $compact is Cherry's document styling for chat replies: a 10px\n // rhythm between elements, inline-code chips, lists, and tables.\n <Prose $compact>{message.content}</Prose>\n ) : (\n message.content\n )}\n {message.role === \"assistant\" &&\n message.sources &&\n message.sources.length > 0 && (\n <ChatSources>\n {message.sources.map((source) => (\n <ChatSourceLink key={source.id} source={source} />\n ))}\n </ChatSources>\n )}\n </ChatMessage>\n ))}\n {loading && lastMessage?.role !== \"assistant\" && <ChatTyping />}\n {error && (\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n )}\n </ChatMessageList>\n );\n}\n\nfunction ChatActions() {\n const { reset } = useChat();\n\n return (\n <IconButton\n onClick={reset}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n );\n}\n\nfunction Chat() {\n return (\n <ChatPanel $title=\"AI Assistant\" $actions={<ChatActions />}>\n <ChatTranscript />\n <ChatInput $glow />\n </ChatPanel>\n );\n}\n\n// App-level chat context: only whether the AI assistant is enabled (an LLM\n// provider is configured). Panel state, the transcript, and streaming all\n// live in Cherry's ChatProvider - read those with useChat() from\n// \"cherry-styled-components\".\nconst ChatContext = createContext<{ isChatActive: boolean }>({\n isChatActive: false,\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const value = useMemo(() => ({ isChatActive }), [isChatActive]);\n\n return (\n <ChatContext.Provider value={value}>\n <ChatProvider\n onSend={sendToAssistant}\n shortcut={isChatActive ? \"i\" : null}\n >\n {children}\n </ChatProvider>\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext };\n";
|
|
1
|
+
export declare const chatTemplate = "\"use client\";\nimport React, { createContext, useCallback, useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n ChatInput,\n ChatMessage,\n ChatMessageList,\n ChatPanel,\n ChatProvider,\n ChatSource,\n ChatSources,\n ChatTyping,\n IconButton,\n Prose,\n useBelowBreakpoint,\n useChat,\n type ChatSendContext,\n type ChatSourceData,\n} from \"cherry-styled-components\";\nimport { RotateCcw } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\nimport { useStrings } from \"@/components/useStrings\";\nimport { useVariant } from \"@/components/useVariant\";\n\nconst mdxComponents = getMDXComponents({});\n\n/** The language/version the reader is looking at; retrieval stays inside it. */\ninterface ChatScope {\n locale?: string;\n version?: string;\n}\n\ntype RagSource = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\n// Map a retrieval hit onto the chip the transcript renders: docs://<slug>\n// becomes an app-relative href, and the slug's last segment becomes a\n// title-cased label.\nfunction toSourceChip(src: RagSource): ChatSourceData {\n const slug = src.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return { id: src.id, label, href };\n}\n\n// Cherry's ChatProvider owns the transcript, panel state, and streaming\n// bookkeeping; this handler owns the transport: POST the question to\n// /api/rag, stream the SSE frames, and patch the assistant bubble as tokens\n// arrive. The provider bounds `history` to the RAG contract (20 entries,\n// 4000 chars each), swallows aborts, and surfaces thrown errors as `error`.\nasync function sendToAssistant(\n question: string,\n { signal, history, setAssistant }: ChatSendContext,\n scope: ChatScope,\n) {\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n question,\n history,\n ...(scope.locale ? { locale: scope.locale } : {}),\n ...(scope.version ? { version: scope.version } : {}),\n }),\n signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: ChatSourceData[] = [];\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop so it lands\n // in the provider's error state instead of dying in a parse-error\n // log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: RagSource[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources\n .filter((s) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n })\n .map(toSourceChip);\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n setAssistant(streamedContent, { text: streamedContent, sources });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAssistant(\n mdxSource ? (\n <MDXRemote {...mdxSource} components={mdxComponents} />\n ) : (\n streamedContent\n ),\n { text: streamedContent, sources },\n );\n }\n }\n }\n}\n\nfunction ChatSourceLink({ source }: { source: ChatSourceData }) {\n const { close } = useChat();\n const isMobileChat = useBelowBreakpoint(\"lg\");\n const router = useRouter();\n\n return (\n <ChatSource\n href={source.href}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // ChatSource renders a plain anchor, so route unmodified left clicks\n // client-side to keep the transcript alive; below lg the panel is a\n // fullscreen dialog, so close it to reveal the navigated page.\n event.preventDefault();\n if (isMobileChat) close();\n router.push(source.href);\n }}\n >\n {source.label}\n </ChatSource>\n );\n}\n\nfunction ChatTranscript() {\n const { messages, loading, error } = useChat();\n const lastMessage = messages[messages.length - 1];\n const t = useStrings();\n\n return (\n <ChatMessageList>\n {messages.map((message) => (\n <ChatMessage key={message.id} $role={message.role}>\n {message.role === \"assistant\" ? (\n // The docs' typographic context lives on the docs page wrapper,\n // so a rendered MDX answer would arrive margin-less here. Prose\n // $compact is Cherry's document styling for chat replies: a 10px\n // rhythm between elements, inline-code chips, lists, and tables.\n <Prose $compact>{message.content}</Prose>\n ) : (\n message.content\n )}\n {message.role === \"assistant\" &&\n message.sources &&\n message.sources.length > 0 && (\n <ChatSources>\n {message.sources.map((source) => (\n <ChatSourceLink key={source.id} source={source} />\n ))}\n </ChatSources>\n )}\n </ChatMessage>\n ))}\n {loading && lastMessage?.role !== \"assistant\" && (\n <ChatTyping>{t.chatAnswering}</ChatTyping>\n )}\n {error && (\n <Callout type=\"danger\">\n <p>\n <strong>{t.chatError}</strong> {error}\n </p>\n </Callout>\n )}\n </ChatMessageList>\n );\n}\n\nfunction ChatActions() {\n const { reset } = useChat();\n const t = useStrings();\n\n return (\n <IconButton onClick={reset} aria-label={t.resetChat} title={t.resetChat}>\n <RotateCcw />\n </IconButton>\n );\n}\n\nfunction Chat() {\n const t = useStrings();\n\n return (\n <ChatPanel $title={t.aiAssistant} $actions={<ChatActions />}>\n <ChatTranscript />\n <ChatInput\n $glow\n placeholder={t.chatPlaceholder}\n aria-label={t.chatInputLabel}\n />\n </ChatPanel>\n );\n}\n\n// App-level chat context: only whether the AI assistant is enabled (an LLM\n// provider is configured). Panel state, the transcript, and streaming all\n// live in Cherry's ChatProvider - read those with useChat() from\n// \"cherry-styled-components\".\nconst ChatContext = createContext<{ isChatActive: boolean }>({\n isChatActive: false,\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const value = useMemo(() => ({ isChatActive }), [isChatActive]);\n const { locale, version } = useVariant();\n const t = useStrings();\n const onSend = useCallback(\n (question: string, context: ChatSendContext) =>\n sendToAssistant(question, context, { locale, version }),\n [locale, version],\n );\n\n return (\n <ChatContext.Provider value={value}>\n <ChatProvider\n onSend={onSend}\n greeting={t.chatGreeting}\n shortcut={isChatActive ? \"i\" : null}\n >\n {children}\n </ChatProvider>\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext };\n";
|