evidence-mcp-dev 0.2.44 → 0.2.45
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/dist/index.js +333 -189
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -62,6 +62,84 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
62
62
|
// src/http.ts
|
|
63
63
|
import { fetch as undiciFetch } from "undici";
|
|
64
64
|
|
|
65
|
+
// src/race.ts
|
|
66
|
+
var OPEN = /* @__PURE__ */ new Set();
|
|
67
|
+
function openRequest(write, name) {
|
|
68
|
+
const ctrl = new AbortController();
|
|
69
|
+
let closed = false;
|
|
70
|
+
const entry = { abandon: () => {
|
|
71
|
+
if (!closed) {
|
|
72
|
+
closed = true;
|
|
73
|
+
write(`abandoned ${name}: server stopped`);
|
|
74
|
+
}
|
|
75
|
+
} };
|
|
76
|
+
OPEN.add(entry);
|
|
77
|
+
write(`try ${name}`);
|
|
78
|
+
return {
|
|
79
|
+
signal: ctrl.signal,
|
|
80
|
+
abort: (why) => {
|
|
81
|
+
if (closed) return;
|
|
82
|
+
closed = true;
|
|
83
|
+
OPEN.delete(entry);
|
|
84
|
+
write(`aborted ${name}: ${why}`);
|
|
85
|
+
ctrl.abort(new Error(`aborted: ${why}`));
|
|
86
|
+
},
|
|
87
|
+
close: (line) => {
|
|
88
|
+
if (closed) return false;
|
|
89
|
+
closed = true;
|
|
90
|
+
OPEN.delete(entry);
|
|
91
|
+
write(line);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function abandonAll() {
|
|
97
|
+
for (const e of OPEN) e.abandon();
|
|
98
|
+
OPEN.clear();
|
|
99
|
+
}
|
|
100
|
+
async function firstOk(tasks, decisive = () => null) {
|
|
101
|
+
if (!tasks.length) return { won: null, results: [] };
|
|
102
|
+
const results2 = new Array(tasks.length);
|
|
103
|
+
const settled = new Array(tasks.length).fill(false);
|
|
104
|
+
return new Promise((resolve4) => {
|
|
105
|
+
let left = tasks.length, done = false;
|
|
106
|
+
const end = (won, why) => {
|
|
107
|
+
done = true;
|
|
108
|
+
tasks.forEach((t, j) => {
|
|
109
|
+
if (!settled[j]) t.abort(why);
|
|
110
|
+
});
|
|
111
|
+
resolve4({ won, results: results2 });
|
|
112
|
+
};
|
|
113
|
+
tasks.forEach((task, i) => {
|
|
114
|
+
task.go().then((r) => {
|
|
115
|
+
results2[i] = r;
|
|
116
|
+
settled[i] = true;
|
|
117
|
+
if (done) return;
|
|
118
|
+
const gone = r.ok ? null : decisive(r);
|
|
119
|
+
if (r.ok) end(r, `${task.name} won`);
|
|
120
|
+
else if (gone) end(null, `${task.name}: ${gone}`);
|
|
121
|
+
else if (--left === 0) {
|
|
122
|
+
done = true;
|
|
123
|
+
resolve4({ won: null, results: results2 });
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function timeoutOr(ms, signal) {
|
|
130
|
+
if (!signal) return AbortSignal.timeout(ms);
|
|
131
|
+
const c = new AbortController();
|
|
132
|
+
const t = setTimeout(() => c.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), ms);
|
|
133
|
+
if (signal.aborted) {
|
|
134
|
+
clearTimeout(t);
|
|
135
|
+
c.abort(signal.reason);
|
|
136
|
+
} else signal.addEventListener("abort", () => {
|
|
137
|
+
clearTimeout(t);
|
|
138
|
+
c.abort(signal.reason);
|
|
139
|
+
}, { once: true });
|
|
140
|
+
return c.signal;
|
|
141
|
+
}
|
|
142
|
+
|
|
65
143
|
// src/contact.ts
|
|
66
144
|
var DEFAULT = "hello@forever-healthy.org";
|
|
67
145
|
var contactEmail = (env = process.env) => str("FH_CONTACT_EMAIL", env) || DEFAULT;
|
|
@@ -266,10 +344,16 @@ async function closeBrowsers() {
|
|
|
266
344
|
}
|
|
267
345
|
}
|
|
268
346
|
}
|
|
269
|
-
async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
347
|
+
async function browserFetch(url, endpoint, cfg = browserConfig(), signal) {
|
|
348
|
+
url = toHttps(url);
|
|
270
349
|
const ctx = await context(endpoint, cfg);
|
|
271
350
|
touchIdle();
|
|
272
351
|
const page = await ctx.newPage();
|
|
352
|
+
const onAbort = () => {
|
|
353
|
+
page.close().catch(() => void 0);
|
|
354
|
+
};
|
|
355
|
+
if (signal?.aborted) onAbort();
|
|
356
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
273
357
|
try {
|
|
274
358
|
let pdfBest = null;
|
|
275
359
|
const pdfReads = [];
|
|
@@ -314,6 +398,8 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
314
398
|
}
|
|
315
399
|
if (!download2) await pause(DOWNLOAD_WAIT_MS / 5);
|
|
316
400
|
}
|
|
401
|
+
const landed = download2 ? download2.url() : page.url();
|
|
402
|
+
if (/^http:\/\//i.test(landed)) throw new Error(`${PLAIN_HTTP} (${new URL(landed).hostname})`);
|
|
317
403
|
if (download2) {
|
|
318
404
|
const d = download2;
|
|
319
405
|
const stream = await d.createReadStream();
|
|
@@ -350,6 +436,7 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
350
436
|
const html = await page.content();
|
|
351
437
|
return { bytes: Buffer.from(html, "utf8"), contentType: contentType || "text/html", url: page.url(), via: "page" };
|
|
352
438
|
} finally {
|
|
439
|
+
signal?.removeEventListener("abort", onAbort);
|
|
353
440
|
await page.close().catch(() => void 0);
|
|
354
441
|
if (isRemote(endpoint)) await ctx.storageState({ path: stateFile(endpoint) }).catch(() => void 0);
|
|
355
442
|
}
|
|
@@ -386,12 +473,17 @@ function httpReason(status, body) {
|
|
|
386
473
|
return m ? `HTTP ${status} ${m[1] ?? m[2]}` : `HTTP ${status}`;
|
|
387
474
|
}
|
|
388
475
|
var DOWNLOAD_HEADERS = { "User-Agent": CHROME_UA, "Accept": "application/pdf,text/html,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9" };
|
|
389
|
-
|
|
476
|
+
var toHttps = (url) => url.replace(/^http:\/\//i, "https://");
|
|
477
|
+
var PLAIN_HTTP = "redirected to plain http";
|
|
478
|
+
var isPlain = (url) => /^http:\/\//i.test(url);
|
|
479
|
+
async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy, signal) {
|
|
480
|
+
url = toHttps(url);
|
|
390
481
|
let last = "unknown error", finalUrl = "", lastBody = "", lastType = "";
|
|
391
482
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
392
483
|
try {
|
|
393
|
-
const init = { headers, signal:
|
|
484
|
+
const init = { headers, signal: timeoutOr(TIMEOUT_MS, signal), redirect: "follow" };
|
|
394
485
|
const res = proxy ? await undiciFetch(url, { ...init, dispatcher: proxyAgent(proxy) }) : await fetch(url, init);
|
|
486
|
+
if (res.url && isPlain(res.url)) throw Object.assign(new Error(`${PLAIN_HTTP} (${new URL(res.url).hostname})`), { final: true });
|
|
395
487
|
if (res.ok) return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "", url: res.url };
|
|
396
488
|
lastBody = (await res.text().catch(() => "")).slice(0, 4e3);
|
|
397
489
|
lastType = res.headers.get("content-type") ?? "";
|
|
@@ -399,9 +491,11 @@ async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy) {
|
|
|
399
491
|
finalUrl = res.url;
|
|
400
492
|
if (res.status !== 429 && res.status < 500) break;
|
|
401
493
|
} catch (e) {
|
|
494
|
+
if (e.final) throw e;
|
|
402
495
|
const code = e?.cause;
|
|
403
496
|
last = e instanceof Error && e.name === "TimeoutError" ? "timeout" : e instanceof Error ? e.message + (code?.code ? ` (${code.code})` : code?.message ? ` (${code.message})` : "") : String(e);
|
|
404
497
|
}
|
|
498
|
+
if (signal?.aborted) break;
|
|
405
499
|
await new Promise((r) => setTimeout(r, 1500));
|
|
406
500
|
}
|
|
407
501
|
throw Object.assign(new Error(last), finalUrl ? { url: finalUrl } : {}, lastBody ? { body: lastBody, contentType: lastType } : {});
|
|
@@ -492,6 +586,36 @@ function checkFulltext(md, title, titleSource, doi, trusted = false, pdf = false
|
|
|
492
586
|
return { ok: true };
|
|
493
587
|
}
|
|
494
588
|
|
|
589
|
+
// src/hosts.ts
|
|
590
|
+
import { connect } from "net";
|
|
591
|
+
var UP_MS = 6e4;
|
|
592
|
+
var DOWN_MS = 5 * 6e4;
|
|
593
|
+
var PROBE_MS = 3e3;
|
|
594
|
+
var seen = /* @__PURE__ */ new Map();
|
|
595
|
+
var key = (host3, port) => `${host3}:${port}`;
|
|
596
|
+
function probe(host3, port, timeoutMs = PROBE_MS) {
|
|
597
|
+
const t0 = Date.now();
|
|
598
|
+
return new Promise((resolve4) => {
|
|
599
|
+
const s = connect({ host: host3, port });
|
|
600
|
+
const done = (error) => {
|
|
601
|
+
s.destroy();
|
|
602
|
+
resolve4({ up: !error, ms: Date.now() - t0, at: Date.now(), error });
|
|
603
|
+
};
|
|
604
|
+
s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
|
|
605
|
+
s.once("connect", () => done(null));
|
|
606
|
+
s.once("error", (e) => done(e.code ?? e.message));
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
async function hostState(host3, port, onDown) {
|
|
610
|
+
const k = key(host3, port), now2 = Date.now(), old = seen.get(k);
|
|
611
|
+
if (old && now2 - old.at < (old.up ? UP_MS : DOWN_MS)) return old;
|
|
612
|
+
const s = await probe(host3, port);
|
|
613
|
+
seen.set(k, s);
|
|
614
|
+
if (!s.up && (!old || old.up)) onDown?.(s);
|
|
615
|
+
return s;
|
|
616
|
+
}
|
|
617
|
+
var downNote = (s) => `host down (${s.error}, since ${new Date(s.at).toTimeString().slice(0, 5)})`;
|
|
618
|
+
|
|
495
619
|
// src/html.ts
|
|
496
620
|
import TurndownService from "turndown";
|
|
497
621
|
import { gfm } from "@joplin/turndown-plugin-gfm";
|
|
@@ -1197,13 +1321,13 @@ var COMPOUND_PREFIX = /* @__PURE__ */ new Set([
|
|
|
1197
1321
|
function dehyphenate(text4) {
|
|
1198
1322
|
if (!text4.includes(BREAK)) return text4;
|
|
1199
1323
|
const lower = text4.toLowerCase();
|
|
1200
|
-
const
|
|
1324
|
+
const seen2 = (s) => new RegExp(`(?<![a-z])${s}(?![a-z])`).test(lower);
|
|
1201
1325
|
return text4.replace(/([A-Za-z]+)\u0000\n([A-Za-z]+)/g, (m, x, y) => {
|
|
1202
1326
|
if (!/^[a-z]/.test(y)) return `${x}-${y}`;
|
|
1203
1327
|
if (SUSPENDED.has(y.toLowerCase())) return `${x}- ${y}`;
|
|
1204
1328
|
const hyph = `${x}-${y}`.toLowerCase(), joined3 = `${x}${y}`.toLowerCase();
|
|
1205
|
-
if (
|
|
1206
|
-
if (
|
|
1329
|
+
if (seen2(hyph)) return `${x}-${y}`;
|
|
1330
|
+
if (seen2(joined3)) return `${x}${y}`;
|
|
1207
1331
|
return COMPOUND_PREFIX.has(x.toLowerCase()) ? `${x}-${y}` : `${x}${y}`;
|
|
1208
1332
|
}).replace(/\u0000\n/g, "-\n").replace(/\u0000/g, "-");
|
|
1209
1333
|
}
|
|
@@ -1219,7 +1343,7 @@ import { request as httpsRequest } from "https";
|
|
|
1219
1343
|
var ENDPOINT = "https://api.brightdata.com/request";
|
|
1220
1344
|
var TIMEOUT_MS2 = 6e4;
|
|
1221
1345
|
function post(url, init) {
|
|
1222
|
-
return new Promise((
|
|
1346
|
+
return new Promise((resolve4, reject) => {
|
|
1223
1347
|
const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
|
|
1224
1348
|
const chunks = [];
|
|
1225
1349
|
res.on("data", (c) => chunks.push(c));
|
|
@@ -1227,7 +1351,7 @@ function post(url, init) {
|
|
|
1227
1351
|
res.on("end", () => {
|
|
1228
1352
|
const body = Buffer.concat(chunks);
|
|
1229
1353
|
const status = res.statusCode ?? 0;
|
|
1230
|
-
|
|
1354
|
+
resolve4({
|
|
1231
1355
|
ok: status >= 200 && status < 300,
|
|
1232
1356
|
status,
|
|
1233
1357
|
headers: { get: (name) => {
|
|
@@ -1243,7 +1367,7 @@ function post(url, init) {
|
|
|
1243
1367
|
});
|
|
1244
1368
|
}
|
|
1245
1369
|
var apiKey = () => process.env.FH_BRIGHTDATA_API_KEY?.trim() || "";
|
|
1246
|
-
async function get(url, postImpl = post) {
|
|
1370
|
+
async function get(url, postImpl = post, signal) {
|
|
1247
1371
|
const token = apiKey();
|
|
1248
1372
|
if (!token) throw new Error("not configured");
|
|
1249
1373
|
const zone = process.env.FH_BRIGHTDATA_ZONE?.trim() || "mcp_unlocker";
|
|
@@ -1251,22 +1375,22 @@ async function get(url, postImpl = post) {
|
|
|
1251
1375
|
method: "POST",
|
|
1252
1376
|
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
|
|
1253
1377
|
body: JSON.stringify({ zone, url, format: "raw" }),
|
|
1254
|
-
signal:
|
|
1378
|
+
signal: timeoutOr(TIMEOUT_MS2, signal)
|
|
1255
1379
|
});
|
|
1256
1380
|
const why = res.headers.get("x-brd-err-msg") ?? res.headers.get("x-brd-error");
|
|
1257
1381
|
if (!res.ok) throw new Error(`unlocker HTTP ${res.status}${why ? `: ${why}` : ""}`);
|
|
1258
1382
|
if (res.headers.get("x-brd-error")) throw new Error(`unlocker refused: ${why}`);
|
|
1259
1383
|
return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "" };
|
|
1260
1384
|
}
|
|
1261
|
-
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url) => get(url) };
|
|
1385
|
+
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url, signal) => get(url, post, signal) };
|
|
1262
1386
|
|
|
1263
1387
|
// src/unlock/zenrows.ts
|
|
1264
1388
|
var TIMEOUT_MS3 = 6e4;
|
|
1265
1389
|
var ACCOUNT = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1266
|
-
async function get2(url, fetchImpl = fetch) {
|
|
1267
|
-
const
|
|
1268
|
-
if (!
|
|
1269
|
-
const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(
|
|
1390
|
+
async function get2(url, fetchImpl = fetch, signal) {
|
|
1391
|
+
const key2 = process.env.FH_ZENROWS_API_KEY?.trim();
|
|
1392
|
+
if (!key2) throw new Error("not configured");
|
|
1393
|
+
const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(key2)}&url=${encodeURIComponent(url)}&mode=auto`, { signal: timeoutOr(TIMEOUT_MS3, signal) });
|
|
1270
1394
|
const bytes = Buffer.from(await r.arrayBuffer());
|
|
1271
1395
|
if (!r.ok) {
|
|
1272
1396
|
let why = "";
|
|
@@ -1280,18 +1404,18 @@ async function get2(url, fetchImpl = fetch) {
|
|
|
1280
1404
|
}
|
|
1281
1405
|
return { bytes, contentType: r.headers.get("content-type") ?? "" };
|
|
1282
1406
|
}
|
|
1283
|
-
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url) => get2(url) };
|
|
1407
|
+
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url, signal) => get2(url, fetch, signal) };
|
|
1284
1408
|
|
|
1285
1409
|
// src/unlock/zyte.ts
|
|
1286
1410
|
var TIMEOUT_MS4 = 6e4;
|
|
1287
1411
|
var ACCOUNT2 = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1288
|
-
async function get3(url, fetchImpl = fetch) {
|
|
1289
|
-
const
|
|
1290
|
-
if (!
|
|
1412
|
+
async function get3(url, fetchImpl = fetch, signal) {
|
|
1413
|
+
const key2 = process.env.FH_ZYTE_API_KEY?.trim();
|
|
1414
|
+
if (!key2) throw new Error("not configured");
|
|
1291
1415
|
const r = await fetchImpl("https://api.zyte.com/v1/extract", {
|
|
1292
1416
|
method: "POST",
|
|
1293
|
-
signal:
|
|
1294
|
-
headers: { authorization: `Basic ${Buffer.from(`${
|
|
1417
|
+
signal: timeoutOr(TIMEOUT_MS4, signal),
|
|
1418
|
+
headers: { authorization: `Basic ${Buffer.from(`${key2}:`).toString("base64")}`, "content-type": "application/json" },
|
|
1295
1419
|
body: JSON.stringify({ url, httpResponseBody: true, httpResponseHeaders: true })
|
|
1296
1420
|
});
|
|
1297
1421
|
const j = await r.json().catch(() => ({}));
|
|
@@ -1303,7 +1427,7 @@ async function get3(url, fetchImpl = fetch) {
|
|
|
1303
1427
|
const contentType = j.httpResponseHeaders?.find((h) => h.name.toLowerCase() === "content-type")?.value ?? "";
|
|
1304
1428
|
return { bytes: Buffer.from(j.httpResponseBody ?? "", "base64"), contentType };
|
|
1305
1429
|
}
|
|
1306
|
-
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url) => get3(url) };
|
|
1430
|
+
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url, signal) => get3(url, fetch, signal) };
|
|
1307
1431
|
|
|
1308
1432
|
// src/unlock.ts
|
|
1309
1433
|
var SERVICES = [zenrows, zyte, brightdata];
|
|
@@ -1311,25 +1435,12 @@ var UNLOCKER_NAMES = SERVICES.map((s) => s.name);
|
|
|
1311
1435
|
var UNLOCKER_PREFIX = new RegExp(`^(${UNLOCKER_NAMES.join("|")}): `);
|
|
1312
1436
|
var accountProblem = (reason) => /^unlocker (HTTP 4\d\d|refused)/.test(reason);
|
|
1313
1437
|
var keyed = (s, env) => !!env[s.keyVar]?.trim();
|
|
1314
|
-
|
|
1315
|
-
const listed = (env.FH_UNLOCKERS ?? "").split(",").map((n) => n.trim().toLowerCase()).filter(Boolean);
|
|
1316
|
-
if (!listed.length) return { order: SERVICES.filter((s) => keyed(s, env)).map((s) => s.name), problems: [] };
|
|
1317
|
-
const problems = [], order2 = [];
|
|
1318
|
-
for (const n of listed) {
|
|
1319
|
-
const s = SERVICES.find((x) => x.name === n);
|
|
1320
|
-
if (!s) problems.push(`FH_UNLOCKERS: unknown unlocker "${n}" (built-in: ${UNLOCKER_NAMES.join(", ")})`);
|
|
1321
|
-
else if (!keyed(s, env)) problems.push(`FH_UNLOCKERS: "${n}" listed, but ${s.keyVar} is unset`);
|
|
1322
|
-
else if (!order2.includes(n)) order2.push(n);
|
|
1323
|
-
}
|
|
1324
|
-
return { order: order2, problems };
|
|
1325
|
-
}
|
|
1326
|
-
var unlockers = (env = process.env) => resolve3(env).order;
|
|
1327
|
-
var unlockerProblems = (env = process.env) => resolve3(env).problems;
|
|
1438
|
+
var unlockers = (env = process.env) => SERVICES.filter((s) => keyed(s, env)).map((s) => s.name);
|
|
1328
1439
|
var unlockerConfigured = () => unlockers().length > 0;
|
|
1329
|
-
async function unlock(url, name) {
|
|
1440
|
+
async function unlock(url, name, signal) {
|
|
1330
1441
|
const s = SERVICES.find((x) => x.name === name);
|
|
1331
1442
|
if (!s) throw new Error(`unknown unlocker ${name}`);
|
|
1332
|
-
return s.get(url);
|
|
1443
|
+
return s.get(url, signal);
|
|
1333
1444
|
}
|
|
1334
1445
|
var HEALTH_URL = "https://example.com/";
|
|
1335
1446
|
async function unlockerHealth(name, unlockImpl = unlock) {
|
|
@@ -2526,7 +2637,11 @@ function order(candidates) {
|
|
|
2526
2637
|
async function download(tier, p, candidates, ctx) {
|
|
2527
2638
|
const usable = candidates.filter((c) => !NCBI.test(c.url));
|
|
2528
2639
|
if (!usable.length && candidates.length) return miss(tier, "only pmc copies (covered by the pmc tier)");
|
|
2529
|
-
const ordered = order(usable
|
|
2640
|
+
const ordered = order(usable.map((c) => {
|
|
2641
|
+
const u = toHttps(c.url);
|
|
2642
|
+
if (u !== c.url) ctx.onTry?.(`http upgraded: ${c.url} \u2192 ${u}`);
|
|
2643
|
+
return u === c.url ? c : { ...c, url: u };
|
|
2644
|
+
})).filter((c) => !ctx.tried.has(c.url));
|
|
2530
2645
|
if (!ordered.length) return miss(tier, "only copies already tried");
|
|
2531
2646
|
const reasons = [];
|
|
2532
2647
|
for (let i = 0; i < ordered.length; i++) {
|
|
@@ -2539,58 +2654,61 @@ async function download(tier, p, candidates, ctx) {
|
|
|
2539
2654
|
if (!x.ok && !gone && /\bHTTP (404|410)\b/.test(x.reason)) gone = x.reason;
|
|
2540
2655
|
return x;
|
|
2541
2656
|
};
|
|
2542
|
-
let r = note(await tryOne(p, c, tier));
|
|
2543
|
-
const target = !r.ok && r.url && r.url !== c.url ? { ...c, url: r.url } : c;
|
|
2544
|
-
if (target !== c) ctx.onTry?.(`${c.url} \u2192 ${target.url}`);
|
|
2545
|
-
ctx.onTry?.(r.ok ? `${target.url} ok fetch` : `${target.url} failed fetch: ${r.reason}`);
|
|
2546
2657
|
const why = (reason) => reason.replace(/^not a pdf \((.*)\)$/, "$1");
|
|
2547
|
-
const
|
|
2658
|
+
const run = (cand, via, name) => {
|
|
2659
|
+
let req = null;
|
|
2660
|
+
return { name, abort: (why2) => req?.abort(why2), go: async () => {
|
|
2661
|
+
req = openRequest((line) => ctx.onTry?.(`${line} ${cand.url}`), name);
|
|
2662
|
+
const x0 = await tryOne(p, cand, tier, via, req.signal);
|
|
2663
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted" };
|
|
2664
|
+
const x = note(x0);
|
|
2665
|
+
if (via !== "plain") recordStage(cand.url, name, x.ok, x.ok ? "" : x.reason);
|
|
2666
|
+
req.close(x.ok ? `ok ${name}` : `failed ${name}: ${via === "plain" ? x.reason : bare(x.reason)}`);
|
|
2667
|
+
if (!x.ok && (bare(x.reason).startsWith(MISMATCH) || accountProblem(bare(x.reason)))) ctx.onAlert?.(`${name}: ${bare(x.reason)}`);
|
|
2668
|
+
return x;
|
|
2669
|
+
} };
|
|
2670
|
+
};
|
|
2671
|
+
const skipped = (url, name) => {
|
|
2672
|
+
const w = walled(url, name);
|
|
2673
|
+
if (w) ctx.onTry?.(`skipped ${name}: ${wallNote(w)} ${url}`);
|
|
2674
|
+
return !!w;
|
|
2675
|
+
};
|
|
2676
|
+
const hostDown = async (host3, port, name, url) => {
|
|
2677
|
+
const h = await hostState(host3, port, (s) => ctx.onAlert?.(`${name}: ${downNote(s)}`));
|
|
2678
|
+
if (!h.up) ctx.onTry?.(`skipped ${name}: ${downNote(h)} ${url}`);
|
|
2679
|
+
return !h.up;
|
|
2680
|
+
};
|
|
2548
2681
|
const f = fetchProxy();
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2682
|
+
const first = [run(c, "plain", "fetch")];
|
|
2683
|
+
if (f && !c.service && !skipped(c.url, fetchProxyName(f)) && !await hostDown(f.host, f.port, fetchProxyName(f), c.url)) first.push(run(c, { proxy: f.proxy, label: f.label }, fetchProxyName(f)));
|
|
2684
|
+
const isGone = (x) => x.ok ? null : x.reason.match(/\bHTTP (404|410)\b/)?.[0] ?? null;
|
|
2685
|
+
const one = await firstOk(first, isGone);
|
|
2686
|
+
if (one.won) return one.won;
|
|
2687
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
2688
|
+
const target = !plain3.ok && plain3.url && plain3.url !== c.url ? { ...c, url: plain3.url } : c;
|
|
2689
|
+
if (target !== c) ctx.onTry?.(`redirect ${c.url} \u2192 ${target.url}`);
|
|
2690
|
+
const plainReason = why(reasonOf(plain3));
|
|
2691
|
+
let r = one.results[1] ?? plain3;
|
|
2559
2692
|
const UNLOCK = /^(HTTP 403|wall page)/;
|
|
2560
2693
|
let browsed = false;
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
const
|
|
2564
|
-
|
|
2565
|
-
browsed =
|
|
2566
|
-
const
|
|
2567
|
-
|
|
2568
|
-
if (
|
|
2569
|
-
ctx.onTry?.(`${target.url} skipped ${name}: ${wallNote(w)}`);
|
|
2570
|
-
continue;
|
|
2571
|
-
}
|
|
2572
|
-
r = note(await tryOne(p, target, tier, { browser: b.endpoint, label: b.label }));
|
|
2573
|
-
recordStage(target.url, name, r.ok, r.ok ? "" : r.reason);
|
|
2574
|
-
ctx.onTry?.(r.ok ? `${target.url} ok ${name}` : `${target.url} failed ${name}: ${bare(r.reason)}`);
|
|
2575
|
-
if (!r.ok && bare(r.reason).startsWith(MISMATCH)) ctx.onAlert?.(`${name}: ${bare(r.reason)}`);
|
|
2576
|
-
}
|
|
2577
|
-
const unlockable = !r.ok && !c.headers && !c.service && (browsed ? /^(HTTP 403|wall page|playwright |chrome |browser )/.test(why(r.reason)) : UNLOCK.test(plainReason) || UNLOCK.test(why(bare(r.reason))));
|
|
2578
|
-
for (const u of unlockable ? unlockers() : []) {
|
|
2579
|
-
const uw = walled(target.url, u);
|
|
2580
|
-
if (uw) {
|
|
2581
|
-
ctx.onTry?.(`${target.url} skipped ${u}: ${wallNote(uw)}`);
|
|
2582
|
-
continue;
|
|
2583
|
-
}
|
|
2584
|
-
r = note(await tryOne(p, target, tier, { unlocker: u }));
|
|
2585
|
-
recordStage(target.url, u, r.ok, r.ok ? "" : r.reason);
|
|
2586
|
-
ctx.onTry?.(r.ok ? `${target.url} ok ${u}` : `${target.url} failed ${u}: ${bare(r.reason)}`);
|
|
2587
|
-
if (!r.ok && accountProblem(bare(r.reason))) ctx.onAlert?.(`${u}: ${bare(r.reason)}`);
|
|
2588
|
-
if (r.ok) break;
|
|
2694
|
+
if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
|
|
2695
|
+
const open = browserStages().filter((b) => !skipped(target.url, stageName(b)));
|
|
2696
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
|
|
2697
|
+
const tasks = open.filter((_, i2) => !down[i2]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
2698
|
+
browsed = tasks.length > 0;
|
|
2699
|
+
const two = await firstOk(tasks, isGone);
|
|
2700
|
+
if (two.won) return two.won;
|
|
2701
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
2589
2702
|
}
|
|
2703
|
+
const unlockable = !gone && !r.ok && !c.headers && !c.service && (browsed ? /^(HTTP 403|wall page|playwright |chrome |browser )/.test(why(reasonOf(r))) : UNLOCK.test(plainReason) || UNLOCK.test(why(bare(reasonOf(r)))));
|
|
2704
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target.url, u));
|
|
2705
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
2706
|
+
if (three.won) return three.won;
|
|
2707
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
2590
2708
|
if (r.ok) return r;
|
|
2591
2709
|
reasons.push(`${gone ?? r.reason}: ${hostOf2(c.url)}`);
|
|
2592
2710
|
if (link && !ctx.tried.has(link) && !NCBI.test(link) && !ordered.slice(i + 1).some((o) => o.url === link)) {
|
|
2593
|
-
ctx.onTry?.(
|
|
2711
|
+
ctx.onTry?.(`pdf link \u2192 ${link}`);
|
|
2594
2712
|
ordered.splice(i + 1, 0, { url: link, version: c.version, source: c.source, host: c.host, pdf: true });
|
|
2595
2713
|
}
|
|
2596
2714
|
}
|
|
@@ -2603,10 +2721,11 @@ function climbsOn(reason, afterBrowser = false) {
|
|
|
2603
2721
|
}
|
|
2604
2722
|
var viaPrefix = (via) => via === "plain" ? "" : "unlocker" in via ? `${via.unlocker}: ` : "proxy" in via ? `${fetchProxyName(via)}: ` : `${stageName({ kind: stageKind(via.browser), label: via.label })}: `;
|
|
2605
2723
|
var bare = (reason) => reason.replace(UNLOCKER_PREFIX, "").replace(STAGE_PREFIX, "");
|
|
2606
|
-
|
|
2724
|
+
var reasonOf = (x) => x.ok ? "" : x.reason;
|
|
2725
|
+
async function tryOne(p, c, tier, via = "plain", signal) {
|
|
2607
2726
|
let got;
|
|
2608
2727
|
try {
|
|
2609
|
-
got = typeof via === "object" && "unlocker" in via ? await unlock(c.url, via.unlocker) : typeof via === "object" ? "proxy" in via ? await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, via.proxy) : await browserFetch(c.url, via.browser) : await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} });
|
|
2728
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(c.url, via.unlocker, signal) : typeof via === "object" ? "proxy" in via ? await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, via.proxy, signal) : await browserFetch(c.url, via.browser, void 0, signal) : await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, void 0, signal);
|
|
2610
2729
|
} catch (e) {
|
|
2611
2730
|
const body = e?.body;
|
|
2612
2731
|
if (c.service && body?.trim()) return { ok: false, reason: `${errMsg(e)} \u2014 ${serviceMessage(Buffer.from(body), e.contentType)}`, url: e?.url };
|
|
@@ -2648,9 +2767,9 @@ function serviceMessage(bytes, contentType = "") {
|
|
|
2648
2767
|
function describe(reason, format, md) {
|
|
2649
2768
|
const words3 = md.split(/\s+/).filter(Boolean).length;
|
|
2650
2769
|
const headings2 = md.split("\n").filter((l) => /^#{2,6}\s/.test(l)).length;
|
|
2651
|
-
const
|
|
2652
|
-
if (reason === "no methods/results") return `no article body (${
|
|
2653
|
-
if (reason === "title missing") return `neither title nor DOI in text (${
|
|
2770
|
+
const seen2 = `${format}, ${words3} words, ${proseWords(md)} in prose, ${headings2} heading${headings2 === 1 ? "" : "s"}`;
|
|
2771
|
+
if (reason === "no methods/results") return `no article body (${seen2})`;
|
|
2772
|
+
if (reason === "title missing") return `neither title nor DOI in text (${seen2})`;
|
|
2654
2773
|
return reason;
|
|
2655
2774
|
}
|
|
2656
2775
|
async function convertBytes(p, bytes, contentType = "") {
|
|
@@ -2739,8 +2858,8 @@ async function pace() {
|
|
|
2739
2858
|
if (calls.length >= PER_WINDOW) await new Promise((r) => setTimeout(r, calls[0] + WINDOW_MS - now2 + 200));
|
|
2740
2859
|
calls.push(Date.now());
|
|
2741
2860
|
}
|
|
2742
|
-
async function coreFetch(url,
|
|
2743
|
-
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${
|
|
2861
|
+
async function coreFetch(url, key2) {
|
|
2862
|
+
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${key2}` };
|
|
2744
2863
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2745
2864
|
await pace();
|
|
2746
2865
|
const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS5), redirect: "follow" });
|
|
@@ -2757,16 +2876,16 @@ async function coreFetch(url, key) {
|
|
|
2757
2876
|
throw new Error("HTTP 429");
|
|
2758
2877
|
}
|
|
2759
2878
|
function coreTier(apiKey2) {
|
|
2760
|
-
const
|
|
2879
|
+
const key2 = apiKey2?.trim();
|
|
2761
2880
|
return {
|
|
2762
2881
|
name: "core",
|
|
2763
2882
|
applies: (p) => p.doi ? true : "no doi",
|
|
2764
2883
|
async run(p, ctx) {
|
|
2765
|
-
if (!
|
|
2884
|
+
if (!key2) return { ...miss(this.name, "needs api key"), skipped: true };
|
|
2766
2885
|
let data;
|
|
2767
2886
|
try {
|
|
2768
2887
|
const q = encodeURIComponent(`doi:"${p.doi}"`);
|
|
2769
|
-
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`,
|
|
2888
|
+
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`, key2));
|
|
2770
2889
|
} catch (e) {
|
|
2771
2890
|
return miss(this.name, errMsg(e));
|
|
2772
2891
|
}
|
|
@@ -2779,10 +2898,10 @@ function coreTier(apiKey2) {
|
|
|
2779
2898
|
}
|
|
2780
2899
|
function coreCandidates(d) {
|
|
2781
2900
|
const out = [];
|
|
2782
|
-
const
|
|
2901
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2783
2902
|
const add = (url, pdf, host3) => {
|
|
2784
|
-
if (!url ||
|
|
2785
|
-
|
|
2903
|
+
if (!url || seen2.has(url)) return;
|
|
2904
|
+
seen2.add(url);
|
|
2786
2905
|
out.push({ url, version: "published", source: "core", host: host3, pdf });
|
|
2787
2906
|
};
|
|
2788
2907
|
for (const w of d.results ?? []) {
|
|
@@ -2815,10 +2934,10 @@ var europepmc = {
|
|
|
2815
2934
|
};
|
|
2816
2935
|
function europepmcCandidates(r, pmcid) {
|
|
2817
2936
|
const out = [];
|
|
2818
|
-
const
|
|
2937
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2819
2938
|
const add = (url, pdf, host3, version) => {
|
|
2820
|
-
if (!url ||
|
|
2821
|
-
|
|
2939
|
+
if (!url || seen2.has(url)) return;
|
|
2940
|
+
seen2.add(url);
|
|
2822
2941
|
out.push({ url, version, source: "europepmc", host: host3, pdf });
|
|
2823
2942
|
};
|
|
2824
2943
|
const id = (r.pmcid ?? pmcid ?? "").toUpperCase() || null;
|
|
@@ -2856,12 +2975,12 @@ var openalex = {
|
|
|
2856
2975
|
};
|
|
2857
2976
|
function openalexCandidates(d) {
|
|
2858
2977
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.locations ?? []].filter((l) => l.is_oa);
|
|
2859
|
-
const
|
|
2978
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2860
2979
|
const out = [];
|
|
2861
2980
|
for (const l of locs) {
|
|
2862
2981
|
for (const [url, pdf] of [[l.pdf_url, true], [l.landing_page_url, false]]) {
|
|
2863
|
-
if (!url ||
|
|
2864
|
-
|
|
2982
|
+
if (!url || seen2.has(url) || /doi\.org\//.test(url)) continue;
|
|
2983
|
+
seen2.add(url);
|
|
2865
2984
|
out.push({ url, version: oaVersion(l.version), source: "openalex", host: l.source?.display_name ?? "unknown", pdf });
|
|
2866
2985
|
}
|
|
2867
2986
|
}
|
|
@@ -2913,17 +3032,17 @@ var hostOf3 = (url) => {
|
|
|
2913
3032
|
};
|
|
2914
3033
|
function tdmCandidates(work, tokens2 = {}, env = process.env) {
|
|
2915
3034
|
const links = (work.message?.link ?? []).filter((l) => l["intended-application"] === "text-mining" && l.URL);
|
|
2916
|
-
const
|
|
3035
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2917
3036
|
const candidates = [];
|
|
2918
3037
|
const missingTokens = /* @__PURE__ */ new Set();
|
|
2919
3038
|
for (const l of links) {
|
|
2920
3039
|
const ct = (l["content-type"] ?? "").toLowerCase();
|
|
2921
|
-
if (
|
|
3040
|
+
if (seen2.has(l.URL)) {
|
|
2922
3041
|
const prev = candidates.find((c) => c.url === l.URL);
|
|
2923
3042
|
if (prev && /pdf/.test(ct)) prev.pdf = true;
|
|
2924
3043
|
continue;
|
|
2925
3044
|
}
|
|
2926
|
-
|
|
3045
|
+
seen2.add(l.URL);
|
|
2927
3046
|
const rule = TOKENED.find((r) => r.host.test(hostOf3(l.URL)));
|
|
2928
3047
|
let headers;
|
|
2929
3048
|
if (rule) {
|
|
@@ -2982,12 +3101,12 @@ var unpaywall = {
|
|
|
2982
3101
|
};
|
|
2983
3102
|
function unpaywallCandidates(d) {
|
|
2984
3103
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.oa_locations ?? []];
|
|
2985
|
-
const
|
|
3104
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2986
3105
|
const out = [];
|
|
2987
3106
|
for (const l of locs) {
|
|
2988
3107
|
for (const [url, pdf] of [[l.url_for_pdf, true], [l.url ?? l.url_for_landing_page, false]]) {
|
|
2989
|
-
if (!url ||
|
|
2990
|
-
|
|
3108
|
+
if (!url || seen2.has(url)) continue;
|
|
3109
|
+
seen2.add(url);
|
|
2991
3110
|
out.push({ url, version: oaVersion(l.version), source: "unpaywall", host: l.host_type ?? "unknown", pdf });
|
|
2992
3111
|
}
|
|
2993
3112
|
}
|
|
@@ -3058,7 +3177,6 @@ var VARIABLES = [
|
|
|
3058
3177
|
"FH_REFRESH_AFTER_DAYS",
|
|
3059
3178
|
"FH_SEARCH_CACHE_DAYS",
|
|
3060
3179
|
"FH_NCBI_API_KEY",
|
|
3061
|
-
"FH_UNLOCKERS",
|
|
3062
3180
|
"FH_ZENROWS_API_KEY",
|
|
3063
3181
|
"FH_ZYTE_API_KEY",
|
|
3064
3182
|
"FH_BRIGHTDATA_API_KEY",
|
|
@@ -3092,16 +3210,16 @@ function resolveTiers(env = process.env) {
|
|
|
3092
3210
|
if (proxyUrl) available.set("proxy", urlTier("proxy", proxyUrl, proxyHeaders(str("FH_PROXY_HEADERS", env))));
|
|
3093
3211
|
const listed = str("FH_TIERS", env);
|
|
3094
3212
|
const order2 = listed ? listed.split(",").map((s) => s.trim()).filter(Boolean) : [...available.keys()];
|
|
3095
|
-
const tiers = [],
|
|
3213
|
+
const tiers = [], seen2 = /* @__PURE__ */ new Set();
|
|
3096
3214
|
for (const name of order2) {
|
|
3097
|
-
if (
|
|
3098
|
-
|
|
3215
|
+
if (seen2.has(name)) continue;
|
|
3216
|
+
seen2.add(name);
|
|
3099
3217
|
const t = available.get(name);
|
|
3100
3218
|
if (t) tiers.push(t);
|
|
3101
3219
|
else if (name === "proxy") problems.push('FH_TIERS: "proxy" listed, but FH_PROXY_URL is unset');
|
|
3102
3220
|
else problems.push(`FH_TIERS: unknown tier "${name}" (built-in: ${BUILTIN.map((t2) => t2.name).join(", ")}; proxy when FH_PROXY_URL is set)`);
|
|
3103
3221
|
}
|
|
3104
|
-
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !
|
|
3222
|
+
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !seen2.has(n)).map((name) => ({ name, enabled: false }))];
|
|
3105
3223
|
return { tiers, all, source: sourceOf("FH_TIERS", env), problems };
|
|
3106
3224
|
}
|
|
3107
3225
|
|
|
@@ -3186,7 +3304,7 @@ var perplexity = {
|
|
|
3186
3304
|
var PROVIDERS = [google, openai, perplexity];
|
|
3187
3305
|
var PROVIDER_NAMES = PROVIDERS.map((p) => p.name);
|
|
3188
3306
|
var providerByName = (name) => PROVIDERS.find((p) => p.name === name) ?? null;
|
|
3189
|
-
var providerForKey = (
|
|
3307
|
+
var providerForKey = (key2) => PROVIDERS.find((p) => p.keyPrefixes.some((k) => key2.startsWith(k))) ?? null;
|
|
3190
3308
|
function providerFor(baseUrl) {
|
|
3191
3309
|
let host3 = "";
|
|
3192
3310
|
try {
|
|
@@ -3198,7 +3316,7 @@ function providerFor(baseUrl) {
|
|
|
3198
3316
|
|
|
3199
3317
|
// src/verify/config.ts
|
|
3200
3318
|
var cleanUrl = (u) => u.replace(/\/+$/, "").replace(/\/(v1beta|v1)(\/decisions)?$|\/decisions$/, "");
|
|
3201
|
-
function
|
|
3319
|
+
function resolve3(env) {
|
|
3202
3320
|
const problems = [];
|
|
3203
3321
|
const field2 = (p, f) => {
|
|
3204
3322
|
const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
|
|
@@ -3217,9 +3335,9 @@ function resolve4(env) {
|
|
|
3217
3335
|
if (sections2.length > 1) return { cfg: null, problems: [`FH_VERIFY_PROVIDER is not set and several sections are filled in (${sections2.map((p) => p.name).join(", ")}): verification is off \u2014 name one`] };
|
|
3218
3336
|
provider = sections2[0] ?? null;
|
|
3219
3337
|
}
|
|
3220
|
-
const [
|
|
3338
|
+
const [key2, keyVar] = field2(provider, "API_KEY");
|
|
3221
3339
|
const [url, urlVar] = field2(provider, "URL");
|
|
3222
|
-
const api_key =
|
|
3340
|
+
const api_key = key2 || null;
|
|
3223
3341
|
let base_url = cleanUrl(url);
|
|
3224
3342
|
if (!base_url && !api_key) {
|
|
3225
3343
|
if (provider) problems.push(`FH_VERIFY_PROVIDER=${provider.name}, but neither ${urlVar} nor ${keyVar} is set: verification is off`);
|
|
@@ -3246,8 +3364,8 @@ function resolve4(env) {
|
|
|
3246
3364
|
}
|
|
3247
3365
|
};
|
|
3248
3366
|
}
|
|
3249
|
-
var verifyConfig = (env = process.env) =>
|
|
3250
|
-
var verifyProblems = (env = process.env) =>
|
|
3367
|
+
var verifyConfig = (env = process.env) => resolve3(env).cfg;
|
|
3368
|
+
var verifyProblems = (env = process.env) => resolve3(env).problems;
|
|
3251
3369
|
function isLocal(baseUrl) {
|
|
3252
3370
|
try {
|
|
3253
3371
|
const h = new URL(baseUrl).hostname;
|
|
@@ -3296,8 +3414,8 @@ function migrateLogName(dir = FH_EVIDENCE_DIR) {
|
|
|
3296
3414
|
}
|
|
3297
3415
|
}
|
|
3298
3416
|
function log(tool, id, message) {
|
|
3299
|
-
const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ");
|
|
3300
|
-
const line = `${stamp()} ${HOST} ${tool} ${id ?? "-"} ${clean2}
|
|
3417
|
+
const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
|
|
3418
|
+
const line = `${stamp()} ${HOST} ${tool} ${(id ?? "-").replace(/https:\/\//g, "")} ${clean2}
|
|
3301
3419
|
`;
|
|
3302
3420
|
try {
|
|
3303
3421
|
mkdirSync4(FH_EVIDENCE_DIR, { recursive: true });
|
|
@@ -3496,8 +3614,8 @@ var human = (n) => {
|
|
|
3496
3614
|
}
|
|
3497
3615
|
return i ? `${n.toFixed(1)} ${u[i]}` : `${n} B`;
|
|
3498
3616
|
};
|
|
3499
|
-
function field(md,
|
|
3500
|
-
const m = new RegExp(`^${
|
|
3617
|
+
function field(md, key2) {
|
|
3618
|
+
const m = new RegExp(`^${key2}:\\s*(.*)$`, "m").exec(md);
|
|
3501
3619
|
return m ? m[1].trim() : "";
|
|
3502
3620
|
}
|
|
3503
3621
|
function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
@@ -3505,10 +3623,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3505
3623
|
evidence_dir: libraryDir,
|
|
3506
3624
|
host: host3,
|
|
3507
3625
|
tiers: tiers.all,
|
|
3508
|
-
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()
|
|
3626
|
+
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
|
|
3509
3627
|
download: downloadInfo(),
|
|
3510
3628
|
verify: verifyInfo(),
|
|
3511
3629
|
unlockers: unlockers().map((provider) => ({ provider })),
|
|
3630
|
+
stages: ownStages(),
|
|
3512
3631
|
entries: 0,
|
|
3513
3632
|
size_bytes: 0,
|
|
3514
3633
|
size: "",
|
|
@@ -3570,6 +3689,10 @@ function noticeTypes(md, metaPath) {
|
|
|
3570
3689
|
}
|
|
3571
3690
|
return out;
|
|
3572
3691
|
}
|
|
3692
|
+
function ownStages() {
|
|
3693
|
+
const f = fetchProxy();
|
|
3694
|
+
return [...f ? [{ name: fetchProxyName(f), host: f.host, port: f.port }] : [], ...browserStages().map((b) => ({ name: stageName(b), host: b.host, port: b.port }))];
|
|
3695
|
+
}
|
|
3573
3696
|
function verifyInfo() {
|
|
3574
3697
|
const v = verifyConfig();
|
|
3575
3698
|
return v ? { provider: v.provider.name, model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
@@ -3597,12 +3720,12 @@ function sections(md) {
|
|
|
3597
3720
|
out[i].bodyEnd = i + 1 < out.length && out[i + 1].start < out[i].end ? out[i + 1].start : out[i].end;
|
|
3598
3721
|
out[i].words = countWords(lines.slice(out[i].start + 1, out[i].end).join("\n"));
|
|
3599
3722
|
}
|
|
3600
|
-
const
|
|
3723
|
+
const seen2 = /* @__PURE__ */ new Map();
|
|
3601
3724
|
for (const s of out) {
|
|
3602
3725
|
const k = s.heading.toLowerCase();
|
|
3603
|
-
|
|
3726
|
+
seen2.set(k, [...seen2.get(k) ?? [], s]);
|
|
3604
3727
|
}
|
|
3605
|
-
for (const group of
|
|
3728
|
+
for (const group of seen2.values()) if (group.length > 1) group.forEach((s, i) => {
|
|
3606
3729
|
s.label = `${s.heading} [${i + 1}/${group.length}]`;
|
|
3607
3730
|
});
|
|
3608
3731
|
return out;
|
|
@@ -4050,9 +4173,9 @@ function metaTags(html) {
|
|
|
4050
4173
|
const head = html.slice(0, 3e5);
|
|
4051
4174
|
for (const m of head.matchAll(/<meta\b[^>]*>/gi)) {
|
|
4052
4175
|
const tag = m[0];
|
|
4053
|
-
const
|
|
4176
|
+
const key2 = (/\b(?:name|property|itemprop)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1] ?? "").toLowerCase();
|
|
4054
4177
|
const val = /\bcontent\s*=\s*"([^"]*)"/i.exec(tag)?.[1] ?? /\bcontent\s*=\s*'([^']*)'/i.exec(tag)?.[1];
|
|
4055
|
-
if (
|
|
4178
|
+
if (key2 && val && val.trim()) out.set(key2, [...out.get(key2) ?? [], val.replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").trim()]);
|
|
4056
4179
|
}
|
|
4057
4180
|
return out;
|
|
4058
4181
|
}
|
|
@@ -4071,8 +4194,8 @@ function pageMeta(html) {
|
|
|
4071
4194
|
};
|
|
4072
4195
|
const type = main ? typeOf(main) : null;
|
|
4073
4196
|
const publisher = names(main?.publisher)[0] ?? tag("og:site_name", "citation_journal_title", "citation_publisher", "dc.publisher")[0] ?? names(site)[0] ?? null;
|
|
4074
|
-
const
|
|
4075
|
-
const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher ||
|
|
4197
|
+
const key2 = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
4198
|
+
const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher || key2(x) !== key2(publisher)));
|
|
4076
4199
|
const fromLd = people(main ? names(main.author) : []);
|
|
4077
4200
|
return {
|
|
4078
4201
|
type: type === "WebPage" ? null : type,
|
|
@@ -4203,11 +4326,11 @@ function isScriptShell(markdownOrHtml) {
|
|
|
4203
4326
|
return { shell: words3 < EMPTY_WORDS || words3 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words3 };
|
|
4204
4327
|
}
|
|
4205
4328
|
var viaName = (via) => typeof via === "object" ? "unlocker" in via ? via.unlocker : "proxy" in via ? fetchProxyName(via) : stageName({ kind: stageKind(via.browser), label: via.label }) : via;
|
|
4206
|
-
async function stage(url, via) {
|
|
4329
|
+
async function stage(url, via, signal) {
|
|
4207
4330
|
const name = viaName(via);
|
|
4208
4331
|
let got;
|
|
4209
4332
|
try {
|
|
4210
|
-
got = typeof via === "object" && "unlocker" in via ? await unlock(url, via.unlocker) : typeof via === "object" ? "proxy" in via ? await fetchBytes(url, BROWSER_HEADERS, via.proxy) : await browserFetch(url, via.browser) : await fetchBytes(url, BROWSER_HEADERS);
|
|
4333
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(url, via.unlocker, signal) : typeof via === "object" ? "proxy" in via ? await fetchBytes(url, BROWSER_HEADERS, via.proxy, signal) : await browserFetch(url, via.browser, void 0, signal) : await fetchBytes(url, BROWSER_HEADERS, void 0, signal);
|
|
4211
4334
|
} catch (e) {
|
|
4212
4335
|
return { ok: false, reason: errMsg(e), url: e?.url, via: name };
|
|
4213
4336
|
}
|
|
@@ -4228,61 +4351,79 @@ async function stage(url, via) {
|
|
|
4228
4351
|
}
|
|
4229
4352
|
return r;
|
|
4230
4353
|
}
|
|
4231
|
-
var climb = async (
|
|
4232
|
-
|
|
4233
|
-
|
|
4354
|
+
var climb = async (given, onTry, onAlert) => {
|
|
4355
|
+
const url = toHttps(given);
|
|
4356
|
+
if (url !== given) onTry?.(`http upgraded \u2192 ${url}`);
|
|
4234
4357
|
let gone;
|
|
4235
|
-
|
|
4236
|
-
|
|
4358
|
+
let shell;
|
|
4359
|
+
const seen2 = (g) => {
|
|
4360
|
+
if (!g.ok) {
|
|
4361
|
+
gone ??= goneReason(g.reason);
|
|
4362
|
+
if (g.shell && !shell) shell = g.shell;
|
|
4363
|
+
}
|
|
4237
4364
|
return g;
|
|
4238
4365
|
};
|
|
4239
|
-
|
|
4240
|
-
const
|
|
4241
|
-
|
|
4242
|
-
|
|
4366
|
+
const write = (line) => onTry?.(line);
|
|
4367
|
+
const run = (target2, via, name, after) => {
|
|
4368
|
+
let req = null;
|
|
4369
|
+
return {
|
|
4370
|
+
name,
|
|
4371
|
+
abort: (why) => req?.abort(why),
|
|
4372
|
+
go: async () => {
|
|
4373
|
+
req = openRequest(write, name);
|
|
4374
|
+
const g = await stage(target2, via, req.signal);
|
|
4375
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted", via: name };
|
|
4376
|
+
seen2(g);
|
|
4377
|
+
if (via !== "fetch") recordStage(target2, name, g.ok, g.ok ? "" : g.reason);
|
|
4378
|
+
after?.(g);
|
|
4379
|
+
req.close(g.ok ? `ok ${name}` : `failed ${name}: ${g.reason}`);
|
|
4380
|
+
if (!g.ok && (g.reason.startsWith(MISMATCH) || accountProblem(g.reason))) onAlert?.(`${name}: ${g.reason}`);
|
|
4381
|
+
return g;
|
|
4382
|
+
}
|
|
4383
|
+
};
|
|
4384
|
+
};
|
|
4385
|
+
const skipped = (target2, name) => {
|
|
4386
|
+
const w = walled(target2, name);
|
|
4387
|
+
if (w) onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4388
|
+
return !!w;
|
|
4389
|
+
};
|
|
4390
|
+
const hostDown = async (host3, port, name) => {
|
|
4391
|
+
const h = await hostState(host3, port, (s) => onAlert?.(`${name}: ${downNote(s)}`));
|
|
4392
|
+
if (!h.up) onTry?.(`skipped ${name}: ${downNote(h)}`);
|
|
4393
|
+
return !h.up;
|
|
4394
|
+
};
|
|
4395
|
+
const f = fetchProxy();
|
|
4396
|
+
const proxyName = f ? fetchProxyName(f) : "";
|
|
4397
|
+
const first = [run(url, "fetch", "fetch", (g) => {
|
|
4398
|
+
if (!g.ok && g.url && g.url !== url) onTry?.(`redirect \u2192 ${g.url}`);
|
|
4399
|
+
})];
|
|
4400
|
+
if (f && !skipped(url, proxyName) && !await hostDown(f.host, f.port, proxyName)) first.push(run(url, { proxy: f.proxy, label: f.label }, proxyName));
|
|
4401
|
+
const isGone = (g) => g.ok ? null : goneReason(g.reason) ?? null;
|
|
4402
|
+
const one = await firstOk(first, isGone);
|
|
4403
|
+
if (one.won) return one.won;
|
|
4404
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
4405
|
+
const firstReason = plain3.ok ? void 0 : plain3.reason;
|
|
4406
|
+
const target = !plain3.ok && plain3.url && plain3.url !== url ? plain3.url : url;
|
|
4407
|
+
let r = one.results[1] ?? plain3;
|
|
4243
4408
|
const plainVia = (g) => g.via === "fetch" || g.via.startsWith("fetch-proxy ");
|
|
4244
4409
|
const met = (g, re) => re.test(g.ok ? "" : g.reason) || plainVia(g) && re.test(firstReason ?? "");
|
|
4245
4410
|
const escalates = (g) => !g.ok && (!plainVia(g) || met(g, /^(HTTP 403|HTTP 429|wall page|script shell)/));
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
if (
|
|
4249
|
-
const
|
|
4250
|
-
const
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
onTry?.(r.ok ? `ok ${name}` : `failed ${name}: ${r.reason}`);
|
|
4257
|
-
}
|
|
4258
|
-
}
|
|
4259
|
-
for (const b of browserStages()) {
|
|
4260
|
-
if (!escalates(r)) break;
|
|
4261
|
-
const name = stageName(b);
|
|
4262
|
-
const w = walled(target, name);
|
|
4263
|
-
if (w) {
|
|
4264
|
-
onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4265
|
-
continue;
|
|
4266
|
-
}
|
|
4267
|
-
r = seen(await stage(target, { browser: b.endpoint, label: b.label }));
|
|
4268
|
-
recordStage(target, name, r.ok, r.ok ? "" : r.reason);
|
|
4269
|
-
if (!r.ok && r.shell && !shell) shell = r.shell;
|
|
4270
|
-
onTry?.(r.ok ? `ok ${name}` : `failed ${name}: ${r.reason}`);
|
|
4271
|
-
if (!r.ok && r.reason.startsWith(MISMATCH)) onAlert?.(`${name}: ${r.reason}`);
|
|
4411
|
+
const notThere = () => gone ? { ...r, ok: false, reason: gone, via: r.via } : null;
|
|
4412
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4413
|
+
if (escalates(r)) {
|
|
4414
|
+
const open = browserStages().filter((b) => !skipped(target, stageName(b)));
|
|
4415
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b))));
|
|
4416
|
+
const tasks = open.filter((_, i) => !down[i]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
4417
|
+
const two = await firstOk(tasks, isGone);
|
|
4418
|
+
if (two.won) return two.won;
|
|
4419
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
4420
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4272
4421
|
}
|
|
4273
4422
|
const unlockable = !r.ok && (!plainVia(r) || met(r, /^(HTTP 403|wall page|script shell)/));
|
|
4274
|
-
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
continue;
|
|
4279
|
-
}
|
|
4280
|
-
r = seen(await stage(target, { unlocker: u }));
|
|
4281
|
-
recordStage(target, u, r.ok, r.ok ? "" : r.reason);
|
|
4282
|
-
onTry?.(r.ok ? `ok ${u}` : `failed ${u}: ${r.reason}`);
|
|
4283
|
-
if (!r.ok && accountProblem(r.reason)) onAlert?.(`${u}: ${r.reason}`);
|
|
4284
|
-
if (r.ok) break;
|
|
4285
|
-
}
|
|
4423
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target, u));
|
|
4424
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
4425
|
+
if (three.won) return three.won;
|
|
4426
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
4286
4427
|
if (!r.ok && shell) {
|
|
4287
4428
|
onTry?.("shell kept: no stage rendered the page, the script shell is served");
|
|
4288
4429
|
return shell;
|
|
@@ -4654,7 +4795,7 @@ ${id}
|
|
|
4654
4795
|
${model}
|
|
4655
4796
|
${threshold}
|
|
4656
4797
|
${text4}`).slice(0, 16);
|
|
4657
|
-
var verdictFile = (libraryDir,
|
|
4798
|
+
var verdictFile = (libraryDir, key2) => join10(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4658
4799
|
function readVerdict(file3) {
|
|
4659
4800
|
if (!existsSync9(file3)) return null;
|
|
4660
4801
|
try {
|
|
@@ -4771,7 +4912,7 @@ function normalizeQuery(q) {
|
|
|
4771
4912
|
return out;
|
|
4772
4913
|
}
|
|
4773
4914
|
var searchKey = (q) => createHash4("sha1").update(JSON.stringify(["clinicaltrials", q.query ?? "", q.intervention ?? "", q.condition ?? "", q.status, q.sort, q.max_results])).digest("hex").slice(0, 16);
|
|
4774
|
-
var searchFile = (libraryDir,
|
|
4915
|
+
var searchFile = (libraryDir, key2) => join11(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4775
4916
|
function searchUrl(q) {
|
|
4776
4917
|
const p = new URLSearchParams();
|
|
4777
4918
|
if (q.query) p.set("query.term", q.query);
|
|
@@ -5394,11 +5535,11 @@ function registerTools(server2) {
|
|
|
5394
5535
|
);
|
|
5395
5536
|
const inflight2 = /* @__PURE__ */ new Map();
|
|
5396
5537
|
function addEntry(id) {
|
|
5397
|
-
const
|
|
5398
|
-
let p = inflight2.get(
|
|
5538
|
+
const key2 = parseId(id).requested;
|
|
5539
|
+
let p = inflight2.get(key2);
|
|
5399
5540
|
if (!p) {
|
|
5400
|
-
p = addEntryNow(id).finally(() => inflight2.delete(
|
|
5401
|
-
inflight2.set(
|
|
5541
|
+
p = addEntryNow(id).finally(() => inflight2.delete(key2));
|
|
5542
|
+
inflight2.set(key2, p);
|
|
5402
5543
|
}
|
|
5403
5544
|
return p;
|
|
5404
5545
|
}
|
|
@@ -5683,12 +5824,13 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5683
5824
|
);
|
|
5684
5825
|
server2.tool(
|
|
5685
5826
|
"fh_info",
|
|
5686
|
-
"The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk; per type (pmid, doi, dailymed, nct) the entries by level (full_text, abstract, title) and retractions; counts of retracted and not-citable entries and of errata, expressions of concern and updates; the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages, whether an unlocker is configured; the configuration and where each value came from \u2014 environment, .env or default, never the value (config); the decision model behind fh_verify_claim and whether it answers right now (verify); the unlockers
|
|
5827
|
+
"The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk; per type (pmid, doi, dailymed, nct) the entries by level (full_text, abstract, title) and retractions; counts of retracted and not-citable entries and of errata, expressions of concern and updates; the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages, whether an unlocker is configured; the configuration and where each value came from \u2014 environment, .env or default, never the value (config); the decision model behind fh_verify_claim and whether it answers right now (verify); the unlockers and whether each answers right now (unlockers); our own stage hosts \u2014 fetch proxy, Playwright servers, Chrome \u2014 and whether each is reachable right now (stages); this server's cache hits and misses for fh_verify_claim and fh_fetch_url since it started (cache).",
|
|
5687
5828
|
{},
|
|
5688
5829
|
async () => {
|
|
5689
5830
|
const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
|
|
5690
5831
|
const cfg = verifyConfig();
|
|
5691
5832
|
const unlockerChecks = Promise.all(info.unlockers.map((u) => unlockerHealth(u.provider)));
|
|
5833
|
+
const stageChecks = Promise.all(info.stages.map((s2) => probe(s2.host, s2.port)));
|
|
5692
5834
|
if (info.verify && cfg) {
|
|
5693
5835
|
const t0 = Date.now();
|
|
5694
5836
|
try {
|
|
@@ -5699,7 +5841,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5699
5841
|
}
|
|
5700
5842
|
}
|
|
5701
5843
|
info.unlockers = (await unlockerChecks).map((h, i) => ({ ...info.unlockers[i], ...h }));
|
|
5702
|
-
|
|
5844
|
+
info.stages = (await stageChecks).map((h, i) => ({ ...info.stages[i], up: h.up, ms: h.ms, error: h.error }));
|
|
5845
|
+
log("info", null, `entries=${info.entries}${info.verify ? ` verify ${info.verify.model} ${info.verify.ok ? `ok ${info.verify.ms} ms` : `down: ${info.verify.error}`}` : " verify not configured"}${info.unlockers.map((u) => ` unlocker ${u.provider} ${u.ok ? `ok ${u.ms} ms` : `down: ${u.error}`}`).join("")}${info.stages.map((s2) => ` stage ${s2.name} ${s2.up ? `up ${s2.ms} ms` : `down: ${s2.error}`}`).join("")}`);
|
|
5703
5846
|
const s = currentStats();
|
|
5704
5847
|
const cache = s ? { since: s.started, verify: s.verify, fetch: s.fetch, search: s.search, pubmed: s.pubmed } : null;
|
|
5705
5848
|
return { content: [{ type: "text", text: compact2({ package: pkg.name, version: pkg.version, log: LOG_FILE, ...info, cache }) }] };
|
|
@@ -5889,6 +6032,7 @@ registerTools(server);
|
|
|
5889
6032
|
startStats(pkg);
|
|
5890
6033
|
migrateLogName();
|
|
5891
6034
|
log("startup", null, `${pkg.name} ${pkg.version}`);
|
|
5892
|
-
|
|
6035
|
+
process.on("exit", abandonAll);
|
|
6036
|
+
for (const problem of [...resolveTiers().problems, ...verifyProblems()]) log("startup", null, `!! ${problem}`);
|
|
5893
6037
|
var transport = new StdioServerTransport();
|
|
5894
6038
|
await server.connect(transport);
|