brainx-skill 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/installation/lib/cli.js +16 -4
- package/installation/lib/literature-mcp.js +536 -0
- package/manifest.json +2 -0
- package/mcp-servers/codex/README.md +24 -4
- package/mcp-servers/codex/UPSTREAM.md +3 -1
- package/mcp-servers/codex/server.mjs +2 -0
- package/mcp-servers/codex/system-prompt.md +30 -19
- package/mcp-servers/codex/test/server.test.mjs +12 -1
- package/mcp-servers/fulltext-resolver/README.md +136 -0
- package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
- package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
- package/mcp-servers/fulltext-resolver/server.mjs +128 -0
- package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
- package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
- package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
- package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
- package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
- package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
- package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
- package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
- package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
- package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
- package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
- package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
- package/package.json +10 -3
- package/skills/bio-neuro-lit/SKILL.md +206 -0
- package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
- package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
- package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
- package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
- package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
- package/skills/brainx-general-guard/SKILL.md +17 -0
- package/skills/brainx-modeling-loop/SKILL.md +63 -24
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +47 -7
- package/skills/brainx-visualization/SKILL.md +157 -0
- package/skills/brainx-visualization/agents/openai.yaml +4 -0
- package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
- package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
- package/skills/package-skills/braincell/SKILL.md +16 -6
- package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
- package/skills/package-skills/braincell/references/braintools/metric.md +152 -0
- package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// JATS conversion behavior adapts yogsoth-ai/biorxiv-mcp convert.py
|
|
2
|
+
// (Apache-2.0); modified into a structured Node.js converter. See ../REUSE.md.
|
|
3
|
+
|
|
4
|
+
import { DOMParser, parseHTML } from 'linkedom';
|
|
5
|
+
import TurndownService from 'turndown';
|
|
6
|
+
|
|
7
|
+
function cleanText(value = '') {
|
|
8
|
+
return String(value).replace(/\s+/g, ' ').trim();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function elementName(node) {
|
|
12
|
+
return String(node.localName || node.nodeName || '').toLowerCase();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function childElements(node) {
|
|
16
|
+
return Array.from(node?.childNodes || []).filter((child) => child.nodeType === 1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function renderInline(node) {
|
|
20
|
+
if (!node) return '';
|
|
21
|
+
if (node.nodeType === 3) return node.nodeValue || '';
|
|
22
|
+
if (node.nodeType !== 1) return '';
|
|
23
|
+
const name = elementName(node);
|
|
24
|
+
const content = Array.from(node.childNodes || []).map(renderInline).join('');
|
|
25
|
+
if (['italic', 'i', 'em'].includes(name)) return `*${content}*`;
|
|
26
|
+
if (['bold', 'b', 'strong'].includes(name)) return `**${content}**`;
|
|
27
|
+
if (name === 'sup') return `<sup>${content}</sup>`;
|
|
28
|
+
if (name === 'sub') return `<sub>${content}</sub>`;
|
|
29
|
+
if (name === 'break' || name === 'br') return '\n';
|
|
30
|
+
if (name === 'ext-link') {
|
|
31
|
+
const href = node.getAttribute('xlink:href') || node.getAttribute('href');
|
|
32
|
+
return href ? `[${content || href}](${href})` : content;
|
|
33
|
+
}
|
|
34
|
+
return content;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function paragraphMarkdown(node) {
|
|
38
|
+
return cleanText(renderInline(node));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function tableMarkdown(table) {
|
|
42
|
+
if (!table) return '';
|
|
43
|
+
const rows = Array.from(table.querySelectorAll('tr')).map((row) =>
|
|
44
|
+
Array.from(row.querySelectorAll('th, td')).map((cell) => cleanText(renderInline(cell))),
|
|
45
|
+
).filter((row) => row.length > 0);
|
|
46
|
+
if (!rows.length) return '';
|
|
47
|
+
const width = Math.max(...rows.map((row) => row.length));
|
|
48
|
+
const normalized = rows.map((row) => [...row, ...Array(Math.max(0, width - row.length)).fill('')]);
|
|
49
|
+
const header = normalized[0];
|
|
50
|
+
const body = normalized.slice(1);
|
|
51
|
+
return [
|
|
52
|
+
`| ${header.join(' | ')} |`,
|
|
53
|
+
`| ${header.map(() => '---').join(' | ')} |`,
|
|
54
|
+
...body.map((row) => `| ${row.join(' | ')} |`),
|
|
55
|
+
].join('\n');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function figureMarkdown(figure) {
|
|
59
|
+
const label = cleanText(figure.querySelector(':scope > label')?.textContent || 'Figure');
|
|
60
|
+
const title = paragraphMarkdown(figure.querySelector(':scope > caption > title'));
|
|
61
|
+
const paragraphs = Array.from(figure.querySelectorAll(':scope > caption > p'))
|
|
62
|
+
.map(paragraphMarkdown)
|
|
63
|
+
.filter(Boolean);
|
|
64
|
+
const caption = [title, ...paragraphs].filter(Boolean).join(' ');
|
|
65
|
+
return caption ? `**${label}.** ${caption}` : '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function listMarkdown(list, depth = 0) {
|
|
69
|
+
const ordered = list.getAttribute('list-type') === 'order';
|
|
70
|
+
return childElements(list)
|
|
71
|
+
.filter((child) => elementName(child) === 'list-item')
|
|
72
|
+
.map((item, index) => {
|
|
73
|
+
const prefix = ordered ? `${index + 1}.` : '-';
|
|
74
|
+
const paragraphs = childElements(item)
|
|
75
|
+
.filter((child) => elementName(child) === 'p')
|
|
76
|
+
.map(paragraphMarkdown)
|
|
77
|
+
.filter(Boolean);
|
|
78
|
+
const nested = childElements(item).find((child) => elementName(child) === 'list');
|
|
79
|
+
const line = `${' '.repeat(depth)}${prefix} ${paragraphs.join(' ')}`.trimEnd();
|
|
80
|
+
return nested ? `${line}\n${listMarkdown(nested, depth + 1)}` : line;
|
|
81
|
+
})
|
|
82
|
+
.join('\n');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function renderBlocks(parent, headingLevel, collectors) {
|
|
86
|
+
const blocks = [];
|
|
87
|
+
for (const child of childElements(parent)) {
|
|
88
|
+
const name = elementName(child);
|
|
89
|
+
if (name === 'title') continue;
|
|
90
|
+
if (name === 'p') {
|
|
91
|
+
const paragraph = paragraphMarkdown(child);
|
|
92
|
+
if (paragraph) blocks.push(paragraph);
|
|
93
|
+
} else if (name === 'sec') {
|
|
94
|
+
blocks.push(renderSection(child, headingLevel, collectors));
|
|
95
|
+
} else if (name === 'fig') {
|
|
96
|
+
const figure = figureMarkdown(child);
|
|
97
|
+
if (figure) {
|
|
98
|
+
collectors.figureCaptions.push(figure);
|
|
99
|
+
blocks.push(figure);
|
|
100
|
+
}
|
|
101
|
+
} else if (name === 'table-wrap') {
|
|
102
|
+
const label = cleanText(child.querySelector(':scope > label')?.textContent || 'Table');
|
|
103
|
+
const caption = cleanText(child.querySelector(':scope > caption')?.textContent || '');
|
|
104
|
+
const table = tableMarkdown(child.querySelector('table'));
|
|
105
|
+
const rendered = [`**${label}.**${caption ? ` ${caption}` : ''}`, table].filter(Boolean).join('\n\n');
|
|
106
|
+
if (rendered) {
|
|
107
|
+
collectors.tables.push(rendered);
|
|
108
|
+
blocks.push(rendered);
|
|
109
|
+
}
|
|
110
|
+
} else if (name === 'list') {
|
|
111
|
+
const list = listMarkdown(child);
|
|
112
|
+
if (list) blocks.push(list);
|
|
113
|
+
} else if (['disp-quote', 'boxed-text', 'statement'].includes(name)) {
|
|
114
|
+
const quote = cleanText(child.textContent);
|
|
115
|
+
if (quote) blocks.push(quote.split('\n').map((line) => `> ${line}`).join('\n'));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return blocks.filter(Boolean).join('\n\n');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderSection(section, headingLevel, collectors) {
|
|
122
|
+
const title = cleanText(section.querySelector(':scope > title')?.textContent || 'Untitled section');
|
|
123
|
+
const level = Math.min(Math.max(headingLevel, 2), 6);
|
|
124
|
+
const body = renderBlocks(section, level + 1, collectors);
|
|
125
|
+
collectors.sections.push({ title, markdown: body });
|
|
126
|
+
return `${'#'.repeat(level)} ${title}${body ? `\n\n${body}` : ''}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function jatsAuthors(document) {
|
|
130
|
+
return Array.from(document.querySelectorAll('article-meta > contrib-group[content-type="author"] > contrib, article-meta > contrib-group > contrib'))
|
|
131
|
+
.map((contributor) => {
|
|
132
|
+
const given = cleanText(contributor.querySelector('given-names')?.textContent);
|
|
133
|
+
const surname = cleanText(contributor.querySelector('surname')?.textContent);
|
|
134
|
+
const collaborative = cleanText(contributor.querySelector('collab')?.textContent);
|
|
135
|
+
return collaborative || [given, surname].filter(Boolean).join(' ');
|
|
136
|
+
})
|
|
137
|
+
.filter(Boolean);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function jatsVersion(document) {
|
|
141
|
+
const customMetadata = new Map(
|
|
142
|
+
Array.from(document.querySelectorAll('custom-meta')).map((entry) => [
|
|
143
|
+
cleanText(entry.querySelector('meta-name')?.textContent).toLowerCase(),
|
|
144
|
+
cleanText(entry.querySelector('meta-value')?.textContent).toLowerCase(),
|
|
145
|
+
]),
|
|
146
|
+
);
|
|
147
|
+
const enabled = (name) => ['yes', 'true', '1'].includes(customMetadata.get(name));
|
|
148
|
+
if (enabled('is-preprint')) return 'submittedVersion';
|
|
149
|
+
if (enabled('is-manuscript')) return 'acceptedVersion';
|
|
150
|
+
return 'publishedVersion';
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function jatsToDocument(xml) {
|
|
154
|
+
const document = new DOMParser().parseFromString(xml, 'text/xml');
|
|
155
|
+
const parserError = document.querySelector('parsererror');
|
|
156
|
+
if (parserError) throw new Error(`Invalid JATS XML: ${cleanText(parserError.textContent)}`);
|
|
157
|
+
|
|
158
|
+
const title = cleanText(document.querySelector('article-meta article-title')?.textContent);
|
|
159
|
+
const authors = jatsAuthors(document);
|
|
160
|
+
const abstractNodes = Array.from(document.querySelectorAll('article-meta > abstract'));
|
|
161
|
+
const abstract = abstractNodes
|
|
162
|
+
.map((node) => Array.from(node.querySelectorAll(':scope > p')).map(paragraphMarkdown).filter(Boolean).join('\n\n'))
|
|
163
|
+
.filter(Boolean)
|
|
164
|
+
.join('\n\n');
|
|
165
|
+
const collectors = { sections: [], figureCaptions: [], tables: [] };
|
|
166
|
+
const body = document.querySelector('article > body') || document.querySelector('body');
|
|
167
|
+
const bodyMarkdown = body ? renderBlocks(body, 2, collectors) : '';
|
|
168
|
+
const references = Array.from(document.querySelectorAll('ref-list > ref'))
|
|
169
|
+
.map((reference) => {
|
|
170
|
+
const label = cleanText(reference.querySelector(':scope > label')?.textContent);
|
|
171
|
+
const citation = cleanText(Array.from(reference.childNodes || [])
|
|
172
|
+
.filter((child) => child !== reference.querySelector(':scope > label'))
|
|
173
|
+
.map((child) => child.textContent || child.nodeValue || '')
|
|
174
|
+
.join(' '));
|
|
175
|
+
return [label, citation].filter(Boolean).join(' ');
|
|
176
|
+
})
|
|
177
|
+
.filter(Boolean);
|
|
178
|
+
const journal = cleanText(document.querySelector('journal-title')?.textContent);
|
|
179
|
+
const year = Number(cleanText(document.querySelector('article-meta > pub-date > year')?.textContent)) || null;
|
|
180
|
+
const doi = cleanText(document.querySelector('article-id[pub-id-type="doi"]')?.textContent) || null;
|
|
181
|
+
const pmcid = cleanText(document.querySelector('article-id[pub-id-type="pmcid"]')?.textContent) || null;
|
|
182
|
+
const version = jatsVersion(document);
|
|
183
|
+
|
|
184
|
+
const header = [
|
|
185
|
+
title ? `# ${title}` : '',
|
|
186
|
+
authors.length ? `**Authors:** ${authors.join(', ')}` : '',
|
|
187
|
+
journal ? `**Journal:** ${journal}${year ? ` (${year})` : ''}` : '',
|
|
188
|
+
abstract ? `## Abstract\n\n${abstract}` : '',
|
|
189
|
+
].filter(Boolean).join('\n\n');
|
|
190
|
+
const referenceMarkdown = references.length
|
|
191
|
+
? `## References\n\n${references.map((reference) => `- ${reference}`).join('\n')}`
|
|
192
|
+
: '';
|
|
193
|
+
const markdown = [header, bodyMarkdown, referenceMarkdown].filter(Boolean).join('\n\n').trim();
|
|
194
|
+
if (!markdown) throw new Error('JATS document contains no extractable text.');
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
title: title || null,
|
|
198
|
+
authors,
|
|
199
|
+
doi,
|
|
200
|
+
pmcid,
|
|
201
|
+
version,
|
|
202
|
+
journal: journal || null,
|
|
203
|
+
year,
|
|
204
|
+
abstract: abstract || null,
|
|
205
|
+
sections: collectors.sections,
|
|
206
|
+
figure_captions: collectors.figureCaptions,
|
|
207
|
+
tables: collectors.tables,
|
|
208
|
+
references,
|
|
209
|
+
markdown,
|
|
210
|
+
original_format: 'jats_xml',
|
|
211
|
+
normalized_format: 'markdown',
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function createTurndown() {
|
|
216
|
+
const turndown = new TurndownService({
|
|
217
|
+
bulletListMarker: '-',
|
|
218
|
+
codeBlockStyle: 'fenced',
|
|
219
|
+
headingStyle: 'atx',
|
|
220
|
+
});
|
|
221
|
+
turndown.remove(['script', 'style', 'noscript', 'nav', 'form', 'button', 'svg']);
|
|
222
|
+
turndown.addRule('table', {
|
|
223
|
+
filter: 'table',
|
|
224
|
+
replacement(_content, node) {
|
|
225
|
+
const table = tableMarkdown(node);
|
|
226
|
+
return table ? `\n\n${table}\n\n` : '';
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
return turndown;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function htmlToDocument(html, sourceUrl) {
|
|
233
|
+
const { document } = parseHTML(html);
|
|
234
|
+
for (const node of document.querySelectorAll('script, style, noscript, nav, form, button, svg, header, footer, aside')) {
|
|
235
|
+
node.remove();
|
|
236
|
+
}
|
|
237
|
+
const root = document.querySelector('.fulltext-view, article, main, [role="main"], .article') || document.body;
|
|
238
|
+
const markdown = createTurndown().turndown(root?.innerHTML || '').trim();
|
|
239
|
+
if (!markdown) throw new Error(`HTML page contains no extractable article text: ${sourceUrl}`);
|
|
240
|
+
return {
|
|
241
|
+
title: cleanText(root?.querySelector('h1')?.textContent || document.querySelector('title')?.textContent) || null,
|
|
242
|
+
authors: [],
|
|
243
|
+
abstract: null,
|
|
244
|
+
sections: [],
|
|
245
|
+
figure_captions: [],
|
|
246
|
+
tables: [],
|
|
247
|
+
references: [],
|
|
248
|
+
markdown,
|
|
249
|
+
original_format: 'html',
|
|
250
|
+
normalized_format: 'markdown',
|
|
251
|
+
source_url: sourceUrl,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Retry, timeout, rate-limit, and response guards adapt cyanheads MCP services
|
|
2
|
+
// (Apache-2.0); modified for this Node 18 resolver. See ../REUSE.md.
|
|
3
|
+
|
|
4
|
+
import { assertPublicHttpUrl } from './identifiers.mjs';
|
|
5
|
+
|
|
6
|
+
export class HttpError extends Error {
|
|
7
|
+
constructor(message, options = {}) {
|
|
8
|
+
super(message, options.cause ? { cause: options.cause } : undefined);
|
|
9
|
+
this.name = 'HttpError';
|
|
10
|
+
this.status = options.status;
|
|
11
|
+
this.retryable = Boolean(options.retryable);
|
|
12
|
+
this.retryAfter = options.retryAfter;
|
|
13
|
+
this.url = options.url;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function parseRetryAfter(value) {
|
|
18
|
+
if (!value) return undefined;
|
|
19
|
+
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
20
|
+
const date = Date.parse(value);
|
|
21
|
+
if (Number.isNaN(date)) return undefined;
|
|
22
|
+
return Math.max(0, Math.round((date - Date.now()) / 1000));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function abortAfter(timeoutMs, externalSignal) {
|
|
26
|
+
const controller = new AbortController();
|
|
27
|
+
const timeout = setTimeout(() => controller.abort(new Error(`Request timed out after ${timeoutMs} ms`)), timeoutMs);
|
|
28
|
+
const abort = () => controller.abort(externalSignal?.reason);
|
|
29
|
+
externalSignal?.addEventListener('abort', abort, { once: true });
|
|
30
|
+
return {
|
|
31
|
+
signal: controller.signal,
|
|
32
|
+
dispose() {
|
|
33
|
+
clearTimeout(timeout);
|
|
34
|
+
externalSignal?.removeEventListener('abort', abort);
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function sleep(milliseconds, signal) {
|
|
40
|
+
if (milliseconds <= 0) return;
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
const timeout = setTimeout(resolve, milliseconds);
|
|
43
|
+
const abort = () => {
|
|
44
|
+
clearTimeout(timeout);
|
|
45
|
+
reject(signal.reason ?? new Error('Request aborted'));
|
|
46
|
+
};
|
|
47
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export class HttpClient {
|
|
52
|
+
constructor(options = {}) {
|
|
53
|
+
this.fetch = options.fetchImpl ?? globalThis.fetch;
|
|
54
|
+
this.timeoutMs = options.timeoutMs ?? Number(process.env.FULLTEXT_HTTP_TIMEOUT_MS || 30_000);
|
|
55
|
+
this.maxBytes = options.maxBytes ?? Number(process.env.FULLTEXT_MAX_BYTES || 8_000_000);
|
|
56
|
+
this.retries = options.retries ?? 2;
|
|
57
|
+
this.userAgent = options.userAgent
|
|
58
|
+
?? process.env.FULLTEXT_RESOLVER_USER_AGENT
|
|
59
|
+
?? 'brainx-fulltext-resolver/1.0 (+https://github.com/chaobrain/BrainX-skill)';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async request(urlValue, options = {}) {
|
|
63
|
+
let lastError;
|
|
64
|
+
for (let attempt = 0; attempt <= this.retries; attempt += 1) {
|
|
65
|
+
try {
|
|
66
|
+
const response = await this.#fetchFollowingRedirects(urlValue, options);
|
|
67
|
+
if (response.ok) return response;
|
|
68
|
+
|
|
69
|
+
const retryAfter = parseRetryAfter(response.headers.get('retry-after'));
|
|
70
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
71
|
+
const error = new HttpError(`HTTP ${response.status} from ${response.url || urlValue}`, {
|
|
72
|
+
status: response.status,
|
|
73
|
+
retryable,
|
|
74
|
+
retryAfter,
|
|
75
|
+
url: response.url || String(urlValue),
|
|
76
|
+
});
|
|
77
|
+
if (!retryable || attempt === this.retries) throw error;
|
|
78
|
+
lastError = error;
|
|
79
|
+
const waitMs = retryAfter === undefined
|
|
80
|
+
? 250 * (2 ** attempt)
|
|
81
|
+
: Math.min(retryAfter * 1000, 10_000);
|
|
82
|
+
await sleep(waitMs, options.signal);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof HttpError && !error.retryable) throw error;
|
|
85
|
+
if (options.signal?.aborted) throw options.signal.reason ?? error;
|
|
86
|
+
lastError = error;
|
|
87
|
+
if (attempt === this.retries) {
|
|
88
|
+
if (error instanceof HttpError) throw error;
|
|
89
|
+
throw new HttpError(`Request failed for ${urlValue}: ${error.message}`, {
|
|
90
|
+
cause: error,
|
|
91
|
+
retryable: true,
|
|
92
|
+
url: String(urlValue),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
await sleep(250 * (2 ** attempt), options.signal);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
throw lastError;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async #fetchFollowingRedirects(urlValue, options) {
|
|
102
|
+
let url = assertPublicHttpUrl(urlValue);
|
|
103
|
+
for (let redirectCount = 0; redirectCount <= 5; redirectCount += 1) {
|
|
104
|
+
const timed = abortAfter(this.timeoutMs, options.signal);
|
|
105
|
+
try {
|
|
106
|
+
const response = await this.fetch(url, {
|
|
107
|
+
headers: {
|
|
108
|
+
accept: options.accept ?? '*/*',
|
|
109
|
+
'user-agent': this.userAgent,
|
|
110
|
+
...options.headers,
|
|
111
|
+
},
|
|
112
|
+
redirect: 'manual',
|
|
113
|
+
signal: timed.signal,
|
|
114
|
+
});
|
|
115
|
+
if (![301, 302, 303, 307, 308].includes(response.status)) return response;
|
|
116
|
+
const location = response.headers.get('location');
|
|
117
|
+
if (!location) return response;
|
|
118
|
+
url = assertPublicHttpUrl(new URL(location, url).toString());
|
|
119
|
+
} finally {
|
|
120
|
+
timed.dispose();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
throw new HttpError(`Too many redirects from ${urlValue}`, {
|
|
124
|
+
retryable: false,
|
|
125
|
+
url: String(urlValue),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async text(url, options = {}) {
|
|
130
|
+
const response = await this.request(url, options);
|
|
131
|
+
const contentLength = Number(response.headers.get('content-length') || 0);
|
|
132
|
+
if (contentLength > this.maxBytes) {
|
|
133
|
+
throw new HttpError(`Response exceeds ${this.maxBytes} bytes: ${response.url || url}`, {
|
|
134
|
+
retryable: false,
|
|
135
|
+
url: response.url || String(url),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
139
|
+
if (buffer.byteLength > this.maxBytes) {
|
|
140
|
+
throw new HttpError(`Response exceeds ${this.maxBytes} bytes: ${response.url || url}`, {
|
|
141
|
+
retryable: false,
|
|
142
|
+
url: response.url || String(url),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
body: buffer.toString('utf8'),
|
|
147
|
+
contentType: response.headers.get('content-type') || '',
|
|
148
|
+
url: response.url || String(url),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async json(url, options = {}) {
|
|
153
|
+
const response = await this.text(url, {
|
|
154
|
+
...options,
|
|
155
|
+
accept: options.accept ?? 'application/json',
|
|
156
|
+
});
|
|
157
|
+
if (/^\s*<(!doctype\s+html|html[\s>])/i.test(response.body)) {
|
|
158
|
+
throw new HttpError(`Expected JSON but received HTML from ${response.url}`, {
|
|
159
|
+
retryable: true,
|
|
160
|
+
url: response.url,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(response.body);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new HttpError(`Invalid JSON from ${response.url}`, {
|
|
167
|
+
cause: error,
|
|
168
|
+
retryable: true,
|
|
169
|
+
url: response.url,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Adapted from DeyangLiu123/openalex-mcp ids.py (MIT); modified for Node.js.
|
|
2
|
+
// See ../REUSE.md and ../THIRD_PARTY_NOTICES.md.
|
|
3
|
+
|
|
4
|
+
import { domainToASCII } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const DOI_PATTERN = /^10\.\d{4,9}\/\S+$/i;
|
|
7
|
+
const PMCID_PATTERN = /^PMC\d+$/i;
|
|
8
|
+
const PMID_PATTERN = /^\d+$/;
|
|
9
|
+
|
|
10
|
+
export function normalizeDoi(value = '') {
|
|
11
|
+
let normalized = decodeURIComponent(String(value).trim());
|
|
12
|
+
normalized = normalized.replace(/^doi:\s*/i, '');
|
|
13
|
+
normalized = normalized.replace(/^https?:\/\/(?:dx\.)?doi\.org\//i, '');
|
|
14
|
+
return normalized.replace(/[\s.]+$/, '').toLowerCase();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function isValidDoi(value) {
|
|
18
|
+
return DOI_PATTERN.test(normalizeDoi(value));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function normalizePmcid(value = '') {
|
|
22
|
+
const normalized = String(value).trim().toUpperCase();
|
|
23
|
+
if (!normalized) return '';
|
|
24
|
+
return normalized.startsWith('PMC') ? normalized : `PMC${normalized}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function normalizePmid(value = '') {
|
|
28
|
+
return String(value).trim();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function normalizeTitle(value = '') {
|
|
32
|
+
return String(value)
|
|
33
|
+
.normalize('NFKC')
|
|
34
|
+
.toLocaleLowerCase('en-US')
|
|
35
|
+
.replace(/[\p{P}\p{S}\s]+/gu, '');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function normalizeAuthors(authors) {
|
|
39
|
+
if (Array.isArray(authors)) {
|
|
40
|
+
return authors.map((author) => String(author).trim()).filter(Boolean);
|
|
41
|
+
}
|
|
42
|
+
if (typeof authors === 'string') {
|
|
43
|
+
return authors.split(/\s*;\s*/).map((author) => author.trim()).filter(Boolean);
|
|
44
|
+
}
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function normalizeRequest(input = {}) {
|
|
49
|
+
const request = {
|
|
50
|
+
doi: normalizeDoi(input.doi),
|
|
51
|
+
pmid: normalizePmid(input.pmid),
|
|
52
|
+
pmcid: normalizePmcid(input.pmcid),
|
|
53
|
+
title: String(input.title ?? '').trim(),
|
|
54
|
+
authors: normalizeAuthors(input.authors),
|
|
55
|
+
year: input.year === undefined ? undefined : Number(input.year),
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
if (!request.doi && !request.pmid && !request.pmcid && !request.title) {
|
|
59
|
+
throw new Error('Provide at least one of doi, pmid, pmcid, or title.');
|
|
60
|
+
}
|
|
61
|
+
if (request.doi && !DOI_PATTERN.test(request.doi)) {
|
|
62
|
+
throw new Error(`Malformed DOI: ${input.doi}`);
|
|
63
|
+
}
|
|
64
|
+
if (request.pmid && !PMID_PATTERN.test(request.pmid)) {
|
|
65
|
+
throw new Error(`Malformed PMID: ${input.pmid}`);
|
|
66
|
+
}
|
|
67
|
+
if (request.pmcid && !PMCID_PATTERN.test(request.pmcid)) {
|
|
68
|
+
throw new Error(`Malformed PMCID: ${input.pmcid}`);
|
|
69
|
+
}
|
|
70
|
+
if (request.year !== undefined && (!Number.isInteger(request.year) || request.year < 1600 || request.year > 3000)) {
|
|
71
|
+
throw new Error(`Malformed publication year: ${input.year}`);
|
|
72
|
+
}
|
|
73
|
+
return request;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function doiFromUrl(value = '') {
|
|
77
|
+
const text = String(value);
|
|
78
|
+
const doiUrlMatch = text.match(/doi\.org\/(10\.\d{4,9}\/[^?#\s]+)/i);
|
|
79
|
+
if (doiUrlMatch) return normalizeDoi(doiUrlMatch[1]);
|
|
80
|
+
|
|
81
|
+
const preprintMatch = text.match(/\/(10\.1101\/[^/?#]+)/i);
|
|
82
|
+
if (preprintMatch) {
|
|
83
|
+
// Remove bioRxiv revision and representation suffixes before comparing work identity.
|
|
84
|
+
const doi = preprintMatch[1].replace(/(?:v\d+)?(?:\.(?:full|source))?(?:\.(?:pdf|xml))?$/i, '');
|
|
85
|
+
return normalizeDoi(doi);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const arxivMatch = text.match(/arxiv\.org\/(?:abs|pdf|html)\/([^?#]+?)(?:\.pdf)?$/i);
|
|
89
|
+
if (arxivMatch) return `10.48550/arxiv.${arxivMatch[1].replace(/v\d+$/i, '').toLowerCase()}`;
|
|
90
|
+
return '';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isPrivateIpv4(hostname) {
|
|
94
|
+
const parts = hostname.split('.').map(Number);
|
|
95
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
return parts[0] === 10
|
|
99
|
+
|| parts[0] === 127
|
|
100
|
+
|| (parts[0] === 169 && parts[1] === 254)
|
|
101
|
+
|| (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)
|
|
102
|
+
|| (parts[0] === 192 && parts[1] === 168)
|
|
103
|
+
|| parts[0] === 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function assertPublicHttpUrl(value) {
|
|
107
|
+
const url = new URL(value);
|
|
108
|
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
109
|
+
throw new Error(`Unsupported source URL protocol: ${url.protocol}`);
|
|
110
|
+
}
|
|
111
|
+
const hostname = domainToASCII(url.hostname).toLowerCase();
|
|
112
|
+
if (!hostname || hostname === 'localhost' || hostname.endsWith('.localhost') || isPrivateIpv4(hostname)) {
|
|
113
|
+
throw new Error(`Refusing non-public source URL: ${value}`);
|
|
114
|
+
}
|
|
115
|
+
if (hostname === '::1' || hostname.startsWith('fc') || hostname.startsWith('fd') || hostname.startsWith('fe80:')) {
|
|
116
|
+
throw new Error(`Refusing non-public source URL: ${value}`);
|
|
117
|
+
}
|
|
118
|
+
return url;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function encodeDoiPath(doi) {
|
|
122
|
+
return normalizeDoi(doi).split('/').map(encodeURIComponent).join('/');
|
|
123
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { doiFromUrl, normalizeDoi } from './identifiers.mjs';
|
|
2
|
+
|
|
3
|
+
export const VERSION_PRIORITY = {
|
|
4
|
+
publishedVersion: 3,
|
|
5
|
+
acceptedVersion: 2,
|
|
6
|
+
submittedVersion: 1,
|
|
7
|
+
unknown: 0,
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const SOURCE_PRIORITY = {
|
|
11
|
+
PMC: 3,
|
|
12
|
+
OpenAlex: 1,
|
|
13
|
+
bioRxiv: 1,
|
|
14
|
+
medRxiv: 1,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const FORMAT_PRIORITY = {
|
|
18
|
+
jats_xml: 3,
|
|
19
|
+
html: 2,
|
|
20
|
+
pdf: 1,
|
|
21
|
+
unknown: 0,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export function normalizeVersion(value, flags = {}) {
|
|
25
|
+
if (Object.hasOwn(VERSION_PRIORITY, value)) return value;
|
|
26
|
+
if (flags.is_published) return 'publishedVersion';
|
|
27
|
+
if (flags.is_accepted) return 'acceptedVersion';
|
|
28
|
+
if (flags.is_preprint) return 'submittedVersion';
|
|
29
|
+
return 'unknown';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function relationshipFor(version, requestedDoi, resolvedDoi) {
|
|
33
|
+
const requested = normalizeDoi(requestedDoi);
|
|
34
|
+
const resolved = normalizeDoi(resolvedDoi);
|
|
35
|
+
if (version === 'submittedVersion') {
|
|
36
|
+
const requestedPreprint = requested.startsWith('10.1101/') || requested.startsWith('10.48550/arxiv.');
|
|
37
|
+
return requestedPreprint && requested === resolved ? 'same_work' : 'preprint_of_requested_work';
|
|
38
|
+
}
|
|
39
|
+
if (version === 'acceptedVersion') return 'accepted_manuscript_of_requested_work';
|
|
40
|
+
if (requested && resolved && requested !== resolved) {
|
|
41
|
+
return 'version_of_requested_work';
|
|
42
|
+
}
|
|
43
|
+
return 'same_work';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function inferFormat(location = {}) {
|
|
47
|
+
const values = [location.fulltext_url, location.pdf_url, location.landing_page_url]
|
|
48
|
+
.filter(Boolean)
|
|
49
|
+
.map(String);
|
|
50
|
+
if (values.some((value) => /(?:fulltextxml|\.xml(?:$|[?#])|source\.xml)/i.test(value))) return 'jats_xml';
|
|
51
|
+
if (values.some((value) => /\.pdf(?:$|[?#])|[?&]pdf=render/i.test(value))) return 'pdf';
|
|
52
|
+
if (values.length > 0) return 'html';
|
|
53
|
+
return 'unknown';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function resolvedDoiFor(location, fallbackDoi = '') {
|
|
57
|
+
return doiFromUrl(location.fulltext_url)
|
|
58
|
+
|| doiFromUrl(location.pdf_url)
|
|
59
|
+
|| doiFromUrl(location.landing_page_url)
|
|
60
|
+
|| normalizeDoi(fallbackDoi);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function candidateScore(candidate) {
|
|
64
|
+
return (VERSION_PRIORITY[candidate.version] ?? 0) * 100
|
|
65
|
+
+ (SOURCE_PRIORITY[candidate.source] ?? 0) * 10
|
|
66
|
+
+ (FORMAT_PRIORITY[candidate.original_format] ?? 0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function sortCandidates(candidates) {
|
|
70
|
+
return [...candidates].sort((left, right) => {
|
|
71
|
+
const scoreDifference = candidateScore(right) - candidateScore(left);
|
|
72
|
+
if (scoreDifference !== 0) return scoreDifference;
|
|
73
|
+
return String(left.source_location).localeCompare(String(right.source_location));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function deduplicateCandidates(candidates) {
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
const result = [];
|
|
80
|
+
for (const candidate of sortCandidates(candidates)) {
|
|
81
|
+
const location = String(candidate.source_location || '').replace(/^http:/, 'https:').replace(/\/$/, '');
|
|
82
|
+
const key = location || `${candidate.source}:${candidate.version}:${candidate.resolved_doi || candidate.identifier || ''}`;
|
|
83
|
+
if (seen.has(key)) continue;
|
|
84
|
+
seen.add(key);
|
|
85
|
+
result.push(candidate);
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function requestedWorkFrom(request, metadata = {}) {
|
|
91
|
+
return {
|
|
92
|
+
title: metadata.title || request.title || null,
|
|
93
|
+
authors: metadata.authors?.length ? metadata.authors : request.authors,
|
|
94
|
+
doi: normalizeDoi(metadata.doi || request.doi) || null,
|
|
95
|
+
pmid: metadata.pmid || request.pmid || null,
|
|
96
|
+
pmcid: metadata.pmcid || request.pmcid || null,
|
|
97
|
+
journal: metadata.journal || null,
|
|
98
|
+
year: metadata.year || request.year || null,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function publicCandidate(candidate) {
|
|
103
|
+
const { retrieval, ...publicFields } = candidate;
|
|
104
|
+
return publicFields;
|
|
105
|
+
}
|