-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvitest-docs.js
More file actions
188 lines (156 loc) · 5.36 KB
/
Copy pathvitest-docs.js
File metadata and controls
188 lines (156 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
* tools/vitest-docs.js
*
* Fetch Vitest testing framework documentation — no API key required.
* Vitest exposes all docs as clean Markdown via llms.txt endpoints.
*
* Tools:
* - get-index → lists all available Vitest doc pages
* - get-page → fetches a specific doc page as Markdown
* - search-docs → searches across all Vitest docs
*/
const BASE = "https://vitest.dev";
export const tools = [
{
name: "get-index",
description:
"Returns a full index of all Vitest documentation pages. " +
"Use this to discover page paths before calling get-page.",
parameters: {},
},
{
name: "get-page",
description:
"Fetches a specific Vitest doc page as clean Markdown. " +
"Use a path like '/guide/' or '/api/' or '/config/'.",
parameters: {
path: "string — doc path, e.g. '/guide/browser/'",
},
},
{
name: "search-docs",
description:
"Searches all Vitest documentation for a keyword or topic. " +
"Good for questions like 'snapshot testing' or 'mock functions'.",
parameters: {
query: "string — what you're looking for",
maxChars: "number (optional) — max characters to return (default 8000)",
},
},
];
/**
* invoke(toolName, args)
*
* @example
* const { index } = await invoke("get-index");
* const { markdown } = await invoke("get-page", { path: "/guide/" });
* const { result } = await invoke("search-docs", { query: "snapshot testing" });
*/
export async function invoke(toolName, args = {}) {
switch (toolName) {
case "get-index":
return getIndex();
case "get-page":
return getPage(args);
case "search-docs":
return searchDocs(args);
default:
throw new Error(`Unknown vitest-docs tool: "${toolName}"`);
}
}
export function normalizeVitestDocPath(raw) {
let normalized = raw;
// Strip base URL if present
if (normalized.startsWith(BASE)) {
normalized = normalized.slice(BASE.length);
}
// Ensure leading slash
if (!normalized.startsWith("/")) {
normalized = `/${normalized}`;
}
// Remove /index.md suffix
normalized = normalized.replace(/\/index\.md$/i, "/");
// Remove .md extension
normalized = normalized.replace(/\.md$/i, "");
return normalized;
}
// ─── Internal handlers ────────────────────────────────────────────────────────
async function getIndex() {
const res = await fetch(`${BASE}/llms.txt`);
if (!res.ok) throw new Error(`Failed to fetch Vitest llms.txt: ${res.status}`);
const index = await res.text();
return { index };
}
async function getPage({ path }) {
if (!path) throw new Error("get-page requires `path`");
const cleanPath = normalizeVitestDocPath(path);
const res = await fetch(`${BASE}${cleanPath}`, {
headers: { Accept: "text/markdown" },
});
if (!res.ok) {
throw new Error(`Vitest page not found: ${path}`);
}
const markdown = await res.text();
return { path: cleanPath, markdown };
}
async function searchDocs({ query, maxChars = 8000 }) {
if (!query) throw new Error("search-docs requires `query`");
const res = await fetch(`${BASE}/llms-full.txt`);
if (!res.ok) throw new Error(`Failed to fetch Vitest full docs: ${res.status}`);
const text = await res.text();
const scored = findRelevantChunks(text, query);
scored.sort((a, b) => b.score - a.score);
const seen = new Set();
let result = "";
for (const { chunk } of scored) {
const normalized = chunk.trim();
if (!normalized || seen.has(normalized)) continue;
seen.add(normalized);
const separator = result.length > 0 ? "\n\n---\n\n" : "";
const remaining = maxChars - result.length - separator.length;
if (remaining <= 0) break;
const snippet = normalized.length > remaining
? normalized.slice(0, Math.max(0, remaining - 3)).trimEnd() + "..."
: normalized;
if (!snippet.trim()) continue;
result += separator + snippet;
if (snippet.length < normalized.length) break;
}
return {
query,
found: seen.size,
result: result || "No relevant sections found.",
};
}
function findRelevantChunks(text, query) {
const lowerQuery = query.toLowerCase();
const escapedQuery = lowerQuery.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(escapedQuery, "g");
const lines = text.split("\n");
const sections = [];
let buffer = [];
for (const line of lines) {
buffer.push(line);
if (line.startsWith("#") && buffer.length > 1) {
const chunk = buffer.join("\n");
const score = (chunk.toLowerCase().match(pattern) || []).length;
if (score > 0) sections.push({ score: score * 3, chunk: chunk.trim() });
buffer = [line];
}
}
if (buffer.length > 0) {
const chunk = buffer.join("\n");
const score = (chunk.toLowerCase().match(pattern) || []).length;
if (score > 0) sections.push({ score: score * 3, chunk: chunk.trim() });
}
if (sections.length > 0) return sections;
const windows = [];
for (let index = 0; index < lines.length; index++) {
if (!lines[index].toLowerCase().includes(lowerQuery)) continue;
const start = Math.max(0, index - 6);
const end = Math.min(lines.length, index + 18);
const chunk = lines.slice(start, end).join("\n").trim();
if (chunk) windows.push({ score: 1, chunk });
}
return windows;
}