@biolibs/europepmc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/article.ts ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * An open-access paper's full text, read out of JATS XML into something a person can read.
3
+ *
4
+ * This is the part of the package that earns its keep. Europe PMC will hand over a paper's whole
5
+ * text, but it hands it over as JATS: a hundred and eighty kilobytes of markup in which the one
6
+ * paragraph somebody wants — which host, which promoter, what yield — is three levels down inside
7
+ * nested `<sec>` elements, wrapped in `<italic>` and interrupted every other sentence by an
8
+ * `<xref>` that renders as "[14]". Handing that on as it stands is not giving anybody the paper.
9
+ *
10
+ * So it is read into sections with their headings, tables as rows, and figures as captions, and
11
+ * three decisions are made here rather than left to whoever reads it:
12
+ *
13
+ * - **A citation marker is not text.** An `<xref>` pointing at the reference list is dropped, so a
14
+ * sentence reads as a sentence. One pointing at a table or a figure is kept, because "as Table 2
15
+ * shows" is part of what the sentence says.
16
+ * - **A table is not a paragraph.** Tables and figures are lifted out of the running text and kept
17
+ * apart, with their labels and captions, since a table flattened into prose is unreadable and a
18
+ * yield is as often in a table as in a sentence.
19
+ * - **A heading is worth more than its words.** Section headings are kept with their depth and
20
+ * their numbering, and {@link sectionsNamed} matches the loose way people name them, so that
21
+ * asking for the methods finds "2. Materials and Methods" and "Experimental Procedures" alike.
22
+ */
23
+ import { Element, ParseError, PullParser } from "@biolibs/seqio";
24
+ import { ask, EuropePmcError } from "./ask.js";
25
+
26
+ /** One section of a paper. */
27
+ export interface Section {
28
+ /** Its heading, or `""` for text that came before any heading. */
29
+ heading: string;
30
+ /** How deeply nested it is: 0 for a top-level section, 1 for one inside that. */
31
+ depth: number;
32
+ /** Its own paragraphs, not counting those of the sections inside it. */
33
+ text: string;
34
+ }
35
+
36
+ /** One table, as rows of cells. */
37
+ export interface Table {
38
+ /** What the paper calls it, such as `Table 2`. */
39
+ label: string;
40
+ /** What it says the table shows. */
41
+ caption: string;
42
+ /** The heading row's cells, if it has one. */
43
+ headings: string[];
44
+ /** The body rows, each a list of cells. */
45
+ rows: string[][];
46
+ }
47
+
48
+ /** One figure, which is a picture and so is only its words. */
49
+ export interface Figure {
50
+ /** What the paper calls it, such as `Figure 1`. */
51
+ label: string;
52
+ /** What it says the figure shows. */
53
+ caption: string;
54
+ }
55
+
56
+ /** A paper, read. */
57
+ export interface Article {
58
+ /** Its title. */
59
+ title: string;
60
+ /** The journal it was published in, and when. */
61
+ journal: string | null;
62
+ year: number | null;
63
+ /** The authors, surname first, as the paper writes them. */
64
+ authors: string[];
65
+ /** The abstract, as one piece of text. */
66
+ abstract: string;
67
+ /** The keywords the paper gives itself. */
68
+ keywords: string[];
69
+ /** Its sections, in the order they are written, each with its own paragraphs. */
70
+ sections: Section[];
71
+ /** Its tables and figures, lifted out of the running text. */
72
+ tables: Table[];
73
+ figures: Figure[];
74
+ /** What it is licensed under, where it says. */
75
+ licence: string | null;
76
+ }
77
+
78
+ /**
79
+ * Tags whose content is lifted out of the running text and kept apart.
80
+ *
81
+ * The reference list is here because some publishers put it inside `<body>` rather than in the back
82
+ * matter, and twenty thousand characters of citations is not something to hand anybody as the text
83
+ * of a section. The section itself is still listed, with its heading and nothing in it.
84
+ */
85
+ const LIFTED = new Set(["table-wrap", "fig", "supplementary-material", "table-wrap-foot", "ref-list"]);
86
+
87
+ /** Tags that are machinery rather than words. */
88
+ const SILENT = new Set(["graphic", "media", "inline-graphic", "object-id", "alt-text"]);
89
+
90
+ /** A section's own words stop where the next section begins. */
91
+ const DEEPER = new Set(["sec"]);
92
+
93
+ /**
94
+ * Tidy a run of words that has had its markup taken out.
95
+ *
96
+ * The brackets are the reason this is more than collapsing whitespace. A paper writes a citation as
97
+ * `[<xref>14</xref>]`, and taking the marker out leaves the brackets standing: "as described
98
+ * before by Sambrook and Russell []." So an empty pair, and the commas and dashes left between
99
+ * markers that were all dropped, go with them.
100
+ */
101
+ const squash = (text: string): string => text
102
+ .replace(/[ \t\r\n]+/g, " ")
103
+ .replace(/[([][\s,;–—-]*[)\]]/g, "")
104
+ .replace(/ ([,.;:)\]])/g, "$1")
105
+ .replace(/([([]) /g, "$1")
106
+ .replace(/ {2,}/g, " ")
107
+ .replace(/ ([.,;:])/g, "$1")
108
+ .trim();
109
+
110
+ /**
111
+ * The words of an element and everything inside it, as running text.
112
+ *
113
+ * A section's own words are its own: the walk does not go down into the sections inside it, or the
114
+ * text of every paragraph would be counted again at every level above it.
115
+ *
116
+ * @param element - The element.
117
+ * @param options - `keepTitle` keeps a `<title>` child's words, which is wanted for a caption and
118
+ * not for a section, whose heading is taken separately.
119
+ * @returns The text, with the markup gone and the spacing tidied.
120
+ */
121
+ export function wordsOf(element: Element, options: { keepTitle?: boolean } = {}): string {
122
+ const out: string[] = [];
123
+ const walk = (one: Element, top: boolean): void => {
124
+ // Whatever was asked for is read, however it is usually treated: a `<label>` is machinery
125
+ // inside a paragraph and is the whole of what is wanted when a table's label is asked for.
126
+ if (!top && (LIFTED.has(one.tag) || SILENT.has(one.tag) || DEEPER.has(one.tag))) return;
127
+ if (one.tag === "label" && !top) return;
128
+ if (one.tag === "title" && options.keepTitle !== true && !top) return;
129
+ // A marker pointing at the reference list renders as "[14]" and is not part of the sentence.
130
+ // One pointing at a table or a figure is: "as Table 2 shows" says something.
131
+ if (one.tag === "xref" && (one.attrib.get("ref-type") ?? "bibr") === "bibr") { if (one.tail !== null) out.push(one.tail); return; }
132
+ if (one.text !== null) out.push(one.text);
133
+ for (const child of one.children) walk(child, false);
134
+ // A paragraph, a list item and a heading each end a run of words; inline markup does not.
135
+ if (!top && (one.tag === "p" || one.tag === "list-item" || one.tag === "title" || one.tag === "td" || one.tag === "th")) out.push("\n");
136
+ if (one.tail !== null) out.push(one.tail);
137
+ };
138
+ walk(element, true);
139
+ return out.join("").split("\n").map(squash).filter((one) => one !== "").join("\n\n");
140
+ }
141
+
142
+ /** The first child with a tag, anywhere inside. */
143
+ const first = (element: Element, tag: string): Element | null => {
144
+ for (const found of element.iter(tag)) if (found !== element) return found;
145
+ return null;
146
+ };
147
+
148
+ /** The heading of a section, which is its `<title>` if it has one. */
149
+ const headingOf = (element: Element): string => {
150
+ const title = element.children.find((one) => one.tag === "title");
151
+ return title === undefined ? "" : squash(wordsOf(title, { keepTitle: true }));
152
+ };
153
+
154
+ /** A table, read out of its wrapper. */
155
+ function tableOf(wrap: Element): Table {
156
+ const label = wrap.children.find((one) => one.tag === "label");
157
+ const caption = wrap.children.find((one) => one.tag === "caption");
158
+ const cells = (row: Element): string[] => row.children.filter((one) => one.tag === "td" || one.tag === "th").map((one) => squash(wordsOf(one, { keepTitle: true })));
159
+ const rowsIn = (tag: string): string[][] => {
160
+ const part = first(wrap, tag);
161
+ return part === null ? [] : [...part.iter("tr")].filter((one) => one.tag === "tr").map(cells);
162
+ };
163
+ const head = rowsIn("thead");
164
+ const body = rowsIn("tbody");
165
+ return {
166
+ label: label === undefined ? "" : squash(wordsOf(label, { keepTitle: true })),
167
+ caption: caption === undefined ? "" : squash(wordsOf(caption, { keepTitle: true })),
168
+ // Some papers have no `thead` and put the headings in the first row of the body.
169
+ headings: head[0] ?? [],
170
+ rows: head.length > 0 ? body : body.slice(0),
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Read a paper out of its JATS XML.
176
+ *
177
+ * @param xml - The document, as Europe PMC sends it.
178
+ * @returns The paper.
179
+ * @throws {@link EuropePmcError} if that is not a JATS article.
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * import { fullTextOf, readArticle, sectionsNamed } from "@biolibs/europepmc";
184
+ *
185
+ * const paper = readArticle(await fullTextOf("PMC12292773"));
186
+ * sectionsNamed(paper, "methods").map((one) => one.heading);
187
+ * ```
188
+ */
189
+ export function readArticle(xml: string): Article {
190
+ let root: Element;
191
+ try {
192
+ const bytes = new TextEncoder().encode(xml);
193
+ const parser = new PullParser(bytes);
194
+ const events = [...parser.feed(bytes.length), ...parser.close()];
195
+ for (const event of events) if (event.kind === "error") throw event.error;
196
+ const started = events.find((event) => event.kind === "start");
197
+ if (started === undefined || started.kind !== "start") throw new ParseError("no element found: line 1, column 0", [1, 0]);
198
+ root = started.elem;
199
+ } catch (cause) {
200
+ throw new EuropePmcError(`That is not a paper Europe PMC could hand over: ${cause instanceof Error ? cause.message : String(cause)}`, "fullTextXML");
201
+ }
202
+ if (root.tag !== "article") throw new EuropePmcError(`Expected a JATS article and got <${root.tag}>. The paper may not be open access.`, "fullTextXML");
203
+
204
+ const titleElement = first(root, "article-title");
205
+ const journal = first(root, "journal-title");
206
+ const abstract = first(root, "abstract");
207
+ const year = [...root.iter("year")].find((one) => one !== root);
208
+ const authors: string[] = [];
209
+ for (const contributor of root.iter("contrib")) {
210
+ if ((contributor.attrib.get("contrib-type") ?? "author") !== "author") continue;
211
+ const surname = first(contributor, "surname")?.text ?? null;
212
+ const given = first(contributor, "given-names")?.text ?? null;
213
+ const name = [surname, given].filter((one) => one !== null).join(" ").trim();
214
+ if (name !== "") authors.push(name);
215
+ }
216
+ const keywords = [...root.iter("kwd")].filter((one) => one !== root).map((one) => squash(wordsOf(one, { keepTitle: true }))).filter((one) => one !== "");
217
+
218
+ const sections: Section[] = [];
219
+ const tables: Table[] = [];
220
+ const figures: Figure[] = [];
221
+ const body = first(root, "body");
222
+ if (body !== null) {
223
+ const walk = (element: Element, depth: number): void => {
224
+ const text = wordsOf(element);
225
+ if (text !== "" || headingOf(element) !== "") sections.push({ heading: headingOf(element), depth, text });
226
+ for (const child of element.children) if (child.tag === "sec") walk(child, depth + 1);
227
+ };
228
+ // Text written before the first section is a section of the paper with no heading. The walk
229
+ // does not descend into the sections, so this is only what is loose.
230
+ const loose = wordsOf(body);
231
+ if (loose !== "") sections.push({ heading: "", depth: 0, text: loose });
232
+ for (const child of body.children) if (child.tag === "sec") walk(child, 0);
233
+ }
234
+ // Lifted from the whole article, so that a table in the back matter is still found.
235
+ for (const wrap of root.iter("table-wrap")) if (wrap !== root) tables.push(tableOf(wrap));
236
+ for (const figure of root.iter("fig")) {
237
+ if (figure === root) continue;
238
+ const label = figure.children.find((one) => one.tag === "label");
239
+ const caption = figure.children.find((one) => one.tag === "caption");
240
+ figures.push({
241
+ label: label === undefined ? "" : squash(wordsOf(label, { keepTitle: true })),
242
+ caption: caption === undefined ? "" : squash(wordsOf(caption, { keepTitle: true })),
243
+ });
244
+ }
245
+
246
+ return {
247
+ title: titleElement === null ? "" : squash(wordsOf(titleElement, { keepTitle: true })),
248
+ journal: journal === null ? null : squash(wordsOf(journal, { keepTitle: true })) || null,
249
+ year: year === undefined || year.text === null || !/^\d{4}$/.test(year.text.trim()) ? null : Number(year.text.trim()),
250
+ authors,
251
+ abstract: abstract === null ? "" : wordsOf(abstract),
252
+ keywords, sections, tables, figures,
253
+ // The licence as a link where the paper gives one, since that is the form anybody can check,
254
+ // and otherwise the words it is stated in.
255
+ licence: (() => {
256
+ const stated = first(root, "license");
257
+ if (stated === null) return null;
258
+ for (const link of stated.iter("ext-link")) {
259
+ const href = link.attrib.get("{http://www.w3.org/1999/xlink}href") ?? link.attrib.get("href");
260
+ if (href !== undefined && href.trim() !== "") return href.trim();
261
+ }
262
+ return squash(wordsOf(stated, { keepTitle: true })) || null;
263
+ })(),
264
+ };
265
+ }
266
+
267
+ /** The headings a kind of section is written under, loosest last. */
268
+ const CALLED: Readonly<Record<string, readonly string[]>> = {
269
+ methods: ["materials and methods", "methods and materials", "experimental procedures", "experimental section",
270
+ "materials & methods", "methods", "experimental"],
271
+ results: ["results and discussion", "results"],
272
+ discussion: ["discussion", "conclusions and discussion"],
273
+ introduction: ["introduction", "background"],
274
+ conclusion: ["conclusions", "conclusion", "concluding remarks", "summary"],
275
+ abstract: ["abstract", "summary"],
276
+ };
277
+
278
+ /** The kinds of section that can be asked for by name. */
279
+ export const SECTION_KINDS = Object.keys(CALLED);
280
+
281
+ /**
282
+ * The sections of a paper written under a given kind of heading.
283
+ *
284
+ * {@link findSection} is this, and says besides whether the heading was that name outright or only
285
+ * contained it, which is worth knowing before passing an answer on.
286
+ *
287
+ * Papers do not agree about what to call anything. The methods are under "Materials and Methods",
288
+ * "Experimental Procedures", "Methods", or a number and then one of those, and the one thing they
289
+ * have in common is that nobody writing a tool can rely on which. So the matching is loose, the
290
+ * numbering is ignored, and the sections *inside* a matching one come with it — a yield in "2.4.
291
+ * Fermentation" belongs to the methods even though its own heading does not say so.
292
+ *
293
+ * @param article - The paper.
294
+ * @param kind - What is wanted: `methods`, `results`, `discussion`, `introduction`, `conclusion`,
295
+ * or any other words, which are matched against the headings as they are.
296
+ * @returns The sections, in the order they are written. Empty if the paper has no such heading.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * import { sectionsNamed } from "@biolibs/europepmc";
301
+ *
302
+ * sectionsNamed(paper, "methods"); // "2. Materials and Methods" and everything under it
303
+ * sectionsNamed(paper, "casein"); // any heading with that word in it
304
+ * ```
305
+ */
306
+ export const sectionsNamed = (article: Article, kind: string): Section[] => findSection(article, kind).sections;
307
+
308
+ /**
309
+ * The sections of a paper written under a given kind of heading, and how they were found.
310
+ *
311
+ * {@link sectionsNamed} is this without the second part. The second part matters when the answer is
312
+ * going to be handed to somebody: a paper with no methods section at all still has headings with
313
+ * the word "methods" in them, and "BNBMs by novel biosynthesis methods" is not the methods. Saying
314
+ * which kind of match it was lets a caller pass that doubt on instead of swallowing it.
315
+ *
316
+ * @param article - The paper.
317
+ * @param kind - What is wanted, as {@link sectionsNamed} takes it.
318
+ * @returns The sections, and whether a heading was that name outright rather than merely containing it.
319
+ */
320
+ export function findSection(article: Article, kind: string): { sections: Section[]; exact: boolean } {
321
+ const asked = kind.trim().toLowerCase();
322
+ if (asked === "") return { sections: [], exact: false };
323
+ // A heading without its numbering: "2.4. Fermentation" is "fermentation".
324
+ const bare = (heading: string): string => heading.toLowerCase().replace(/^[\d.\s]+/, "").replace(/[.:]\s*$/, "").trim();
325
+ const wanted = CALLED[asked] ?? [asked];
326
+ // A heading that is one of the names outright wins over one that merely contains it, so that
327
+ // "Methods" is preferred to "Supplementary Methods" wherever the paper has both.
328
+ const exact = article.sections.findIndex((one) => wanted.some((name) => bare(one.heading) === name));
329
+ const found = exact >= 0 ? exact
330
+ : article.sections.findIndex((one) => one.heading !== "" && wanted.some((name) => bare(one.heading).includes(name)));
331
+ if (found < 0) return { sections: [], exact: false };
332
+ // Everything under it is part of it, down to the next heading at the same depth or shallower.
333
+ const start = article.sections[found]!;
334
+ const out = [start];
335
+ for (const one of article.sections.slice(found + 1)) {
336
+ if (one.depth <= start.depth) break;
337
+ out.push(one);
338
+ }
339
+ return { sections: out, exact: exact >= 0 };
340
+ }
341
+
342
+ /**
343
+ * Fetch one open-access paper's full text.
344
+ *
345
+ * @param pmcid - Its PubMed Central ID, such as `PMC12292773`.
346
+ * @returns The JATS XML, to be read with {@link readArticle}.
347
+ * @throws {@link EuropePmcError} if there is no full text to be had, which for a paper that is not
348
+ * open access is the usual answer.
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * import { fullTextOf } from "@biolibs/europepmc";
353
+ *
354
+ * const xml = await fullTextOf("PMC12292773");
355
+ * ```
356
+ */
357
+ export async function fullTextOf(pmcid: string): Promise<string> {
358
+ const id = pmcid.trim().toUpperCase();
359
+ if (!/^PMC\d{1,12}$/.test(id)) throw new EuropePmcError(`${JSON.stringify(pmcid)} is not a PubMed Central ID. One looks like PMC12292773.`, "fullTextXML");
360
+ try {
361
+ return await ask(`${id}/fullTextXML`);
362
+ } catch (cause) {
363
+ if (cause instanceof EuropePmcError && cause.status === 404) {
364
+ throw new EuropePmcError(`Europe PMC has no full text for ${id}. Only open-access papers can be read in full; for the rest there is the abstract.`, cause.url, 404);
365
+ }
366
+ throw cause;
367
+ }
368
+ }
package/src/ask.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Asking Europe PMC something: the one part of this package that touches the network.
3
+ *
4
+ * Everything else is given a {@link Transport}, so the rest can be run, and tested, without one.
5
+ *
6
+ * Europe PMC's REST service needs no key and no account. What it asks of a client is that it names
7
+ * itself, so that heavy use can be traced to a piece of software rather than to nobody. It is told
8
+ * the software's name and nothing else: never a person, never an address, unless somebody sets one
9
+ * on purpose.
10
+ */
11
+ import { BioError } from "@biolibs/core";
12
+
13
+ /** Where the service lives. */
14
+ export const SERVICE = "https://www.ebi.ac.uk/europepmc/webservices/rest";
15
+
16
+ /** Something went wrong asking Europe PMC. */
17
+ export class EuropePmcError extends BioError {
18
+ /** The HTTP status, or `null` if there was no answer at all. */
19
+ readonly status: number | null;
20
+ /** The address that was asked for. */
21
+ readonly url: string;
22
+ /**
23
+ * Whether the service could not be reached at all.
24
+ *
25
+ * It is a field of its own because a missing status does not mean what it looks like it means.
26
+ * An ID that is the wrong shape is refused before anything is sent, and so has no status either,
27
+ * and telling somebody their device is offline when what is wrong is their typing sends them to
28
+ * check the wrong thing.
29
+ */
30
+ readonly offline: boolean;
31
+
32
+ /**
33
+ * @param message - What went wrong, in words.
34
+ * @param url - What was asked for.
35
+ * @param status - The HTTP status, if there was one.
36
+ * @param offline - Whether the service could not be reached at all.
37
+ */
38
+ constructor(message: string, url: string, status: number | null = null, offline = false) {
39
+ super(message);
40
+ this.name = "EuropePmcError";
41
+ this.url = url;
42
+ this.status = status;
43
+ this.offline = offline;
44
+ }
45
+ }
46
+
47
+ /** A successful reply, before anything is done with it. */
48
+ export interface Reply {
49
+ /** The `Content-Type` header, or `null` if there was none. */
50
+ contentType: string | null;
51
+ /** The body, as text. */
52
+ body: string;
53
+ }
54
+
55
+ /**
56
+ * Sends a request.
57
+ *
58
+ * @param url - The whole address, query string and all.
59
+ * @param headers - What to send with it.
60
+ * @returns The reply, if the service answered with success.
61
+ * @throws {@link EuropePmcError} otherwise.
62
+ */
63
+ export type Transport = (url: string, headers: Readonly<Record<string, string>>) => Promise<Reply>;
64
+
65
+ /** The default {@link Transport}: the platform's `fetch`. */
66
+ export const fetchTransport: Transport = async (url, headers) => {
67
+ let response: Response;
68
+ try {
69
+ response = await fetch(url, { headers: { ...headers } });
70
+ } catch (cause) {
71
+ throw new EuropePmcError(`Europe PMC could not be reached: ${cause instanceof Error ? cause.message : String(cause)}`, url, null, true);
72
+ }
73
+ if (!response.ok) throw new EuropePmcError(`Europe PMC answered ${response.status} ${response.statusText}.`, url, response.status);
74
+ return { contentType: response.headers.get("content-type"), body: await response.text() };
75
+ };
76
+
77
+ /** The settings every request shares. */
78
+ export interface Settings {
79
+ /**
80
+ * What to call this software when asking. Europe PMC asks a client to name itself so that heavy
81
+ * use can be traced to a program; it is never a person's name.
82
+ */
83
+ tool: string;
84
+ /**
85
+ * An address Europe PMC could use to get in touch about heavy use, if somebody has given one for
86
+ * that on purpose. It is never taken from a lab, a document or a device.
87
+ */
88
+ email: string | null;
89
+ /** The most characters of any reply that will be read. A paper is not a genome, but some are long. */
90
+ mostCharacters: number;
91
+ /** Sends a request. Replace it to use something else, or to test without a network. */
92
+ transport: Transport;
93
+ }
94
+
95
+ /** Shared settings. */
96
+ export const settings: Settings = {
97
+ tool: "biolibs-europepmc",
98
+ email: null,
99
+ mostCharacters: 4_000_000,
100
+ transport: fetchTransport,
101
+ };
102
+
103
+ /**
104
+ * Ask the service for something.
105
+ *
106
+ * @param path - The path under the service, such as `search` or `PMC123/fullTextXML`.
107
+ * @param query - The query string, as pairs. Anything `undefined` is left out.
108
+ * @returns The body, as text.
109
+ * @throws {@link EuropePmcError} if it could not be reached, answered with a failure, or sent back
110
+ * more than {@link Settings.mostCharacters}.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * import { ask } from "@biolibs/europepmc";
115
+ *
116
+ * const body = await ask("search", { query: "casein AND yeast", format: "json", pageSize: 5 });
117
+ * ```
118
+ */
119
+ export async function ask(path: string, query: Readonly<Record<string, string | number | undefined>> = {}): Promise<string> {
120
+ const search = new URLSearchParams();
121
+ for (const [name, value] of Object.entries(query)) if (value !== undefined) search.set(name, String(value));
122
+ // The service names it `email`, and sends nothing back that depends on it: it is a way to be told
123
+ // off before being blocked, and it only goes if somebody put one in the settings.
124
+ if (settings.email !== null && settings.email.trim() !== "") search.set("email", settings.email.trim());
125
+ const url = `${SERVICE}/${path}${search.size === 0 ? "" : `?${search.toString()}`}`;
126
+ let reply: Reply;
127
+ try {
128
+ reply = await settings.transport(url, { "User-Agent": settings.tool, Accept: "application/json, application/xml;q=0.9, */*;q=0.8" });
129
+ } catch (cause) {
130
+ // The transport is replaceable, and this says it throws one kind of error. One that threw
131
+ // something else still failed to deliver a request, which is what being offline is.
132
+ if (cause instanceof EuropePmcError) throw cause;
133
+ throw new EuropePmcError(`Europe PMC could not be reached: ${cause instanceof Error ? cause.message : String(cause)}`, url, null, true);
134
+ }
135
+ if (reply.body.length > settings.mostCharacters) {
136
+ throw new EuropePmcError(`That reply is ${reply.body.length.toLocaleString("en-US")} characters, which is more than one ask reads.`, url);
137
+ }
138
+ return reply.body;
139
+ }
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@biolibs/europepmc`: searching the literature, and reading an open-access paper as sections,
4
+ * tables and figures instead of as JATS XML.
5
+ *
6
+ * There is no Biopython counterpart to be a port of. What there is instead is a service that will
7
+ * hand over a paper's whole text, and a format — JATS — that nobody reads by choice. Europe PMC
8
+ * needs no key and no account; it asks only that a client name itself, which {@link settings} does
9
+ * and which is the only thing it ever sends about who is asking.
10
+ *
11
+ * - `ask.ts`: `settings`, `ask`, `EuropePmcError` — one place that touches the network
12
+ * - `search.ts`: `searchArticles`, `Found` — the literature by keyword, saying plainly whether each
13
+ * result's full text can actually be read
14
+ * - `article.ts`: `fullTextOf`, `readArticle`, `sectionsNamed` — a paper, read out of its markup
15
+ * - `trail.ts`: `referencesOf`, `citationsOf` — what a paper cited, and who has cited it
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { fullTextOf, readArticle, searchArticles, sectionsNamed } from "@biolibs/europepmc";
20
+ *
21
+ * const found = await searchArticles('"kappa-casein" AND "Pichia pastoris"', { corpus: "open-access" });
22
+ * const readable = found.results.find((one) => one.fullText);
23
+ * if (readable?.pmcid != null) {
24
+ * const paper = readArticle(await fullTextOf(readable.pmcid));
25
+ * for (const section of sectionsNamed(paper, "methods")) console.log(section.heading, section.text.slice(0, 200));
26
+ * }
27
+ * ```
28
+ */
29
+
30
+ export * from "./ask.js";
31
+ export * from "./search.js";
32
+ export * from "./article.js";
33
+ export * from "./trail.js";