evidence-mcp-dev 0.2.44 → 0.2.46
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 +438 -247
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -9,9 +9,16 @@ console.debug = toStderr;
|
|
|
9
9
|
// src/env.ts
|
|
10
10
|
import { existsSync, readFileSync } from "fs";
|
|
11
11
|
import { join, resolve } from "path";
|
|
12
|
-
function
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
function argEnv(argv = process.argv) {
|
|
13
|
+
for (let i = 0; i < argv.length; i++) {
|
|
14
|
+
if (argv[i] === "--env" && argv[i + 1]) return argv[i + 1];
|
|
15
|
+
if (argv[i].startsWith("--env=")) return argv[i].slice(6) || null;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
function dotenvFile(env = process.env, argv = process.argv) {
|
|
20
|
+
const named = argEnv(argv)?.trim() || env.FH_ENV?.trim();
|
|
21
|
+
if (named) return resolve(named);
|
|
15
22
|
if (existsSync(resolve(".env"))) return resolve(".env");
|
|
16
23
|
const lib = env.FH_EVIDENCE_DIR?.trim() || (existsSync("/evidence") ? "/evidence" : "evidence");
|
|
17
24
|
return join(resolve(lib), ".env");
|
|
@@ -62,6 +69,84 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
62
69
|
// src/http.ts
|
|
63
70
|
import { fetch as undiciFetch } from "undici";
|
|
64
71
|
|
|
72
|
+
// src/race.ts
|
|
73
|
+
var OPEN = /* @__PURE__ */ new Set();
|
|
74
|
+
function openRequest(write, name) {
|
|
75
|
+
const ctrl = new AbortController();
|
|
76
|
+
let closed = false;
|
|
77
|
+
const entry = { abandon: () => {
|
|
78
|
+
if (!closed) {
|
|
79
|
+
closed = true;
|
|
80
|
+
write(`abandoned ${name}: server stopped`);
|
|
81
|
+
}
|
|
82
|
+
} };
|
|
83
|
+
OPEN.add(entry);
|
|
84
|
+
write(`try ${name}`);
|
|
85
|
+
return {
|
|
86
|
+
signal: ctrl.signal,
|
|
87
|
+
abort: (why) => {
|
|
88
|
+
if (closed) return;
|
|
89
|
+
closed = true;
|
|
90
|
+
OPEN.delete(entry);
|
|
91
|
+
write(`aborted ${name}: ${why}`);
|
|
92
|
+
ctrl.abort(new Error(`aborted: ${why}`));
|
|
93
|
+
},
|
|
94
|
+
close: (line) => {
|
|
95
|
+
if (closed) return false;
|
|
96
|
+
closed = true;
|
|
97
|
+
OPEN.delete(entry);
|
|
98
|
+
write(line);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function abandonAll() {
|
|
104
|
+
for (const e of OPEN) e.abandon();
|
|
105
|
+
OPEN.clear();
|
|
106
|
+
}
|
|
107
|
+
async function firstOk(tasks, decisive = () => null) {
|
|
108
|
+
if (!tasks.length) return { won: null, results: [] };
|
|
109
|
+
const results2 = new Array(tasks.length);
|
|
110
|
+
const settled = new Array(tasks.length).fill(false);
|
|
111
|
+
return new Promise((resolve4) => {
|
|
112
|
+
let left = tasks.length, done = false;
|
|
113
|
+
const end = (won, why) => {
|
|
114
|
+
done = true;
|
|
115
|
+
tasks.forEach((t, j) => {
|
|
116
|
+
if (!settled[j]) t.abort(why);
|
|
117
|
+
});
|
|
118
|
+
resolve4({ won, results: results2 });
|
|
119
|
+
};
|
|
120
|
+
tasks.forEach((task, i) => {
|
|
121
|
+
task.go().then((r) => {
|
|
122
|
+
results2[i] = r;
|
|
123
|
+
settled[i] = true;
|
|
124
|
+
if (done) return;
|
|
125
|
+
const gone = r.ok ? null : decisive(r);
|
|
126
|
+
if (r.ok) end(r, `${task.name} won`);
|
|
127
|
+
else if (gone) end(null, `${task.name}: ${gone}`);
|
|
128
|
+
else if (--left === 0) {
|
|
129
|
+
done = true;
|
|
130
|
+
resolve4({ won: null, results: results2 });
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function timeoutOr(ms, signal) {
|
|
137
|
+
if (!signal) return AbortSignal.timeout(ms);
|
|
138
|
+
const c = new AbortController();
|
|
139
|
+
const t = setTimeout(() => c.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), ms);
|
|
140
|
+
if (signal.aborted) {
|
|
141
|
+
clearTimeout(t);
|
|
142
|
+
c.abort(signal.reason);
|
|
143
|
+
} else signal.addEventListener("abort", () => {
|
|
144
|
+
clearTimeout(t);
|
|
145
|
+
c.abort(signal.reason);
|
|
146
|
+
}, { once: true });
|
|
147
|
+
return c.signal;
|
|
148
|
+
}
|
|
149
|
+
|
|
65
150
|
// src/contact.ts
|
|
66
151
|
var DEFAULT = "hello@forever-healthy.org";
|
|
67
152
|
var contactEmail = (env = process.env) => str("FH_CONTACT_EMAIL", env) || DEFAULT;
|
|
@@ -266,10 +351,16 @@ async function closeBrowsers() {
|
|
|
266
351
|
}
|
|
267
352
|
}
|
|
268
353
|
}
|
|
269
|
-
async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
354
|
+
async function browserFetch(url, endpoint, cfg = browserConfig(), signal) {
|
|
355
|
+
url = toHttps(url);
|
|
270
356
|
const ctx = await context(endpoint, cfg);
|
|
271
357
|
touchIdle();
|
|
272
358
|
const page = await ctx.newPage();
|
|
359
|
+
const onAbort = () => {
|
|
360
|
+
page.close().catch(() => void 0);
|
|
361
|
+
};
|
|
362
|
+
if (signal?.aborted) onAbort();
|
|
363
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
273
364
|
try {
|
|
274
365
|
let pdfBest = null;
|
|
275
366
|
const pdfReads = [];
|
|
@@ -314,6 +405,8 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
314
405
|
}
|
|
315
406
|
if (!download2) await pause(DOWNLOAD_WAIT_MS / 5);
|
|
316
407
|
}
|
|
408
|
+
const landed = download2 ? download2.url() : page.url();
|
|
409
|
+
if (/^http:\/\//i.test(landed)) throw new Error(`${PLAIN_HTTP} (${new URL(landed).hostname})`);
|
|
317
410
|
if (download2) {
|
|
318
411
|
const d = download2;
|
|
319
412
|
const stream = await d.createReadStream();
|
|
@@ -350,6 +443,7 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
350
443
|
const html = await page.content();
|
|
351
444
|
return { bytes: Buffer.from(html, "utf8"), contentType: contentType || "text/html", url: page.url(), via: "page" };
|
|
352
445
|
} finally {
|
|
446
|
+
signal?.removeEventListener("abort", onAbort);
|
|
353
447
|
await page.close().catch(() => void 0);
|
|
354
448
|
if (isRemote(endpoint)) await ctx.storageState({ path: stateFile(endpoint) }).catch(() => void 0);
|
|
355
449
|
}
|
|
@@ -386,12 +480,17 @@ function httpReason(status, body) {
|
|
|
386
480
|
return m ? `HTTP ${status} ${m[1] ?? m[2]}` : `HTTP ${status}`;
|
|
387
481
|
}
|
|
388
482
|
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
|
-
|
|
483
|
+
var toHttps = (url) => url.replace(/^http:\/\//i, "https://");
|
|
484
|
+
var PLAIN_HTTP = "redirected to plain http";
|
|
485
|
+
var isPlain = (url) => /^http:\/\//i.test(url);
|
|
486
|
+
async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy, signal) {
|
|
487
|
+
url = toHttps(url);
|
|
390
488
|
let last = "unknown error", finalUrl = "", lastBody = "", lastType = "";
|
|
391
489
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
392
490
|
try {
|
|
393
|
-
const init = { headers, signal:
|
|
491
|
+
const init = { headers, signal: timeoutOr(TIMEOUT_MS, signal), redirect: "follow" };
|
|
394
492
|
const res = proxy ? await undiciFetch(url, { ...init, dispatcher: proxyAgent(proxy) }) : await fetch(url, init);
|
|
493
|
+
if (res.url && isPlain(res.url)) throw Object.assign(new Error(`${PLAIN_HTTP} (${new URL(res.url).hostname})`), { final: true });
|
|
395
494
|
if (res.ok) return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "", url: res.url };
|
|
396
495
|
lastBody = (await res.text().catch(() => "")).slice(0, 4e3);
|
|
397
496
|
lastType = res.headers.get("content-type") ?? "";
|
|
@@ -399,9 +498,11 @@ async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy) {
|
|
|
399
498
|
finalUrl = res.url;
|
|
400
499
|
if (res.status !== 429 && res.status < 500) break;
|
|
401
500
|
} catch (e) {
|
|
501
|
+
if (e.final) throw e;
|
|
402
502
|
const code = e?.cause;
|
|
403
503
|
last = e instanceof Error && e.name === "TimeoutError" ? "timeout" : e instanceof Error ? e.message + (code?.code ? ` (${code.code})` : code?.message ? ` (${code.message})` : "") : String(e);
|
|
404
504
|
}
|
|
505
|
+
if (signal?.aborted) break;
|
|
405
506
|
await new Promise((r) => setTimeout(r, 1500));
|
|
406
507
|
}
|
|
407
508
|
throw Object.assign(new Error(last), finalUrl ? { url: finalUrl } : {}, lastBody ? { body: lastBody, contentType: lastType } : {});
|
|
@@ -492,6 +593,36 @@ function checkFulltext(md, title, titleSource, doi, trusted = false, pdf = false
|
|
|
492
593
|
return { ok: true };
|
|
493
594
|
}
|
|
494
595
|
|
|
596
|
+
// src/hosts.ts
|
|
597
|
+
import { connect } from "net";
|
|
598
|
+
var UP_MS = 6e4;
|
|
599
|
+
var DOWN_MS = 5 * 6e4;
|
|
600
|
+
var PROBE_MS = 3e3;
|
|
601
|
+
var seen = /* @__PURE__ */ new Map();
|
|
602
|
+
var key = (host3, port) => `${host3}:${port}`;
|
|
603
|
+
function probe(host3, port, timeoutMs = PROBE_MS) {
|
|
604
|
+
const t0 = Date.now();
|
|
605
|
+
return new Promise((resolve4) => {
|
|
606
|
+
const s = connect({ host: host3, port });
|
|
607
|
+
const done = (error) => {
|
|
608
|
+
s.destroy();
|
|
609
|
+
resolve4({ up: !error, ms: Date.now() - t0, at: Date.now(), error });
|
|
610
|
+
};
|
|
611
|
+
s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
|
|
612
|
+
s.once("connect", () => done(null));
|
|
613
|
+
s.once("error", (e) => done(e.code ?? e.message));
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
async function hostState(host3, port, onDown) {
|
|
617
|
+
const k = key(host3, port), now2 = Date.now(), old = seen.get(k);
|
|
618
|
+
if (old && now2 - old.at < (old.up ? UP_MS : DOWN_MS)) return old;
|
|
619
|
+
const s = await probe(host3, port);
|
|
620
|
+
seen.set(k, s);
|
|
621
|
+
if (!s.up && (!old || old.up)) onDown?.(s);
|
|
622
|
+
return s;
|
|
623
|
+
}
|
|
624
|
+
var downNote = (s) => `host down (${s.error}, since ${new Date(s.at).toTimeString().slice(0, 5)})`;
|
|
625
|
+
|
|
495
626
|
// src/html.ts
|
|
496
627
|
import TurndownService from "turndown";
|
|
497
628
|
import { gfm } from "@joplin/turndown-plugin-gfm";
|
|
@@ -1197,13 +1328,13 @@ var COMPOUND_PREFIX = /* @__PURE__ */ new Set([
|
|
|
1197
1328
|
function dehyphenate(text4) {
|
|
1198
1329
|
if (!text4.includes(BREAK)) return text4;
|
|
1199
1330
|
const lower = text4.toLowerCase();
|
|
1200
|
-
const
|
|
1331
|
+
const seen2 = (s) => new RegExp(`(?<![a-z])${s}(?![a-z])`).test(lower);
|
|
1201
1332
|
return text4.replace(/([A-Za-z]+)\u0000\n([A-Za-z]+)/g, (m, x, y) => {
|
|
1202
1333
|
if (!/^[a-z]/.test(y)) return `${x}-${y}`;
|
|
1203
1334
|
if (SUSPENDED.has(y.toLowerCase())) return `${x}- ${y}`;
|
|
1204
1335
|
const hyph = `${x}-${y}`.toLowerCase(), joined3 = `${x}${y}`.toLowerCase();
|
|
1205
|
-
if (
|
|
1206
|
-
if (
|
|
1336
|
+
if (seen2(hyph)) return `${x}-${y}`;
|
|
1337
|
+
if (seen2(joined3)) return `${x}${y}`;
|
|
1207
1338
|
return COMPOUND_PREFIX.has(x.toLowerCase()) ? `${x}-${y}` : `${x}${y}`;
|
|
1208
1339
|
}).replace(/\u0000\n/g, "-\n").replace(/\u0000/g, "-");
|
|
1209
1340
|
}
|
|
@@ -1219,7 +1350,7 @@ import { request as httpsRequest } from "https";
|
|
|
1219
1350
|
var ENDPOINT = "https://api.brightdata.com/request";
|
|
1220
1351
|
var TIMEOUT_MS2 = 6e4;
|
|
1221
1352
|
function post(url, init) {
|
|
1222
|
-
return new Promise((
|
|
1353
|
+
return new Promise((resolve4, reject) => {
|
|
1223
1354
|
const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
|
|
1224
1355
|
const chunks = [];
|
|
1225
1356
|
res.on("data", (c) => chunks.push(c));
|
|
@@ -1227,7 +1358,7 @@ function post(url, init) {
|
|
|
1227
1358
|
res.on("end", () => {
|
|
1228
1359
|
const body = Buffer.concat(chunks);
|
|
1229
1360
|
const status = res.statusCode ?? 0;
|
|
1230
|
-
|
|
1361
|
+
resolve4({
|
|
1231
1362
|
ok: status >= 200 && status < 300,
|
|
1232
1363
|
status,
|
|
1233
1364
|
headers: { get: (name) => {
|
|
@@ -1243,7 +1374,7 @@ function post(url, init) {
|
|
|
1243
1374
|
});
|
|
1244
1375
|
}
|
|
1245
1376
|
var apiKey = () => process.env.FH_BRIGHTDATA_API_KEY?.trim() || "";
|
|
1246
|
-
async function get(url, postImpl = post) {
|
|
1377
|
+
async function get(url, postImpl = post, signal) {
|
|
1247
1378
|
const token = apiKey();
|
|
1248
1379
|
if (!token) throw new Error("not configured");
|
|
1249
1380
|
const zone = process.env.FH_BRIGHTDATA_ZONE?.trim() || "mcp_unlocker";
|
|
@@ -1251,22 +1382,22 @@ async function get(url, postImpl = post) {
|
|
|
1251
1382
|
method: "POST",
|
|
1252
1383
|
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
|
|
1253
1384
|
body: JSON.stringify({ zone, url, format: "raw" }),
|
|
1254
|
-
signal:
|
|
1385
|
+
signal: timeoutOr(TIMEOUT_MS2, signal)
|
|
1255
1386
|
});
|
|
1256
1387
|
const why = res.headers.get("x-brd-err-msg") ?? res.headers.get("x-brd-error");
|
|
1257
1388
|
if (!res.ok) throw new Error(`unlocker HTTP ${res.status}${why ? `: ${why}` : ""}`);
|
|
1258
1389
|
if (res.headers.get("x-brd-error")) throw new Error(`unlocker refused: ${why}`);
|
|
1259
1390
|
return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "" };
|
|
1260
1391
|
}
|
|
1261
|
-
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url) => get(url) };
|
|
1392
|
+
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url, signal) => get(url, post, signal) };
|
|
1262
1393
|
|
|
1263
1394
|
// src/unlock/zenrows.ts
|
|
1264
1395
|
var TIMEOUT_MS3 = 6e4;
|
|
1265
1396
|
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(
|
|
1397
|
+
async function get2(url, fetchImpl = fetch, signal) {
|
|
1398
|
+
const key2 = process.env.FH_ZENROWS_API_KEY?.trim();
|
|
1399
|
+
if (!key2) throw new Error("not configured");
|
|
1400
|
+
const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(key2)}&url=${encodeURIComponent(url)}&mode=auto`, { signal: timeoutOr(TIMEOUT_MS3, signal) });
|
|
1270
1401
|
const bytes = Buffer.from(await r.arrayBuffer());
|
|
1271
1402
|
if (!r.ok) {
|
|
1272
1403
|
let why = "";
|
|
@@ -1280,18 +1411,18 @@ async function get2(url, fetchImpl = fetch) {
|
|
|
1280
1411
|
}
|
|
1281
1412
|
return { bytes, contentType: r.headers.get("content-type") ?? "" };
|
|
1282
1413
|
}
|
|
1283
|
-
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url) => get2(url) };
|
|
1414
|
+
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url, signal) => get2(url, fetch, signal) };
|
|
1284
1415
|
|
|
1285
1416
|
// src/unlock/zyte.ts
|
|
1286
1417
|
var TIMEOUT_MS4 = 6e4;
|
|
1287
1418
|
var ACCOUNT2 = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1288
|
-
async function get3(url, fetchImpl = fetch) {
|
|
1289
|
-
const
|
|
1290
|
-
if (!
|
|
1419
|
+
async function get3(url, fetchImpl = fetch, signal) {
|
|
1420
|
+
const key2 = process.env.FH_ZYTE_API_KEY?.trim();
|
|
1421
|
+
if (!key2) throw new Error("not configured");
|
|
1291
1422
|
const r = await fetchImpl("https://api.zyte.com/v1/extract", {
|
|
1292
1423
|
method: "POST",
|
|
1293
|
-
signal:
|
|
1294
|
-
headers: { authorization: `Basic ${Buffer.from(`${
|
|
1424
|
+
signal: timeoutOr(TIMEOUT_MS4, signal),
|
|
1425
|
+
headers: { authorization: `Basic ${Buffer.from(`${key2}:`).toString("base64")}`, "content-type": "application/json" },
|
|
1295
1426
|
body: JSON.stringify({ url, httpResponseBody: true, httpResponseHeaders: true })
|
|
1296
1427
|
});
|
|
1297
1428
|
const j = await r.json().catch(() => ({}));
|
|
@@ -1303,7 +1434,7 @@ async function get3(url, fetchImpl = fetch) {
|
|
|
1303
1434
|
const contentType = j.httpResponseHeaders?.find((h) => h.name.toLowerCase() === "content-type")?.value ?? "";
|
|
1304
1435
|
return { bytes: Buffer.from(j.httpResponseBody ?? "", "base64"), contentType };
|
|
1305
1436
|
}
|
|
1306
|
-
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url) => get3(url) };
|
|
1437
|
+
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url, signal) => get3(url, fetch, signal) };
|
|
1307
1438
|
|
|
1308
1439
|
// src/unlock.ts
|
|
1309
1440
|
var SERVICES = [zenrows, zyte, brightdata];
|
|
@@ -1311,25 +1442,12 @@ var UNLOCKER_NAMES = SERVICES.map((s) => s.name);
|
|
|
1311
1442
|
var UNLOCKER_PREFIX = new RegExp(`^(${UNLOCKER_NAMES.join("|")}): `);
|
|
1312
1443
|
var accountProblem = (reason) => /^unlocker (HTTP 4\d\d|refused)/.test(reason);
|
|
1313
1444
|
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;
|
|
1445
|
+
var unlockers = (env = process.env) => SERVICES.filter((s) => keyed(s, env)).map((s) => s.name);
|
|
1328
1446
|
var unlockerConfigured = () => unlockers().length > 0;
|
|
1329
|
-
async function unlock(url, name) {
|
|
1447
|
+
async function unlock(url, name, signal) {
|
|
1330
1448
|
const s = SERVICES.find((x) => x.name === name);
|
|
1331
1449
|
if (!s) throw new Error(`unknown unlocker ${name}`);
|
|
1332
|
-
return s.get(url);
|
|
1450
|
+
return s.get(url, signal);
|
|
1333
1451
|
}
|
|
1334
1452
|
var HEALTH_URL = "https://example.com/";
|
|
1335
1453
|
async function unlockerHealth(name, unlockImpl = unlock) {
|
|
@@ -1344,7 +1462,7 @@ async function unlockerHealth(name, unlockImpl = unlock) {
|
|
|
1344
1462
|
}
|
|
1345
1463
|
|
|
1346
1464
|
// src/walls.ts
|
|
1347
|
-
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
1465
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync2 } from "fs";
|
|
1348
1466
|
import { join as join5 } from "path";
|
|
1349
1467
|
|
|
1350
1468
|
// src/entry.ts
|
|
@@ -2461,7 +2579,7 @@ var host = (url) => {
|
|
|
2461
2579
|
return "";
|
|
2462
2580
|
}
|
|
2463
2581
|
};
|
|
2464
|
-
var file = (dir, h) => join5(dir, "walls", `${h.replace(/[^a-z0-9.-]/g, "_")}.json`);
|
|
2582
|
+
var file = (dir, h) => join5(dir, ".walls", `${h.replace(/[^a-z0-9.-]/g, "_")}.json`);
|
|
2465
2583
|
var legacy = (stage2) => stage2.replace(/^(playwright|chrome) /, "browser ");
|
|
2466
2584
|
function read(dir, h) {
|
|
2467
2585
|
try {
|
|
@@ -2493,12 +2611,21 @@ function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
|
|
|
2493
2611
|
delete all[stage2];
|
|
2494
2612
|
} else all[stage2] = { streak: (all[stage2]?.streak ?? 0) + 1, date: now(), reason: why };
|
|
2495
2613
|
try {
|
|
2496
|
-
mkdirSync3(join5(dir, "walls"), { recursive: true });
|
|
2614
|
+
mkdirSync3(join5(dir, ".walls"), { recursive: true });
|
|
2497
2615
|
writeAtomic(file(dir, h), JSON.stringify(all) + "\n");
|
|
2498
2616
|
} catch {
|
|
2499
2617
|
}
|
|
2500
2618
|
}
|
|
2501
2619
|
var wallNote = (r) => `${r.reason} ${r.streak}\xD7 on this host, last ${r.date.slice(0, 10)}`;
|
|
2620
|
+
function migrateWalls(dir = FH_EVIDENCE_DIR) {
|
|
2621
|
+
const a = join5(dir, "walls"), b = join5(dir, ".walls");
|
|
2622
|
+
if (existsSync5(a) && !existsSync5(b)) {
|
|
2623
|
+
try {
|
|
2624
|
+
renameSync2(a, b);
|
|
2625
|
+
} catch {
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2502
2629
|
|
|
2503
2630
|
// src/tiers/tier.ts
|
|
2504
2631
|
var looked = (t, p, ctx) => ctx.lookups?.get(t.name) ?? t.lookup(p);
|
|
@@ -2526,7 +2653,11 @@ function order(candidates) {
|
|
|
2526
2653
|
async function download(tier, p, candidates, ctx) {
|
|
2527
2654
|
const usable = candidates.filter((c) => !NCBI.test(c.url));
|
|
2528
2655
|
if (!usable.length && candidates.length) return miss(tier, "only pmc copies (covered by the pmc tier)");
|
|
2529
|
-
const ordered = order(usable
|
|
2656
|
+
const ordered = order(usable.map((c) => {
|
|
2657
|
+
const u = toHttps(c.url);
|
|
2658
|
+
if (u !== c.url) ctx.onTry?.(`http upgraded: ${c.url} \u2192 ${u}`);
|
|
2659
|
+
return u === c.url ? c : { ...c, url: u };
|
|
2660
|
+
})).filter((c) => !ctx.tried.has(c.url));
|
|
2530
2661
|
if (!ordered.length) return miss(tier, "only copies already tried");
|
|
2531
2662
|
const reasons = [];
|
|
2532
2663
|
for (let i = 0; i < ordered.length; i++) {
|
|
@@ -2539,58 +2670,61 @@ async function download(tier, p, candidates, ctx) {
|
|
|
2539
2670
|
if (!x.ok && !gone && /\bHTTP (404|410)\b/.test(x.reason)) gone = x.reason;
|
|
2540
2671
|
return x;
|
|
2541
2672
|
};
|
|
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
2673
|
const why = (reason) => reason.replace(/^not a pdf \((.*)\)$/, "$1");
|
|
2547
|
-
const
|
|
2674
|
+
const run = (cand, via, name) => {
|
|
2675
|
+
let req = null;
|
|
2676
|
+
return { name, abort: (why2) => req?.abort(why2), go: async () => {
|
|
2677
|
+
req = openRequest((line) => ctx.onTry?.(`${line} ${cand.url}`), name);
|
|
2678
|
+
const x0 = await tryOne(p, cand, tier, via, req.signal);
|
|
2679
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted" };
|
|
2680
|
+
const x = note(x0);
|
|
2681
|
+
if (via !== "plain") recordStage(cand.url, name, x.ok, x.ok ? "" : x.reason);
|
|
2682
|
+
req.close(x.ok ? `ok ${name}` : `failed ${name}: ${via === "plain" ? x.reason : bare(x.reason)}`);
|
|
2683
|
+
if (!x.ok && (bare(x.reason).startsWith(MISMATCH) || accountProblem(bare(x.reason)))) ctx.onAlert?.(`${name}: ${bare(x.reason)}`);
|
|
2684
|
+
return x;
|
|
2685
|
+
} };
|
|
2686
|
+
};
|
|
2687
|
+
const skipped = (url, name) => {
|
|
2688
|
+
const w = walled(url, name);
|
|
2689
|
+
if (w) ctx.onTry?.(`skipped ${name}: ${wallNote(w)} ${url}`);
|
|
2690
|
+
return !!w;
|
|
2691
|
+
};
|
|
2692
|
+
const hostDown = async (host3, port, name, url) => {
|
|
2693
|
+
const h = await hostState(host3, port, (s) => ctx.onAlert?.(`${name}: ${downNote(s)}`));
|
|
2694
|
+
if (!h.up) ctx.onTry?.(`skipped ${name}: ${downNote(h)} ${url}`);
|
|
2695
|
+
return !h.up;
|
|
2696
|
+
};
|
|
2548
2697
|
const f = fetchProxy();
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2698
|
+
const first = [run(c, "plain", "fetch")];
|
|
2699
|
+
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)));
|
|
2700
|
+
const isGone = (x) => x.ok ? null : x.reason.match(/\bHTTP (404|410)\b/)?.[0] ?? null;
|
|
2701
|
+
const one = await firstOk(first, isGone);
|
|
2702
|
+
if (one.won) return one.won;
|
|
2703
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
2704
|
+
const target = !plain3.ok && plain3.url && plain3.url !== c.url ? { ...c, url: plain3.url } : c;
|
|
2705
|
+
if (target !== c) ctx.onTry?.(`redirect ${c.url} \u2192 ${target.url}`);
|
|
2706
|
+
const plainReason = why(reasonOf(plain3));
|
|
2707
|
+
let r = one.results[1] ?? plain3;
|
|
2559
2708
|
const UNLOCK = /^(HTTP 403|wall page)/;
|
|
2560
2709
|
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;
|
|
2710
|
+
if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
|
|
2711
|
+
const open = browserStages().filter((b) => !skipped(target.url, stageName(b)));
|
|
2712
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
|
|
2713
|
+
const tasks = open.filter((_, i2) => !down[i2]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
2714
|
+
browsed = tasks.length > 0;
|
|
2715
|
+
const two = await firstOk(tasks, isGone);
|
|
2716
|
+
if (two.won) return two.won;
|
|
2717
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
2589
2718
|
}
|
|
2719
|
+
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)))));
|
|
2720
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target.url, u));
|
|
2721
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
2722
|
+
if (three.won) return three.won;
|
|
2723
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
2590
2724
|
if (r.ok) return r;
|
|
2591
2725
|
reasons.push(`${gone ?? r.reason}: ${hostOf2(c.url)}`);
|
|
2592
2726
|
if (link && !ctx.tried.has(link) && !NCBI.test(link) && !ordered.slice(i + 1).some((o) => o.url === link)) {
|
|
2593
|
-
ctx.onTry?.(
|
|
2727
|
+
ctx.onTry?.(`pdf link \u2192 ${link}`);
|
|
2594
2728
|
ordered.splice(i + 1, 0, { url: link, version: c.version, source: c.source, host: c.host, pdf: true });
|
|
2595
2729
|
}
|
|
2596
2730
|
}
|
|
@@ -2603,10 +2737,11 @@ function climbsOn(reason, afterBrowser = false) {
|
|
|
2603
2737
|
}
|
|
2604
2738
|
var viaPrefix = (via) => via === "plain" ? "" : "unlocker" in via ? `${via.unlocker}: ` : "proxy" in via ? `${fetchProxyName(via)}: ` : `${stageName({ kind: stageKind(via.browser), label: via.label })}: `;
|
|
2605
2739
|
var bare = (reason) => reason.replace(UNLOCKER_PREFIX, "").replace(STAGE_PREFIX, "");
|
|
2606
|
-
|
|
2740
|
+
var reasonOf = (x) => x.ok ? "" : x.reason;
|
|
2741
|
+
async function tryOne(p, c, tier, via = "plain", signal) {
|
|
2607
2742
|
let got;
|
|
2608
2743
|
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 ?? {} });
|
|
2744
|
+
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
2745
|
} catch (e) {
|
|
2611
2746
|
const body = e?.body;
|
|
2612
2747
|
if (c.service && body?.trim()) return { ok: false, reason: `${errMsg(e)} \u2014 ${serviceMessage(Buffer.from(body), e.contentType)}`, url: e?.url };
|
|
@@ -2648,9 +2783,9 @@ function serviceMessage(bytes, contentType = "") {
|
|
|
2648
2783
|
function describe(reason, format, md) {
|
|
2649
2784
|
const words3 = md.split(/\s+/).filter(Boolean).length;
|
|
2650
2785
|
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 (${
|
|
2786
|
+
const seen2 = `${format}, ${words3} words, ${proseWords(md)} in prose, ${headings2} heading${headings2 === 1 ? "" : "s"}`;
|
|
2787
|
+
if (reason === "no methods/results") return `no article body (${seen2})`;
|
|
2788
|
+
if (reason === "title missing") return `neither title nor DOI in text (${seen2})`;
|
|
2654
2789
|
return reason;
|
|
2655
2790
|
}
|
|
2656
2791
|
async function convertBytes(p, bytes, contentType = "") {
|
|
@@ -2739,8 +2874,8 @@ async function pace() {
|
|
|
2739
2874
|
if (calls.length >= PER_WINDOW) await new Promise((r) => setTimeout(r, calls[0] + WINDOW_MS - now2 + 200));
|
|
2740
2875
|
calls.push(Date.now());
|
|
2741
2876
|
}
|
|
2742
|
-
async function coreFetch(url,
|
|
2743
|
-
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${
|
|
2877
|
+
async function coreFetch(url, key2) {
|
|
2878
|
+
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${key2}` };
|
|
2744
2879
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2745
2880
|
await pace();
|
|
2746
2881
|
const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS5), redirect: "follow" });
|
|
@@ -2757,16 +2892,16 @@ async function coreFetch(url, key) {
|
|
|
2757
2892
|
throw new Error("HTTP 429");
|
|
2758
2893
|
}
|
|
2759
2894
|
function coreTier(apiKey2) {
|
|
2760
|
-
const
|
|
2895
|
+
const key2 = apiKey2?.trim();
|
|
2761
2896
|
return {
|
|
2762
2897
|
name: "core",
|
|
2763
2898
|
applies: (p) => p.doi ? true : "no doi",
|
|
2764
2899
|
async run(p, ctx) {
|
|
2765
|
-
if (!
|
|
2900
|
+
if (!key2) return { ...miss(this.name, "needs api key"), skipped: true };
|
|
2766
2901
|
let data;
|
|
2767
2902
|
try {
|
|
2768
2903
|
const q = encodeURIComponent(`doi:"${p.doi}"`);
|
|
2769
|
-
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`,
|
|
2904
|
+
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`, key2));
|
|
2770
2905
|
} catch (e) {
|
|
2771
2906
|
return miss(this.name, errMsg(e));
|
|
2772
2907
|
}
|
|
@@ -2779,10 +2914,10 @@ function coreTier(apiKey2) {
|
|
|
2779
2914
|
}
|
|
2780
2915
|
function coreCandidates(d) {
|
|
2781
2916
|
const out = [];
|
|
2782
|
-
const
|
|
2917
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2783
2918
|
const add = (url, pdf, host3) => {
|
|
2784
|
-
if (!url ||
|
|
2785
|
-
|
|
2919
|
+
if (!url || seen2.has(url)) return;
|
|
2920
|
+
seen2.add(url);
|
|
2786
2921
|
out.push({ url, version: "published", source: "core", host: host3, pdf });
|
|
2787
2922
|
};
|
|
2788
2923
|
for (const w of d.results ?? []) {
|
|
@@ -2815,10 +2950,10 @@ var europepmc = {
|
|
|
2815
2950
|
};
|
|
2816
2951
|
function europepmcCandidates(r, pmcid) {
|
|
2817
2952
|
const out = [];
|
|
2818
|
-
const
|
|
2953
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2819
2954
|
const add = (url, pdf, host3, version) => {
|
|
2820
|
-
if (!url ||
|
|
2821
|
-
|
|
2955
|
+
if (!url || seen2.has(url)) return;
|
|
2956
|
+
seen2.add(url);
|
|
2822
2957
|
out.push({ url, version, source: "europepmc", host: host3, pdf });
|
|
2823
2958
|
};
|
|
2824
2959
|
const id = (r.pmcid ?? pmcid ?? "").toUpperCase() || null;
|
|
@@ -2856,12 +2991,12 @@ var openalex = {
|
|
|
2856
2991
|
};
|
|
2857
2992
|
function openalexCandidates(d) {
|
|
2858
2993
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.locations ?? []].filter((l) => l.is_oa);
|
|
2859
|
-
const
|
|
2994
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2860
2995
|
const out = [];
|
|
2861
2996
|
for (const l of locs) {
|
|
2862
2997
|
for (const [url, pdf] of [[l.pdf_url, true], [l.landing_page_url, false]]) {
|
|
2863
|
-
if (!url ||
|
|
2864
|
-
|
|
2998
|
+
if (!url || seen2.has(url) || /doi\.org\//.test(url)) continue;
|
|
2999
|
+
seen2.add(url);
|
|
2865
3000
|
out.push({ url, version: oaVersion(l.version), source: "openalex", host: l.source?.display_name ?? "unknown", pdf });
|
|
2866
3001
|
}
|
|
2867
3002
|
}
|
|
@@ -2913,17 +3048,17 @@ var hostOf3 = (url) => {
|
|
|
2913
3048
|
};
|
|
2914
3049
|
function tdmCandidates(work, tokens2 = {}, env = process.env) {
|
|
2915
3050
|
const links = (work.message?.link ?? []).filter((l) => l["intended-application"] === "text-mining" && l.URL);
|
|
2916
|
-
const
|
|
3051
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2917
3052
|
const candidates = [];
|
|
2918
3053
|
const missingTokens = /* @__PURE__ */ new Set();
|
|
2919
3054
|
for (const l of links) {
|
|
2920
3055
|
const ct = (l["content-type"] ?? "").toLowerCase();
|
|
2921
|
-
if (
|
|
3056
|
+
if (seen2.has(l.URL)) {
|
|
2922
3057
|
const prev = candidates.find((c) => c.url === l.URL);
|
|
2923
3058
|
if (prev && /pdf/.test(ct)) prev.pdf = true;
|
|
2924
3059
|
continue;
|
|
2925
3060
|
}
|
|
2926
|
-
|
|
3061
|
+
seen2.add(l.URL);
|
|
2927
3062
|
const rule = TOKENED.find((r) => r.host.test(hostOf3(l.URL)));
|
|
2928
3063
|
let headers;
|
|
2929
3064
|
if (rule) {
|
|
@@ -2982,12 +3117,12 @@ var unpaywall = {
|
|
|
2982
3117
|
};
|
|
2983
3118
|
function unpaywallCandidates(d) {
|
|
2984
3119
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.oa_locations ?? []];
|
|
2985
|
-
const
|
|
3120
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2986
3121
|
const out = [];
|
|
2987
3122
|
for (const l of locs) {
|
|
2988
3123
|
for (const [url, pdf] of [[l.url_for_pdf, true], [l.url ?? l.url_for_landing_page, false]]) {
|
|
2989
|
-
if (!url ||
|
|
2990
|
-
|
|
3124
|
+
if (!url || seen2.has(url)) continue;
|
|
3125
|
+
seen2.add(url);
|
|
2991
3126
|
out.push({ url, version: oaVersion(l.version), source: "unpaywall", host: l.host_type ?? "unknown", pdf });
|
|
2992
3127
|
}
|
|
2993
3128
|
}
|
|
@@ -3025,6 +3160,7 @@ function urlTier(name, template, headers) {
|
|
|
3025
3160
|
// src/config.ts
|
|
3026
3161
|
var VARIABLES = [
|
|
3027
3162
|
"FH_EVIDENCE_DIR",
|
|
3163
|
+
"FH_LOG_KEEP_DAYS",
|
|
3028
3164
|
"FH_ENV",
|
|
3029
3165
|
"FH_TIERS",
|
|
3030
3166
|
"FH_CONTACT_EMAIL",
|
|
@@ -3058,7 +3194,6 @@ var VARIABLES = [
|
|
|
3058
3194
|
"FH_REFRESH_AFTER_DAYS",
|
|
3059
3195
|
"FH_SEARCH_CACHE_DAYS",
|
|
3060
3196
|
"FH_NCBI_API_KEY",
|
|
3061
|
-
"FH_UNLOCKERS",
|
|
3062
3197
|
"FH_ZENROWS_API_KEY",
|
|
3063
3198
|
"FH_ZYTE_API_KEY",
|
|
3064
3199
|
"FH_BRIGHTDATA_API_KEY",
|
|
@@ -3092,16 +3227,16 @@ function resolveTiers(env = process.env) {
|
|
|
3092
3227
|
if (proxyUrl) available.set("proxy", urlTier("proxy", proxyUrl, proxyHeaders(str("FH_PROXY_HEADERS", env))));
|
|
3093
3228
|
const listed = str("FH_TIERS", env);
|
|
3094
3229
|
const order2 = listed ? listed.split(",").map((s) => s.trim()).filter(Boolean) : [...available.keys()];
|
|
3095
|
-
const tiers = [],
|
|
3230
|
+
const tiers = [], seen2 = /* @__PURE__ */ new Set();
|
|
3096
3231
|
for (const name of order2) {
|
|
3097
|
-
if (
|
|
3098
|
-
|
|
3232
|
+
if (seen2.has(name)) continue;
|
|
3233
|
+
seen2.add(name);
|
|
3099
3234
|
const t = available.get(name);
|
|
3100
3235
|
if (t) tiers.push(t);
|
|
3101
3236
|
else if (name === "proxy") problems.push('FH_TIERS: "proxy" listed, but FH_PROXY_URL is unset');
|
|
3102
3237
|
else problems.push(`FH_TIERS: unknown tier "${name}" (built-in: ${BUILTIN.map((t2) => t2.name).join(", ")}; proxy when FH_PROXY_URL is set)`);
|
|
3103
3238
|
}
|
|
3104
|
-
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !
|
|
3239
|
+
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !seen2.has(n)).map((name) => ({ name, enabled: false }))];
|
|
3105
3240
|
return { tiers, all, source: sourceOf("FH_TIERS", env), problems };
|
|
3106
3241
|
}
|
|
3107
3242
|
|
|
@@ -3186,7 +3321,7 @@ var perplexity = {
|
|
|
3186
3321
|
var PROVIDERS = [google, openai, perplexity];
|
|
3187
3322
|
var PROVIDER_NAMES = PROVIDERS.map((p) => p.name);
|
|
3188
3323
|
var providerByName = (name) => PROVIDERS.find((p) => p.name === name) ?? null;
|
|
3189
|
-
var providerForKey = (
|
|
3324
|
+
var providerForKey = (key2) => PROVIDERS.find((p) => p.keyPrefixes.some((k) => key2.startsWith(k))) ?? null;
|
|
3190
3325
|
function providerFor(baseUrl) {
|
|
3191
3326
|
let host3 = "";
|
|
3192
3327
|
try {
|
|
@@ -3198,7 +3333,7 @@ function providerFor(baseUrl) {
|
|
|
3198
3333
|
|
|
3199
3334
|
// src/verify/config.ts
|
|
3200
3335
|
var cleanUrl = (u) => u.replace(/\/+$/, "").replace(/\/(v1beta|v1)(\/decisions)?$|\/decisions$/, "");
|
|
3201
|
-
function
|
|
3336
|
+
function resolve3(env) {
|
|
3202
3337
|
const problems = [];
|
|
3203
3338
|
const field2 = (p, f) => {
|
|
3204
3339
|
const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
|
|
@@ -3217,9 +3352,9 @@ function resolve4(env) {
|
|
|
3217
3352
|
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
3353
|
provider = sections2[0] ?? null;
|
|
3219
3354
|
}
|
|
3220
|
-
const [
|
|
3355
|
+
const [key2, keyVar] = field2(provider, "API_KEY");
|
|
3221
3356
|
const [url, urlVar] = field2(provider, "URL");
|
|
3222
|
-
const api_key =
|
|
3357
|
+
const api_key = key2 || null;
|
|
3223
3358
|
let base_url = cleanUrl(url);
|
|
3224
3359
|
if (!base_url && !api_key) {
|
|
3225
3360
|
if (provider) problems.push(`FH_VERIFY_PROVIDER=${provider.name}, but neither ${urlVar} nor ${keyVar} is set: verification is off`);
|
|
@@ -3246,8 +3381,8 @@ function resolve4(env) {
|
|
|
3246
3381
|
}
|
|
3247
3382
|
};
|
|
3248
3383
|
}
|
|
3249
|
-
var verifyConfig = (env = process.env) =>
|
|
3250
|
-
var verifyProblems = (env = process.env) =>
|
|
3384
|
+
var verifyConfig = (env = process.env) => resolve3(env).cfg;
|
|
3385
|
+
var verifyProblems = (env = process.env) => resolve3(env).problems;
|
|
3251
3386
|
function isLocal(baseUrl) {
|
|
3252
3387
|
try {
|
|
3253
3388
|
const h = new URL(baseUrl).hostname;
|
|
@@ -3258,18 +3393,30 @@ function isLocal(baseUrl) {
|
|
|
3258
3393
|
}
|
|
3259
3394
|
|
|
3260
3395
|
// src/log.ts
|
|
3261
|
-
import { appendFileSync, existsSync as
|
|
3396
|
+
import { appendFileSync, existsSync as existsSync6, mkdirSync as mkdirSync4, readdirSync as readdirSync2, renameSync as renameSync3, statSync, unlinkSync as unlinkSync2 } from "fs";
|
|
3262
3397
|
import { hostname } from "os";
|
|
3263
|
-
import { join as join6 } from "path";
|
|
3398
|
+
import { basename as basename2, dirname as dirname2, join as join6 } from "path";
|
|
3264
3399
|
var HOST = hostname();
|
|
3265
|
-
var
|
|
3400
|
+
var LOG_DIR = join6(FH_EVIDENCE_DIR, "logs");
|
|
3401
|
+
var LOG_FILE = join6(LOG_DIR, "evidence.log");
|
|
3266
3402
|
function stamp() {
|
|
3267
3403
|
const d = /* @__PURE__ */ new Date();
|
|
3268
3404
|
const p = (n) => String(n).padStart(2, "0");
|
|
3269
3405
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
3270
3406
|
}
|
|
3271
|
-
var LOG_MAX_BYTES =
|
|
3272
|
-
|
|
3407
|
+
var LOG_MAX_BYTES = 5 * 1024 * 1024;
|
|
3408
|
+
var DAY_MS = 864e5;
|
|
3409
|
+
var stampOf = (t) => {
|
|
3410
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
3411
|
+
return `${t.getFullYear()}-${p(t.getMonth() + 1)}-${p(t.getDate())}-${p(t.getHours())}${p(t.getMinutes())}${p(t.getSeconds())}`;
|
|
3412
|
+
};
|
|
3413
|
+
function datedName(file3, when) {
|
|
3414
|
+
const base = join6(dirname2(file3), `${basename2(file3, ".log")}-${stampOf(when)}`);
|
|
3415
|
+
let name = `${base}.log`;
|
|
3416
|
+
for (let n = 2; existsSync6(name); n++) name = `${base}-${n}.log`;
|
|
3417
|
+
return name;
|
|
3418
|
+
}
|
|
3419
|
+
function rotateIfLarge(file3, max = LOG_MAX_BYTES, keepDays = num("FH_LOG_KEEP_DAYS", 7)) {
|
|
3273
3420
|
let size = 0;
|
|
3274
3421
|
try {
|
|
3275
3422
|
size = statSync(file3).size;
|
|
@@ -3277,30 +3424,47 @@ function rotateIfLarge(file3, max = LOG_MAX_BYTES) {
|
|
|
3277
3424
|
return false;
|
|
3278
3425
|
}
|
|
3279
3426
|
if (size <= max) return false;
|
|
3427
|
+
let moved = false;
|
|
3280
3428
|
try {
|
|
3281
|
-
|
|
3282
|
-
|
|
3429
|
+
renameSync3(file3, datedName(file3, /* @__PURE__ */ new Date()));
|
|
3430
|
+
moved = true;
|
|
3431
|
+
} catch {
|
|
3432
|
+
}
|
|
3433
|
+
pruneLogs(file3, keepDays);
|
|
3434
|
+
return moved;
|
|
3435
|
+
}
|
|
3436
|
+
function pruneLogs(file3, keepDays, now2 = Date.now()) {
|
|
3437
|
+
const dir = dirname2(file3), stem2 = basename2(file3, ".log");
|
|
3438
|
+
try {
|
|
3439
|
+
const old1 = `${file3}.1`;
|
|
3440
|
+
if (existsSync6(old1)) renameSync3(old1, datedName(file3, statSync(old1).mtime));
|
|
3441
|
+
for (const f of readdirSync2(dir)) {
|
|
3442
|
+
if (!f.startsWith(`${stem2}-`) || !f.endsWith(".log")) continue;
|
|
3443
|
+
const path = join6(dir, f);
|
|
3444
|
+
if (now2 - statSync(path).mtimeMs > keepDays * DAY_MS) unlinkSync2(path);
|
|
3445
|
+
}
|
|
3283
3446
|
} catch {
|
|
3284
|
-
return false;
|
|
3285
3447
|
}
|
|
3286
3448
|
}
|
|
3287
3449
|
function migrateLogName(dir = FH_EVIDENCE_DIR) {
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3450
|
+
const logs = join6(dir, "logs");
|
|
3451
|
+
for (const [from, to] of [["evidence.log", "evidence.log"], ["evidence.log.1", "evidence.log.1"], ["library.log", "evidence.log"], ["library.log.1", "evidence.log.1"]]) {
|
|
3452
|
+
const a = join6(dir, from), b = join6(logs, to);
|
|
3453
|
+
if (existsSync6(a) && !existsSync6(b)) {
|
|
3291
3454
|
try {
|
|
3292
|
-
|
|
3455
|
+
mkdirSync4(logs, { recursive: true });
|
|
3456
|
+
renameSync3(a, b);
|
|
3293
3457
|
} catch {
|
|
3294
3458
|
}
|
|
3295
3459
|
}
|
|
3296
3460
|
}
|
|
3297
3461
|
}
|
|
3298
3462
|
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}
|
|
3463
|
+
const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
|
|
3464
|
+
const line = `${stamp()} ${HOST} ${tool} ${(id ?? "-").replace(/https:\/\//g, "")} ${clean2}
|
|
3301
3465
|
`;
|
|
3302
3466
|
try {
|
|
3303
|
-
mkdirSync4(
|
|
3467
|
+
mkdirSync4(LOG_DIR, { recursive: true });
|
|
3304
3468
|
rotateIfLarge(LOG_FILE);
|
|
3305
3469
|
appendFileSync(LOG_FILE, line);
|
|
3306
3470
|
} catch {
|
|
@@ -3308,7 +3472,7 @@ function log(tool, id, message) {
|
|
|
3308
3472
|
}
|
|
3309
3473
|
|
|
3310
3474
|
// src/stats.ts
|
|
3311
|
-
import { mkdirSync as mkdirSync5, readdirSync as
|
|
3475
|
+
import { mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync2, unlinkSync as unlinkSync3 } from "fs";
|
|
3312
3476
|
import { join as join7 } from "path";
|
|
3313
3477
|
var HEARTBEAT_MS = 5 * 6e4;
|
|
3314
3478
|
var STALE_MS = 20 * 6e4;
|
|
@@ -3322,7 +3486,7 @@ function startStats(pkg2, libraryDir = FH_EVIDENCE_DIR) {
|
|
|
3322
3486
|
setInterval(publish, HEARTBEAT_MS).unref();
|
|
3323
3487
|
const stop = () => {
|
|
3324
3488
|
try {
|
|
3325
|
-
if (file2)
|
|
3489
|
+
if (file2) unlinkSync3(file2);
|
|
3326
3490
|
} catch {
|
|
3327
3491
|
}
|
|
3328
3492
|
};
|
|
@@ -3334,7 +3498,7 @@ function sweep(dir, staleMs = STALE_MS) {
|
|
|
3334
3498
|
let n = 0;
|
|
3335
3499
|
let names2;
|
|
3336
3500
|
try {
|
|
3337
|
-
names2 =
|
|
3501
|
+
names2 = readdirSync3(dir);
|
|
3338
3502
|
} catch {
|
|
3339
3503
|
return 0;
|
|
3340
3504
|
}
|
|
@@ -3343,7 +3507,7 @@ function sweep(dir, staleMs = STALE_MS) {
|
|
|
3343
3507
|
const p = join7(dir, name);
|
|
3344
3508
|
try {
|
|
3345
3509
|
if (Date.now() - statSync2(p).mtimeMs > staleMs) {
|
|
3346
|
-
|
|
3510
|
+
unlinkSync3(p);
|
|
3347
3511
|
n++;
|
|
3348
3512
|
}
|
|
3349
3513
|
} catch {
|
|
@@ -3367,7 +3531,7 @@ function publish() {
|
|
|
3367
3531
|
}
|
|
3368
3532
|
|
|
3369
3533
|
// src/tools.ts
|
|
3370
|
-
import { existsSync as
|
|
3534
|
+
import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs";
|
|
3371
3535
|
import { z } from "zod";
|
|
3372
3536
|
|
|
3373
3537
|
// src/cascade.ts
|
|
@@ -3477,11 +3641,11 @@ function libraryIdForUrl(raw) {
|
|
|
3477
3641
|
}
|
|
3478
3642
|
|
|
3479
3643
|
// src/info.ts
|
|
3480
|
-
import { existsSync as
|
|
3481
|
-
import { dirname as
|
|
3644
|
+
import { existsSync as existsSync7, readdirSync as readdirSync4, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
|
|
3645
|
+
import { dirname as dirname3, join as join8 } from "path";
|
|
3482
3646
|
function* metaFiles(dir) {
|
|
3483
|
-
if (!
|
|
3484
|
-
for (const name of
|
|
3647
|
+
if (!existsSync7(dir)) return;
|
|
3648
|
+
for (const name of readdirSync4(dir)) {
|
|
3485
3649
|
const p = join8(dir, name);
|
|
3486
3650
|
if (statSync3(p).isDirectory()) yield* metaFiles(p);
|
|
3487
3651
|
else if (name.endsWith("-meta.md")) yield p;
|
|
@@ -3496,8 +3660,8 @@ var human = (n) => {
|
|
|
3496
3660
|
}
|
|
3497
3661
|
return i ? `${n.toFixed(1)} ${u[i]}` : `${n} B`;
|
|
3498
3662
|
};
|
|
3499
|
-
function field(md,
|
|
3500
|
-
const m = new RegExp(`^${
|
|
3663
|
+
function field(md, key2) {
|
|
3664
|
+
const m = new RegExp(`^${key2}:\\s*(.*)$`, "m").exec(md);
|
|
3501
3665
|
return m ? m[1].trim() : "";
|
|
3502
3666
|
}
|
|
3503
3667
|
function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
@@ -3505,10 +3669,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3505
3669
|
evidence_dir: libraryDir,
|
|
3506
3670
|
host: host3,
|
|
3507
3671
|
tiers: tiers.all,
|
|
3508
|
-
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()
|
|
3672
|
+
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
|
|
3509
3673
|
download: downloadInfo(),
|
|
3510
3674
|
verify: verifyInfo(),
|
|
3511
3675
|
unlockers: unlockers().map((provider) => ({ provider })),
|
|
3676
|
+
stages: ownStages(),
|
|
3512
3677
|
entries: 0,
|
|
3513
3678
|
size_bytes: 0,
|
|
3514
3679
|
size: "",
|
|
@@ -3521,7 +3686,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3521
3686
|
concerns: 0,
|
|
3522
3687
|
updates: 0
|
|
3523
3688
|
};
|
|
3524
|
-
for (const type of
|
|
3689
|
+
for (const type of existsSync7(libraryDir) ? readdirSync4(libraryDir) : []) {
|
|
3525
3690
|
const typeDir = join8(libraryDir, type);
|
|
3526
3691
|
if (!statSync3(typeDir).isDirectory()) continue;
|
|
3527
3692
|
for (const meta of metaFiles(typeDir)) {
|
|
@@ -3534,8 +3699,8 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3534
3699
|
const t = info.types[type] ??= { entries: 0, full_text: 0, abstract: 0, title: 0, retracted: 0 };
|
|
3535
3700
|
t.entries++;
|
|
3536
3701
|
if (level === "full_text" || level === "abstract" || level === "title") t[level]++;
|
|
3537
|
-
const dir =
|
|
3538
|
-
for (const f of
|
|
3702
|
+
const dir = dirname3(meta);
|
|
3703
|
+
for (const f of readdirSync4(dir)) {
|
|
3539
3704
|
try {
|
|
3540
3705
|
const st = statSync3(join8(dir, f));
|
|
3541
3706
|
if (st.isFile()) info.size_bytes += st.size;
|
|
@@ -3570,6 +3735,10 @@ function noticeTypes(md, metaPath) {
|
|
|
3570
3735
|
}
|
|
3571
3736
|
return out;
|
|
3572
3737
|
}
|
|
3738
|
+
function ownStages() {
|
|
3739
|
+
const f = fetchProxy();
|
|
3740
|
+
return [...f ? [{ name: fetchProxyName(f), host: f.host, port: f.port }] : [], ...browserStages().map((b) => ({ name: stageName(b), host: b.host, port: b.port }))];
|
|
3741
|
+
}
|
|
3573
3742
|
function verifyInfo() {
|
|
3574
3743
|
const v = verifyConfig();
|
|
3575
3744
|
return v ? { provider: v.provider.name, model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
@@ -3597,12 +3766,12 @@ function sections(md) {
|
|
|
3597
3766
|
out[i].bodyEnd = i + 1 < out.length && out[i + 1].start < out[i].end ? out[i + 1].start : out[i].end;
|
|
3598
3767
|
out[i].words = countWords(lines.slice(out[i].start + 1, out[i].end).join("\n"));
|
|
3599
3768
|
}
|
|
3600
|
-
const
|
|
3769
|
+
const seen2 = /* @__PURE__ */ new Map();
|
|
3601
3770
|
for (const s of out) {
|
|
3602
3771
|
const k = s.heading.toLowerCase();
|
|
3603
|
-
|
|
3772
|
+
seen2.set(k, [...seen2.get(k) ?? [], s]);
|
|
3604
3773
|
}
|
|
3605
|
-
for (const group of
|
|
3774
|
+
for (const group of seen2.values()) if (group.length > 1) group.forEach((s, i) => {
|
|
3606
3775
|
s.label = `${s.heading} [${i + 1}/${group.length}]`;
|
|
3607
3776
|
});
|
|
3608
3777
|
return out;
|
|
@@ -3991,7 +4160,7 @@ function parseCsl(json2) {
|
|
|
3991
4160
|
|
|
3992
4161
|
// src/urlfetch.ts
|
|
3993
4162
|
import { createHash as createHash2 } from "crypto";
|
|
3994
|
-
import { existsSync as
|
|
4163
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6 } from "fs";
|
|
3995
4164
|
import { join as join9 } from "path";
|
|
3996
4165
|
|
|
3997
4166
|
// src/pagemeta.ts
|
|
@@ -4050,9 +4219,9 @@ function metaTags(html) {
|
|
|
4050
4219
|
const head = html.slice(0, 3e5);
|
|
4051
4220
|
for (const m of head.matchAll(/<meta\b[^>]*>/gi)) {
|
|
4052
4221
|
const tag = m[0];
|
|
4053
|
-
const
|
|
4222
|
+
const key2 = (/\b(?:name|property|itemprop)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1] ?? "").toLowerCase();
|
|
4054
4223
|
const val = /\bcontent\s*=\s*"([^"]*)"/i.exec(tag)?.[1] ?? /\bcontent\s*=\s*'([^']*)'/i.exec(tag)?.[1];
|
|
4055
|
-
if (
|
|
4224
|
+
if (key2 && val && val.trim()) out.set(key2, [...out.get(key2) ?? [], val.replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").trim()]);
|
|
4056
4225
|
}
|
|
4057
4226
|
return out;
|
|
4058
4227
|
}
|
|
@@ -4071,8 +4240,8 @@ function pageMeta(html) {
|
|
|
4071
4240
|
};
|
|
4072
4241
|
const type = main ? typeOf(main) : null;
|
|
4073
4242
|
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 ||
|
|
4243
|
+
const key2 = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
4244
|
+
const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher || key2(x) !== key2(publisher)));
|
|
4076
4245
|
const fromLd = people(main ? names(main.author) : []);
|
|
4077
4246
|
return {
|
|
4078
4247
|
type: type === "WebPage" ? null : type,
|
|
@@ -4155,7 +4324,7 @@ function renderUrlMeta(m) {
|
|
|
4155
4324
|
return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
|
|
4156
4325
|
}
|
|
4157
4326
|
function readUrlMeta(p) {
|
|
4158
|
-
if (!
|
|
4327
|
+
if (!existsSync8(p.meta)) return null;
|
|
4159
4328
|
const md = readFileSync6(p.meta, "utf8");
|
|
4160
4329
|
const f = (k) => {
|
|
4161
4330
|
const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
|
|
@@ -4203,11 +4372,11 @@ function isScriptShell(markdownOrHtml) {
|
|
|
4203
4372
|
return { shell: words3 < EMPTY_WORDS || words3 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words3 };
|
|
4204
4373
|
}
|
|
4205
4374
|
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) {
|
|
4375
|
+
async function stage(url, via, signal) {
|
|
4207
4376
|
const name = viaName(via);
|
|
4208
4377
|
let got;
|
|
4209
4378
|
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);
|
|
4379
|
+
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
4380
|
} catch (e) {
|
|
4212
4381
|
return { ok: false, reason: errMsg(e), url: e?.url, via: name };
|
|
4213
4382
|
}
|
|
@@ -4228,61 +4397,79 @@ async function stage(url, via) {
|
|
|
4228
4397
|
}
|
|
4229
4398
|
return r;
|
|
4230
4399
|
}
|
|
4231
|
-
var climb = async (
|
|
4232
|
-
|
|
4233
|
-
|
|
4400
|
+
var climb = async (given, onTry, onAlert) => {
|
|
4401
|
+
const url = toHttps(given);
|
|
4402
|
+
if (url !== given) onTry?.(`http upgraded \u2192 ${url}`);
|
|
4234
4403
|
let gone;
|
|
4235
|
-
|
|
4236
|
-
|
|
4404
|
+
let shell;
|
|
4405
|
+
const seen2 = (g) => {
|
|
4406
|
+
if (!g.ok) {
|
|
4407
|
+
gone ??= goneReason(g.reason);
|
|
4408
|
+
if (g.shell && !shell) shell = g.shell;
|
|
4409
|
+
}
|
|
4237
4410
|
return g;
|
|
4238
4411
|
};
|
|
4239
|
-
|
|
4240
|
-
const
|
|
4241
|
-
|
|
4242
|
-
|
|
4412
|
+
const write = (line) => onTry?.(line);
|
|
4413
|
+
const run = (target2, via, name, after) => {
|
|
4414
|
+
let req = null;
|
|
4415
|
+
return {
|
|
4416
|
+
name,
|
|
4417
|
+
abort: (why) => req?.abort(why),
|
|
4418
|
+
go: async () => {
|
|
4419
|
+
req = openRequest(write, name);
|
|
4420
|
+
const g = await stage(target2, via, req.signal);
|
|
4421
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted", via: name };
|
|
4422
|
+
seen2(g);
|
|
4423
|
+
if (via !== "fetch") recordStage(target2, name, g.ok, g.ok ? "" : g.reason);
|
|
4424
|
+
after?.(g);
|
|
4425
|
+
req.close(g.ok ? `ok ${name}` : `failed ${name}: ${g.reason}`);
|
|
4426
|
+
if (!g.ok && (g.reason.startsWith(MISMATCH) || accountProblem(g.reason))) onAlert?.(`${name}: ${g.reason}`);
|
|
4427
|
+
return g;
|
|
4428
|
+
}
|
|
4429
|
+
};
|
|
4430
|
+
};
|
|
4431
|
+
const skipped = (target2, name) => {
|
|
4432
|
+
const w = walled(target2, name);
|
|
4433
|
+
if (w) onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4434
|
+
return !!w;
|
|
4435
|
+
};
|
|
4436
|
+
const hostDown = async (host3, port, name) => {
|
|
4437
|
+
const h = await hostState(host3, port, (s) => onAlert?.(`${name}: ${downNote(s)}`));
|
|
4438
|
+
if (!h.up) onTry?.(`skipped ${name}: ${downNote(h)}`);
|
|
4439
|
+
return !h.up;
|
|
4440
|
+
};
|
|
4441
|
+
const f = fetchProxy();
|
|
4442
|
+
const proxyName = f ? fetchProxyName(f) : "";
|
|
4443
|
+
const first = [run(url, "fetch", "fetch", (g) => {
|
|
4444
|
+
if (!g.ok && g.url && g.url !== url) onTry?.(`redirect \u2192 ${g.url}`);
|
|
4445
|
+
})];
|
|
4446
|
+
if (f && !skipped(url, proxyName) && !await hostDown(f.host, f.port, proxyName)) first.push(run(url, { proxy: f.proxy, label: f.label }, proxyName));
|
|
4447
|
+
const isGone = (g) => g.ok ? null : goneReason(g.reason) ?? null;
|
|
4448
|
+
const one = await firstOk(first, isGone);
|
|
4449
|
+
if (one.won) return one.won;
|
|
4450
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
4451
|
+
const firstReason = plain3.ok ? void 0 : plain3.reason;
|
|
4452
|
+
const target = !plain3.ok && plain3.url && plain3.url !== url ? plain3.url : url;
|
|
4453
|
+
let r = one.results[1] ?? plain3;
|
|
4243
4454
|
const plainVia = (g) => g.via === "fetch" || g.via.startsWith("fetch-proxy ");
|
|
4244
4455
|
const met = (g, re) => re.test(g.ok ? "" : g.reason) || plainVia(g) && re.test(firstReason ?? "");
|
|
4245
4456
|
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}`);
|
|
4457
|
+
const notThere = () => gone ? { ...r, ok: false, reason: gone, via: r.via } : null;
|
|
4458
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4459
|
+
if (escalates(r)) {
|
|
4460
|
+
const open = browserStages().filter((b) => !skipped(target, stageName(b)));
|
|
4461
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b))));
|
|
4462
|
+
const tasks = open.filter((_, i) => !down[i]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
4463
|
+
const two = await firstOk(tasks, isGone);
|
|
4464
|
+
if (two.won) return two.won;
|
|
4465
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
4466
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4272
4467
|
}
|
|
4273
4468
|
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
|
-
}
|
|
4469
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target, u));
|
|
4470
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
4471
|
+
if (three.won) return three.won;
|
|
4472
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
4286
4473
|
if (!r.ok && shell) {
|
|
4287
4474
|
onTry?.("shell kept: no stage rendered the page, the script shell is served");
|
|
4288
4475
|
return shell;
|
|
@@ -4452,7 +4639,7 @@ function titleLine(m, md) {
|
|
|
4452
4639
|
}
|
|
4453
4640
|
function serve(requested, p, m, args, cached) {
|
|
4454
4641
|
const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
|
|
4455
|
-
const read2 = (file3) =>
|
|
4642
|
+
const read2 = (file3) => existsSync8(file3) ? readFileSync6(file3, "utf8") : "";
|
|
4456
4643
|
if (args.title_only) return { ok: true, text: `Contents of ${requested}:
|
|
4457
4644
|
${titleLine(m, read2(p.md))}`, cached, meta: m };
|
|
4458
4645
|
const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
|
|
@@ -4477,7 +4664,7 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4477
4664
|
let stored = readUrlMeta(p);
|
|
4478
4665
|
if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
|
|
4479
4666
|
const html = stored.files.find((f) => f.endsWith("-page.html"));
|
|
4480
|
-
if (html &&
|
|
4667
|
+
if (html && existsSync8(join9(p.entryDir, html))) {
|
|
4481
4668
|
try {
|
|
4482
4669
|
const page = await convert(readFileSync6(join9(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
|
|
4483
4670
|
if (page.md !== null) {
|
|
@@ -4523,11 +4710,11 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4523
4710
|
|
|
4524
4711
|
// src/verify/cache.ts
|
|
4525
4712
|
import { createHash as createHash3 } from "crypto";
|
|
4526
|
-
import { existsSync as
|
|
4527
|
-
import { dirname as
|
|
4713
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync8 } from "fs";
|
|
4714
|
+
import { dirname as dirname4, join as join10 } from "path";
|
|
4528
4715
|
|
|
4529
4716
|
// src/verify/verify.ts
|
|
4530
|
-
import { existsSync as
|
|
4717
|
+
import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
|
|
4531
4718
|
var QUESTION = "Does the paper state this, in substance? Ignore section labels and definitions of terms in parentheses. Every fact and number of the statement must be stated in the paper or follow from its numbers; a rounded number counts. If any part of the statement is absent from the paper or contradicted by it, answer false.";
|
|
4532
4719
|
function cleanMarkdown(md) {
|
|
4533
4720
|
return paperYearOnly(dropReferences(md)).replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\]\([^)]*\)/g, "]").replace(/^\s*#+\s*(see more about|more for you|back to top)\b.*$/gim, "").replace(/\n{3,}/g, "\n\n");
|
|
@@ -4600,7 +4787,7 @@ async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
|
|
|
4600
4787
|
if (p.error) return { id: p.requested, error: p.error };
|
|
4601
4788
|
const paths = entryPaths(libraryDir, p.type, p.id);
|
|
4602
4789
|
if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
|
|
4603
|
-
const full =
|
|
4790
|
+
const full = existsSync9(paths.fulltextMd);
|
|
4604
4791
|
if (full) return { id: p.requested, basis: "full_text", text: readFileSync7(paths.fulltextMd, "utf8") };
|
|
4605
4792
|
const meta = readMeta(paths);
|
|
4606
4793
|
return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync7(paths.md, "utf8") };
|
|
@@ -4654,9 +4841,9 @@ ${id}
|
|
|
4654
4841
|
${model}
|
|
4655
4842
|
${threshold}
|
|
4656
4843
|
${text4}`).slice(0, 16);
|
|
4657
|
-
var verdictFile = (libraryDir,
|
|
4844
|
+
var verdictFile = (libraryDir, key2) => join10(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4658
4845
|
function readVerdict(file3) {
|
|
4659
|
-
if (!
|
|
4846
|
+
if (!existsSync10(file3)) return null;
|
|
4660
4847
|
try {
|
|
4661
4848
|
return JSON.parse(readFileSync8(file3, "utf8"));
|
|
4662
4849
|
} catch {
|
|
@@ -4668,7 +4855,7 @@ function lookup2(file3, maxDays) {
|
|
|
4668
4855
|
return c && daysSince(c.date) < maxDays ? c : null;
|
|
4669
4856
|
}
|
|
4670
4857
|
function remember(file3, c) {
|
|
4671
|
-
mkdirSync7(
|
|
4858
|
+
mkdirSync7(dirname4(file3), { recursive: true });
|
|
4672
4859
|
writeAtomic(file3, JSON.stringify(c, null, 2) + "\n");
|
|
4673
4860
|
}
|
|
4674
4861
|
async function verifyCached(claim, id, cfg, decide, libraryDir = FH_EVIDENCE_DIR, read2 = readPaper) {
|
|
@@ -4732,8 +4919,8 @@ var reviewTypes = (types) => types.filter((t) => t !== "Journal Article" && !/^R
|
|
|
4732
4919
|
|
|
4733
4920
|
// src/trials.ts
|
|
4734
4921
|
import { createHash as createHash4 } from "crypto";
|
|
4735
|
-
import { existsSync as
|
|
4736
|
-
import { dirname as
|
|
4922
|
+
import { existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync9 } from "fs";
|
|
4923
|
+
import { dirname as dirname5, join as join11 } from "path";
|
|
4737
4924
|
var searchCacheDays = () => settings().search_cache_days;
|
|
4738
4925
|
var API2 = "https://clinicaltrials.gov/api/v2/studies";
|
|
4739
4926
|
var FIELDS = ["NCTId", "BriefTitle", "OverallStatus", "WhyStopped", "Phase", "StudyType", "EnrollmentCount", "EnrollmentType", "StartDate", "PrimaryCompletionDate", "CompletionDate", "LastUpdatePostDate", "PrimaryOutcomeMeasure", "PrimaryOutcomeTimeFrame", "Condition", "InterventionName", "LeadSponsorName", "HasResults"];
|
|
@@ -4771,7 +4958,7 @@ function normalizeQuery(q) {
|
|
|
4771
4958
|
return out;
|
|
4772
4959
|
}
|
|
4773
4960
|
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,
|
|
4961
|
+
var searchFile = (libraryDir, key2) => join11(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4775
4962
|
function searchUrl(q) {
|
|
4776
4963
|
const p = new URLSearchParams();
|
|
4777
4964
|
if (q.query) p.set("query.term", q.query);
|
|
@@ -4823,7 +5010,7 @@ async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveF
|
|
|
4823
5010
|
const q = normalizeQuery(raw);
|
|
4824
5011
|
if ("error" in q) return { ok: false, error: q.error };
|
|
4825
5012
|
const file3 = searchFile(libraryDir, searchKey(q));
|
|
4826
|
-
if (
|
|
5013
|
+
if (existsSync11(file3)) {
|
|
4827
5014
|
try {
|
|
4828
5015
|
const r = JSON.parse(readFileSync9(file3, "utf8"));
|
|
4829
5016
|
if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
|
|
@@ -4844,7 +5031,7 @@ async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveF
|
|
|
4844
5031
|
}
|
|
4845
5032
|
const result = { source: "clinicaltrials", query: q, total: parsed.total, columns: COLUMNS, rows: parsed.rows, searched: today() };
|
|
4846
5033
|
try {
|
|
4847
|
-
mkdirSync8(
|
|
5034
|
+
mkdirSync8(dirname5(file3), { recursive: true });
|
|
4848
5035
|
writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
|
|
4849
5036
|
} catch {
|
|
4850
5037
|
}
|
|
@@ -4857,8 +5044,8 @@ function trialsLogId(q) {
|
|
|
4857
5044
|
|
|
4858
5045
|
// src/pubmedsearch.ts
|
|
4859
5046
|
import { createHash as createHash5 } from "crypto";
|
|
4860
|
-
import { existsSync as
|
|
4861
|
-
import { dirname as
|
|
5047
|
+
import { existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
|
|
5048
|
+
import { dirname as dirname6 } from "path";
|
|
4862
5049
|
var MAX_RESULTS2 = 100;
|
|
4863
5050
|
var DEFAULT_RESULTS2 = 20;
|
|
4864
5051
|
var COLUMNS2 = ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"];
|
|
@@ -4938,7 +5125,7 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
|
|
|
4938
5125
|
const q = normalizeQuery2(raw);
|
|
4939
5126
|
if ("error" in q) return { ok: false, error: q.error };
|
|
4940
5127
|
const file3 = searchFile(libraryDir, searchKey2(q));
|
|
4941
|
-
if (
|
|
5128
|
+
if (existsSync12(file3)) {
|
|
4942
5129
|
try {
|
|
4943
5130
|
const r = JSON.parse(readFileSync10(file3, "utf8"));
|
|
4944
5131
|
if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
|
|
@@ -4961,7 +5148,7 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
|
|
|
4961
5148
|
}
|
|
4962
5149
|
const result = { source: "pubmed", query: q, total, columns: COLUMNS2, rows, searched: today() };
|
|
4963
5150
|
try {
|
|
4964
|
-
mkdirSync9(
|
|
5151
|
+
mkdirSync9(dirname6(file3), { recursive: true });
|
|
4965
5152
|
writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
|
|
4966
5153
|
} catch {
|
|
4967
5154
|
}
|
|
@@ -5089,12 +5276,12 @@ function resultsText(nct, md, maxChars) {
|
|
|
5089
5276
|
}
|
|
5090
5277
|
|
|
5091
5278
|
// src/missing.ts
|
|
5092
|
-
import { existsSync as
|
|
5279
|
+
import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
|
|
5093
5280
|
import { join as join12 } from "path";
|
|
5094
5281
|
var missingFile = (p) => join12(p.entryDir, `${p.entry}-missing.md`);
|
|
5095
5282
|
function readMissing(p) {
|
|
5096
5283
|
const f = missingFile(p);
|
|
5097
|
-
if (!
|
|
5284
|
+
if (!existsSync13(f)) return null;
|
|
5098
5285
|
const md = readFileSync11(f, "utf8");
|
|
5099
5286
|
const get4 = (k) => /^$/.test(k) ? "" : (new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md)?.[1] ?? "").trim();
|
|
5100
5287
|
const checked = get4("checked"), reason = get4("reason");
|
|
@@ -5259,7 +5446,7 @@ Reading a document
|
|
|
5259
5446
|
|
|
5260
5447
|
Status fields: pmid, pmcid, setid, nctid, publications, year, publication_types, retracted, corrections, citable, comment, has_abstract, level, version, retrieved_by, glyphs_unresolved, error. Funding and conflicts of interest: fh_library_read section "Declarations". Answers carry only what the call did not send: no echo of the ID, claim or query; a field that is null or an empty list is left out. fh_verify_claim always has verdict, score (null: no judgement) and basis.
|
|
5261
5448
|
|
|
5262
|
-
Where records come from: PubMed for the record and abstract; the full text from PubMed Central, Europe PMC, publishers' text-mining links, Unpaywall, OpenAlex, CORE, and a proxy URL template from the configuration. Every action is appended as one line to <library>/evidence.log.`;
|
|
5449
|
+
Where records come from: PubMed for the record and abstract; the full text from PubMed Central, Europe PMC, publishers' text-mining links, Unpaywall, OpenAlex, CORE, and a proxy URL template from the configuration. Every action is appended as one line to <library>/logs/evidence.log.`;
|
|
5263
5450
|
var idSchema = z.string().describe('ID as "type:value": a paper "pmid:30955454" (bare digits count as pmid) or "doi:10.5812/asjsm.110753" (a paper PubMed does not index; a DOI PubMed indexes is taken as its PMID), a drug label "dailymed:<set ID>" (the set ID from its DailyMed page URL), or a trial record "nct:05173896" (the eight digits; nct:NCT05173896 and a bare NCT05173896 are accepted).');
|
|
5264
5451
|
var levelWord = (m) => m.level === "abstract" && !m.has_abstract ? "title" : m.level;
|
|
5265
5452
|
var json = (s) => ({ content: [{ type: "text", text: statusAnswer(s) }] });
|
|
@@ -5394,11 +5581,11 @@ function registerTools(server2) {
|
|
|
5394
5581
|
);
|
|
5395
5582
|
const inflight2 = /* @__PURE__ */ new Map();
|
|
5396
5583
|
function addEntry(id) {
|
|
5397
|
-
const
|
|
5398
|
-
let p = inflight2.get(
|
|
5584
|
+
const key2 = parseId(id).requested;
|
|
5585
|
+
let p = inflight2.get(key2);
|
|
5399
5586
|
if (!p) {
|
|
5400
|
-
p = addEntryNow(id).finally(() => inflight2.delete(
|
|
5401
|
-
inflight2.set(
|
|
5587
|
+
p = addEntryNow(id).finally(() => inflight2.delete(key2));
|
|
5588
|
+
inflight2.set(key2, p);
|
|
5402
5589
|
}
|
|
5403
5590
|
return p;
|
|
5404
5591
|
}
|
|
@@ -5596,7 +5783,7 @@ function registerTools(server2) {
|
|
|
5596
5783
|
}
|
|
5597
5784
|
added = true;
|
|
5598
5785
|
}
|
|
5599
|
-
const full =
|
|
5786
|
+
const full = existsSync14(paths.fulltextMd);
|
|
5600
5787
|
const md = readFileSync12(full ? paths.fulltextMd : paths.md, "utf8");
|
|
5601
5788
|
const text4 = full ? "full_text" : "abstract";
|
|
5602
5789
|
const base = added ? { requested: parsed.requested, entry: paths.entry, text: text4, added: true } : { requested: parsed.requested, entry: paths.entry, text: text4 };
|
|
@@ -5617,7 +5804,7 @@ function registerTools(server2) {
|
|
|
5617
5804
|
const cap = max_chars ?? 6e3;
|
|
5618
5805
|
let sec = readSection(md, section2, cap);
|
|
5619
5806
|
let via = "";
|
|
5620
|
-
if (!sec && /abstract/i.test(section2) && full &&
|
|
5807
|
+
if (!sec && /abstract/i.test(section2) && full && existsSync14(paths.md)) {
|
|
5621
5808
|
sec = readSection(readFileSync12(paths.md, "utf8"), "abstract", cap);
|
|
5622
5809
|
via = " (from the abstract file)";
|
|
5623
5810
|
}
|
|
@@ -5683,12 +5870,13 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5683
5870
|
);
|
|
5684
5871
|
server2.tool(
|
|
5685
5872
|
"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
|
|
5873
|
+
"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
5874
|
{},
|
|
5688
5875
|
async () => {
|
|
5689
5876
|
const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
|
|
5690
5877
|
const cfg = verifyConfig();
|
|
5691
5878
|
const unlockerChecks = Promise.all(info.unlockers.map((u) => unlockerHealth(u.provider)));
|
|
5879
|
+
const stageChecks = Promise.all(info.stages.map((s2) => probe(s2.host, s2.port)));
|
|
5692
5880
|
if (info.verify && cfg) {
|
|
5693
5881
|
const t0 = Date.now();
|
|
5694
5882
|
try {
|
|
@@ -5699,7 +5887,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5699
5887
|
}
|
|
5700
5888
|
}
|
|
5701
5889
|
info.unlockers = (await unlockerChecks).map((h, i) => ({ ...info.unlockers[i], ...h }));
|
|
5702
|
-
|
|
5890
|
+
info.stages = (await stageChecks).map((h, i) => ({ ...info.stages[i], up: h.up, ms: h.ms, error: h.error }));
|
|
5891
|
+
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
5892
|
const s = currentStats();
|
|
5704
5893
|
const cache = s ? { since: s.started, verify: s.verify, fetch: s.fetch, search: s.search, pubmed: s.pubmed } : null;
|
|
5705
5894
|
return { content: [{ type: "text", text: compact2({ package: pkg.name, version: pkg.version, log: LOG_FILE, ...info, cache }) }] };
|
|
@@ -5745,8 +5934,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5745
5934
|
return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
|
|
5746
5935
|
}
|
|
5747
5936
|
}
|
|
5748
|
-
const file3 = pid.type === "pmid" ? paths.md :
|
|
5749
|
-
const md =
|
|
5937
|
+
const file3 = pid.type === "pmid" ? paths.md : existsSync14(paths.fulltextMd) ? paths.fulltextMd : paths.md;
|
|
5938
|
+
const md = existsSync14(file3) ? readFileSync12(file3, "utf8") : "";
|
|
5750
5939
|
const text4 = title_only ? `Contents of ${url}:
|
|
5751
5940
|
${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
|
|
5752
5941
|
bump("fetch", had);
|
|
@@ -5853,7 +6042,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
5853
6042
|
return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
|
|
5854
6043
|
}
|
|
5855
6044
|
const raw = e.paths.fulltextRaw("json");
|
|
5856
|
-
const r =
|
|
6045
|
+
const r = existsSync14(raw) ? recordSummary(readFileSync12(raw, "utf8")) : null;
|
|
5857
6046
|
if (!r) {
|
|
5858
6047
|
log("trials", e.requested, "record error: no stored record");
|
|
5859
6048
|
return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
|
|
@@ -5872,7 +6061,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
5872
6061
|
log("trials", nct, `results error: ${e.error}`);
|
|
5873
6062
|
return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
|
|
5874
6063
|
}
|
|
5875
|
-
const md =
|
|
6064
|
+
const md = existsSync14(e.paths.fulltextMd) ? readFileSync12(e.paths.fulltextMd, "utf8") : "";
|
|
5876
6065
|
const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
|
|
5877
6066
|
log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
|
|
5878
6067
|
return { content: [{ type: "text", text: leanJson(r) }] };
|
|
@@ -5888,7 +6077,9 @@ var server = new McpServer(
|
|
|
5888
6077
|
registerTools(server);
|
|
5889
6078
|
startStats(pkg);
|
|
5890
6079
|
migrateLogName();
|
|
6080
|
+
migrateWalls();
|
|
5891
6081
|
log("startup", null, `${pkg.name} ${pkg.version}`);
|
|
5892
|
-
|
|
6082
|
+
process.on("exit", abandonAll);
|
|
6083
|
+
for (const problem of [...resolveTiers().problems, ...verifyProblems()]) log("startup", null, `!! ${problem}`);
|
|
5893
6084
|
var transport = new StdioServerTransport();
|
|
5894
6085
|
await server.connect(transport);
|