searchfetch 3.3.4 → 4.1.0
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 +147 -120
- package/package.json +32 -28
- package/src/browser.js +213 -0
- package/src/compose.js +126 -0
- package/src/extract.js +233 -0
- package/src/index.js +45 -0
- package/src/markdown.js +50 -0
- package/src/server.js +174 -0
- package/src/templates.js +273 -0
- package/templates/crates-package.json +1 -1
- package/templates/devto.json +1 -1
- package/templates/docker-hub.json +1 -1
- package/templates/docs-page.json +1 -1
- package/templates/docs-rs.json +1 -1
- package/templates/duckduckgo-lite-search.json +49 -0
- package/templates/duckduckgo-search.json +3 -1
- package/templates/github-issue.json +1 -1
- package/templates/github-repo.json +1 -1
- package/templates/gitlab.json +1 -1
- package/templates/go-pkg.json +1 -1
- package/templates/google-search.json +3 -1
- package/templates/javadoc.json +1 -1
- package/templates/mdn-web-docs.json +1 -1
- package/templates/npm-package.json +1 -1
- package/templates/pypi-package.json +1 -1
- package/templates/raw.json +1 -1
- package/templates/reddit.json +1 -1
- package/templates/wikipedia.json +1 -1
- package/templates/youtube.json +1 -1
- package/index.js +0 -1276
- package/lib/output.js +0 -9
- package/lib/selectors.js +0 -27
- package/templates/__init__.py +0 -1
package/index.js
DELETED
|
@@ -1,1276 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// === IMPORTS =============================================================
|
|
4
|
-
import { readdirSync, readFileSync, realpathSync } from "node:fs";
|
|
5
|
-
import { dirname, join } from "node:path";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
8
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
|
-
import { z } from "zod";
|
|
10
|
-
import { launch, ensureBinary } from "cloakbrowser";
|
|
11
|
-
import * as cheerio from "cheerio";
|
|
12
|
-
import TurndownService from "turndown";
|
|
13
|
-
import { splitSelectors } from "./lib/selectors.js";
|
|
14
|
-
import { paginate } from "./lib/output.js";
|
|
15
|
-
|
|
16
|
-
// === BROWSER MANAGER =====================================================
|
|
17
|
-
class BrowserManager {
|
|
18
|
-
constructor() {
|
|
19
|
-
this.browser = null;
|
|
20
|
-
this.launchPromise = null;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async getBrowser() {
|
|
24
|
-
if (this.browser && this.browser.isConnected()) return this.browser;
|
|
25
|
-
if (this.launchPromise) return this.launchPromise;
|
|
26
|
-
|
|
27
|
-
this.launchPromise = launch({
|
|
28
|
-
headless: true,
|
|
29
|
-
humanize: true,
|
|
30
|
-
args: [
|
|
31
|
-
"--disable-blink-features=AutomationControlled",
|
|
32
|
-
"--no-sandbox",
|
|
33
|
-
"--disable-dev-shm-usage",
|
|
34
|
-
],
|
|
35
|
-
})
|
|
36
|
-
.then((browser) => {
|
|
37
|
-
this.browser = browser;
|
|
38
|
-
this.browser.on("disconnected", () => {
|
|
39
|
-
if (this.browser === browser) this.browser = null;
|
|
40
|
-
});
|
|
41
|
-
return browser;
|
|
42
|
-
})
|
|
43
|
-
.finally(() => {
|
|
44
|
-
this.launchPromise = null;
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
return this.launchPromise;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async close() {
|
|
51
|
-
const browser = await (this.launchPromise ?? this.browser);
|
|
52
|
-
this.browser = null;
|
|
53
|
-
if (browser) await browser.close();
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const browserManager = new BrowserManager();
|
|
58
|
-
|
|
59
|
-
const cleanup = async () => {
|
|
60
|
-
await browserManager.close();
|
|
61
|
-
process.exit(0);
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
// === TURNDOWN ============================================================
|
|
65
|
-
const turndown = new TurndownService({
|
|
66
|
-
headingStyle: "atx",
|
|
67
|
-
codeBlockStyle: "fenced",
|
|
68
|
-
emDelimiter: "*",
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
// === BUILT-IN TEMPLATES (loaded from templates/*.json) ====================
|
|
72
|
-
|
|
73
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
74
|
-
const __dirname = dirname(__filename);
|
|
75
|
-
const TEMPLATES_DIR = join(__dirname, "templates");
|
|
76
|
-
|
|
77
|
-
function loadBuiltinTemplates() {
|
|
78
|
-
let files;
|
|
79
|
-
try {
|
|
80
|
-
files = readdirSync(TEMPLATES_DIR);
|
|
81
|
-
} catch (err) {
|
|
82
|
-
throw new Error(`Cannot read templates directory '${TEMPLATES_DIR}': ${err.message}`);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const jsonFiles = files.filter((f) => f.endsWith(".json")).sort();
|
|
86
|
-
|
|
87
|
-
if (jsonFiles.length === 0) {
|
|
88
|
-
throw new Error(`No template JSON files found in '${TEMPLATES_DIR}'`);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const templates = [];
|
|
92
|
-
for (const file of jsonFiles) {
|
|
93
|
-
const filePath = join(TEMPLATES_DIR, file);
|
|
94
|
-
const content = readFileSync(filePath, "utf-8");
|
|
95
|
-
let template;
|
|
96
|
-
try {
|
|
97
|
-
template = JSON.parse(content);
|
|
98
|
-
} catch (err) {
|
|
99
|
-
throw new Error(`Invalid JSON in template file '${filePath}': ${err.message}`);
|
|
100
|
-
}
|
|
101
|
-
if (!template.name || typeof template.name !== "string") {
|
|
102
|
-
throw new Error(`Template file '${filePath}' is missing a valid "name" field`);
|
|
103
|
-
}
|
|
104
|
-
templates.push(template);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// Sort by "order" field for deterministic URL-pattern matching
|
|
108
|
-
templates.sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
|
|
109
|
-
|
|
110
|
-
return templates;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const BUILTIN_TEMPLATES = loadBuiltinTemplates();
|
|
114
|
-
|
|
115
|
-
function parseInlineTemplate(value) {
|
|
116
|
-
const template = JSON.parse(value);
|
|
117
|
-
if (
|
|
118
|
-
!template ||
|
|
119
|
-
typeof template !== "object" ||
|
|
120
|
-
Array.isArray(template) ||
|
|
121
|
-
!Array.isArray(template.sections)
|
|
122
|
-
) {
|
|
123
|
-
throw new Error("Inline template must be an object with a sections array.");
|
|
124
|
-
}
|
|
125
|
-
template.name ??= "custom";
|
|
126
|
-
for (const section of template.sections) {
|
|
127
|
-
if (!section || typeof section.name !== "string")
|
|
128
|
-
throw new Error("Every section must have a name.");
|
|
129
|
-
}
|
|
130
|
-
return template;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// === TEMPLATE LOOKUP =====================================================
|
|
134
|
-
const TEMPLATE_MAP = new Map();
|
|
135
|
-
for (const t of BUILTIN_TEMPLATES) {
|
|
136
|
-
TEMPLATE_MAP.set(t.name, t);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function getTemplateByName(name) {
|
|
140
|
-
const t = TEMPLATE_MAP.get(name);
|
|
141
|
-
if (!t) {
|
|
142
|
-
const names = [...TEMPLATE_MAP.keys()].join(", ");
|
|
143
|
-
throw new Error(`Unknown template '${name}'. Available: ${names}`);
|
|
144
|
-
}
|
|
145
|
-
return t;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function detectTemplateByUrl(url) {
|
|
149
|
-
for (const template of BUILTIN_TEMPLATES) {
|
|
150
|
-
if (!template.url_patterns) continue;
|
|
151
|
-
for (const pattern of template.url_patterns) {
|
|
152
|
-
try {
|
|
153
|
-
if (new RegExp(pattern).test(url)) {
|
|
154
|
-
return template;
|
|
155
|
-
}
|
|
156
|
-
} catch (_invalidRegex) {
|
|
157
|
-
// Invalid URL patterns are tolerated — templates may contain
|
|
158
|
-
// broad patterns that don't compile correctly in every context.
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return null;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// === URL TEMPLATE RESOLUTION =============================================
|
|
166
|
-
|
|
167
|
-
function validateUrl(value) {
|
|
168
|
-
const url = new URL(value);
|
|
169
|
-
if (!["http:", "https:"].includes(url.protocol) || !url.hostname)
|
|
170
|
-
throw new Error("URL must use HTTP or HTTPS and include a hostname");
|
|
171
|
-
return value;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function resolveUrlTemplate(template, providedParams) {
|
|
175
|
-
if (!template.url_template) throw new Error(`Template '${template.name}' has no url_template.`);
|
|
176
|
-
return template.url_template.replace(/\{(\w+)\}/g, (_, name) => {
|
|
177
|
-
const def = template.url_params?.[name] ?? {};
|
|
178
|
-
let value = Object.hasOwn(providedParams, name) ? providedParams[name] : undefined;
|
|
179
|
-
value ??= def.default;
|
|
180
|
-
if (value == null && def.required) {
|
|
181
|
-
throw new Error(
|
|
182
|
-
`Required URL parameter '${name}' not provided for template '${template.name}'.`,
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
value = String(value ?? "");
|
|
186
|
-
return def.encode === "url" ? encodeURIComponent(value) : value;
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// === SEARCH PARAM MAPPING ================================================
|
|
191
|
-
|
|
192
|
-
function resolveEngineToTemplateName(engine) {
|
|
193
|
-
if (engine === "duckduckgo") return "duckduckgo-search";
|
|
194
|
-
if (engine === "google") return "google-search";
|
|
195
|
-
return engine;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function mapSearchParams(engine, query, region, safeSearch) {
|
|
199
|
-
const params = { query };
|
|
200
|
-
const resolved = resolveEngineToTemplateName(engine);
|
|
201
|
-
|
|
202
|
-
if (resolved === "duckduckgo-search") {
|
|
203
|
-
if (region !== null && region !== undefined) {
|
|
204
|
-
params.kl = region;
|
|
205
|
-
}
|
|
206
|
-
if (safeSearch === true) {
|
|
207
|
-
params.kp = "1";
|
|
208
|
-
} else if (safeSearch === false) {
|
|
209
|
-
params.kp = "-2";
|
|
210
|
-
}
|
|
211
|
-
} else if (resolved === "google-search") {
|
|
212
|
-
if (region !== null && region !== undefined) {
|
|
213
|
-
const parts = region.split("-");
|
|
214
|
-
params.gl = parts[0];
|
|
215
|
-
if (parts.length > 1) params.hl = parts[1];
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
return params;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// === FETCH ===============================================================
|
|
223
|
-
|
|
224
|
-
const FETCH_MAX_ATTEMPTS = 2;
|
|
225
|
-
const HTTP_429_RETRY_DELAY_MS = 2000;
|
|
226
|
-
|
|
227
|
-
function sleep(ms) {
|
|
228
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function parseRetryAfterMs(value) {
|
|
232
|
-
if (!value) return HTTP_429_RETRY_DELAY_MS;
|
|
233
|
-
const seconds = Number(value);
|
|
234
|
-
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
235
|
-
return Math.min(seconds * 1000, 30000);
|
|
236
|
-
}
|
|
237
|
-
const dateMs = Date.parse(value);
|
|
238
|
-
if (Number.isFinite(dateMs)) {
|
|
239
|
-
return Math.min(Math.max(dateMs - Date.now(), 0), 30000);
|
|
240
|
-
}
|
|
241
|
-
return HTTP_429_RETRY_DELAY_MS;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function makeHttpStatusError(status, url, retryAfterMs = null) {
|
|
245
|
-
const err = new Error(`HTTP ${status} when fetching ${url}`);
|
|
246
|
-
err.httpStatus = status;
|
|
247
|
-
err.retryAfterMs = retryAfterMs;
|
|
248
|
-
return err;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
function isAccessDenied($) {
|
|
252
|
-
const title = ($("title").text() || "").toLowerCase();
|
|
253
|
-
const bodyText = ($("body").text() || "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
254
|
-
|
|
255
|
-
const titleDenyPatterns = [
|
|
256
|
-
"are you a robot",
|
|
257
|
-
"access denied",
|
|
258
|
-
"forbidden",
|
|
259
|
-
"unusual traffic",
|
|
260
|
-
"sorry, you have been blocked",
|
|
261
|
-
"verify you are human",
|
|
262
|
-
"one more step",
|
|
263
|
-
"security check",
|
|
264
|
-
"ddos protection",
|
|
265
|
-
];
|
|
266
|
-
|
|
267
|
-
if (titleDenyPatterns.some((pattern) => title.includes(pattern))) return true;
|
|
268
|
-
|
|
269
|
-
const strongBodyDenyPatterns = [
|
|
270
|
-
"to continue, please type the characters",
|
|
271
|
-
"our systems have detected unusual traffic",
|
|
272
|
-
"sorry, you have been blocked",
|
|
273
|
-
"bots use duckduckgo too",
|
|
274
|
-
];
|
|
275
|
-
|
|
276
|
-
if (strongBodyDenyPatterns.some((pattern) => bodyText.includes(pattern))) return true;
|
|
277
|
-
|
|
278
|
-
const shortBodyDenyPatterns = ["verify you are human", "are you a robot", "access denied"];
|
|
279
|
-
|
|
280
|
-
if (bodyText.length < 1200 && shortBodyDenyPatterns.some((pattern) => bodyText.includes(pattern)))
|
|
281
|
-
return true;
|
|
282
|
-
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
async function fetchHtml(url, template, blockMedia) {
|
|
287
|
-
validateUrl(url);
|
|
288
|
-
const browser = await browserManager.getBrowser();
|
|
289
|
-
const context = await browser.newContext();
|
|
290
|
-
|
|
291
|
-
try {
|
|
292
|
-
// Pre-load cookies from template
|
|
293
|
-
if (template && template.cookies && template.cookies.length > 0) {
|
|
294
|
-
await context.addCookies(template.cookies);
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
const page = await context.newPage();
|
|
298
|
-
|
|
299
|
-
try {
|
|
300
|
-
// Route blocked resource types
|
|
301
|
-
if (blockMedia) {
|
|
302
|
-
const blockedTypes =
|
|
303
|
-
template && template.block_resources
|
|
304
|
-
? template.block_resources
|
|
305
|
-
: ["image", "media", "font"];
|
|
306
|
-
|
|
307
|
-
if (blockedTypes.length > 0) {
|
|
308
|
-
await page.route("**/*", (route) => {
|
|
309
|
-
const type = route.request().resourceType();
|
|
310
|
-
if (blockedTypes.includes(type)) {
|
|
311
|
-
return route.abort();
|
|
312
|
-
} else {
|
|
313
|
-
return route.continue();
|
|
314
|
-
}
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15000 });
|
|
320
|
-
if (response && response.status() >= 400) {
|
|
321
|
-
const status = response.status();
|
|
322
|
-
throw makeHttpStatusError(
|
|
323
|
-
status,
|
|
324
|
-
url,
|
|
325
|
-
status === 429 ? parseRetryAfterMs(response.headers()["retry-after"]) : null,
|
|
326
|
-
);
|
|
327
|
-
}
|
|
328
|
-
try {
|
|
329
|
-
await page.waitForLoadState("networkidle", { timeout: 5000 });
|
|
330
|
-
} catch (err) {
|
|
331
|
-
if (err.name !== "TimeoutError") throw err;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
const pageContent = await page.content();
|
|
335
|
-
|
|
336
|
-
// Check for CAPTCHA / access-denied pages
|
|
337
|
-
const $ = cheerio.load(pageContent);
|
|
338
|
-
if (isAccessDenied($)) {
|
|
339
|
-
throw new Error(
|
|
340
|
-
`Access denied: CAPTCHA or block page detected at ${url}. The site is blocking automated access.`,
|
|
341
|
-
);
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
return pageContent;
|
|
345
|
-
} finally {
|
|
346
|
-
await page.close();
|
|
347
|
-
}
|
|
348
|
-
} finally {
|
|
349
|
-
await context.close();
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
async function fetchHtmlWithRetry(url, template, blockMedia) {
|
|
354
|
-
let lastError;
|
|
355
|
-
for (let attempt = 0; attempt < FETCH_MAX_ATTEMPTS; attempt++) {
|
|
356
|
-
try {
|
|
357
|
-
return await fetchHtml(url, template, blockMedia);
|
|
358
|
-
} catch (err) {
|
|
359
|
-
lastError = err;
|
|
360
|
-
if (attempt < FETCH_MAX_ATTEMPTS - 1 && err.httpStatus === 429) {
|
|
361
|
-
await sleep(err.retryAfterMs ?? HTTP_429_RETRY_DELAY_MS);
|
|
362
|
-
continue;
|
|
363
|
-
}
|
|
364
|
-
if (
|
|
365
|
-
attempt < FETCH_MAX_ATTEMPTS - 1 &&
|
|
366
|
-
(err.name === "TimeoutError" ||
|
|
367
|
-
err.message.includes("browser has been closed") ||
|
|
368
|
-
err.message.includes("Target closed") ||
|
|
369
|
-
err.message.includes("net::") ||
|
|
370
|
-
err.message.includes("ERR_") ||
|
|
371
|
-
err.message.includes("Navigation failed") ||
|
|
372
|
-
err.message.includes("navigating"))
|
|
373
|
-
) {
|
|
374
|
-
await sleep(500);
|
|
375
|
-
continue;
|
|
376
|
-
}
|
|
377
|
-
throw err;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
throw lastError;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
// === SOURCE MARKDOWN DETECTION ===========================================
|
|
384
|
-
|
|
385
|
-
function isMarkdownContent(text) {
|
|
386
|
-
if (!text) return false;
|
|
387
|
-
const htmlTagCount = (text.match(/<\w+[^>]*>/g) || []).length;
|
|
388
|
-
if (htmlTagCount > 3) return false;
|
|
389
|
-
const patterns = [
|
|
390
|
-
/^#{1,6}\s+\S/m,
|
|
391
|
-
/\[.+?\]\(.+?\)/,
|
|
392
|
-
/```\w*\n/,
|
|
393
|
-
/^\s*[-*+]\s+\S/m,
|
|
394
|
-
/\*\*[^*]+\*\*/,
|
|
395
|
-
/^>\s+\S/m,
|
|
396
|
-
];
|
|
397
|
-
for (const pat of patterns) {
|
|
398
|
-
if (pat.test(text)) return true;
|
|
399
|
-
}
|
|
400
|
-
return false;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
function stripSourceMarkdown(content) {
|
|
404
|
-
return content
|
|
405
|
-
.replace(/^@twoslash-cache:.*$/gm, "")
|
|
406
|
-
.replace(/\n{3,}/g, "\n\n")
|
|
407
|
-
.trim();
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
function resolveSourceUrl(sourceTemplate, url) {
|
|
411
|
-
if (sourceTemplate === "{url}.md") {
|
|
412
|
-
const parsed = new URL(url);
|
|
413
|
-
parsed.pathname = `${parsed.pathname.replace(/\/+$/, "")}.md`;
|
|
414
|
-
parsed.hash = "";
|
|
415
|
-
return parsed.href;
|
|
416
|
-
}
|
|
417
|
-
return sourceTemplate.replace("{url}", url);
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
async function fetchSourceMarkdown(sourceUrl, template, blockMedia) {
|
|
421
|
-
validateUrl(sourceUrl);
|
|
422
|
-
const browser = await browserManager.getBrowser();
|
|
423
|
-
const context = await browser.newContext();
|
|
424
|
-
|
|
425
|
-
try {
|
|
426
|
-
if (template && template.cookies && template.cookies.length > 0) {
|
|
427
|
-
await context.addCookies(template.cookies);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
const page = await context.newPage();
|
|
431
|
-
try {
|
|
432
|
-
if (blockMedia) {
|
|
433
|
-
const blockedTypes =
|
|
434
|
-
template && template.block_resources
|
|
435
|
-
? template.block_resources
|
|
436
|
-
: ["image", "media", "font"];
|
|
437
|
-
if (blockedTypes.length > 0) {
|
|
438
|
-
await page.route("**/*", (route) => {
|
|
439
|
-
const type = route.request().resourceType();
|
|
440
|
-
if (blockedTypes.includes(type)) return route.abort();
|
|
441
|
-
else return route.continue();
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
let response;
|
|
447
|
-
try {
|
|
448
|
-
response = await page.goto(sourceUrl, {
|
|
449
|
-
waitUntil: "domcontentloaded",
|
|
450
|
-
timeout: 10000,
|
|
451
|
-
});
|
|
452
|
-
} catch (_) {
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
if (!response || response.status() >= 400) return null;
|
|
457
|
-
const contentType = (response.headers()["content-type"] ?? "").toLowerCase();
|
|
458
|
-
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml"))
|
|
459
|
-
return null;
|
|
460
|
-
let text = await response.text();
|
|
461
|
-
|
|
462
|
-
if (!text || typeof text !== "string") return null;
|
|
463
|
-
|
|
464
|
-
text = stripSourceMarkdown(text.trim());
|
|
465
|
-
return isMarkdownContent(text) ? text : null;
|
|
466
|
-
} finally {
|
|
467
|
-
await page.close();
|
|
468
|
-
}
|
|
469
|
-
} catch (_) {
|
|
470
|
-
return null;
|
|
471
|
-
} finally {
|
|
472
|
-
await context.close();
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// === HTML CLEANUP ========================================================
|
|
477
|
-
|
|
478
|
-
const DEFAULT_REMOVE_SELECTORS = [
|
|
479
|
-
"script",
|
|
480
|
-
"style",
|
|
481
|
-
"svg",
|
|
482
|
-
"nav",
|
|
483
|
-
"footer",
|
|
484
|
-
"noscript",
|
|
485
|
-
"iframe",
|
|
486
|
-
".advertisement",
|
|
487
|
-
];
|
|
488
|
-
|
|
489
|
-
function applyRemove($, template) {
|
|
490
|
-
const removeSelectors = template?.remove ?? DEFAULT_REMOVE_SELECTORS;
|
|
491
|
-
|
|
492
|
-
for (const selector of removeSelectors) {
|
|
493
|
-
try {
|
|
494
|
-
$(selector).remove();
|
|
495
|
-
} catch (_invalidSelector) {
|
|
496
|
-
// Invalid remove selectors are tolerated — templates can express
|
|
497
|
-
// broad cleanup rules that don't apply to every page.
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
// Strip style attributes and data:image src
|
|
502
|
-
$("[style]").removeAttr("style");
|
|
503
|
-
$("*").each((_i, el) => {
|
|
504
|
-
const src = $(el).attr("src");
|
|
505
|
-
if (src && src.startsWith("data:image")) {
|
|
506
|
-
$(el).removeAttr("src");
|
|
507
|
-
}
|
|
508
|
-
});
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// === EXTRACTION ENGINE ===================================================
|
|
512
|
-
|
|
513
|
-
/** Search descendants and the enclosing element, never neighboring result subtrees. */
|
|
514
|
-
function findScoped($parent, selector) {
|
|
515
|
-
if (!selector?.trim()) return $parent;
|
|
516
|
-
const descendants = $parent.find(selector);
|
|
517
|
-
return descendants.length ? descendants : $parent.closest(selector);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
function findFirstMatch($parent, selectorStr) {
|
|
521
|
-
for (const selector of splitSelectors(selectorStr)) {
|
|
522
|
-
const matches = findScoped($parent, selector);
|
|
523
|
-
if (matches.length) return matches;
|
|
524
|
-
}
|
|
525
|
-
return $parent.slice(0, 0);
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
function resolveTopElements($, selectorStr) {
|
|
529
|
-
for (const selector of splitSelectors(selectorStr)) {
|
|
530
|
-
const matches = selector ? $(selector) : $("body");
|
|
531
|
-
if (matches.length) return matches;
|
|
532
|
-
}
|
|
533
|
-
return $();
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
// === TRANSFORMS ==========================================================
|
|
537
|
-
|
|
538
|
-
function applyTransform(value, transform, origin) {
|
|
539
|
-
const transforms = Array.isArray(transform) ? transform : [transform];
|
|
540
|
-
let result = value;
|
|
541
|
-
|
|
542
|
-
for (const t of transforms) {
|
|
543
|
-
if (!result) continue;
|
|
544
|
-
switch (t) {
|
|
545
|
-
case "strip":
|
|
546
|
-
result = result.trim();
|
|
547
|
-
break;
|
|
548
|
-
|
|
549
|
-
case "decode_google_url":
|
|
550
|
-
if (result.startsWith("/url?q=")) {
|
|
551
|
-
try {
|
|
552
|
-
const urlPart = result.split("/url?q=")[1].split("&")[0];
|
|
553
|
-
result = decodeURIComponent(urlPart);
|
|
554
|
-
} catch (_) {
|
|
555
|
-
// Leave as-is
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
break;
|
|
559
|
-
|
|
560
|
-
case "decode_ddg_url":
|
|
561
|
-
if (result.includes("/l/?uddg=")) {
|
|
562
|
-
try {
|
|
563
|
-
const queryString = result.split("?")[1] || "";
|
|
564
|
-
const params = new URLSearchParams(queryString);
|
|
565
|
-
const uddg = params.get("uddg");
|
|
566
|
-
if (uddg) result = uddg;
|
|
567
|
-
} catch (_) {
|
|
568
|
-
// Leave as-is
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
break;
|
|
572
|
-
|
|
573
|
-
case "json_parse":
|
|
574
|
-
try {
|
|
575
|
-
result = JSON.stringify(JSON.parse(result), null, 2);
|
|
576
|
-
} catch (_) {
|
|
577
|
-
// Leave as-is
|
|
578
|
-
}
|
|
579
|
-
break;
|
|
580
|
-
|
|
581
|
-
case "resolve_href":
|
|
582
|
-
if (origin) {
|
|
583
|
-
try {
|
|
584
|
-
result = new URL(result, origin).href;
|
|
585
|
-
} catch (_) {
|
|
586
|
-
// Leave as-is
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
break;
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
return result;
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// === EXTRACTION ==========================================================
|
|
597
|
-
|
|
598
|
-
function extractValue($el, section, origin) {
|
|
599
|
-
let value;
|
|
600
|
-
|
|
601
|
-
switch (section.format) {
|
|
602
|
-
case "text":
|
|
603
|
-
value = $el.text().replace(/\s+/g, " ").trim();
|
|
604
|
-
break;
|
|
605
|
-
|
|
606
|
-
case "markdown": {
|
|
607
|
-
const html = $el.html() || "";
|
|
608
|
-
value = turndown
|
|
609
|
-
.turndown(html)
|
|
610
|
-
.replace(/\n{3,}/g, "\n\n")
|
|
611
|
-
.trim();
|
|
612
|
-
break;
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
case "attribute":
|
|
616
|
-
value = $el.attr(section.attribute) || "";
|
|
617
|
-
break;
|
|
618
|
-
|
|
619
|
-
case "html":
|
|
620
|
-
value = $el.html() || "";
|
|
621
|
-
break;
|
|
622
|
-
|
|
623
|
-
default:
|
|
624
|
-
value = $el.text().replace(/\s+/g, " ").trim();
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
if (section.transform && value) {
|
|
628
|
-
value = applyTransform(value, section.transform, origin);
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
return value;
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* Extract one child section, scoped to $parentEl.
|
|
636
|
-
* Returns { type: "value", text } or null.
|
|
637
|
-
*/
|
|
638
|
-
function extractChildSection($, $parentEl, section, origin) {
|
|
639
|
-
const elements = findFirstMatch($parentEl, section.selector);
|
|
640
|
-
|
|
641
|
-
if (!elements || elements.length === 0) {
|
|
642
|
-
if (section.required) {
|
|
643
|
-
throw new Error(`Required section '${section.name}' not found on page.`);
|
|
644
|
-
}
|
|
645
|
-
return null;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
const el = elements.eq(0);
|
|
649
|
-
const value = extractValue(el, section, origin);
|
|
650
|
-
return { type: "value", text: value };
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
/**
|
|
654
|
-
* Extract a top-level section from the document.
|
|
655
|
-
* Returns a SectionResult or null.
|
|
656
|
-
*/
|
|
657
|
-
function extractSection($, section, context) {
|
|
658
|
-
const elements = resolveTopElements($, section.selector);
|
|
659
|
-
|
|
660
|
-
if (!elements || elements.length === 0) {
|
|
661
|
-
if (section.required) {
|
|
662
|
-
throw new Error(`Required section '${section.name}' not found on page.`);
|
|
663
|
-
}
|
|
664
|
-
return null;
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
// Determine limit
|
|
668
|
-
let limit = elements.length;
|
|
669
|
-
if (section.multiple && section.max_items != null) {
|
|
670
|
-
limit = Math.min(limit, section.max_items);
|
|
671
|
-
}
|
|
672
|
-
// Override max_items with max_results for first multiple+children section
|
|
673
|
-
if (
|
|
674
|
-
context.isWebsearch &&
|
|
675
|
-
context.maxResultsOverride != null &&
|
|
676
|
-
!context._maxResultsConsumed &&
|
|
677
|
-
section.multiple &&
|
|
678
|
-
section.children &&
|
|
679
|
-
section.children.length > 0
|
|
680
|
-
) {
|
|
681
|
-
limit = Math.min(elements.length, context.maxResultsOverride);
|
|
682
|
-
context._maxResultsConsumed = true;
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
if (section.multiple) {
|
|
686
|
-
const items = [];
|
|
687
|
-
|
|
688
|
-
for (let i = 0; i < limit; i++) {
|
|
689
|
-
const el = elements.eq(i);
|
|
690
|
-
|
|
691
|
-
if (section.children && section.children.length > 0) {
|
|
692
|
-
// Multiple parents, each with children
|
|
693
|
-
const childValues = {};
|
|
694
|
-
for (const child of section.children) {
|
|
695
|
-
const cr = extractChildSection($, el, child, context.origin);
|
|
696
|
-
if (cr && cr.type === "value" && cr.text !== null && cr.text !== undefined) {
|
|
697
|
-
childValues[child.name] = cr.text;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
if (Object.keys(childValues).length > 0) {
|
|
701
|
-
items.push(childValues);
|
|
702
|
-
}
|
|
703
|
-
} else {
|
|
704
|
-
// Multiple parents, no children
|
|
705
|
-
const value = extractValue(el, section, context.origin);
|
|
706
|
-
if (value && value.trim()) {
|
|
707
|
-
items.push(value.trim());
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
if (section.children && section.children.length > 0) {
|
|
713
|
-
return { section, type: "children-multiple", items };
|
|
714
|
-
} else {
|
|
715
|
-
return { section, type: "list", items };
|
|
716
|
-
}
|
|
717
|
-
} else {
|
|
718
|
-
// Single parent
|
|
719
|
-
const el = elements.eq(0);
|
|
720
|
-
|
|
721
|
-
if (section.children && section.children.length > 0) {
|
|
722
|
-
// Single parent with children — parent format ignored
|
|
723
|
-
const childValues = {};
|
|
724
|
-
for (const child of section.children) {
|
|
725
|
-
const cr = extractChildSection($, el, child, context.origin);
|
|
726
|
-
if (cr && cr.type === "value" && cr.text !== null && cr.text !== undefined) {
|
|
727
|
-
childValues[child.name] = cr.text;
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return { section, type: "children", items: childValues };
|
|
731
|
-
} else {
|
|
732
|
-
const value = extractValue(el, section, context.origin);
|
|
733
|
-
return { section, type: "value", text: value };
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
function extractTemplate($, template, context) {
|
|
739
|
-
const results = [];
|
|
740
|
-
|
|
741
|
-
for (const section of template.sections) {
|
|
742
|
-
const result = extractSection($, section, context);
|
|
743
|
-
if (result !== null) results.push(result);
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
return results;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// === COMPOSITION: WEBFETCH ===============================================
|
|
750
|
-
|
|
751
|
-
function isCommentStyle(items) {
|
|
752
|
-
if (!items || items.length === 0) return false;
|
|
753
|
-
// Ignore empty fields so Python's empty-string placeholders decide identically.
|
|
754
|
-
const keys = Object.entries(items[0])
|
|
755
|
-
.filter(([, value]) => String(value ?? "").trim())
|
|
756
|
-
.map(([key]) => key.toLowerCase());
|
|
757
|
-
return (
|
|
758
|
-
(keys.includes("author") || keys.includes("user")) &&
|
|
759
|
-
(keys.includes("comment") || keys.includes("body"))
|
|
760
|
-
);
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
function composeSections(extracted, template, startIndex, maxLength) {
|
|
764
|
-
const parts = [];
|
|
765
|
-
|
|
766
|
-
for (const result of extracted) {
|
|
767
|
-
if (result.type === "value") {
|
|
768
|
-
const text = result.text;
|
|
769
|
-
if (text && String(text).trim()) {
|
|
770
|
-
parts.push(`## ${result.section.name}\n\n${String(text).trim()}`);
|
|
771
|
-
}
|
|
772
|
-
} else if (result.type === "list") {
|
|
773
|
-
if (result.items && result.items.length > 0) {
|
|
774
|
-
const listText = result.items.map((item) => `- ${String(item).trim()}`).join("\n");
|
|
775
|
-
parts.push(`## ${result.section.name}\n\n${listText}`);
|
|
776
|
-
}
|
|
777
|
-
} else if (result.type === "children") {
|
|
778
|
-
if (result.items && Object.keys(result.items).length > 0) {
|
|
779
|
-
for (const [childName, value] of Object.entries(result.items)) {
|
|
780
|
-
if (value && String(value).trim()) {
|
|
781
|
-
parts.push(`## ${childName}\n\n${String(value).trim()}`);
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
} else if (result.type === "children-multiple") {
|
|
786
|
-
if (result.items && result.items.length > 0) {
|
|
787
|
-
if (isCommentStyle(result.items)) {
|
|
788
|
-
const commentParts = [];
|
|
789
|
-
for (const item of result.items) {
|
|
790
|
-
const author = String(
|
|
791
|
-
item["Author"] || item["author"] || item["User"] || item["user"] || "",
|
|
792
|
-
).trim();
|
|
793
|
-
const comment = String(
|
|
794
|
-
item["Comment"] || item["Body"] || item["comment"] || item["body"] || "",
|
|
795
|
-
).trim();
|
|
796
|
-
if (author) {
|
|
797
|
-
commentParts.push(`**${author}:**\n\n${comment}`);
|
|
798
|
-
} else if (comment) {
|
|
799
|
-
commentParts.push(comment);
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
if (commentParts.length > 0) {
|
|
803
|
-
parts.push(`## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`);
|
|
804
|
-
}
|
|
805
|
-
} else {
|
|
806
|
-
const itemParts = [];
|
|
807
|
-
for (const item of result.items) {
|
|
808
|
-
const lines = [];
|
|
809
|
-
for (const [key, value] of Object.entries(item)) {
|
|
810
|
-
if (value && String(value).trim()) {
|
|
811
|
-
lines.push(` ${key}: ${String(value).trim()}`);
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
if (lines.length > 0) itemParts.push(lines.join("\n"));
|
|
815
|
-
}
|
|
816
|
-
if (itemParts.length > 0) {
|
|
817
|
-
parts.push(`## ${result.section.name}\n\n${itemParts.join("\n\n")}`);
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
if (parts.length === 0) {
|
|
825
|
-
return "(No content extracted from this page.)";
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
return paginate(parts.join("\n\n---\n\n"), template?.name ?? "auto", startIndex, maxLength);
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
// === COMPOSITION: WEBSEARCH ==============================================
|
|
832
|
-
|
|
833
|
-
function composeSearchResults(extracted) {
|
|
834
|
-
// Find the search results section (first children-multiple)
|
|
835
|
-
const searchSection = extracted.find((r) => r.type === "children-multiple");
|
|
836
|
-
|
|
837
|
-
if (!searchSection || !searchSection.items || searchSection.items.length === 0) {
|
|
838
|
-
// Fall back to section-based output
|
|
839
|
-
return composeSections(extracted, null, 0, Infinity);
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
const items = searchSection.items;
|
|
843
|
-
const parts = [];
|
|
844
|
-
|
|
845
|
-
for (let i = 0; i < items.length; i++) {
|
|
846
|
-
const item = items[i];
|
|
847
|
-
const num = parts.length + 1;
|
|
848
|
-
|
|
849
|
-
const title = item["Title"] || item["title"] || Object.values(item)[0] || "";
|
|
850
|
-
const url = item["URL"] || item["url"] || item["Url"] || "";
|
|
851
|
-
const snippet = item["Snippet"] || item["snippet"] || "";
|
|
852
|
-
|
|
853
|
-
// Filter out non-http URLs and google internal links
|
|
854
|
-
let cleanUrl = url;
|
|
855
|
-
try {
|
|
856
|
-
const parsed = new URL(cleanUrl);
|
|
857
|
-
if (
|
|
858
|
-
!["http:", "https:"].includes(parsed.protocol) ||
|
|
859
|
-
parsed.hostname === "support.google.com" ||
|
|
860
|
-
(["google.com", "www.google.com"].includes(parsed.hostname) &&
|
|
861
|
-
parsed.pathname === "/search")
|
|
862
|
-
)
|
|
863
|
-
cleanUrl = "";
|
|
864
|
-
} catch {
|
|
865
|
-
cleanUrl = "";
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
if (!title) continue;
|
|
869
|
-
|
|
870
|
-
const lines = [`[${num}] ${title}`];
|
|
871
|
-
if (cleanUrl) lines.push(` URL: ${cleanUrl}`);
|
|
872
|
-
if (snippet) lines.push(` Snippet: ${snippet}`);
|
|
873
|
-
|
|
874
|
-
parts.push(lines.join("\n"));
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
if (parts.length === 0) {
|
|
878
|
-
return "(No content extracted from this page.)";
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
return `## ${searchSection.section.name}\n\n${parts.join("\n\n")}`;
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
// === GENERIC FALLBACK ====================================================
|
|
885
|
-
|
|
886
|
-
function genericFallback($, startIndex, maxLength) {
|
|
887
|
-
applyRemove($, null);
|
|
888
|
-
|
|
889
|
-
const bodyHtml = $("body").html() || "";
|
|
890
|
-
let markdown = turndown
|
|
891
|
-
.turndown(bodyHtml)
|
|
892
|
-
.replace(/\n{3,}/g, "\n\n")
|
|
893
|
-
.trim();
|
|
894
|
-
|
|
895
|
-
if (!markdown || markdown.trim().length === 0) {
|
|
896
|
-
return "(No content extracted from this page.)";
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
return paginate(markdown, "auto (fallback)", startIndex, maxLength);
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
// === SEARCH TEMPLATE RESOLUTION ==========================================
|
|
903
|
-
|
|
904
|
-
function resolveSearchTemplate(engine, query, region, safeSearch) {
|
|
905
|
-
const templateName = resolveEngineToTemplateName(engine);
|
|
906
|
-
|
|
907
|
-
let template;
|
|
908
|
-
if (templateName.startsWith("{")) {
|
|
909
|
-
try {
|
|
910
|
-
template = parseInlineTemplate(templateName);
|
|
911
|
-
} catch (e) {
|
|
912
|
-
throw new Error(`Invalid inline JSON template: ${e.message}`);
|
|
913
|
-
}
|
|
914
|
-
} else {
|
|
915
|
-
template = getTemplateByName(templateName);
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
if (!template.url_template) {
|
|
919
|
-
throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
const params = mapSearchParams(engine, query, region, safeSearch);
|
|
923
|
-
let url = resolveUrlTemplate(template, params);
|
|
924
|
-
|
|
925
|
-
// Set both explicit states; null preserves the template default.
|
|
926
|
-
if (templateName === "google-search" && safeSearch != null) {
|
|
927
|
-
const parsed = new URL(url);
|
|
928
|
-
parsed.searchParams.set("safe", safeSearch ? "active" : "off");
|
|
929
|
-
url = parsed.href;
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
return { template, url };
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
function resolveDuckDuckGoLiteTemplate(query, region, safeSearch) {
|
|
936
|
-
const template = {
|
|
937
|
-
...getTemplateByName("duckduckgo-search"),
|
|
938
|
-
name: "duckduckgo-lite-search",
|
|
939
|
-
url_template: "https://lite.duckduckgo.com/lite/?q={query}&kl={kl}&kp={kp}",
|
|
940
|
-
sections: [
|
|
941
|
-
{
|
|
942
|
-
name: "Results",
|
|
943
|
-
selector: "a.result-link",
|
|
944
|
-
multiple: true,
|
|
945
|
-
max_items: 10,
|
|
946
|
-
children: [
|
|
947
|
-
{ name: "Title", selector: "", format: "text" },
|
|
948
|
-
{
|
|
949
|
-
name: "URL",
|
|
950
|
-
selector: "",
|
|
951
|
-
format: "attribute",
|
|
952
|
-
attribute: "href",
|
|
953
|
-
transform: "decode_ddg_url",
|
|
954
|
-
},
|
|
955
|
-
],
|
|
956
|
-
},
|
|
957
|
-
],
|
|
958
|
-
};
|
|
959
|
-
const params = mapSearchParams("duckduckgo", query, region, safeSearch);
|
|
960
|
-
return { template, url: resolveUrlTemplate(template, params), engine: "duckduckgo-lite" };
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
function resolveSearchCandidates(engine, query, region, safeSearch) {
|
|
964
|
-
const primary = { ...resolveSearchTemplate(engine, query, region, safeSearch), engine };
|
|
965
|
-
if (engine === "google") {
|
|
966
|
-
return [
|
|
967
|
-
primary,
|
|
968
|
-
{
|
|
969
|
-
...resolveSearchTemplate("duckduckgo", query, region, safeSearch),
|
|
970
|
-
engine: "duckduckgo",
|
|
971
|
-
},
|
|
972
|
-
resolveDuckDuckGoLiteTemplate(query, region, safeSearch),
|
|
973
|
-
];
|
|
974
|
-
}
|
|
975
|
-
if (engine === "duckduckgo") {
|
|
976
|
-
return [primary, resolveDuckDuckGoLiteTemplate(query, region, safeSearch)];
|
|
977
|
-
}
|
|
978
|
-
return [primary];
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
// === MCP SERVER & TOOLS ==================================================
|
|
982
|
-
|
|
983
|
-
const server = new McpServer({ name: "searchfetch", version: "3.3.4" });
|
|
984
|
-
|
|
985
|
-
// --- websearch tool ---
|
|
986
|
-
|
|
987
|
-
server.registerTool(
|
|
988
|
-
"websearch",
|
|
989
|
-
{
|
|
990
|
-
title: "Web Search",
|
|
991
|
-
description:
|
|
992
|
-
"Search the web using DuckDuckGo or Google. Returns a clean list of titles, URLs, and snippets. Excellent for researching general knowledge, news, and finding URLs.",
|
|
993
|
-
inputSchema: z.object({
|
|
994
|
-
query: z.string().trim().min(1).describe("The search query string."),
|
|
995
|
-
engine: z
|
|
996
|
-
.string()
|
|
997
|
-
.default("duckduckgo")
|
|
998
|
-
.describe(
|
|
999
|
-
"Search engine to use. Can be 'duckduckgo' or 'google'. Default is 'duckduckgo'.",
|
|
1000
|
-
),
|
|
1001
|
-
region: z
|
|
1002
|
-
.string()
|
|
1003
|
-
.nullable()
|
|
1004
|
-
.default(null)
|
|
1005
|
-
.describe(
|
|
1006
|
-
"Region and language code to localize search results (e.g., 'us-en', 'uk-en', 'de-de'). For DuckDuckGo it maps directly. For Google, 'us' is country code and 'en' is language. Default is null (uses template default).",
|
|
1007
|
-
),
|
|
1008
|
-
safe_search: z
|
|
1009
|
-
.boolean()
|
|
1010
|
-
.nullable()
|
|
1011
|
-
.default(null)
|
|
1012
|
-
.describe(
|
|
1013
|
-
"Enable safe search filtering. null = use template default. Applies to both DuckDuckGo and Google.",
|
|
1014
|
-
),
|
|
1015
|
-
max_results: z
|
|
1016
|
-
.number()
|
|
1017
|
-
.int()
|
|
1018
|
-
.positive()
|
|
1019
|
-
.default(10)
|
|
1020
|
-
.describe("Maximum number of search results to return. Default is 10."),
|
|
1021
|
-
block_media: z
|
|
1022
|
-
.boolean()
|
|
1023
|
-
.default(true)
|
|
1024
|
-
.describe(
|
|
1025
|
-
"Block images, videos, and fonts entirely at the network layer. Default is true.",
|
|
1026
|
-
),
|
|
1027
|
-
}),
|
|
1028
|
-
},
|
|
1029
|
-
async ({ query, engine, region, safe_search, max_results, block_media }) => {
|
|
1030
|
-
try {
|
|
1031
|
-
const candidates = resolveSearchCandidates(engine, query, region, safe_search);
|
|
1032
|
-
let extracted;
|
|
1033
|
-
let selectedEngine;
|
|
1034
|
-
let lastError;
|
|
1035
|
-
|
|
1036
|
-
for (const candidate of candidates) {
|
|
1037
|
-
try {
|
|
1038
|
-
const html = await fetchHtmlWithRetry(candidate.url, candidate.template, block_media);
|
|
1039
|
-
const $ = cheerio.load(html);
|
|
1040
|
-
applyRemove($, candidate.template);
|
|
1041
|
-
extracted = extractTemplate($, candidate.template, {
|
|
1042
|
-
origin: candidate.url,
|
|
1043
|
-
isWebsearch: true,
|
|
1044
|
-
maxResultsOverride: max_results,
|
|
1045
|
-
_maxResultsConsumed: false,
|
|
1046
|
-
});
|
|
1047
|
-
const resultSection = extracted.find((result) => result.type === "children-multiple");
|
|
1048
|
-
if (resultSection?.items?.length > 0) {
|
|
1049
|
-
selectedEngine = candidate.engine;
|
|
1050
|
-
break;
|
|
1051
|
-
}
|
|
1052
|
-
lastError = new Error(`No results extracted from ${candidate.engine}.`);
|
|
1053
|
-
} catch (err) {
|
|
1054
|
-
lastError = err;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
if (!extracted || !selectedEngine) throw lastError || new Error("No search results found.");
|
|
1059
|
-
|
|
1060
|
-
let result = composeSearchResults(extracted);
|
|
1061
|
-
if (selectedEngine !== engine) {
|
|
1062
|
-
result =
|
|
1063
|
-
`[websearch: ${engine} was unavailable; results are from ${selectedEngine}.]\n\n` +
|
|
1064
|
-
result;
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
return { content: [{ type: "text", text: result }] };
|
|
1068
|
-
} catch (err) {
|
|
1069
|
-
return {
|
|
1070
|
-
content: [{ type: "text", text: `Search Error: ${err.message}` }],
|
|
1071
|
-
isError: true,
|
|
1072
|
-
};
|
|
1073
|
-
}
|
|
1074
|
-
},
|
|
1075
|
-
);
|
|
1076
|
-
|
|
1077
|
-
// --- webfetch tool ---
|
|
1078
|
-
|
|
1079
|
-
server.registerTool(
|
|
1080
|
-
"webfetch",
|
|
1081
|
-
{
|
|
1082
|
-
title: "Web Fetch",
|
|
1083
|
-
description:
|
|
1084
|
-
"Fetch and extract the main text content from any webpage. Fully executes JavaScript to load React/SPAs and aggressively strips images/media (including base64) to save context tokens.",
|
|
1085
|
-
inputSchema: z.object({
|
|
1086
|
-
url: z
|
|
1087
|
-
.string()
|
|
1088
|
-
.url()
|
|
1089
|
-
.refine(
|
|
1090
|
-
(value) => ["http:", "https:"].includes(new URL(value).protocol),
|
|
1091
|
-
"URL must use HTTP or HTTPS",
|
|
1092
|
-
)
|
|
1093
|
-
.describe("The full URL of the webpage to fetch (must start with http/https)."),
|
|
1094
|
-
template: z
|
|
1095
|
-
.string()
|
|
1096
|
-
.default("auto")
|
|
1097
|
-
.describe(
|
|
1098
|
-
"Template to use: 'auto' (auto-detect from URL), a built-in page template name " +
|
|
1099
|
-
"(wikipedia, reddit, mdn-web-docs, gitlab, youtube, devto, go-pkg, javadoc, " +
|
|
1100
|
-
"github-repo, github-issue, npm-package, pypi-package, crates-package, " +
|
|
1101
|
-
"docker-hub, docs-rs, docs-page), 'raw' for minimal-filtering full-page output, " +
|
|
1102
|
-
"or inline JSON.",
|
|
1103
|
-
),
|
|
1104
|
-
start_index: z
|
|
1105
|
-
.number()
|
|
1106
|
-
.int()
|
|
1107
|
-
.nonnegative()
|
|
1108
|
-
.default(0)
|
|
1109
|
-
.describe("Character offset for pagination. Default: 0."),
|
|
1110
|
-
max_length: z
|
|
1111
|
-
.number()
|
|
1112
|
-
.int()
|
|
1113
|
-
.positive()
|
|
1114
|
-
.default(10000)
|
|
1115
|
-
.describe("Maximum characters to return per request. Default is 10000."),
|
|
1116
|
-
block_media: z
|
|
1117
|
-
.boolean()
|
|
1118
|
-
.default(true)
|
|
1119
|
-
.describe(
|
|
1120
|
-
"Block images, videos, and fonts entirely at the network layer. Default is true.",
|
|
1121
|
-
),
|
|
1122
|
-
}),
|
|
1123
|
-
},
|
|
1124
|
-
async ({ url, template: templateParam, start_index, max_length, block_media }) => {
|
|
1125
|
-
try {
|
|
1126
|
-
// 1. Resolve template
|
|
1127
|
-
let template;
|
|
1128
|
-
|
|
1129
|
-
if (templateParam.startsWith("{")) {
|
|
1130
|
-
try {
|
|
1131
|
-
template = parseInlineTemplate(templateParam);
|
|
1132
|
-
} catch (e) {
|
|
1133
|
-
throw new Error(`Invalid inline JSON template: ${e.message}`);
|
|
1134
|
-
}
|
|
1135
|
-
} else if (templateParam === "auto") {
|
|
1136
|
-
template = detectTemplateByUrl(url);
|
|
1137
|
-
} else {
|
|
1138
|
-
template = getTemplateByName(templateParam);
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
// 2. Try source markdown if template specifies source_url
|
|
1142
|
-
let sourceMd = null;
|
|
1143
|
-
if (template && template.source_url) {
|
|
1144
|
-
const sourceUrl = resolveSourceUrl(template.source_url, url);
|
|
1145
|
-
sourceMd = await fetchSourceMarkdown(sourceUrl, template, block_media);
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
if (sourceMd !== null) {
|
|
1149
|
-
return {
|
|
1150
|
-
content: [
|
|
1151
|
-
{ type: "text", text: paginate(sourceMd, template.name, start_index, max_length) },
|
|
1152
|
-
],
|
|
1153
|
-
};
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
|
-
// 3. Fetch
|
|
1157
|
-
const html = await fetchHtmlWithRetry(url, template, block_media);
|
|
1158
|
-
|
|
1159
|
-
// 4. Extract and compose
|
|
1160
|
-
const $ = cheerio.load(html);
|
|
1161
|
-
|
|
1162
|
-
if (template) {
|
|
1163
|
-
applyRemove($, template);
|
|
1164
|
-
|
|
1165
|
-
const pageOrigin = url;
|
|
1166
|
-
const context = {
|
|
1167
|
-
origin: pageOrigin,
|
|
1168
|
-
isWebsearch: false,
|
|
1169
|
-
};
|
|
1170
|
-
|
|
1171
|
-
const extracted = extractTemplate($, template, context);
|
|
1172
|
-
const result = composeSections(extracted, template, start_index, max_length);
|
|
1173
|
-
return { content: [{ type: "text", text: result }] };
|
|
1174
|
-
} else {
|
|
1175
|
-
// Generic fallback
|
|
1176
|
-
const result = genericFallback($, start_index, max_length);
|
|
1177
|
-
return { content: [{ type: "text", text: result }] };
|
|
1178
|
-
}
|
|
1179
|
-
} catch (err) {
|
|
1180
|
-
return {
|
|
1181
|
-
content: [{ type: "text", text: `Fetch Error: ${err.message}` }],
|
|
1182
|
-
isError: true,
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
},
|
|
1186
|
-
);
|
|
1187
|
-
|
|
1188
|
-
// === EXPORTS (for testing without starting server) =========================
|
|
1189
|
-
|
|
1190
|
-
export {
|
|
1191
|
-
BrowserManager,
|
|
1192
|
-
applyRemove,
|
|
1193
|
-
server,
|
|
1194
|
-
loadBuiltinTemplates,
|
|
1195
|
-
getTemplateByName,
|
|
1196
|
-
detectTemplateByUrl,
|
|
1197
|
-
resolveUrlTemplate,
|
|
1198
|
-
resolveEngineToTemplateName,
|
|
1199
|
-
mapSearchParams,
|
|
1200
|
-
resolveSearchTemplate,
|
|
1201
|
-
resolveSearchCandidates,
|
|
1202
|
-
isMarkdownContent,
|
|
1203
|
-
stripSourceMarkdown,
|
|
1204
|
-
resolveSourceUrl,
|
|
1205
|
-
parseRetryAfterMs,
|
|
1206
|
-
isAccessDenied,
|
|
1207
|
-
findScoped,
|
|
1208
|
-
findFirstMatch,
|
|
1209
|
-
resolveTopElements,
|
|
1210
|
-
applyTransform,
|
|
1211
|
-
extractValue,
|
|
1212
|
-
extractChildSection,
|
|
1213
|
-
extractSection,
|
|
1214
|
-
extractTemplate,
|
|
1215
|
-
composeSections,
|
|
1216
|
-
composeSearchResults,
|
|
1217
|
-
genericFallback,
|
|
1218
|
-
isMainModule,
|
|
1219
|
-
BUILTIN_TEMPLATES,
|
|
1220
|
-
TEMPLATE_MAP,
|
|
1221
|
-
};
|
|
1222
|
-
|
|
1223
|
-
// === MAIN =================================================================
|
|
1224
|
-
|
|
1225
|
-
function redirectStartupOutputToStderr() {
|
|
1226
|
-
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
1227
|
-
const originalConsoleLog = console.log;
|
|
1228
|
-
const originalConsoleInfo = console.info;
|
|
1229
|
-
|
|
1230
|
-
process.stdout.write = (chunk, encoding, callback) => {
|
|
1231
|
-
return process.stderr.write(chunk, encoding, callback);
|
|
1232
|
-
};
|
|
1233
|
-
console.log = (...args) => console.error(...args);
|
|
1234
|
-
console.info = (...args) => console.error(...args);
|
|
1235
|
-
|
|
1236
|
-
return () => {
|
|
1237
|
-
process.stdout.write = originalStdoutWrite;
|
|
1238
|
-
console.log = originalConsoleLog;
|
|
1239
|
-
console.info = originalConsoleInfo;
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
function isMainModule(argvPath = process.argv[1], modulePath = __filename) {
|
|
1244
|
-
if (!argvPath) return false;
|
|
1245
|
-
try {
|
|
1246
|
-
return realpathSync(argvPath) === realpathSync(modulePath);
|
|
1247
|
-
} catch {
|
|
1248
|
-
return false;
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
async function main() {
|
|
1253
|
-
process.on("SIGINT", cleanup);
|
|
1254
|
-
process.on("SIGTERM", cleanup);
|
|
1255
|
-
|
|
1256
|
-
const restoreStdout = redirectStartupOutputToStderr();
|
|
1257
|
-
try {
|
|
1258
|
-
await ensureBinary();
|
|
1259
|
-
} finally {
|
|
1260
|
-
restoreStdout();
|
|
1261
|
-
}
|
|
1262
|
-
const transport = new StdioServerTransport();
|
|
1263
|
-
await server.connect(transport);
|
|
1264
|
-
process.stdin.once("end", cleanup);
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
// Guard: only start server when run directly (including via npm bin symlink),
|
|
1268
|
-
// not when imported. Uses realpath so that `npx` / `node_modules/.bin`
|
|
1269
|
-
// symlinks resolve to the module file correctly.
|
|
1270
|
-
const isMain = isMainModule();
|
|
1271
|
-
if (isMain) {
|
|
1272
|
-
main().catch((err) => {
|
|
1273
|
-
console.error(err);
|
|
1274
|
-
process.exit(1);
|
|
1275
|
-
});
|
|
1276
|
-
}
|