SPB Git

Repository Public Research preview

bibtex.mjs 7.6 KB 134 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : LLM API toolkits8 * File             : scholarly/mcp/lib/bibtex.mjs9 * Module           : scholarly10 * Repository       : https://git.spboucher.ai/llm-api-toolkits11 * Created          : 2026-11-1012 * Last Modified    : 2026-11-1013 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: dev@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { normalizeDoi } from "./normalize.mjs";4344/** A small, strict-enough BibTeX reader: entries, braced or quoted values, @string macros, # concatenation. */45const ACCENTS = { "`": "̀", "'": "́", "^": "̂", "~": "̃", '"': "̈", "=": "̄", ".": "̇", u: "̆", v: "̌", H: "̋", c: "̧", k: "̨", r: "̊" };46const SPECIAL = { ss: "ß", ae: "æ", AE: "Æ", oe: "œ", OE: "Œ", o: "ø", O: "Ø", l: "ł", L: "Ł", aa: "å", AA: "Å", i: "ı", j: "ȷ" };4748export function latexToText(s) {49  let t = String(s ?? "");50  t = t.replace(/\\([`'^~"=.])\s*\{?\\?([a-zA-Z])\}?/g, (_, a, ch) => (ch + ACCENTS[a]).normalize("NFC"));51  t = t.replace(/\\([uvHckr])\s*\{\\?([a-zA-Z])\}/g, (_, a, ch) => (ch + ACCENTS[a]).normalize("NFC"));52  t = t.replace(/\\(ss|ae|AE|oe|OE|aa|AA|o|O|l|L|i|j)(?![a-zA-Z])\s*(\{\})?/g, (_, k) => SPECIAL[k]);53  t = t.replace(/\\(?:textit|textbf|emph|textsc|texttt|mathrm|text|mbox|url)\s*\{([^{}]*)\}/g, "$1");54  t = t.replace(/\\&/g, "&").replace(/\\%/g, "%").replace(/\\_/g, "_").replace(/\\\$/g, "$").replace(/\\#/g, "#").replace(/~/g, " ").replace(/---/g, "—").replace(/--/g, "–");55  t = t.replace(/\$([^$]*)\$/g, "$1").replace(/\\[a-zA-Z]+\s*/g, "").replace(/[{}]/g, "");56  return t.replace(/\s+/g, " ").trim();57}5859export function splitAuthors(field) {60  if (!field) return [];61  const parts = [];62  let depth = 0, cur = "";63  const toks = String(field).split(/(\s+and\s+)/i);64  for (const tk of toks) {65    if (/^\s+and\s+$/i.test(tk) && depth === 0) { parts.push(cur); cur = ""; continue; }66    for (const ch of tk) { if (ch === "{") depth++; else if (ch === "}") depth = Math.max(0, depth - 1); }67    cur += tk;68  }69  parts.push(cur);70  return parts.map((p) => p.trim()).filter((p) => p && !/^others$/i.test(p)).map((raw) => {71    const corporate = /^\{.*\}$/.test(raw);72    const name = latexToText(raw);73    if (corporate) return { family: name, given: null, name };74    if (name.includes(",")) { const [fam, ...rest] = name.split(",").map((x) => x.trim()); const given = rest.filter(Boolean).pop() ?? null; return { family: fam, given, name: [given, fam].filter(Boolean).join(" ") }; }75    const w = name.split(/\s+/);76    let i = w.length - 1;77    while (i > 0 && /^(van|von|der|den|de|del|della|di|da|dos|du|la|le|ter|ten)$/.test(w[i - 1])) i--;78    return { family: w.slice(i).join(" "), given: w.slice(0, i).join(" ") || null, name };79  });80}8182export function parseBibtex(text) {83  const src = String(text ?? ""), entries = [], errors = [], strings = { jan: "January", feb: "February", mar: "March", apr: "April", may: "May", jun: "June", jul: "July", aug: "August", sep: "September", oct: "October", nov: "November", dec: "December" };84  let i = 0;85  const line = (pos) => src.slice(0, pos).split("\n").length;86  function readValue() {87    let out = "";88    for (;;) {89      while (/\s/.test(src[i] ?? "")) i++;90      if (src[i] === "{") { let depth = 0, start = i; do { if (src[i] === "{") depth++; else if (src[i] === "}") depth--; i++; if (i > src.length) throw new Error("unbalanced braces"); } while (depth > 0); out += src.slice(start + 1, i - 1); }91      else if (src[i] === '"') { let depth = 0; i++; const start = i; while (i < src.length && !(src[i] === '"' && depth === 0)) { if (src[i] === "{") depth++; else if (src[i] === "}") depth--; i++; } if (i >= src.length) throw new Error("unterminated string"); out += src.slice(start, i); i++; }92      else { const m = /^[A-Za-z0-9_.:+\-/]+/.exec(src.slice(i)); if (!m) throw new Error("expected a value"); i += m[0].length; out += /^\d+$/.test(m[0]) ? m[0] : strings[m[0].toLowerCase()] ?? m[0]; }93      while (/\s/.test(src[i] ?? "")) i++;94      if (src[i] === "#") { i++; continue; }95      return out;96    }97  }98  while (i < src.length) {99    const at = src.indexOf("@", i);100    if (at === -1) break;101    i = at + 1;102    const tm = /^\s*([A-Za-z]+)\s*([({])/.exec(src.slice(i));103    if (!tm) continue;104    const type = tm[1].toLowerCase(), startLine = line(at);105    i += tm[0].length;106    try {107      if (type === "comment" || type === "preamble") { let depth = 1; while (i < src.length && depth > 0) { if (src[i] === "{" || src[i] === "(") depth++; else if (src[i] === "}" || src[i] === ")") depth--; i++; } continue; }108      if (type === "string") { const km = /^\s*([A-Za-z0-9_.:+\-]+)\s*=/.exec(src.slice(i)); if (!km) throw new Error("malformed @string"); i += km[0].length; strings[km[1].toLowerCase()] = readValue(); continue; }109      const km = /^\s*([^,\s{}()]*)\s*,/.exec(src.slice(i));110      if (!km) throw new Error("missing citation key");111      i += km[0].length;112      const fields = {};113      for (;;) {114        while (/[\s,]/.test(src[i] ?? "")) i++;115        if (src[i] === "}" || src[i] === ")") { i++; break; }116        if (i >= src.length) throw new Error("entry is not closed");117        const fm = /^([A-Za-z][A-Za-z0-9_\-:]*)\s*=/.exec(src.slice(i));118        if (!fm) throw new Error(`expected a field name near "${src.slice(i, i + 20).replace(/\s+/g, " ")}"`);119        i += fm[0].length;120        fields[fm[1].toLowerCase()] = readValue();121      }122      const doi = normalizeDoi(fields.doi ?? "") ?? (/doi\.org\//i.test(fields.url ?? "") ? normalizeDoi(fields.url) : null);123      const eprint = /arxiv/i.test(`${fields.archiveprefix ?? ""} ${fields.eprinttype ?? ""} ${fields.journal ?? ""} ${fields.url ?? ""}`) ? (/(\d{4}\.\d{4,5})/.exec(`${fields.eprint ?? ""} ${fields.journal ?? ""} ${fields.url ?? ""}`)?.[1] ?? null) : null;124      entries.push({125        key: km[1], type, line: startLine, raw_fields: fields,126        title: fields.title ? latexToText(fields.title) : null, authors: splitAuthors(fields.author ?? fields.editor ?? ""), year: Number(/\b(1[5-9]\d\d|20\d\d)\b/.exec(fields.year ?? fields.date ?? "")?.[1] ?? NaN) || null,127        venue: latexToText(fields.journal ?? fields.journaltitle ?? fields.booktitle ?? fields.publisher ?? "") || null, volume: fields.volume ?? null, issue: fields.number ?? fields.issue ?? null, pages: fields.pages ? latexToText(fields.pages) : null,128        doi, arxiv: eprint, url: fields.url ?? null,129      });130    } catch (e) { errors.push({ line: startLine, type, message: e.message }); }131  }132  return { entries, errors };133}134
Files main
Menu

Theme