-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresend-docs.js
More file actions
313 lines (262 loc) · 8.41 KB
/
Copy pathresend-docs.js
File metadata and controls
313 lines (262 loc) · 8.41 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/**
* tools/resend-docs.js
*
* Fetch Resend email API documentation — no API key required.
* Resend exposes docs as Markdown via llms.txt endpoints.
*
* Tools:
* - get-index → lists all available Resend doc pages
* - get-page → fetches a specific doc page as Markdown
* - search-docs → searches across all Resend docs
*/
const BASE = "https://resend.com";
const SEARCH_STOP_WORDS = new Set([
"a",
"an",
"and",
"for",
"how",
"i",
"in",
"of",
"or",
"the",
"to",
"with",
]);
export const tools = [
{
name: "get-index",
description:
"Returns a full index of all Resend documentation pages. " +
"Use this to discover paths before calling get-page.",
parameters: {},
},
{
name: "get-page",
description:
"Fetches a specific Resend doc page as clean Markdown. " +
"Examples: '/docs/send-with-nodejs', '/docs/api-reference/emails/send-email', '/docs/dashboard/api-keys'.",
parameters: {
path: "string — doc path, e.g. '/docs/send-with-nodejs'",
},
},
{
name: "search-docs",
description:
"Searches all Resend documentation for a keyword or topic. " +
"Good for questions about sending emails, domains, API keys, React Email, webhooks.",
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: "/docs/send-with-nodejs" });
* const { result } = await invoke("search-docs", { query: "react email templates" });
*/
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 resend-docs tool: "${toolName}"`);
}
}
/**
* Normalize a Resend doc path:
* - Strips absolute URL prefix (https://resend.com)
* - Removes .md / index.md suffixes
* - Ensures leading /
* - Strips query params and hash
*/
export function normalizeResendDocPath(path) {
if (!path) return "";
let normalized = path;
if (normalized.startsWith("http://") || normalized.startsWith("https://")) {
try {
const url = new URL(normalized);
normalized = url.pathname;
} catch {
normalized = normalized.replace(/^https?:\/\/[^/]+/, "");
}
}
normalized = normalized.split(/[?#]/)[0];
normalized = normalized.replace(/\/index\.md$/i, "");
normalized = normalized.replace(/\.md$/i, "");
if (!normalized.startsWith("/")) {
normalized = `/${normalized}`;
}
if (normalized.length > 1 && normalized.endsWith("/")) {
normalized = normalized.slice(0, -1);
}
return normalized;
}
// ─── Internal handlers ────────────────────────────────────────────────────────
async function getIndex() {
let res;
try {
res = await fetch(`${BASE}/llms.txt`);
} catch (err) {
throw new Error(`Network error fetching Resend index: ${err.message}`);
}
if (!res.ok) {
throw new Error(
res.status === 404
? "Resend docs index not found (404). The site may have changed its structure."
: `Failed to fetch Resend 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 = normalizeResendDocPath(path);
for (const candidateUrl of getPageCandidates(cleanPath)) {
let res;
try {
res = await fetch(candidateUrl, {
headers: { Accept: "text/markdown" },
});
} catch {
continue;
}
if (!res.ok) continue;
const text = await res.text();
if (isHtmlResponse(res.headers.get("content-type"), text)) continue;
return { path: cleanPath, markdown: text };
}
throw new Error(`Resend page not found: ${path}. Check the path or use get-index to discover available pages.`);
}
async function searchDocs({ query, maxChars = 8000 }) {
if (!query) throw new Error("search-docs requires `query`");
// Resend does NOT have llms-full.txt (it 404s) — use llms.txt instead
let res;
try {
res = await fetch(`${BASE}/llms.txt`);
} catch (err) {
throw new Error(`Network error loading Resend docs: ${err.message}`);
}
if (!res.ok) {
throw new Error(
res.status === 404
? "Resend docs not found (404). The site may have changed its structure."
: `Could not load Resend docs: ${res.status}`,
);
}
const fullText = await res.text();
const lowerQuery = query.toLowerCase();
const queryTerms = toQueryTerms(query);
const sections = splitSections(fullText);
const scored = [];
for (const chunk of sections) {
const score = scoreChunk(chunk, lowerQuery, queryTerms);
if (score > 0) scored.push({ score, chunk });
}
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;
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;
seen.add(normalized);
result += separator + snippet;
if (snippet.length < normalized.length) break;
}
return {
query,
found: seen.size,
result: result || "No relevant sections found.",
};
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function getPageCandidates(cleanPath) {
const candidates = [
`${BASE}${cleanPath}.md`,
`${BASE}${cleanPath}/index.md`,
`${BASE}${cleanPath}`,
];
return [...new Set(candidates)];
}
function splitSections(text) {
const lines = text.split("\n");
const sections = [];
let buffer = [];
for (const line of lines) {
const isBoundary = line.startsWith("#") || /^---+\s*$/.test(line);
if (isBoundary && buffer.length > 0) {
const chunk = buffer.join("\n").trim();
if (chunk) sections.push(chunk);
buffer = /^---+\s*$/.test(line) ? [] : [line];
continue;
}
buffer.push(line);
}
if (buffer.length > 0) {
const chunk = buffer.join("\n").trim();
if (chunk) sections.push(chunk);
}
return sections;
}
function scoreChunk(chunk, lowerQuery, queryTerms) {
const lowerChunk = chunk.toLowerCase();
// Exact full-query match bonus
let score = lowerChunk.includes(lowerQuery) ? 10 : 0;
// Heading boost: if the chunk starts with #, terms in the heading are worth more
const headingLine = chunk.startsWith("#") ? chunk.split("\n")[0].toLowerCase() : "";
let distinctMatches = 0;
for (const term of queryTerms) {
const matches = lowerChunk.match(new RegExp(escapeRegExp(term), "g")) || [];
if (matches.length > 0) {
distinctMatches += 1;
score += matches.length * 2;
}
// Heading boost
if (headingLine && headingLine.includes(term)) {
score += 3;
}
}
// Multi-term bonus: reward sections matching multiple distinct terms
if (queryTerms.length > 1 && distinctMatches > 1) {
score += distinctMatches * 3;
}
return score;
}
function toQueryTerms(query) {
const terms = query
.toLowerCase()
.split(/[^a-z0-9]+/)
.map((term) => normalizeTerm(term))
.filter((term) => term && !SEARCH_STOP_WORDS.has(term));
return [...new Set(terms)];
}
function normalizeTerm(term) {
if (!term) return "";
if (term.endsWith("ies") && term.length > 4) return `${term.slice(0, -3)}y`;
if (term.endsWith("s") && term.length > 3 && !term.endsWith("ss")) return term.slice(0, -1);
return term;
}
function isHtmlResponse(contentType, text) {
const normalizedType = contentType || "";
return normalizedType.includes("text/html") || text.trimStart().startsWith("<!DOCTYPE html") || text.includes("<html");
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}