doccupine 0.0.155 → 0.0.157
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 +1 -0
- package/dist/generator/app-scaffolder.d.ts +1 -0
- package/dist/generator/app-scaffolder.js +1 -0
- package/dist/generator/icon-registry-generator.d.ts +33 -0
- package/dist/generator/icon-registry-generator.js +130 -0
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +1 -0
- package/dist/generator/mdx-reconciliation-coordinator.js +1 -0
- package/dist/lib/icon-registry.d.ts +56 -0
- package/dist/lib/icon-registry.js +165 -0
- package/dist/mdx-to-nextjs-generator.d.ts +1 -0
- package/dist/mdx-to-nextjs-generator.js +11 -0
- package/dist/templates/components/layout/Icon.d.ts +1 -1
- package/dist/templates/components/layout/Icon.js +18 -8
- package/dist/templates/package.js +17 -17
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +56 -15
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
- **MCP server** - exposes `search_docs`, `get_doc`, and `list_docs` tools for AI agents
|
|
26
26
|
- **Custom fonts** - Google Fonts or local fonts via `fonts.json`
|
|
27
27
|
- **Static assets** - `public/` directory is watched and synced to the generated app
|
|
28
|
+
- **Lean icons** - only the Lucide glyphs your pages, navigation, and components use are bundled; an unknown icon name warns when the site is generated and renders nothing
|
|
28
29
|
- **Password protection** - gate the whole site behind a shared password with `SITE_PASSWORD`
|
|
29
30
|
- **Zero config to start** - `npx doccupine` scaffolds everything and starts the server
|
|
30
31
|
|
|
@@ -4,6 +4,7 @@ interface AppStructureCallbacks {
|
|
|
4
4
|
generateSiteLayout(): Promise<string>;
|
|
5
5
|
updateSitemap(): Promise<void>;
|
|
6
6
|
updateLlmsFiles(): Promise<void>;
|
|
7
|
+
updateIconRegistry(): Promise<void>;
|
|
7
8
|
}
|
|
8
9
|
interface StarterDocumentCallbacks {
|
|
9
10
|
writeStarterFilesIfEmpty(files: Iterable<readonly [string, string | Uint8Array]>): Promise<void>;
|
|
@@ -43,6 +43,7 @@ export class AppScaffolder {
|
|
|
43
43
|
}
|
|
44
44
|
await callbacks.updateSitemap();
|
|
45
45
|
await callbacks.updateLlmsFiles();
|
|
46
|
+
await callbacks.updateIconRegistry();
|
|
46
47
|
}
|
|
47
48
|
async createStartingDocs(callbacks) {
|
|
48
49
|
await callbacks.writeStarterFilesIfEmpty(Object.entries(startingDocsStructure));
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { PageMeta } from "../lib/types.js";
|
|
2
|
+
/** Icon names the generated components use on their own, whatever the docs say. */
|
|
3
|
+
export declare function builtinIconNames(): string[];
|
|
4
|
+
/**
|
|
5
|
+
* Keeps `components/layout/IconRegistry.ts` in step with the icon names the
|
|
6
|
+
* site uses: sidebar icons from frontmatter, `icon` entries in navigation.json,
|
|
7
|
+
* `<Icon>` and `icon` props in MDX, and the glyphs the generated components
|
|
8
|
+
* draw themselves. Unknown names are reported once and left out, so a typo
|
|
9
|
+
* renders nothing rather than failing the build.
|
|
10
|
+
*/
|
|
11
|
+
export declare class IconRegistryGenerator {
|
|
12
|
+
private readonly outputDir;
|
|
13
|
+
private readonly builtinNames;
|
|
14
|
+
private pages;
|
|
15
|
+
private mdxSources;
|
|
16
|
+
private lastWritten;
|
|
17
|
+
private lastWarning;
|
|
18
|
+
constructor(outputDir: string, builtinNames?: readonly string[]);
|
|
19
|
+
/** Called after every MDX pass with the published pages and their sources. */
|
|
20
|
+
updateFromPages(pages: readonly PageMeta[], mdxSources: ReadonlyMap<string, string>): Promise<void>;
|
|
21
|
+
/** Re-reads navigation.json (already copied to the output) and rewrites. */
|
|
22
|
+
refresh(): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Scaffold-time guarantee that the file the Icon template imports exists.
|
|
25
|
+
* An existing registry is left alone: the MDX pass that follows rewrites it
|
|
26
|
+
* only if its content changed, so a rerun over an unchanged site touches
|
|
27
|
+
* nothing.
|
|
28
|
+
*/
|
|
29
|
+
ensurePresent(): Promise<void>;
|
|
30
|
+
private collectReferences;
|
|
31
|
+
private write;
|
|
32
|
+
private warnUnknown;
|
|
33
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { ICON_REGISTRY_FILE, INDIRECT_TEMPLATE_ICON_NAMES, collectMdxIconNames, collectNavigationIconNames, collectTemplateIconNames, renderIconRegistry, resolveLucideIconName, } from "../lib/icon-registry.js";
|
|
3
|
+
import { readOutputFileIfPresent, resolveOutputPath, } from "../lib/output-safety.js";
|
|
4
|
+
import { appStructure } from "../lib/structures.js";
|
|
5
|
+
import { writeFileAtomic } from "../lib/utils.js";
|
|
6
|
+
/** Icon names the generated components use on their own, whatever the docs say. */
|
|
7
|
+
export function builtinIconNames() {
|
|
8
|
+
return [
|
|
9
|
+
...collectTemplateIconNames(appStructure),
|
|
10
|
+
...INDIRECT_TEMPLATE_ICON_NAMES,
|
|
11
|
+
];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Keeps `components/layout/IconRegistry.ts` in step with the icon names the
|
|
15
|
+
* site uses: sidebar icons from frontmatter, `icon` entries in navigation.json,
|
|
16
|
+
* `<Icon>` and `icon` props in MDX, and the glyphs the generated components
|
|
17
|
+
* draw themselves. Unknown names are reported once and left out, so a typo
|
|
18
|
+
* renders nothing rather than failing the build.
|
|
19
|
+
*/
|
|
20
|
+
export class IconRegistryGenerator {
|
|
21
|
+
outputDir;
|
|
22
|
+
builtinNames;
|
|
23
|
+
pages = [];
|
|
24
|
+
mdxSources = new Map();
|
|
25
|
+
lastWritten = null;
|
|
26
|
+
lastWarning = "";
|
|
27
|
+
constructor(outputDir, builtinNames = builtinIconNames()) {
|
|
28
|
+
this.outputDir = outputDir;
|
|
29
|
+
this.builtinNames = builtinNames;
|
|
30
|
+
}
|
|
31
|
+
/** Called after every MDX pass with the published pages and their sources. */
|
|
32
|
+
async updateFromPages(pages, mdxSources) {
|
|
33
|
+
this.pages = pages;
|
|
34
|
+
this.mdxSources = mdxSources;
|
|
35
|
+
await this.write();
|
|
36
|
+
}
|
|
37
|
+
/** Re-reads navigation.json (already copied to the output) and rewrites. */
|
|
38
|
+
async refresh() {
|
|
39
|
+
await this.write();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Scaffold-time guarantee that the file the Icon template imports exists.
|
|
43
|
+
* An existing registry is left alone: the MDX pass that follows rewrites it
|
|
44
|
+
* only if its content changed, so a rerun over an unchanged site touches
|
|
45
|
+
* nothing.
|
|
46
|
+
*/
|
|
47
|
+
async ensurePresent() {
|
|
48
|
+
const existing = await readOutputFileIfPresent(this.outputDir, ICON_REGISTRY_FILE);
|
|
49
|
+
if (existing !== null)
|
|
50
|
+
return;
|
|
51
|
+
await this.write();
|
|
52
|
+
}
|
|
53
|
+
collectReferences(navigationJson) {
|
|
54
|
+
const references = this.builtinNames.map((name) => ({
|
|
55
|
+
name,
|
|
56
|
+
source: "",
|
|
57
|
+
}));
|
|
58
|
+
for (const page of this.pages) {
|
|
59
|
+
if (page.navIcon) {
|
|
60
|
+
references.push({
|
|
61
|
+
name: page.navIcon,
|
|
62
|
+
source: `${page.path} (navIcon)`,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
if (page.categoryIcon) {
|
|
66
|
+
references.push({
|
|
67
|
+
name: page.categoryIcon,
|
|
68
|
+
source: `${page.path} (categoryIcon)`,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const [source, content] of this.mdxSources) {
|
|
73
|
+
for (const name of collectMdxIconNames(content)) {
|
|
74
|
+
references.push({ name, source });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const name of collectNavigationIconNames(navigationJson)) {
|
|
78
|
+
references.push({ name, source: "navigation.json" });
|
|
79
|
+
}
|
|
80
|
+
return references;
|
|
81
|
+
}
|
|
82
|
+
async write() {
|
|
83
|
+
const navigationJson = await readOutputFileIfPresent(this.outputDir, "navigation.json");
|
|
84
|
+
const ids = new Set();
|
|
85
|
+
const unknown = new Map();
|
|
86
|
+
for (const { name, source } of this.collectReferences(navigationJson)) {
|
|
87
|
+
const id = resolveLucideIconName(name);
|
|
88
|
+
if (id) {
|
|
89
|
+
ids.add(id);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const sources = unknown.get(name) ?? new Set();
|
|
93
|
+
if (source)
|
|
94
|
+
sources.add(source);
|
|
95
|
+
unknown.set(name, sources);
|
|
96
|
+
}
|
|
97
|
+
this.warnUnknown(unknown);
|
|
98
|
+
const content = renderIconRegistry(ids);
|
|
99
|
+
if (content === this.lastWritten)
|
|
100
|
+
return;
|
|
101
|
+
if (this.lastWritten === null) {
|
|
102
|
+
// First pass of this run: an unchanged file from the previous run is
|
|
103
|
+
// left alone so the dev server sees no spurious rebuild.
|
|
104
|
+
const existing = await readOutputFileIfPresent(this.outputDir, ICON_REGISTRY_FILE);
|
|
105
|
+
if (existing === content) {
|
|
106
|
+
this.lastWritten = content;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
await writeFileAtomic(resolveOutputPath(this.outputDir, ICON_REGISTRY_FILE), content);
|
|
111
|
+
this.lastWritten = content;
|
|
112
|
+
}
|
|
113
|
+
warnUnknown(unknown) {
|
|
114
|
+
const lines = [...unknown]
|
|
115
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
116
|
+
.map(([name, sources]) => {
|
|
117
|
+
const where = [...sources].sort().join(", ");
|
|
118
|
+
return `"${name}"${where ? ` in ${where}` : ""}`;
|
|
119
|
+
});
|
|
120
|
+
const message = lines.join("\n");
|
|
121
|
+
if (message === this.lastWarning)
|
|
122
|
+
return;
|
|
123
|
+
this.lastWarning = message;
|
|
124
|
+
if (!message)
|
|
125
|
+
return;
|
|
126
|
+
console.warn(chalk.yellow(`⚠️ Unknown Lucide icon name${lines.length === 1 ? "" : "s"}, rendering nothing (see https://lucide.dev/icons):`));
|
|
127
|
+
for (const line of lines)
|
|
128
|
+
console.warn(chalk.yellow(` ${line}`));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -35,6 +35,7 @@ interface MdxReconciliationCoordinatorOptions {
|
|
|
35
35
|
updateRootLayout(pages?: PageMeta[]): Promise<void>;
|
|
36
36
|
updateSitemap(pages?: PageMeta[]): Promise<void>;
|
|
37
37
|
updateLlmsFiles(pages?: PageMeta[]): Promise<void>;
|
|
38
|
+
updateIconRegistry(pages: PageMeta[], mdxSources: ReadonlyMap<string, string>): Promise<void>;
|
|
38
39
|
generateSectionIndexPages(pages?: PageMeta[], declaredSlugs?: Set<string>): Promise<void>;
|
|
39
40
|
maybeUpdateSections(): Promise<void>;
|
|
40
41
|
removeOwnedRoute(slug: string): Promise<void>;
|
|
@@ -317,6 +317,7 @@ export class MdxReconciliationCoordinator {
|
|
|
317
317
|
await this.options.updateRootLayout(pages);
|
|
318
318
|
await this.options.updateSitemap(pages);
|
|
319
319
|
await this.options.updateLlmsFiles(pages);
|
|
320
|
+
await this.options.updateIconRegistry(pages, this.successfulMdxContent);
|
|
320
321
|
await this.options.generateSectionIndexPages(pages, declaredSlugs);
|
|
321
322
|
}
|
|
322
323
|
async handleFileChange(action, filePath) {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated file, relative to the output directory, that maps the Lucide icon
|
|
3
|
+
* names a site uses to statically imported glyphs. The Icon template resolves
|
|
4
|
+
* every name through it, so the app bundles only those glyphs instead of the
|
|
5
|
+
* whole Lucide set.
|
|
6
|
+
*/
|
|
7
|
+
export declare const ICON_REGISTRY_FILE = "components/layout/IconRegistry.ts";
|
|
8
|
+
/** An icon name together with where it was authored, for warnings. */
|
|
9
|
+
export interface IconReference {
|
|
10
|
+
name: string;
|
|
11
|
+
/** Source description, e.g. "guide.mdx (navIcon)"; empty for built-ins. */
|
|
12
|
+
source: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Lucide derives each PascalCase export from its kebab-case id by capitalising
|
|
16
|
+
* every segment ("arrow-down-a-z" -> "ArrowDownAZ"). The generated Icon
|
|
17
|
+
* component applies the same transform to whatever authors write, so both
|
|
18
|
+
* spellings land on one registry key.
|
|
19
|
+
*/
|
|
20
|
+
export declare function toPascalIconName(name: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Resolves an authored name, kebab-case id or PascalCase export name, to
|
|
23
|
+
* Lucide's kebab-case id. Returns null for a name Lucide does not have.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveLucideIconName(name: string): string | null;
|
|
26
|
+
/**
|
|
27
|
+
* Icon names an MDX document renders: `<Icon name="...">` and the `icon`
|
|
28
|
+
* attribute of the authoring components. Frontmatter and code (fenced blocks
|
|
29
|
+
* and inline spans) are skipped, so documenting an icon does not bundle it.
|
|
30
|
+
*/
|
|
31
|
+
export declare function collectMdxIconNames(content: string): string[];
|
|
32
|
+
/**
|
|
33
|
+
* Every `icon` string in navigation.json, at any depth: category icons,
|
|
34
|
+
* link icons, and the icons of nested link groups, in either the array or the
|
|
35
|
+
* per-section object form. Malformed JSON contributes nothing.
|
|
36
|
+
*/
|
|
37
|
+
export declare function collectNavigationIconNames(json: string | null): string[];
|
|
38
|
+
/**
|
|
39
|
+
* Icon names the generated components draw themselves: `<Icon name="...">`
|
|
40
|
+
* literals plus the string literals inside `name={...}` expressions, across
|
|
41
|
+
* every template source.
|
|
42
|
+
*/
|
|
43
|
+
export declare function collectTemplateIconNames(templates: Record<string, string>): string[];
|
|
44
|
+
/**
|
|
45
|
+
* Template icons that reach `<Icon>` through a variable rather than a literal
|
|
46
|
+
* `name`, so the template scan cannot see them: Callout's per-type defaults
|
|
47
|
+
* and the "rocket" category icon of the placeholder navigation shown before
|
|
48
|
+
* any page exists (SectionNavProvider, site layout).
|
|
49
|
+
*/
|
|
50
|
+
export declare const INDIRECT_TEMPLATE_ICON_NAMES: readonly string[];
|
|
51
|
+
/**
|
|
52
|
+
* Renders IconRegistry.ts for the given Lucide kebab-case ids. The output is
|
|
53
|
+
* Prettier-canonical for the generated app's config (double quotes, trailing
|
|
54
|
+
* commas, 80 columns), since the generator never runs a formatter.
|
|
55
|
+
*/
|
|
56
|
+
export declare function renderIconRegistry(kebabIds: Iterable<string>): string;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { iconNames } from "lucide-react/dynamic.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* Generated file, relative to the output directory, that maps the Lucide icon
|
|
4
|
+
* names a site uses to statically imported glyphs. The Icon template resolves
|
|
5
|
+
* every name through it, so the app bundles only those glyphs instead of the
|
|
6
|
+
* whole Lucide set.
|
|
7
|
+
*/
|
|
8
|
+
export const ICON_REGISTRY_FILE = "components/layout/IconRegistry.ts";
|
|
9
|
+
/** Lucide's kebab-case ids: the canonical spelling every other form resolves to. */
|
|
10
|
+
const KEBAB_IDS = new Set(iconNames);
|
|
11
|
+
/**
|
|
12
|
+
* Lucide derives each PascalCase export from its kebab-case id by capitalising
|
|
13
|
+
* every segment ("arrow-down-a-z" -> "ArrowDownAZ"). The generated Icon
|
|
14
|
+
* component applies the same transform to whatever authors write, so both
|
|
15
|
+
* spellings land on one registry key.
|
|
16
|
+
*/
|
|
17
|
+
export function toPascalIconName(name) {
|
|
18
|
+
return name
|
|
19
|
+
.split("-")
|
|
20
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
21
|
+
.join("");
|
|
22
|
+
}
|
|
23
|
+
const KEBAB_BY_PASCAL = new Map(iconNames.map((id) => [toPascalIconName(id), id]));
|
|
24
|
+
/**
|
|
25
|
+
* Resolves an authored name, kebab-case id or PascalCase export name, to
|
|
26
|
+
* Lucide's kebab-case id. Returns null for a name Lucide does not have.
|
|
27
|
+
*/
|
|
28
|
+
export function resolveLucideIconName(name) {
|
|
29
|
+
const trimmed = name.trim();
|
|
30
|
+
if (KEBAB_IDS.has(trimmed))
|
|
31
|
+
return trimmed;
|
|
32
|
+
return KEBAB_BY_PASCAL.get(toPascalIconName(trimmed)) ?? null;
|
|
33
|
+
}
|
|
34
|
+
// A quoted attribute value in JSX: name="x", name='x', name={"x"}, name={'x'}.
|
|
35
|
+
const QUOTED_VALUE = `(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:"([^"]*)"|'([^']*)')\\s*\\})`;
|
|
36
|
+
// <Icon name="..."> in any attribute position, also across line breaks.
|
|
37
|
+
const ICON_TAG_LITERAL = new RegExp(`<Icon\\b[^>]*?\\bname=${QUOTED_VALUE}`, "g");
|
|
38
|
+
// icon="..." on any component that forwards it to Icon (Card, Callout, Steps,
|
|
39
|
+
// Tabs, Badge, Button, Prompt).
|
|
40
|
+
const ICON_ATTRIBUTE = new RegExp(`\\bicon=${QUOTED_VALUE}`, "g");
|
|
41
|
+
// <Icon name={expr}>: literals inside the expression, for templates that pick
|
|
42
|
+
// a glyph inline (name={copied ? "check" : "copy"}).
|
|
43
|
+
const ICON_TAG_EXPRESSION = /<Icon\b[^>]*?\bname=\{([^}]*)\}/g;
|
|
44
|
+
const STRING_LITERAL = /"([^"\\]*)"|'([^'\\]*)'/g;
|
|
45
|
+
const FENCED_CODE = /^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[^\n]*$/gm;
|
|
46
|
+
const INLINE_CODE = /`[^`\n]*`/g;
|
|
47
|
+
const FRONTMATTER = /^\uFEFF?---[^\n]*\r?\n[\s\S]*?\r?\n---[^\n]*\r?\n?/;
|
|
48
|
+
function quotedValues(pattern, text) {
|
|
49
|
+
const names = [];
|
|
50
|
+
for (const match of text.matchAll(pattern)) {
|
|
51
|
+
const value = match.slice(1).find((group) => group !== undefined);
|
|
52
|
+
if (value)
|
|
53
|
+
names.push(value);
|
|
54
|
+
}
|
|
55
|
+
return names;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Icon names an MDX document renders: `<Icon name="...">` and the `icon`
|
|
59
|
+
* attribute of the authoring components. Frontmatter and code (fenced blocks
|
|
60
|
+
* and inline spans) are skipped, so documenting an icon does not bundle it.
|
|
61
|
+
*/
|
|
62
|
+
export function collectMdxIconNames(content) {
|
|
63
|
+
const body = content
|
|
64
|
+
.replace(FRONTMATTER, "")
|
|
65
|
+
.replace(FENCED_CODE, "")
|
|
66
|
+
.replace(INLINE_CODE, "");
|
|
67
|
+
return [
|
|
68
|
+
...quotedValues(ICON_TAG_LITERAL, body),
|
|
69
|
+
...quotedValues(ICON_ATTRIBUTE, body),
|
|
70
|
+
];
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Every `icon` string in navigation.json, at any depth: category icons,
|
|
74
|
+
* link icons, and the icons of nested link groups, in either the array or the
|
|
75
|
+
* per-section object form. Malformed JSON contributes nothing.
|
|
76
|
+
*/
|
|
77
|
+
export function collectNavigationIconNames(json) {
|
|
78
|
+
if (!json)
|
|
79
|
+
return [];
|
|
80
|
+
let parsed;
|
|
81
|
+
try {
|
|
82
|
+
parsed = JSON.parse(json);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
const names = [];
|
|
88
|
+
const walk = (value) => {
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
value.forEach(walk);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (!value || typeof value !== "object")
|
|
94
|
+
return;
|
|
95
|
+
for (const [key, child] of Object.entries(value)) {
|
|
96
|
+
if (key === "icon" && typeof child === "string")
|
|
97
|
+
names.push(child);
|
|
98
|
+
else
|
|
99
|
+
walk(child);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
walk(parsed);
|
|
103
|
+
return names;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Icon names the generated components draw themselves: `<Icon name="...">`
|
|
107
|
+
* literals plus the string literals inside `name={...}` expressions, across
|
|
108
|
+
* every template source.
|
|
109
|
+
*/
|
|
110
|
+
export function collectTemplateIconNames(templates) {
|
|
111
|
+
const names = [];
|
|
112
|
+
for (const source of Object.values(templates)) {
|
|
113
|
+
names.push(...quotedValues(ICON_TAG_LITERAL, source));
|
|
114
|
+
for (const match of source.matchAll(ICON_TAG_EXPRESSION)) {
|
|
115
|
+
names.push(...quotedValues(STRING_LITERAL, match[1]));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return names;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Template icons that reach `<Icon>` through a variable rather than a literal
|
|
122
|
+
* `name`, so the template scan cannot see them: Callout's per-type defaults
|
|
123
|
+
* and the "rocket" category icon of the placeholder navigation shown before
|
|
124
|
+
* any page exists (SectionNavProvider, site layout).
|
|
125
|
+
*/
|
|
126
|
+
export const INDIRECT_TEMPLATE_ICON_NAMES = [
|
|
127
|
+
"CircleAlert",
|
|
128
|
+
"Info",
|
|
129
|
+
"TriangleAlert",
|
|
130
|
+
"OctagonAlert",
|
|
131
|
+
"Check",
|
|
132
|
+
"rocket",
|
|
133
|
+
];
|
|
134
|
+
const PRINT_WIDTH = 80;
|
|
135
|
+
/**
|
|
136
|
+
* Renders IconRegistry.ts for the given Lucide kebab-case ids. The output is
|
|
137
|
+
* Prettier-canonical for the generated app's config (double quotes, trailing
|
|
138
|
+
* commas, 80 columns), since the generator never runs a formatter.
|
|
139
|
+
*/
|
|
140
|
+
export function renderIconRegistry(kebabIds) {
|
|
141
|
+
const exportNames = [...new Set([...kebabIds].map(toPascalIconName))].sort();
|
|
142
|
+
const lines = [
|
|
143
|
+
"// Generated by Doccupine from the icon names your pages, navigation, and",
|
|
144
|
+
"// components use, so the site bundles only those glyphs. Do not edit: it",
|
|
145
|
+
"// is rewritten whenever those names change.",
|
|
146
|
+
'import type { LucideIcon } from "lucide-react";',
|
|
147
|
+
];
|
|
148
|
+
if (exportNames.length > 0) {
|
|
149
|
+
const inline = `import { ${exportNames.join(", ")} } from "lucide-react";`;
|
|
150
|
+
if (inline.length <= PRINT_WIDTH) {
|
|
151
|
+
lines.push(inline);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
lines.push("import {", ...exportNames.map((name) => ` ${name},`), '} from "lucide-react";');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
lines.push("");
|
|
158
|
+
if (exportNames.length === 0) {
|
|
159
|
+
lines.push("export const iconRegistry: Record<string, LucideIcon> = {};");
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
lines.push("export const iconRegistry: Record<string, LucideIcon> = {", ...exportNames.map((name) => ` ${name},`), "};");
|
|
163
|
+
}
|
|
164
|
+
return lines.join("\n") + "\n";
|
|
165
|
+
}
|
|
@@ -29,6 +29,7 @@ export declare class MDXToNextJSGenerator {
|
|
|
29
29
|
private projectConfigRepository;
|
|
30
30
|
private publicAssetManager;
|
|
31
31
|
private iconAssetManager;
|
|
32
|
+
private iconRegistryGenerator;
|
|
32
33
|
private watchCoordinator;
|
|
33
34
|
constructor(watchDir: string, outputDir: string, openApiSpecs?: NormalizedOpenApiSpec[], rootDir?: string);
|
|
34
35
|
private outputPath;
|
|
@@ -19,6 +19,7 @@ import { MdxReconciliationCoordinator } from "./generator/mdx-reconciliation-coo
|
|
|
19
19
|
import { ProjectConfigRepository } from "./generator/project-config-repository.js";
|
|
20
20
|
import { PublicAssetManager } from "./generator/public-asset-manager.js";
|
|
21
21
|
import { ICON_SOURCE_FILES, IconAssetManager, } from "./generator/icon-asset-manager.js";
|
|
22
|
+
import { IconRegistryGenerator } from "./generator/icon-registry-generator.js";
|
|
22
23
|
import { WatchCoordinator } from "./generator/watch-coordinator.js";
|
|
23
24
|
import { SectionIndexGenerator } from "./generator/section-index-generator.js";
|
|
24
25
|
import { OpenApiRefreshCoordinator, } from "./generator/openapi-refresh-coordinator.js";
|
|
@@ -58,6 +59,7 @@ export class MDXToNextJSGenerator {
|
|
|
58
59
|
projectConfigRepository;
|
|
59
60
|
publicAssetManager;
|
|
60
61
|
iconAssetManager;
|
|
62
|
+
iconRegistryGenerator;
|
|
61
63
|
watchCoordinator;
|
|
62
64
|
constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
|
|
63
65
|
this.watchDir = path.resolve(watchDir);
|
|
@@ -67,6 +69,7 @@ export class MDXToNextJSGenerator {
|
|
|
67
69
|
this.artifacts = new GeneratedArtifacts(this.outputDir);
|
|
68
70
|
this.sourceFs = new SecureSourceFs(this.watchDir, this.rootDir);
|
|
69
71
|
this.appScaffolder = new AppScaffolder(this.outputDir);
|
|
72
|
+
this.iconRegistryGenerator = new IconRegistryGenerator(this.outputDir);
|
|
70
73
|
this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
|
|
71
74
|
this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
|
|
72
75
|
this.generatedPagePublisher = new GeneratedPagePublisher(this.outputDir, this.generatedRouteManager);
|
|
@@ -95,6 +98,7 @@ export class MDXToNextJSGenerator {
|
|
|
95
98
|
updateRootLayout: (pages) => this.updateRootLayout(pages),
|
|
96
99
|
updateSitemap: (pages) => this.updateSitemap(pages),
|
|
97
100
|
updateLlmsFiles: (pages) => this.updateLlmsFiles(pages),
|
|
101
|
+
updateIconRegistry: (pages, mdxSources) => this.iconRegistryGenerator.updateFromPages(pages, mdxSources),
|
|
98
102
|
generateSectionIndexPages: (pages, declaredSlugs) => this.generateSectionIndexPages(pages, declaredSlugs),
|
|
99
103
|
maybeUpdateSections: () => this.maybeUpdateSections(),
|
|
100
104
|
removeOwnedRoute: (slug) => this.removeOwnedRoute(slug),
|
|
@@ -226,6 +230,7 @@ export class MDXToNextJSGenerator {
|
|
|
226
230
|
generateSiteLayout: () => this.generateSiteLayout(),
|
|
227
231
|
updateSitemap: () => this.updateSitemap(),
|
|
228
232
|
updateLlmsFiles: () => this.updateLlmsFiles(),
|
|
233
|
+
updateIconRegistry: () => this.iconRegistryGenerator.ensurePresent(),
|
|
229
234
|
});
|
|
230
235
|
}
|
|
231
236
|
async createStartingDocs() {
|
|
@@ -325,6 +330,9 @@ export class MDXToNextJSGenerator {
|
|
|
325
330
|
await this.updateRobots();
|
|
326
331
|
await this.updateLlmsFiles();
|
|
327
332
|
}
|
|
333
|
+
if (fileName === "navigation.json") {
|
|
334
|
+
await this.iconRegistryGenerator.refresh();
|
|
335
|
+
}
|
|
328
336
|
}
|
|
329
337
|
catch (error) {
|
|
330
338
|
console.error(chalk.red(`❌ Error copying ${fileName}:`), error);
|
|
@@ -345,6 +353,9 @@ export class MDXToNextJSGenerator {
|
|
|
345
353
|
await this.updateRobots();
|
|
346
354
|
await this.updateLlmsFiles();
|
|
347
355
|
}
|
|
356
|
+
if (fileName === "navigation.json") {
|
|
357
|
+
await this.iconRegistryGenerator.refresh();
|
|
358
|
+
}
|
|
348
359
|
}
|
|
349
360
|
catch (error) {
|
|
350
361
|
console.error(chalk.red(`❌ Error removing ${fileName}:`), error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const iconTemplate = "import {
|
|
1
|
+
export declare const iconTemplate = "import type { LucideIcon } from \"lucide-react\";\n\nimport { iconRegistry } from \"@/components/layout/IconRegistry\";\n\n/**\n * A Lucide icon name: the kebab-case id (\"arrow-right\") or the PascalCase\n * export name (\"ArrowRight\"). Names resolve through IconRegistry.ts, which\n * Doccupine generates from the names used across the site, so the app bundles\n * only those glyphs. An unknown name renders nothing.\n */\nexport type IconProps = string;\n\ninterface Props {\n name: IconProps;\n color?: string;\n size?: string | number;\n className?: string;\n}\n\n// Lucide derives every PascalCase export from its kebab-case id by capitalising\n// each segment (\"arrow-down-a-z\" -> \"ArrowDownAZ\"); the registry is keyed by\n// that export name, so both spellings resolve to the same entry.\nfunction toRegistryKey(name: string): string {\n return name\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\"\");\n}\n\nconst Icon = ({ name, color, size, className }: Props) => {\n if (!name) return null;\n const Glyph: LucideIcon | undefined = iconRegistry[toRegistryKey(name)];\n if (!Glyph) return null;\n\n const numericSize = size != null ? Number(size) : undefined;\n\n return <Glyph color={color} size={numericSize} className={className} />;\n};\n\nexport { Icon };\n";
|
|
@@ -1,15 +1,26 @@
|
|
|
1
|
-
export const iconTemplate = `import {
|
|
1
|
+
export const iconTemplate = `import type { LucideIcon } from "lucide-react";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
import { iconRegistry } from "@/components/layout/IconRegistry";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A Lucide icon name: the kebab-case id ("arrow-right") or the PascalCase
|
|
7
|
+
* export name ("ArrowRight"). Names resolve through IconRegistry.ts, which
|
|
8
|
+
* Doccupine generates from the names used across the site, so the app bundles
|
|
9
|
+
* only those glyphs. An unknown name renders nothing.
|
|
10
|
+
*/
|
|
11
|
+
export type IconProps = string;
|
|
4
12
|
|
|
5
13
|
interface Props {
|
|
6
|
-
name:
|
|
14
|
+
name: IconProps;
|
|
7
15
|
color?: string;
|
|
8
16
|
size?: string | number;
|
|
9
17
|
className?: string;
|
|
10
18
|
}
|
|
11
19
|
|
|
12
|
-
|
|
20
|
+
// Lucide derives every PascalCase export from its kebab-case id by capitalising
|
|
21
|
+
// each segment ("arrow-down-a-z" -> "ArrowDownAZ"); the registry is keyed by
|
|
22
|
+
// that export name, so both spellings resolve to the same entry.
|
|
23
|
+
function toRegistryKey(name: string): string {
|
|
13
24
|
return name
|
|
14
25
|
.split("-")
|
|
15
26
|
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
@@ -18,13 +29,12 @@ function transformIconName(name: string): string {
|
|
|
18
29
|
|
|
19
30
|
const Icon = ({ name, color, size, className }: Props) => {
|
|
20
31
|
if (!name) return null;
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
if (!LucideIcon) return null;
|
|
32
|
+
const Glyph: LucideIcon | undefined = iconRegistry[toRegistryKey(name)];
|
|
33
|
+
if (!Glyph) return null;
|
|
24
34
|
|
|
25
35
|
const numericSize = size != null ? Number(size) : undefined;
|
|
26
36
|
|
|
27
|
-
return <
|
|
37
|
+
return <Glyph color={color} size={numericSize} className={className} />;
|
|
28
38
|
};
|
|
29
39
|
|
|
30
40
|
export { Icon };
|
|
@@ -12,21 +12,21 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
12
12
|
"type-check": "tsgo --noEmit",
|
|
13
13
|
},
|
|
14
14
|
dependencies: {
|
|
15
|
-
"@langchain/anthropic": "^1.5.
|
|
16
|
-
"@langchain/core": "^1.2.
|
|
17
|
-
"@langchain/google-genai": "^2.
|
|
18
|
-
"@langchain/openai": "^1.5.
|
|
15
|
+
"@langchain/anthropic": "^1.5.9",
|
|
16
|
+
"@langchain/core": "^1.2.9",
|
|
17
|
+
"@langchain/google-genai": "^2.3.0",
|
|
18
|
+
"@langchain/openai": "^1.5.11",
|
|
19
19
|
"@mdx-js/react": "^3.1.1",
|
|
20
20
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
21
21
|
"beautiful-mermaid": "^1.1.3",
|
|
22
|
-
"cherry-styled-components": "^0.2.
|
|
23
|
-
langchain: "^1.5.
|
|
24
|
-
"lucide-react": "^1.
|
|
22
|
+
"cherry-styled-components": "^0.2.17",
|
|
23
|
+
langchain: "^1.5.10",
|
|
24
|
+
"lucide-react": "^1.41.0",
|
|
25
25
|
minisearch: "^7.2.0",
|
|
26
|
-
next: "16.3.
|
|
26
|
+
next: "16.3.4",
|
|
27
27
|
"next-mdx-remote": "^6.0.0",
|
|
28
|
-
"posthog-js": "^1.
|
|
29
|
-
"posthog-node": "^5.
|
|
28
|
+
"posthog-js": "^1.427.2",
|
|
29
|
+
"posthog-node": "^5.51.6",
|
|
30
30
|
react: "19.2.8",
|
|
31
31
|
"react-dom": "19.2.8",
|
|
32
32
|
"rehype-highlight": "^7.0.2",
|
|
@@ -35,25 +35,25 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
35
35
|
"remark-gfm": "^4.0.1",
|
|
36
36
|
"styled-components": "^6.5.3",
|
|
37
37
|
unified: "^11.0.5",
|
|
38
|
-
zod: "^4.4
|
|
38
|
+
zod: "^4.5.4",
|
|
39
39
|
},
|
|
40
40
|
devDependencies: {
|
|
41
|
-
"@next/env": "16.3.
|
|
42
|
-
"@next/eslint-plugin-next": "16.3.
|
|
41
|
+
"@next/env": "16.3.4",
|
|
42
|
+
"@next/eslint-plugin-next": "16.3.4",
|
|
43
43
|
"@types/node": "^26",
|
|
44
44
|
"@types/react": "^19",
|
|
45
45
|
"@types/react-dom": "^19",
|
|
46
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
47
|
-
"@typescript-eslint/parser": "^8.
|
|
46
|
+
"@typescript-eslint/eslint-plugin": "^8.69.0",
|
|
47
|
+
"@typescript-eslint/parser": "^8.69.0",
|
|
48
48
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
|
49
49
|
eslint: "^10",
|
|
50
50
|
"eslint-plugin-import": "^2.32.0",
|
|
51
51
|
"eslint-plugin-jsx-a11y": "^6.10.2",
|
|
52
52
|
"eslint-plugin-react": "^7.37.5",
|
|
53
53
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
54
|
-
globals: "^17.
|
|
54
|
+
globals: "^17.12.0",
|
|
55
55
|
prettier: "^3.9.6",
|
|
56
|
-
tsx: "^4.23.
|
|
56
|
+
tsx: "^4.23.13",
|
|
57
57
|
typescript: "npm:@typescript/typescript6@^6.0.2",
|
|
58
58
|
},
|
|
59
59
|
}, null, 2) + "\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";
|
|
1
|
+
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport {\n McpServer,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register the documentation index as a resource\n server.registerResource(\n \"docs-list\",\n \"docs://list\",\n {\n title: \"Documentation index\",\n description:\n \"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read\",\n mimeType: \"application/json\",\n },\n async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n mimeType: \"application/json\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n },\n );\n\n // Register every documentation page as a readable docs://<route> resource.\n // `{+path}` is a reserved expansion so nested routes keep their slashes.\n // The fixed docs://list resource above is matched before this template.\n server.registerResource(\n \"doc\",\n new ResourceTemplate(\"docs://{+path}\", { list: undefined }),\n {\n title: \"Documentation page\",\n description:\n \"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index\",\n mimeType: \"text/markdown\",\n },\n async (uri, _variables, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path: uri.href });\n signal.throwIfAborted();\n if (!doc) {\n throw new Error(`Document not found: ${uri.href}`);\n }\n return {\n contents: [\n { uri: doc.uri, mimeType: \"text/markdown\", text: doc.content },\n ],\n };\n },\n );\n\n return server;\n}\n";
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export const mcpServerTemplate = `import path from "node:path";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
McpServer,
|
|
5
|
+
ResourceTemplate,
|
|
6
|
+
} from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
7
|
import { z } from "zod";
|
|
5
8
|
import {
|
|
6
9
|
listDocs,
|
|
@@ -470,20 +473,58 @@ export function createMCPServer(): McpServer {
|
|
|
470
473
|
},
|
|
471
474
|
);
|
|
472
475
|
|
|
473
|
-
// Register documentation as
|
|
474
|
-
server.
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
476
|
+
// Register the documentation index as a resource
|
|
477
|
+
server.registerResource(
|
|
478
|
+
"docs-list",
|
|
479
|
+
"docs://list",
|
|
480
|
+
{
|
|
481
|
+
title: "Documentation index",
|
|
482
|
+
description:
|
|
483
|
+
"JSON index of every documentation page: name, path, and docs:// URI readable with resources/read",
|
|
484
|
+
mimeType: "application/json",
|
|
485
|
+
},
|
|
486
|
+
async () => {
|
|
487
|
+
const docs = await listDocs();
|
|
488
|
+
return {
|
|
489
|
+
contents: [
|
|
490
|
+
{
|
|
491
|
+
uri: "docs://list",
|
|
492
|
+
mimeType: "application/json",
|
|
493
|
+
text: resourceText(
|
|
494
|
+
docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),
|
|
495
|
+
),
|
|
496
|
+
},
|
|
497
|
+
],
|
|
498
|
+
};
|
|
499
|
+
},
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
// Register every documentation page as a readable docs://<route> resource.
|
|
503
|
+
// \`{+path}\` is a reserved expansion so nested routes keep their slashes.
|
|
504
|
+
// The fixed docs://list resource above is matched before this template.
|
|
505
|
+
server.registerResource(
|
|
506
|
+
"doc",
|
|
507
|
+
new ResourceTemplate("docs://{+path}", { list: undefined }),
|
|
508
|
+
{
|
|
509
|
+
title: "Documentation page",
|
|
510
|
+
description:
|
|
511
|
+
"The Markdown content of one documentation page, addressed by the docs:// URI from the docs://list index",
|
|
512
|
+
mimeType: "text/markdown",
|
|
513
|
+
},
|
|
514
|
+
async (uri, _variables, { signal }) => {
|
|
515
|
+
signal.throwIfAborted();
|
|
516
|
+
const doc = await getDoc({ path: uri.href });
|
|
517
|
+
signal.throwIfAborted();
|
|
518
|
+
if (!doc) {
|
|
519
|
+
throw new Error(\`Document not found: \${uri.href}\`);
|
|
520
|
+
}
|
|
521
|
+
return {
|
|
522
|
+
contents: [
|
|
523
|
+
{ uri: doc.uri, mimeType: "text/markdown", text: doc.content },
|
|
524
|
+
],
|
|
525
|
+
};
|
|
526
|
+
},
|
|
527
|
+
);
|
|
487
528
|
|
|
488
529
|
return server;
|
|
489
530
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.157",
|
|
4
4
|
"description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"engines": {
|
|
11
11
|
"node": ">=22.12.0"
|
|
12
12
|
},
|
|
13
|
-
"packageManager": "pnpm@
|
|
13
|
+
"packageManager": "pnpm@12.3.4",
|
|
14
14
|
"scripts": {
|
|
15
15
|
"clean": "node scripts/clean.mjs",
|
|
16
16
|
"build": "pnpm clean && tsc",
|
|
@@ -42,24 +42,25 @@
|
|
|
42
42
|
"author": "Luan Gjokaj",
|
|
43
43
|
"license": "SEE LICENSE IN LICENSE",
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@readme/openapi-parser": "^
|
|
45
|
+
"@readme/openapi-parser": "^9.0.0",
|
|
46
46
|
"chalk": "^6.0.0",
|
|
47
47
|
"chokidar": "^5.0.0",
|
|
48
48
|
"commander": "^15.0.0",
|
|
49
49
|
"fs-extra": "^11.4.0",
|
|
50
50
|
"gray-matter": "^4.0.3",
|
|
51
|
-
"
|
|
51
|
+
"lucide-react": "^1.41.0",
|
|
52
|
+
"next": "^16.3.4",
|
|
52
53
|
"prompts": "^2.4.2",
|
|
53
54
|
"react": "^19.2.8",
|
|
54
55
|
"react-dom": "^19.2.8"
|
|
55
56
|
},
|
|
56
57
|
"devDependencies": {
|
|
57
58
|
"@types/fs-extra": "^11.0.4",
|
|
58
|
-
"@types/node": "^26.
|
|
59
|
+
"@types/node": "^26.4.1",
|
|
59
60
|
"@types/prompts": "^2.4.9",
|
|
60
61
|
"prettier": "^3.9.6",
|
|
61
62
|
"typescript": "^7.0.2",
|
|
62
|
-
"vitest": "^
|
|
63
|
+
"vitest": "^5.0.0"
|
|
63
64
|
},
|
|
64
65
|
"files": [
|
|
65
66
|
"dist/**/*"
|