docrev 0.11.0 → 0.11.2

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.
Files changed (123) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +202 -184
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -431
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/build.d.ts +80 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +207 -4
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/build.d.ts.map +1 -1
  15. package/dist/lib/commands/build.js +34 -12
  16. package/dist/lib/commands/build.js.map +1 -1
  17. package/dist/lib/commands/utilities.js +164 -164
  18. package/dist/lib/commands/word-tools.js +8 -8
  19. package/dist/lib/grammar.js +3 -3
  20. package/dist/lib/macro-filter.lua +201 -201
  21. package/dist/lib/pdf-comments.js +44 -44
  22. package/dist/lib/plugins.js +57 -57
  23. package/dist/lib/pptx-color-filter.lua +37 -37
  24. package/dist/lib/pptx-themes.js +115 -115
  25. package/dist/lib/schema.d.ts.map +1 -1
  26. package/dist/lib/schema.js +8 -2
  27. package/dist/lib/schema.js.map +1 -1
  28. package/dist/lib/spelling.js +2 -2
  29. package/dist/lib/templates.js +387 -387
  30. package/dist/lib/themes.js +51 -51
  31. package/dist/lib/trackchanges.d.ts +41 -25
  32. package/dist/lib/trackchanges.d.ts.map +1 -1
  33. package/dist/lib/trackchanges.js +90 -151
  34. package/dist/lib/trackchanges.js.map +1 -1
  35. package/dist/lib/types.d.ts +0 -7
  36. package/dist/lib/types.d.ts.map +1 -1
  37. package/docs-src/build.py +113 -113
  38. package/docs-src/extra.css +208 -208
  39. package/docs-src/md-to-html.lua +6 -6
  40. package/docs-src/template.html +116 -116
  41. package/eslint.config.js +27 -27
  42. package/lib/anchor-match.ts +307 -307
  43. package/lib/annotations.ts +664 -664
  44. package/lib/build.ts +2047 -1770
  45. package/lib/citations.ts +160 -160
  46. package/lib/commands/build.ts +885 -860
  47. package/lib/commands/citations.ts +515 -515
  48. package/lib/commands/comments.ts +1050 -1050
  49. package/lib/commands/context.ts +176 -176
  50. package/lib/commands/core.ts +309 -309
  51. package/lib/commands/doi.ts +451 -451
  52. package/lib/commands/file-ops.ts +372 -372
  53. package/lib/commands/history.ts +320 -320
  54. package/lib/commands/index.ts +87 -87
  55. package/lib/commands/init.ts +259 -259
  56. package/lib/commands/merge-resolve.ts +378 -378
  57. package/lib/commands/preview.ts +178 -178
  58. package/lib/commands/project-info.ts +244 -244
  59. package/lib/commands/quality.ts +517 -517
  60. package/lib/commands/response.ts +454 -454
  61. package/lib/commands/section-boundaries.ts +82 -82
  62. package/lib/commands/sections.ts +451 -451
  63. package/lib/commands/sync.ts +689 -689
  64. package/lib/commands/text-ops.ts +449 -449
  65. package/lib/commands/utilities.ts +448 -448
  66. package/lib/commands/verify-anchors.ts +272 -272
  67. package/lib/commands/word-tools.ts +340 -340
  68. package/lib/comment-realign.ts +99 -99
  69. package/lib/config.ts +84 -84
  70. package/lib/crossref.ts +781 -781
  71. package/lib/csl.ts +191 -191
  72. package/lib/dependencies.ts +132 -132
  73. package/lib/diff-engine.ts +465 -465
  74. package/lib/doi-cache.ts +115 -115
  75. package/lib/doi.ts +879 -879
  76. package/lib/equations.ts +506 -506
  77. package/lib/errors.ts +350 -350
  78. package/lib/format.ts +541 -541
  79. package/lib/git.ts +326 -326
  80. package/lib/grammar.ts +303 -303
  81. package/lib/image-registry.ts +180 -180
  82. package/lib/import.ts +906 -906
  83. package/lib/journals.ts +543 -543
  84. package/lib/macro-filter.lua +201 -201
  85. package/lib/macros.ts +273 -273
  86. package/lib/merge.ts +633 -633
  87. package/lib/ooxml.ts +768 -768
  88. package/lib/orcid.ts +144 -144
  89. package/lib/pdf-comments.ts +263 -263
  90. package/lib/pdf-import.ts +524 -524
  91. package/lib/plugins.ts +362 -362
  92. package/lib/postprocess.ts +188 -188
  93. package/lib/pptx-color-filter.lua +37 -37
  94. package/lib/pptx-template.ts +469 -469
  95. package/lib/pptx-themes.ts +483 -483
  96. package/lib/protect-restore.ts +520 -520
  97. package/lib/rate-limiter.ts +127 -127
  98. package/lib/response.ts +197 -197
  99. package/lib/restore-references.ts +240 -240
  100. package/lib/review.ts +327 -327
  101. package/lib/schema.ts +494 -488
  102. package/lib/scientific-words.ts +73 -73
  103. package/lib/sections.ts +428 -428
  104. package/lib/slides.ts +756 -756
  105. package/lib/spelling.ts +334 -334
  106. package/lib/templates.ts +526 -526
  107. package/lib/themes.ts +742 -742
  108. package/lib/trackchanges.ts +166 -247
  109. package/lib/tui.ts +450 -450
  110. package/lib/types.ts +546 -558
  111. package/lib/undo.ts +250 -250
  112. package/lib/utils.ts +69 -69
  113. package/lib/variables.ts +179 -179
  114. package/lib/word-extraction.ts +525 -525
  115. package/lib/word.ts +526 -526
  116. package/lib/wordcomments.ts +789 -789
  117. package/mkdocs.yml +64 -64
  118. package/package.json +137 -137
  119. package/scripts/postbuild.js +47 -47
  120. package/skill/REFERENCE.md +550 -539
  121. package/skill/SKILL.md +302 -295
  122. package/tsconfig.json +26 -26
  123. package/types/index.d.ts +531 -525
package/lib/doi.ts CHANGED
@@ -1,879 +1,879 @@
1
- /**
2
- * DOI validation and fetching utilities
3
- * Check DOIs in .bib files, fetch BibTeX from DOIs
4
- */
5
-
6
- import * as fs from 'fs';
7
- import type { BibEntry, DoiCheckResult, BibtexFetchResult, DoiLookupResult, BibCheckResult } from './types.js';
8
- import { crossrefLimiter, dataciteLimiter, doiOrgLimiter } from './rate-limiter.js';
9
- import { getCachedDoi, cacheDoi } from './doi-cache.js';
10
-
11
- // Entry types that typically don't have DOIs
12
- const NO_DOI_TYPES = new Set([
13
- 'book', // Books often don't have DOIs (chapters might)
14
- 'inbook', // Book chapters - variable
15
- 'thesis', // Theses rarely have DOIs
16
- 'mastersthesis',
17
- 'phdthesis',
18
- 'misc', // Catch-all, often no DOI
19
- 'unpublished', // By definition
20
- 'manual', // Software manuals
21
- 'techreport', // Some do, many don't
22
- 'booklet',
23
- ]);
24
-
25
- // Thresholds for the heuristic DOI-match score (title + author + year +
26
- // journal). `high` auto-accepts, `medium` asks the user, below `medium` is a
27
- // weak guess. `runnerUpMargin` is how far the best must beat the second-best
28
- // to count as high — guards against picking the wrong one of two near-ties.
29
- const DOI_CONFIDENCE = {
30
- high: 120,
31
- medium: 70,
32
- runnerUpMargin: 30,
33
- };
34
-
35
- // Entry types that should have DOIs
36
- const EXPECT_DOI_TYPES = new Set([
37
- 'article', // Journal articles should have DOIs
38
- 'inproceedings', // Conference papers usually do
39
- 'proceedings',
40
- 'incollection', // Book chapters in collections
41
- ]);
42
-
43
- /**
44
- * Parse .bib file and extract entries with DOI info
45
- */
46
- export function parseBibEntries(bibPath: string): BibEntry[] {
47
- if (!fs.existsSync(bibPath)) {
48
- return [];
49
- }
50
-
51
- const content = fs.readFileSync(bibPath, 'utf-8');
52
- const entries: BibEntry[] = [];
53
- const lines = content.split('\n');
54
-
55
- // Pattern for bib entries: @type{key,
56
- const entryPattern = /@(\w+)\s*\{\s*([^,\s]+)\s*,/g;
57
-
58
- let match: RegExpExecArray | null;
59
- while ((match = entryPattern.exec(content)) !== null) {
60
- const type = match[1]!.toLowerCase();
61
- const key = match[2]!;
62
- const startPos = match.index;
63
-
64
- // Find the line number
65
- let line = 1;
66
- for (let i = 0; i < startPos; i++) {
67
- if (content[i] === '\n') line++;
68
- }
69
-
70
- // Find the end of this entry (matching closing brace)
71
- let braceCount = 0;
72
- let entryEnd = startPos;
73
- let inEntry = false;
74
-
75
- for (let i = startPos; i < content.length; i++) {
76
- if (content[i] === '{') {
77
- braceCount++;
78
- inEntry = true;
79
- } else if (content[i] === '}') {
80
- braceCount--;
81
- if (inEntry && braceCount === 0) {
82
- entryEnd = i + 1;
83
- break;
84
- }
85
- }
86
- }
87
-
88
- const entryContent = content.slice(startPos, entryEnd);
89
-
90
- // Extract DOI field
91
- const doiMatch = entryContent.match(/\bdoi\s*=\s*[{"]([^}"]+)[}"]/i);
92
- let doi = doiMatch ? doiMatch[1]!.trim() : null;
93
-
94
- // Clean DOI - remove URL prefix if present
95
- if (doi) {
96
- doi = doi.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '');
97
- }
98
-
99
- // Extract title for display
100
- const titleMatch = entryContent.match(/\btitle\s*=\s*[{"]([^}"]+)[}"]/i);
101
- const title = titleMatch ? titleMatch[1]!.trim().slice(0, 60) : '';
102
-
103
- // Extract author for lookup
104
- const authorMatch = entryContent.match(/\bauthor\s*=\s*[{"]([^}"]+)[}"]/i);
105
- const authorRaw = authorMatch ? authorMatch[1]!.trim() : '';
106
-
107
- // Extract year
108
- const yearMatch = entryContent.match(/\byear\s*=\s*[{"]?(\d{4})[}""]?/i);
109
- const year = yearMatch ? parseInt(yearMatch[1]!) : null;
110
-
111
- // Extract journal
112
- const journalMatch = entryContent.match(/\bjournal\s*=\s*[{"]([^}"]+)[}"]/i);
113
- const journal = journalMatch ? journalMatch[1]!.trim() : '';
114
-
115
- // Check for skip marker: nodoi = {true} or nodoi = true
116
- const skipMatch = entryContent.match(/\bnodoi\s*=\s*[{"]?(true|yes|1)[}""]?/i);
117
- const skip = !!skipMatch;
118
-
119
- // Check for comment marker immediately before entry: % no-doi
120
- // Only look at the text between the last entry end (or start) and this entry
121
- const linesBefore = content.slice(Math.max(0, startPos - 200), startPos);
122
- // Find the last closing brace or start of file to avoid matching comments for previous entries
123
- const lastEntryEnd = linesBefore.lastIndexOf('}');
124
- const relevantBefore = lastEntryEnd >= 0 ? linesBefore.slice(lastEntryEnd + 1) : linesBefore;
125
- const commentSkip = /% *no-?doi/i.test(relevantBefore);
126
-
127
- entries.push({
128
- key,
129
- type,
130
- doi: doi || null,
131
- title,
132
- authorRaw,
133
- year,
134
- journal,
135
- skip: skip || commentSkip,
136
- expectDoi: EXPECT_DOI_TYPES.has(type),
137
- noDoi: NO_DOI_TYPES.has(type),
138
- line,
139
- });
140
- }
141
-
142
- return entries;
143
- }
144
-
145
- /**
146
- * Validate DOI format
147
- */
148
- export function isValidDoiFormat(doi: string): boolean {
149
- if (!doi) return false;
150
- // DOI format: 10.prefix/suffix
151
- // Prefix is 4+ digits, suffix can contain most characters
152
- return /^10\.\d{4,}\/[^\s]+$/.test(doi);
153
- }
154
-
155
- interface CheckDoiOptions {
156
- skipCache?: boolean;
157
- }
158
-
159
- /**
160
- * Check if DOI resolves (exists) - tries Crossref first, then DataCite
161
- * Results are cached for 7 days to reduce API calls.
162
- */
163
- export async function checkDoi(doi: string, options: CheckDoiOptions = {}): Promise<DoiCheckResult & { cached?: boolean }> {
164
- if (!isValidDoiFormat(doi)) {
165
- return { valid: false, error: 'Invalid DOI format' };
166
- }
167
-
168
- // Check cache first (unless skipped)
169
- if (!options.skipCache) {
170
- const cached = getCachedDoi(doi);
171
- if (cached) {
172
- return { ...cached, cached: true } as DoiCheckResult & { cached?: boolean };
173
- }
174
- }
175
-
176
- // One resolution path: doi.org content negotiation returns CSL-JSON and
177
- // federates every registration agency (Crossref, DataCite, mEDRA, ...), so
178
- // there is no registrar to guess and no Crossref-then-DataCite fallback.
179
- try {
180
- const response = await doiOrgLimiter.fetchWithRetry(
181
- `https://doi.org/${encodeURIComponent(doi)}`,
182
- {
183
- headers: {
184
- 'Accept': 'application/vnd.citationstyles.csl+json',
185
- 'User-Agent': 'docrev (https://github.com/gcol33/docrev)',
186
- },
187
- redirect: 'follow',
188
- },
189
- );
190
-
191
- if (response.status === 404 || response.status === 410) {
192
- // Definitive: the registry resolved and the DOI is not registered.
193
- const result: DoiCheckResult = { valid: false, error: 'DOI not found' };
194
- cacheDoi(doi, result);
195
- return result;
196
- }
197
-
198
- if (!response.ok) {
199
- // 5xx or unexpected: the registry is reachable but not answering — the
200
- // DOI's status is unknown, so do not declare it invalid or cache it.
201
- return { valid: false, unreachable: true, error: `HTTP ${response.status}` };
202
- }
203
-
204
- const work = await response.json() as any;
205
- const result: DoiCheckResult = {
206
- valid: true,
207
- source: 'doi.org',
208
- metadata: metadataFromCsl(work),
209
- };
210
-
211
- cacheDoi(doi, result);
212
- return result;
213
- } catch (err) {
214
- // Network failure / timeout: cannot reach the resolver. Unknown, not invalid.
215
- return { valid: false, unreachable: true, error: (err as Error).message };
216
- }
217
- }
218
-
219
- /**
220
- * Extract docrev's metadata fields from a CSL-JSON record — the shape doi.org
221
- * content negotiation returns for any registrar.
222
- */
223
- function metadataFromCsl(work: any): DoiCheckResult['metadata'] {
224
- const dateParts =
225
- work?.issued?.['date-parts']?.[0] ||
226
- work?.published?.['date-parts']?.[0] ||
227
- work?.created?.['date-parts']?.[0];
228
- const year = Array.isArray(dateParts) ? dateParts[0] : undefined;
229
-
230
- const authors = Array.isArray(work?.author)
231
- ? work.author
232
- .map((a: any) => `${a.given || a.givenName || ''} ${a.family || a.familyName || ''}`.trim())
233
- .filter((s: string) => s.length > 0)
234
- : [];
235
-
236
- const title = Array.isArray(work?.title) ? work.title[0] : work?.title;
237
- const journal = Array.isArray(work?.['container-title'])
238
- ? work['container-title'][0]
239
- : work?.['container-title'] || work?.publisher;
240
-
241
- return {
242
- title: title || '',
243
- authors,
244
- year: year || 0,
245
- journal: journal || '',
246
- type: work?.type,
247
- };
248
- }
249
-
250
- /**
251
- * Fetch BibTeX from DOI using content negotiation
252
- */
253
- export async function fetchBibtex(doi: string): Promise<BibtexFetchResult> {
254
- // Clean DOI
255
- doi = doi.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '');
256
-
257
- if (!isValidDoiFormat(doi)) {
258
- return { success: false, error: 'Invalid DOI format' };
259
- }
260
-
261
- try {
262
- const response = await doiOrgLimiter.fetchWithRetry(
263
- `https://doi.org/${encodeURIComponent(doi)}`,
264
- {
265
- headers: {
266
- 'Accept': 'application/x-bibtex',
267
- 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev)',
268
- },
269
- redirect: 'follow',
270
- }
271
- );
272
-
273
- if (!response.ok) {
274
- return { success: false, error: `HTTP ${response.status}` };
275
- }
276
-
277
- const bibtex = await response.text();
278
-
279
- if (!bibtex.includes('@')) {
280
- return { success: false, error: 'Invalid BibTeX response' };
281
- }
282
-
283
- return { success: true, bibtex: bibtex.trim() };
284
- } catch (err) {
285
- return { success: false, error: (err as Error).message };
286
- }
287
- }
288
-
289
- interface CheckBibDoisOptions {
290
- checkMissing?: boolean;
291
- parallel?: number;
292
- }
293
-
294
- /**
295
- * Check all DOIs in a .bib file
296
- */
297
- export async function checkBibDois(bibPath: string, options: CheckBibDoisOptions = {}): Promise<BibCheckResult> {
298
- const { checkMissing = false, parallel = 5 } = options;
299
-
300
- const entries = parseBibEntries(bibPath);
301
- const results: Array<BibEntry & { status: string; message?: string; metadata?: object }> = [];
302
-
303
- let valid = 0;
304
- let invalid = 0;
305
- let unreachable = 0;
306
- let missing = 0;
307
- let skipped = 0;
308
-
309
- // Process in batches to avoid rate limiting
310
- for (let i = 0; i < entries.length; i += parallel) {
311
- const batch = entries.slice(i, i + parallel);
312
-
313
- const batchResults = await Promise.all(
314
- batch.map(async (entry) => {
315
- // Skip if marked
316
- if (entry.skip) {
317
- skipped++;
318
- return { ...entry, status: 'skipped', message: 'Marked as no-doi' };
319
- }
320
-
321
- // No DOI field
322
- if (!entry.doi) {
323
- if (entry.noDoi) {
324
- // Expected - books, theses, etc.
325
- skipped++;
326
- return { ...entry, status: 'skipped', message: `${entry.type} typically has no DOI` };
327
- } else if (entry.expectDoi) {
328
- // Should have DOI but doesn't
329
- missing++;
330
- return { ...entry, status: 'missing', message: 'Expected DOI for article/proceedings' };
331
- } else {
332
- skipped++;
333
- return { ...entry, status: 'skipped', message: 'No DOI field' };
334
- }
335
- }
336
-
337
- // Validate DOI format first
338
- if (!isValidDoiFormat(entry.doi)) {
339
- invalid++;
340
- return { ...entry, status: 'invalid', message: 'Invalid DOI format' };
341
- }
342
-
343
- // Check if DOI resolves
344
- const check = await checkDoi(entry.doi);
345
- if (check.valid) {
346
- valid++;
347
- return { ...entry, status: 'valid', metadata: check.metadata };
348
- } else if (check.unreachable) {
349
- // Registry unreachable — the DOI may be perfectly valid; don't
350
- // condemn it. Offline runs report unreachable, not a wall of invalid.
351
- unreachable++;
352
- return { ...entry, status: 'unreachable', message: check.error };
353
- } else {
354
- invalid++;
355
- return { ...entry, status: 'invalid', message: check.error };
356
- }
357
- })
358
- );
359
-
360
- results.push(...batchResults);
361
-
362
- // Small delay between batches to be nice to the API
363
- if (i + parallel < entries.length) {
364
- await new Promise(r => setTimeout(r, 200));
365
- }
366
- }
367
-
368
- return { entries: results, valid, invalid, unreachable, missing, skipped };
369
- }
370
-
371
- interface DataCiteItem {
372
- id: string;
373
- attributes: {
374
- titles?: Array<{ title: string }>;
375
- creators?: Array<{ givenName?: string; familyName?: string }>;
376
- publicationYear: number;
377
- publisher?: string;
378
- };
379
- }
380
-
381
- /**
382
- * Search DataCite API (for Zenodo, Figshare, etc.)
383
- */
384
- async function searchDataCite(title: string, author: string = '', year: number | null = null): Promise<any[]> {
385
- try {
386
- // DataCite query syntax
387
- let query = `titles.title:${title.replace(/[{}]/g, '')}`;
388
- if (author) {
389
- query += ` AND creators.name:${author}`;
390
- }
391
- if (year) {
392
- query += ` AND publicationYear:${year}`;
393
- }
394
-
395
- const params = new URLSearchParams({
396
- query: query,
397
- 'page[size]': '5',
398
- });
399
-
400
- const response = await dataciteLimiter.fetchWithRetry(
401
- `https://api.datacite.org/dois?${params}`,
402
- {
403
- headers: {
404
- 'Accept': 'application/vnd.api+json',
405
- 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev)',
406
- },
407
- }
408
- );
409
-
410
- if (!response.ok) return [];
411
-
412
- const data = await response.json() as { data?: DataCiteItem[] };
413
- const items = data.data || [];
414
-
415
- return items.map(item => {
416
- const attrs = item.attributes;
417
- return {
418
- DOI: item.id,
419
- title: [attrs.titles?.[0]?.title || ''],
420
- author: attrs.creators?.map(c => ({ family: c.familyName, given: c.givenName })) || [],
421
- 'published-print': { 'date-parts': [[attrs.publicationYear]] },
422
- 'container-title': [attrs.publisher || ''],
423
- score: 50, // Base score for DataCite results
424
- source: 'datacite',
425
- };
426
- });
427
- } catch {
428
- return [];
429
- }
430
- }
431
-
432
- /**
433
- * Normalize text for comparison (lowercase, remove special chars)
434
- */
435
- function normalizeForMatching(text: string): string {
436
- return (text || '')
437
- .toLowerCase()
438
- .replace(/[{}\\]/g, '') // Remove LaTeX braces
439
- .replace(/[^a-z0-9\s]/g, ' ') // Replace special chars with space
440
- .replace(/\s+/g, ' ')
441
- .trim();
442
- }
443
-
444
- /**
445
- * Check if DOI looks like a supplement, figure, or review (not the main paper)
446
- */
447
- function isSupplementOrReview(doi: string, title: string = '', journal: string = ''): boolean {
448
- const doiLower = (doi || '').toLowerCase();
449
- const titleLower = (title || '').toLowerCase();
450
- const journalLower = (journal || '').toLowerCase();
451
-
452
- // Supplement/figure DOI patterns
453
- if (/\.suppl|\/suppl|\.figure|\/figure|\.s\d+$|_s\d+$/i.test(doiLower)) {
454
- return true;
455
- }
456
-
457
- // F1000/Faculty Opinions (post-publication reviews)
458
- if (/10\.3410\/f\./i.test(doiLower) || /faculty opinions/i.test(journalLower)) {
459
- return true;
460
- }
461
-
462
- // Title suggests it's supplementary material
463
- if (/^supplementary|^supporting information|^appendix/i.test(titleLower)) {
464
- return true;
465
- }
466
-
467
- return false;
468
- }
469
-
470
- interface CrossrefItem {
471
- DOI: string;
472
- title?: string[];
473
- author?: Array<{ given?: string; family?: string }>;
474
- 'published-print'?: { 'date-parts': number[][] };
475
- 'published-online'?: { 'date-parts': number[][] };
476
- 'container-title'?: string[];
477
- score?: number;
478
- type?: string;
479
- }
480
-
481
- /**
482
- * Search for DOI by title and author using Crossref API (+ DataCite fallback)
483
- */
484
- export async function lookupDoi(
485
- title: string,
486
- author: string = '',
487
- year: number | null = null,
488
- journal: string = ''
489
- ): Promise<DoiLookupResult> {
490
- if (!title || title.length < 10) {
491
- return { found: false, error: 'Title too short for reliable search' };
492
- }
493
-
494
- // Check for keywords that suggest Zenodo/DataCite sources
495
- const likelyZenodo = /\b(IPBES|zenodo|assessment report|secretariat)\b/i.test(title);
496
-
497
- try {
498
- // Build query - title is most important, add author and journal if available
499
- let query = title;
500
- if (author) {
501
- query = `${title} ${author}`;
502
- }
503
- // Add journal to query for better matching
504
- if (journal) {
505
- query = `${query} ${journal}`;
506
- }
507
-
508
- let items: CrossrefItem[] = [];
509
-
510
- // Try structured bibliographic query first (more accurate)
511
- const structuredParams = new URLSearchParams({
512
- rows: '10',
513
- select: 'DOI,title,author,published-print,published-online,container-title,score,type',
514
- });
515
- structuredParams.set('query.bibliographic', title);
516
- if (author) {
517
- structuredParams.set('query.author', author);
518
- }
519
- if (journal) {
520
- structuredParams.set('query.container-title', journal);
521
- }
522
-
523
- let response = await crossrefLimiter.fetchWithRetry(
524
- `https://api.crossref.org/works?${structuredParams}`,
525
- {
526
- headers: {
527
- 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
528
- },
529
- }
530
- );
531
-
532
- if (response.ok) {
533
- const data = await response.json() as { message?: { items?: CrossrefItem[] } };
534
- items = data.message?.items || [];
535
- }
536
-
537
- // If structured query found few results, also try query.title (often better for exact matches)
538
- if (items.length < 5) {
539
- const titleParams = new URLSearchParams({
540
- rows: '10',
541
- select: 'DOI,title,author,published-print,published-online,container-title,score,type',
542
- });
543
- titleParams.set('query.title', title);
544
-
545
- const response2 = await crossrefLimiter.fetchWithRetry(
546
- `https://api.crossref.org/works?${titleParams}`,
547
- {
548
- headers: {
549
- 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
550
- },
551
- }
552
- );
553
-
554
- if (response2.ok) {
555
- const data = await response2.json() as { message?: { items?: CrossrefItem[] } };
556
- const newItems = data.message?.items || [];
557
- // Merge results, avoiding duplicates
558
- const existingDois = new Set(items.map(i => i.DOI));
559
- for (const item of newItems) {
560
- if (!existingDois.has(item.DOI)) {
561
- items.push(item);
562
- }
563
- }
564
- }
565
- }
566
-
567
- // If still nothing, try basic query (most lenient)
568
- if (items.length === 0) {
569
- const basicParams = new URLSearchParams({
570
- query: query,
571
- rows: '10',
572
- select: 'DOI,title,author,published-print,published-online,container-title,score,type',
573
- });
574
-
575
- response = await crossrefLimiter.fetchWithRetry(
576
- `https://api.crossref.org/works?${basicParams}`,
577
- {
578
- headers: {
579
- 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
580
- },
581
- }
582
- );
583
-
584
- if (response.ok) {
585
- const data = await response.json() as { message?: { items?: CrossrefItem[] } };
586
- items = data.message?.items || [];
587
- }
588
- }
589
-
590
- // Also search DataCite for Zenodo/institutional repos
591
- if (likelyZenodo || items.length === 0) {
592
- const dataciteItems = await searchDataCite(title, author, year);
593
- items = [...items, ...dataciteItems];
594
- }
595
-
596
- if (items.length === 0) {
597
- return { found: false, error: 'No results found' };
598
- }
599
-
600
- const normalizedSearchTitle = normalizeForMatching(title);
601
- const normalizedJournal = normalizeForMatching(journal);
602
-
603
- // Score the results
604
- const scored = items.map(item => {
605
- let score = 0;
606
- const itemTitle = item.title?.[0] || '';
607
- const itemJournal = item['container-title']?.[0] || '';
608
- const normalizedItemTitle = normalizeForMatching(itemTitle);
609
- const normalizedItemJournal = normalizeForMatching(itemJournal);
610
-
611
- // === PENALTY: Supplement/figure/review DOIs ===
612
- if (isSupplementOrReview(item.DOI, itemTitle, itemJournal)) {
613
- score -= 100; // Heavy penalty - almost never want these
614
- }
615
-
616
- // === Title similarity (most important) ===
617
- if (normalizedItemTitle === normalizedSearchTitle) {
618
- score += 100; // Exact match
619
- } else if (normalizedItemTitle.includes(normalizedSearchTitle) ||
620
- normalizedSearchTitle.includes(normalizedItemTitle)) {
621
- score += 50;
622
- } else {
623
- // Check word overlap
624
- const searchWords = normalizedSearchTitle.split(/\s+/).filter(w => w.length > 3);
625
- const itemWords = normalizedItemTitle.split(/\s+/).filter(w => w.length > 3);
626
- const overlap = searchWords.filter(w =>
627
- itemWords.some(iw => iw.includes(w) || w.includes(iw))
628
- );
629
- score += (overlap.length / Math.max(searchWords.length, 1)) * 40;
630
- }
631
-
632
- // === Author match ===
633
- if (author && item.author) {
634
- const authorLower = author.toLowerCase();
635
- const hasAuthor = item.author.some(a =>
636
- (a.family || '').toLowerCase().includes(authorLower) ||
637
- authorLower.includes((a.family || '').toLowerCase())
638
- );
639
- if (hasAuthor) score += 30;
640
- }
641
-
642
- // === Journal match (NEW) ===
643
- if (normalizedJournal && normalizedItemJournal) {
644
- // Check for journal name match (handles abbreviations)
645
- const journalWords = normalizedJournal.split(/\s+/).filter(w => w.length > 2);
646
- const itemJournalWords = normalizedItemJournal.split(/\s+/).filter(w => w.length > 2);
647
-
648
- // Count matching words
649
- const journalOverlap = journalWords.filter(w =>
650
- itemJournalWords.some(iw => iw.includes(w) || w.includes(iw))
651
- );
652
-
653
- if (journalOverlap.length >= Math.min(2, journalWords.length)) {
654
- score += 40; // Good journal match
655
- } else if (journalOverlap.length >= 1) {
656
- score += 15; // Partial match
657
- }
658
-
659
- // Bonus for exact journal match
660
- if (normalizedItemJournal === normalizedJournal) {
661
- score += 20;
662
- }
663
- }
664
-
665
- // === Year match - CRITICAL for accuracy ===
666
- const itemYear = item['published-print']?.['date-parts']?.[0]?.[0] ||
667
- item['published-online']?.['date-parts']?.[0]?.[0];
668
- if (year && itemYear) {
669
- if (itemYear === year) {
670
- score += 50; // Exact match - required for high confidence
671
- } else if (Math.abs(itemYear - year) === 1) {
672
- score += 20; // Off by one (common for online-first)
673
- } else {
674
- score -= 50; // Wrong year = likely wrong paper
675
- }
676
- } else if (year && !itemYear) {
677
- score -= 10; // Can't verify year
678
- }
679
-
680
- // Crossref's own relevance score (capped)
681
- score += Math.min(item.score || 0, 10);
682
-
683
- return {
684
- doi: item.DOI,
685
- title: itemTitle,
686
- authors: item.author?.map(a => `${a.given || ''} ${a.family || ''}`.trim()) || [],
687
- year: itemYear,
688
- journal: itemJournal,
689
- score,
690
- crossrefScore: item.score,
691
- isSupplement: isSupplementOrReview(item.DOI, itemTitle, itemJournal),
692
- };
693
- });
694
-
695
- // Sort by our score
696
- scored.sort((a, b) => b.score - a.score);
697
-
698
- // Filter out supplements for the "best" pick (but keep in alternatives)
699
- const mainPapers = scored.filter(s => !s.isSupplement);
700
- const best = mainPapers.length > 0 ? mainPapers[0] : scored[0];
701
-
702
- if (!best) {
703
- return { found: false, error: 'No valid results found' };
704
- }
705
-
706
- // Confidence: a "high" pick must clear the high threshold AND beat the
707
- // runner-up by a margin, so two near-identical candidates are reported as
708
- // "medium" (needs review) instead of one being auto-written as if certain.
709
- const runnerUp = (mainPapers.length > 0 ? mainPapers : scored).find(s => s.doi !== best.doi);
710
- const margin = runnerUp ? best.score - runnerUp.score : Infinity;
711
- let confidence: 'low' | 'medium' | 'high' = 'low';
712
- if (best.score >= DOI_CONFIDENCE.high && margin >= DOI_CONFIDENCE.runnerUpMargin) confidence = 'high';
713
- else if (best.score >= DOI_CONFIDENCE.medium) confidence = 'medium';
714
-
715
- // === NEW: Try DataCite if Crossref confidence is low ===
716
- if (confidence === 'low' && !likelyZenodo) {
717
- const dataciteItems = await searchDataCite(title, author, year);
718
- if (dataciteItems.length > 0) {
719
- // Score DataCite results with same logic
720
- for (const dcItem of dataciteItems) {
721
- const dcTitle = dcItem.title?.[0] || '';
722
- const normalizedDcTitle = normalizeForMatching(dcTitle);
723
- let dcScore = 0;
724
-
725
- // Title match
726
- if (normalizedDcTitle === normalizedSearchTitle) {
727
- dcScore += 100;
728
- } else if (normalizedDcTitle.includes(normalizedSearchTitle) ||
729
- normalizedSearchTitle.includes(normalizedDcTitle)) {
730
- dcScore += 50;
731
- }
732
-
733
- // Year match
734
- const dcYear = dcItem['published-print']?.['date-parts']?.[0]?.[0];
735
- if (year && dcYear && dcYear === year) {
736
- dcScore += 50;
737
- }
738
-
739
- if (dcScore > best.score) {
740
- return {
741
- found: true,
742
- doi: dcItem.DOI,
743
- confidence: dcScore >= DOI_CONFIDENCE.high ? 'high' : dcScore >= DOI_CONFIDENCE.medium ? 'medium' : 'low',
744
- score: dcScore,
745
- metadata: {
746
- title: dcTitle,
747
- authors: dcItem.author?.map((a: any) => `${a.given || ''} ${a.family || ''}`.trim()) || [],
748
- year: dcYear,
749
- journal: dcItem['container-title']?.[0] || '',
750
- },
751
- alternatives: scored.slice(0, 2),
752
- };
753
- }
754
- }
755
- }
756
- }
757
-
758
- return {
759
- found: true,
760
- doi: best.doi,
761
- confidence,
762
- score: best.score,
763
- metadata: {
764
- title: best.title,
765
- authors: best.authors,
766
- year: best.year || 0,
767
- journal: best.journal,
768
- },
769
- alternatives: scored.filter(s => s.doi !== best.doi).slice(0, 3),
770
- };
771
- } catch (err) {
772
- return { found: false, error: (err as Error).message };
773
- }
774
- }
775
-
776
- interface LookupMissingDoisOptions {
777
- parallel?: number;
778
- onProgress?: (current: number, total: number) => void;
779
- }
780
-
781
- interface LookupMissingDoiResult {
782
- key: string;
783
- title: string;
784
- type: string;
785
- journal: string;
786
- result: DoiLookupResult;
787
- }
788
-
789
- /**
790
- * Look up DOIs for all entries missing them in a .bib file
791
- */
792
- export async function lookupMissingDois(
793
- bibPath: string,
794
- options: LookupMissingDoisOptions = {}
795
- ): Promise<LookupMissingDoiResult[]> {
796
- const { parallel = 3, onProgress } = options;
797
-
798
- const entries = parseBibEntries(bibPath);
799
- const missing = entries.filter(e =>
800
- !e.doi &&
801
- !e.skip &&
802
- !NO_DOI_TYPES.has(e.type)
803
- );
804
-
805
- const results: LookupMissingDoiResult[] = [];
806
-
807
- for (let i = 0; i < missing.length; i += parallel) {
808
- const batch = missing.slice(i, i + parallel);
809
-
810
- const batchResults = await Promise.all(
811
- batch.map(async (entry) => {
812
- // Extract first author's last name from the entry
813
- // This is tricky because BibTeX author format varies
814
- let author = '';
815
- if (entry.authorRaw) {
816
- // Try to get first author's last name
817
- const firstAuthor = entry.authorRaw.split(' and ')[0];
818
- if (firstAuthor) {
819
- const parts = firstAuthor.split(',');
820
- author = parts[0]?.trim() || '';
821
- }
822
- }
823
-
824
- const result = await lookupDoi(entry.title, author, entry.year, entry.journal);
825
-
826
- return {
827
- key: entry.key,
828
- title: entry.title,
829
- type: entry.type,
830
- journal: entry.journal,
831
- result,
832
- };
833
- })
834
- );
835
-
836
- results.push(...batchResults);
837
-
838
- if (onProgress) {
839
- onProgress(Math.min(i + parallel, missing.length), missing.length);
840
- }
841
-
842
- // Rate limiting
843
- if (i + parallel < missing.length) {
844
- await new Promise(r => setTimeout(r, 300));
845
- }
846
- }
847
-
848
- return results;
849
- }
850
-
851
- interface AddToBibResult {
852
- success: boolean;
853
- key?: string;
854
- error?: string;
855
- }
856
-
857
- /**
858
- * Add a BibTeX entry to a .bib file
859
- */
860
- export function addToBib(bibPath: string, bibtex: string): AddToBibResult {
861
- // Extract key from BibTeX
862
- const keyMatch = bibtex.match(/@\w+\s*\{\s*([^,\s]+)/);
863
- if (!keyMatch) {
864
- return { success: false, error: 'Could not extract citation key from BibTeX' };
865
- }
866
- const key = keyMatch[1];
867
-
868
- // Check if key already exists
869
- const existing = fs.existsSync(bibPath) ? fs.readFileSync(bibPath, 'utf-8') : '';
870
- if (existing.includes(`{${key},`) || existing.includes(`{${key}\n`)) {
871
- return { success: false, error: `Key "${key}" already exists in ${bibPath}` };
872
- }
873
-
874
- // Append to file
875
- const newContent = existing.trim() + '\n\n' + bibtex + '\n';
876
- fs.writeFileSync(bibPath, newContent, 'utf-8');
877
-
878
- return { success: true, key };
879
- }
1
+ /**
2
+ * DOI validation and fetching utilities
3
+ * Check DOIs in .bib files, fetch BibTeX from DOIs
4
+ */
5
+
6
+ import * as fs from 'fs';
7
+ import type { BibEntry, DoiCheckResult, BibtexFetchResult, DoiLookupResult, BibCheckResult } from './types.js';
8
+ import { crossrefLimiter, dataciteLimiter, doiOrgLimiter } from './rate-limiter.js';
9
+ import { getCachedDoi, cacheDoi } from './doi-cache.js';
10
+
11
+ // Entry types that typically don't have DOIs
12
+ const NO_DOI_TYPES = new Set([
13
+ 'book', // Books often don't have DOIs (chapters might)
14
+ 'inbook', // Book chapters - variable
15
+ 'thesis', // Theses rarely have DOIs
16
+ 'mastersthesis',
17
+ 'phdthesis',
18
+ 'misc', // Catch-all, often no DOI
19
+ 'unpublished', // By definition
20
+ 'manual', // Software manuals
21
+ 'techreport', // Some do, many don't
22
+ 'booklet',
23
+ ]);
24
+
25
+ // Thresholds for the heuristic DOI-match score (title + author + year +
26
+ // journal). `high` auto-accepts, `medium` asks the user, below `medium` is a
27
+ // weak guess. `runnerUpMargin` is how far the best must beat the second-best
28
+ // to count as high — guards against picking the wrong one of two near-ties.
29
+ const DOI_CONFIDENCE = {
30
+ high: 120,
31
+ medium: 70,
32
+ runnerUpMargin: 30,
33
+ };
34
+
35
+ // Entry types that should have DOIs
36
+ const EXPECT_DOI_TYPES = new Set([
37
+ 'article', // Journal articles should have DOIs
38
+ 'inproceedings', // Conference papers usually do
39
+ 'proceedings',
40
+ 'incollection', // Book chapters in collections
41
+ ]);
42
+
43
+ /**
44
+ * Parse .bib file and extract entries with DOI info
45
+ */
46
+ export function parseBibEntries(bibPath: string): BibEntry[] {
47
+ if (!fs.existsSync(bibPath)) {
48
+ return [];
49
+ }
50
+
51
+ const content = fs.readFileSync(bibPath, 'utf-8');
52
+ const entries: BibEntry[] = [];
53
+ const lines = content.split('\n');
54
+
55
+ // Pattern for bib entries: @type{key,
56
+ const entryPattern = /@(\w+)\s*\{\s*([^,\s]+)\s*,/g;
57
+
58
+ let match: RegExpExecArray | null;
59
+ while ((match = entryPattern.exec(content)) !== null) {
60
+ const type = match[1]!.toLowerCase();
61
+ const key = match[2]!;
62
+ const startPos = match.index;
63
+
64
+ // Find the line number
65
+ let line = 1;
66
+ for (let i = 0; i < startPos; i++) {
67
+ if (content[i] === '\n') line++;
68
+ }
69
+
70
+ // Find the end of this entry (matching closing brace)
71
+ let braceCount = 0;
72
+ let entryEnd = startPos;
73
+ let inEntry = false;
74
+
75
+ for (let i = startPos; i < content.length; i++) {
76
+ if (content[i] === '{') {
77
+ braceCount++;
78
+ inEntry = true;
79
+ } else if (content[i] === '}') {
80
+ braceCount--;
81
+ if (inEntry && braceCount === 0) {
82
+ entryEnd = i + 1;
83
+ break;
84
+ }
85
+ }
86
+ }
87
+
88
+ const entryContent = content.slice(startPos, entryEnd);
89
+
90
+ // Extract DOI field
91
+ const doiMatch = entryContent.match(/\bdoi\s*=\s*[{"]([^}"]+)[}"]/i);
92
+ let doi = doiMatch ? doiMatch[1]!.trim() : null;
93
+
94
+ // Clean DOI - remove URL prefix if present
95
+ if (doi) {
96
+ doi = doi.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '');
97
+ }
98
+
99
+ // Extract title for display
100
+ const titleMatch = entryContent.match(/\btitle\s*=\s*[{"]([^}"]+)[}"]/i);
101
+ const title = titleMatch ? titleMatch[1]!.trim().slice(0, 60) : '';
102
+
103
+ // Extract author for lookup
104
+ const authorMatch = entryContent.match(/\bauthor\s*=\s*[{"]([^}"]+)[}"]/i);
105
+ const authorRaw = authorMatch ? authorMatch[1]!.trim() : '';
106
+
107
+ // Extract year
108
+ const yearMatch = entryContent.match(/\byear\s*=\s*[{"]?(\d{4})[}""]?/i);
109
+ const year = yearMatch ? parseInt(yearMatch[1]!) : null;
110
+
111
+ // Extract journal
112
+ const journalMatch = entryContent.match(/\bjournal\s*=\s*[{"]([^}"]+)[}"]/i);
113
+ const journal = journalMatch ? journalMatch[1]!.trim() : '';
114
+
115
+ // Check for skip marker: nodoi = {true} or nodoi = true
116
+ const skipMatch = entryContent.match(/\bnodoi\s*=\s*[{"]?(true|yes|1)[}""]?/i);
117
+ const skip = !!skipMatch;
118
+
119
+ // Check for comment marker immediately before entry: % no-doi
120
+ // Only look at the text between the last entry end (or start) and this entry
121
+ const linesBefore = content.slice(Math.max(0, startPos - 200), startPos);
122
+ // Find the last closing brace or start of file to avoid matching comments for previous entries
123
+ const lastEntryEnd = linesBefore.lastIndexOf('}');
124
+ const relevantBefore = lastEntryEnd >= 0 ? linesBefore.slice(lastEntryEnd + 1) : linesBefore;
125
+ const commentSkip = /% *no-?doi/i.test(relevantBefore);
126
+
127
+ entries.push({
128
+ key,
129
+ type,
130
+ doi: doi || null,
131
+ title,
132
+ authorRaw,
133
+ year,
134
+ journal,
135
+ skip: skip || commentSkip,
136
+ expectDoi: EXPECT_DOI_TYPES.has(type),
137
+ noDoi: NO_DOI_TYPES.has(type),
138
+ line,
139
+ });
140
+ }
141
+
142
+ return entries;
143
+ }
144
+
145
+ /**
146
+ * Validate DOI format
147
+ */
148
+ export function isValidDoiFormat(doi: string): boolean {
149
+ if (!doi) return false;
150
+ // DOI format: 10.prefix/suffix
151
+ // Prefix is 4+ digits, suffix can contain most characters
152
+ return /^10\.\d{4,}\/[^\s]+$/.test(doi);
153
+ }
154
+
155
+ interface CheckDoiOptions {
156
+ skipCache?: boolean;
157
+ }
158
+
159
+ /**
160
+ * Check if DOI resolves (exists) - tries Crossref first, then DataCite
161
+ * Results are cached for 7 days to reduce API calls.
162
+ */
163
+ export async function checkDoi(doi: string, options: CheckDoiOptions = {}): Promise<DoiCheckResult & { cached?: boolean }> {
164
+ if (!isValidDoiFormat(doi)) {
165
+ return { valid: false, error: 'Invalid DOI format' };
166
+ }
167
+
168
+ // Check cache first (unless skipped)
169
+ if (!options.skipCache) {
170
+ const cached = getCachedDoi(doi);
171
+ if (cached) {
172
+ return { ...cached, cached: true } as DoiCheckResult & { cached?: boolean };
173
+ }
174
+ }
175
+
176
+ // One resolution path: doi.org content negotiation returns CSL-JSON and
177
+ // federates every registration agency (Crossref, DataCite, mEDRA, ...), so
178
+ // there is no registrar to guess and no Crossref-then-DataCite fallback.
179
+ try {
180
+ const response = await doiOrgLimiter.fetchWithRetry(
181
+ `https://doi.org/${encodeURIComponent(doi)}`,
182
+ {
183
+ headers: {
184
+ 'Accept': 'application/vnd.citationstyles.csl+json',
185
+ 'User-Agent': 'docrev (https://github.com/gcol33/docrev)',
186
+ },
187
+ redirect: 'follow',
188
+ },
189
+ );
190
+
191
+ if (response.status === 404 || response.status === 410) {
192
+ // Definitive: the registry resolved and the DOI is not registered.
193
+ const result: DoiCheckResult = { valid: false, error: 'DOI not found' };
194
+ cacheDoi(doi, result);
195
+ return result;
196
+ }
197
+
198
+ if (!response.ok) {
199
+ // 5xx or unexpected: the registry is reachable but not answering — the
200
+ // DOI's status is unknown, so do not declare it invalid or cache it.
201
+ return { valid: false, unreachable: true, error: `HTTP ${response.status}` };
202
+ }
203
+
204
+ const work = await response.json() as any;
205
+ const result: DoiCheckResult = {
206
+ valid: true,
207
+ source: 'doi.org',
208
+ metadata: metadataFromCsl(work),
209
+ };
210
+
211
+ cacheDoi(doi, result);
212
+ return result;
213
+ } catch (err) {
214
+ // Network failure / timeout: cannot reach the resolver. Unknown, not invalid.
215
+ return { valid: false, unreachable: true, error: (err as Error).message };
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Extract docrev's metadata fields from a CSL-JSON record — the shape doi.org
221
+ * content negotiation returns for any registrar.
222
+ */
223
+ function metadataFromCsl(work: any): DoiCheckResult['metadata'] {
224
+ const dateParts =
225
+ work?.issued?.['date-parts']?.[0] ||
226
+ work?.published?.['date-parts']?.[0] ||
227
+ work?.created?.['date-parts']?.[0];
228
+ const year = Array.isArray(dateParts) ? dateParts[0] : undefined;
229
+
230
+ const authors = Array.isArray(work?.author)
231
+ ? work.author
232
+ .map((a: any) => `${a.given || a.givenName || ''} ${a.family || a.familyName || ''}`.trim())
233
+ .filter((s: string) => s.length > 0)
234
+ : [];
235
+
236
+ const title = Array.isArray(work?.title) ? work.title[0] : work?.title;
237
+ const journal = Array.isArray(work?.['container-title'])
238
+ ? work['container-title'][0]
239
+ : work?.['container-title'] || work?.publisher;
240
+
241
+ return {
242
+ title: title || '',
243
+ authors,
244
+ year: year || 0,
245
+ journal: journal || '',
246
+ type: work?.type,
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Fetch BibTeX from DOI using content negotiation
252
+ */
253
+ export async function fetchBibtex(doi: string): Promise<BibtexFetchResult> {
254
+ // Clean DOI
255
+ doi = doi.replace(/^https?:\/\/(dx\.)?doi\.org\//i, '');
256
+
257
+ if (!isValidDoiFormat(doi)) {
258
+ return { success: false, error: 'Invalid DOI format' };
259
+ }
260
+
261
+ try {
262
+ const response = await doiOrgLimiter.fetchWithRetry(
263
+ `https://doi.org/${encodeURIComponent(doi)}`,
264
+ {
265
+ headers: {
266
+ 'Accept': 'application/x-bibtex',
267
+ 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev)',
268
+ },
269
+ redirect: 'follow',
270
+ }
271
+ );
272
+
273
+ if (!response.ok) {
274
+ return { success: false, error: `HTTP ${response.status}` };
275
+ }
276
+
277
+ const bibtex = await response.text();
278
+
279
+ if (!bibtex.includes('@')) {
280
+ return { success: false, error: 'Invalid BibTeX response' };
281
+ }
282
+
283
+ return { success: true, bibtex: bibtex.trim() };
284
+ } catch (err) {
285
+ return { success: false, error: (err as Error).message };
286
+ }
287
+ }
288
+
289
+ interface CheckBibDoisOptions {
290
+ checkMissing?: boolean;
291
+ parallel?: number;
292
+ }
293
+
294
+ /**
295
+ * Check all DOIs in a .bib file
296
+ */
297
+ export async function checkBibDois(bibPath: string, options: CheckBibDoisOptions = {}): Promise<BibCheckResult> {
298
+ const { checkMissing = false, parallel = 5 } = options;
299
+
300
+ const entries = parseBibEntries(bibPath);
301
+ const results: Array<BibEntry & { status: string; message?: string; metadata?: object }> = [];
302
+
303
+ let valid = 0;
304
+ let invalid = 0;
305
+ let unreachable = 0;
306
+ let missing = 0;
307
+ let skipped = 0;
308
+
309
+ // Process in batches to avoid rate limiting
310
+ for (let i = 0; i < entries.length; i += parallel) {
311
+ const batch = entries.slice(i, i + parallel);
312
+
313
+ const batchResults = await Promise.all(
314
+ batch.map(async (entry) => {
315
+ // Skip if marked
316
+ if (entry.skip) {
317
+ skipped++;
318
+ return { ...entry, status: 'skipped', message: 'Marked as no-doi' };
319
+ }
320
+
321
+ // No DOI field
322
+ if (!entry.doi) {
323
+ if (entry.noDoi) {
324
+ // Expected - books, theses, etc.
325
+ skipped++;
326
+ return { ...entry, status: 'skipped', message: `${entry.type} typically has no DOI` };
327
+ } else if (entry.expectDoi) {
328
+ // Should have DOI but doesn't
329
+ missing++;
330
+ return { ...entry, status: 'missing', message: 'Expected DOI for article/proceedings' };
331
+ } else {
332
+ skipped++;
333
+ return { ...entry, status: 'skipped', message: 'No DOI field' };
334
+ }
335
+ }
336
+
337
+ // Validate DOI format first
338
+ if (!isValidDoiFormat(entry.doi)) {
339
+ invalid++;
340
+ return { ...entry, status: 'invalid', message: 'Invalid DOI format' };
341
+ }
342
+
343
+ // Check if DOI resolves
344
+ const check = await checkDoi(entry.doi);
345
+ if (check.valid) {
346
+ valid++;
347
+ return { ...entry, status: 'valid', metadata: check.metadata };
348
+ } else if (check.unreachable) {
349
+ // Registry unreachable — the DOI may be perfectly valid; don't
350
+ // condemn it. Offline runs report unreachable, not a wall of invalid.
351
+ unreachable++;
352
+ return { ...entry, status: 'unreachable', message: check.error };
353
+ } else {
354
+ invalid++;
355
+ return { ...entry, status: 'invalid', message: check.error };
356
+ }
357
+ })
358
+ );
359
+
360
+ results.push(...batchResults);
361
+
362
+ // Small delay between batches to be nice to the API
363
+ if (i + parallel < entries.length) {
364
+ await new Promise(r => setTimeout(r, 200));
365
+ }
366
+ }
367
+
368
+ return { entries: results, valid, invalid, unreachable, missing, skipped };
369
+ }
370
+
371
+ interface DataCiteItem {
372
+ id: string;
373
+ attributes: {
374
+ titles?: Array<{ title: string }>;
375
+ creators?: Array<{ givenName?: string; familyName?: string }>;
376
+ publicationYear: number;
377
+ publisher?: string;
378
+ };
379
+ }
380
+
381
+ /**
382
+ * Search DataCite API (for Zenodo, Figshare, etc.)
383
+ */
384
+ async function searchDataCite(title: string, author: string = '', year: number | null = null): Promise<any[]> {
385
+ try {
386
+ // DataCite query syntax
387
+ let query = `titles.title:${title.replace(/[{}]/g, '')}`;
388
+ if (author) {
389
+ query += ` AND creators.name:${author}`;
390
+ }
391
+ if (year) {
392
+ query += ` AND publicationYear:${year}`;
393
+ }
394
+
395
+ const params = new URLSearchParams({
396
+ query: query,
397
+ 'page[size]': '5',
398
+ });
399
+
400
+ const response = await dataciteLimiter.fetchWithRetry(
401
+ `https://api.datacite.org/dois?${params}`,
402
+ {
403
+ headers: {
404
+ 'Accept': 'application/vnd.api+json',
405
+ 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev)',
406
+ },
407
+ }
408
+ );
409
+
410
+ if (!response.ok) return [];
411
+
412
+ const data = await response.json() as { data?: DataCiteItem[] };
413
+ const items = data.data || [];
414
+
415
+ return items.map(item => {
416
+ const attrs = item.attributes;
417
+ return {
418
+ DOI: item.id,
419
+ title: [attrs.titles?.[0]?.title || ''],
420
+ author: attrs.creators?.map(c => ({ family: c.familyName, given: c.givenName })) || [],
421
+ 'published-print': { 'date-parts': [[attrs.publicationYear]] },
422
+ 'container-title': [attrs.publisher || ''],
423
+ score: 50, // Base score for DataCite results
424
+ source: 'datacite',
425
+ };
426
+ });
427
+ } catch {
428
+ return [];
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Normalize text for comparison (lowercase, remove special chars)
434
+ */
435
+ function normalizeForMatching(text: string): string {
436
+ return (text || '')
437
+ .toLowerCase()
438
+ .replace(/[{}\\]/g, '') // Remove LaTeX braces
439
+ .replace(/[^a-z0-9\s]/g, ' ') // Replace special chars with space
440
+ .replace(/\s+/g, ' ')
441
+ .trim();
442
+ }
443
+
444
+ /**
445
+ * Check if DOI looks like a supplement, figure, or review (not the main paper)
446
+ */
447
+ function isSupplementOrReview(doi: string, title: string = '', journal: string = ''): boolean {
448
+ const doiLower = (doi || '').toLowerCase();
449
+ const titleLower = (title || '').toLowerCase();
450
+ const journalLower = (journal || '').toLowerCase();
451
+
452
+ // Supplement/figure DOI patterns
453
+ if (/\.suppl|\/suppl|\.figure|\/figure|\.s\d+$|_s\d+$/i.test(doiLower)) {
454
+ return true;
455
+ }
456
+
457
+ // F1000/Faculty Opinions (post-publication reviews)
458
+ if (/10\.3410\/f\./i.test(doiLower) || /faculty opinions/i.test(journalLower)) {
459
+ return true;
460
+ }
461
+
462
+ // Title suggests it's supplementary material
463
+ if (/^supplementary|^supporting information|^appendix/i.test(titleLower)) {
464
+ return true;
465
+ }
466
+
467
+ return false;
468
+ }
469
+
470
+ interface CrossrefItem {
471
+ DOI: string;
472
+ title?: string[];
473
+ author?: Array<{ given?: string; family?: string }>;
474
+ 'published-print'?: { 'date-parts': number[][] };
475
+ 'published-online'?: { 'date-parts': number[][] };
476
+ 'container-title'?: string[];
477
+ score?: number;
478
+ type?: string;
479
+ }
480
+
481
+ /**
482
+ * Search for DOI by title and author using Crossref API (+ DataCite fallback)
483
+ */
484
+ export async function lookupDoi(
485
+ title: string,
486
+ author: string = '',
487
+ year: number | null = null,
488
+ journal: string = ''
489
+ ): Promise<DoiLookupResult> {
490
+ if (!title || title.length < 10) {
491
+ return { found: false, error: 'Title too short for reliable search' };
492
+ }
493
+
494
+ // Check for keywords that suggest Zenodo/DataCite sources
495
+ const likelyZenodo = /\b(IPBES|zenodo|assessment report|secretariat)\b/i.test(title);
496
+
497
+ try {
498
+ // Build query - title is most important, add author and journal if available
499
+ let query = title;
500
+ if (author) {
501
+ query = `${title} ${author}`;
502
+ }
503
+ // Add journal to query for better matching
504
+ if (journal) {
505
+ query = `${query} ${journal}`;
506
+ }
507
+
508
+ let items: CrossrefItem[] = [];
509
+
510
+ // Try structured bibliographic query first (more accurate)
511
+ const structuredParams = new URLSearchParams({
512
+ rows: '10',
513
+ select: 'DOI,title,author,published-print,published-online,container-title,score,type',
514
+ });
515
+ structuredParams.set('query.bibliographic', title);
516
+ if (author) {
517
+ structuredParams.set('query.author', author);
518
+ }
519
+ if (journal) {
520
+ structuredParams.set('query.container-title', journal);
521
+ }
522
+
523
+ let response = await crossrefLimiter.fetchWithRetry(
524
+ `https://api.crossref.org/works?${structuredParams}`,
525
+ {
526
+ headers: {
527
+ 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
528
+ },
529
+ }
530
+ );
531
+
532
+ if (response.ok) {
533
+ const data = await response.json() as { message?: { items?: CrossrefItem[] } };
534
+ items = data.message?.items || [];
535
+ }
536
+
537
+ // If structured query found few results, also try query.title (often better for exact matches)
538
+ if (items.length < 5) {
539
+ const titleParams = new URLSearchParams({
540
+ rows: '10',
541
+ select: 'DOI,title,author,published-print,published-online,container-title,score,type',
542
+ });
543
+ titleParams.set('query.title', title);
544
+
545
+ const response2 = await crossrefLimiter.fetchWithRetry(
546
+ `https://api.crossref.org/works?${titleParams}`,
547
+ {
548
+ headers: {
549
+ 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
550
+ },
551
+ }
552
+ );
553
+
554
+ if (response2.ok) {
555
+ const data = await response2.json() as { message?: { items?: CrossrefItem[] } };
556
+ const newItems = data.message?.items || [];
557
+ // Merge results, avoiding duplicates
558
+ const existingDois = new Set(items.map(i => i.DOI));
559
+ for (const item of newItems) {
560
+ if (!existingDois.has(item.DOI)) {
561
+ items.push(item);
562
+ }
563
+ }
564
+ }
565
+ }
566
+
567
+ // If still nothing, try basic query (most lenient)
568
+ if (items.length === 0) {
569
+ const basicParams = new URLSearchParams({
570
+ query: query,
571
+ rows: '10',
572
+ select: 'DOI,title,author,published-print,published-online,container-title,score,type',
573
+ });
574
+
575
+ response = await crossrefLimiter.fetchWithRetry(
576
+ `https://api.crossref.org/works?${basicParams}`,
577
+ {
578
+ headers: {
579
+ 'User-Agent': 'docrev/0.6.0 (https://github.com/gcol33/docrev; mailto:docrev@example.com)',
580
+ },
581
+ }
582
+ );
583
+
584
+ if (response.ok) {
585
+ const data = await response.json() as { message?: { items?: CrossrefItem[] } };
586
+ items = data.message?.items || [];
587
+ }
588
+ }
589
+
590
+ // Also search DataCite for Zenodo/institutional repos
591
+ if (likelyZenodo || items.length === 0) {
592
+ const dataciteItems = await searchDataCite(title, author, year);
593
+ items = [...items, ...dataciteItems];
594
+ }
595
+
596
+ if (items.length === 0) {
597
+ return { found: false, error: 'No results found' };
598
+ }
599
+
600
+ const normalizedSearchTitle = normalizeForMatching(title);
601
+ const normalizedJournal = normalizeForMatching(journal);
602
+
603
+ // Score the results
604
+ const scored = items.map(item => {
605
+ let score = 0;
606
+ const itemTitle = item.title?.[0] || '';
607
+ const itemJournal = item['container-title']?.[0] || '';
608
+ const normalizedItemTitle = normalizeForMatching(itemTitle);
609
+ const normalizedItemJournal = normalizeForMatching(itemJournal);
610
+
611
+ // === PENALTY: Supplement/figure/review DOIs ===
612
+ if (isSupplementOrReview(item.DOI, itemTitle, itemJournal)) {
613
+ score -= 100; // Heavy penalty - almost never want these
614
+ }
615
+
616
+ // === Title similarity (most important) ===
617
+ if (normalizedItemTitle === normalizedSearchTitle) {
618
+ score += 100; // Exact match
619
+ } else if (normalizedItemTitle.includes(normalizedSearchTitle) ||
620
+ normalizedSearchTitle.includes(normalizedItemTitle)) {
621
+ score += 50;
622
+ } else {
623
+ // Check word overlap
624
+ const searchWords = normalizedSearchTitle.split(/\s+/).filter(w => w.length > 3);
625
+ const itemWords = normalizedItemTitle.split(/\s+/).filter(w => w.length > 3);
626
+ const overlap = searchWords.filter(w =>
627
+ itemWords.some(iw => iw.includes(w) || w.includes(iw))
628
+ );
629
+ score += (overlap.length / Math.max(searchWords.length, 1)) * 40;
630
+ }
631
+
632
+ // === Author match ===
633
+ if (author && item.author) {
634
+ const authorLower = author.toLowerCase();
635
+ const hasAuthor = item.author.some(a =>
636
+ (a.family || '').toLowerCase().includes(authorLower) ||
637
+ authorLower.includes((a.family || '').toLowerCase())
638
+ );
639
+ if (hasAuthor) score += 30;
640
+ }
641
+
642
+ // === Journal match (NEW) ===
643
+ if (normalizedJournal && normalizedItemJournal) {
644
+ // Check for journal name match (handles abbreviations)
645
+ const journalWords = normalizedJournal.split(/\s+/).filter(w => w.length > 2);
646
+ const itemJournalWords = normalizedItemJournal.split(/\s+/).filter(w => w.length > 2);
647
+
648
+ // Count matching words
649
+ const journalOverlap = journalWords.filter(w =>
650
+ itemJournalWords.some(iw => iw.includes(w) || w.includes(iw))
651
+ );
652
+
653
+ if (journalOverlap.length >= Math.min(2, journalWords.length)) {
654
+ score += 40; // Good journal match
655
+ } else if (journalOverlap.length >= 1) {
656
+ score += 15; // Partial match
657
+ }
658
+
659
+ // Bonus for exact journal match
660
+ if (normalizedItemJournal === normalizedJournal) {
661
+ score += 20;
662
+ }
663
+ }
664
+
665
+ // === Year match - CRITICAL for accuracy ===
666
+ const itemYear = item['published-print']?.['date-parts']?.[0]?.[0] ||
667
+ item['published-online']?.['date-parts']?.[0]?.[0];
668
+ if (year && itemYear) {
669
+ if (itemYear === year) {
670
+ score += 50; // Exact match - required for high confidence
671
+ } else if (Math.abs(itemYear - year) === 1) {
672
+ score += 20; // Off by one (common for online-first)
673
+ } else {
674
+ score -= 50; // Wrong year = likely wrong paper
675
+ }
676
+ } else if (year && !itemYear) {
677
+ score -= 10; // Can't verify year
678
+ }
679
+
680
+ // Crossref's own relevance score (capped)
681
+ score += Math.min(item.score || 0, 10);
682
+
683
+ return {
684
+ doi: item.DOI,
685
+ title: itemTitle,
686
+ authors: item.author?.map(a => `${a.given || ''} ${a.family || ''}`.trim()) || [],
687
+ year: itemYear,
688
+ journal: itemJournal,
689
+ score,
690
+ crossrefScore: item.score,
691
+ isSupplement: isSupplementOrReview(item.DOI, itemTitle, itemJournal),
692
+ };
693
+ });
694
+
695
+ // Sort by our score
696
+ scored.sort((a, b) => b.score - a.score);
697
+
698
+ // Filter out supplements for the "best" pick (but keep in alternatives)
699
+ const mainPapers = scored.filter(s => !s.isSupplement);
700
+ const best = mainPapers.length > 0 ? mainPapers[0] : scored[0];
701
+
702
+ if (!best) {
703
+ return { found: false, error: 'No valid results found' };
704
+ }
705
+
706
+ // Confidence: a "high" pick must clear the high threshold AND beat the
707
+ // runner-up by a margin, so two near-identical candidates are reported as
708
+ // "medium" (needs review) instead of one being auto-written as if certain.
709
+ const runnerUp = (mainPapers.length > 0 ? mainPapers : scored).find(s => s.doi !== best.doi);
710
+ const margin = runnerUp ? best.score - runnerUp.score : Infinity;
711
+ let confidence: 'low' | 'medium' | 'high' = 'low';
712
+ if (best.score >= DOI_CONFIDENCE.high && margin >= DOI_CONFIDENCE.runnerUpMargin) confidence = 'high';
713
+ else if (best.score >= DOI_CONFIDENCE.medium) confidence = 'medium';
714
+
715
+ // === NEW: Try DataCite if Crossref confidence is low ===
716
+ if (confidence === 'low' && !likelyZenodo) {
717
+ const dataciteItems = await searchDataCite(title, author, year);
718
+ if (dataciteItems.length > 0) {
719
+ // Score DataCite results with same logic
720
+ for (const dcItem of dataciteItems) {
721
+ const dcTitle = dcItem.title?.[0] || '';
722
+ const normalizedDcTitle = normalizeForMatching(dcTitle);
723
+ let dcScore = 0;
724
+
725
+ // Title match
726
+ if (normalizedDcTitle === normalizedSearchTitle) {
727
+ dcScore += 100;
728
+ } else if (normalizedDcTitle.includes(normalizedSearchTitle) ||
729
+ normalizedSearchTitle.includes(normalizedDcTitle)) {
730
+ dcScore += 50;
731
+ }
732
+
733
+ // Year match
734
+ const dcYear = dcItem['published-print']?.['date-parts']?.[0]?.[0];
735
+ if (year && dcYear && dcYear === year) {
736
+ dcScore += 50;
737
+ }
738
+
739
+ if (dcScore > best.score) {
740
+ return {
741
+ found: true,
742
+ doi: dcItem.DOI,
743
+ confidence: dcScore >= DOI_CONFIDENCE.high ? 'high' : dcScore >= DOI_CONFIDENCE.medium ? 'medium' : 'low',
744
+ score: dcScore,
745
+ metadata: {
746
+ title: dcTitle,
747
+ authors: dcItem.author?.map((a: any) => `${a.given || ''} ${a.family || ''}`.trim()) || [],
748
+ year: dcYear,
749
+ journal: dcItem['container-title']?.[0] || '',
750
+ },
751
+ alternatives: scored.slice(0, 2),
752
+ };
753
+ }
754
+ }
755
+ }
756
+ }
757
+
758
+ return {
759
+ found: true,
760
+ doi: best.doi,
761
+ confidence,
762
+ score: best.score,
763
+ metadata: {
764
+ title: best.title,
765
+ authors: best.authors,
766
+ year: best.year || 0,
767
+ journal: best.journal,
768
+ },
769
+ alternatives: scored.filter(s => s.doi !== best.doi).slice(0, 3),
770
+ };
771
+ } catch (err) {
772
+ return { found: false, error: (err as Error).message };
773
+ }
774
+ }
775
+
776
+ interface LookupMissingDoisOptions {
777
+ parallel?: number;
778
+ onProgress?: (current: number, total: number) => void;
779
+ }
780
+
781
+ interface LookupMissingDoiResult {
782
+ key: string;
783
+ title: string;
784
+ type: string;
785
+ journal: string;
786
+ result: DoiLookupResult;
787
+ }
788
+
789
+ /**
790
+ * Look up DOIs for all entries missing them in a .bib file
791
+ */
792
+ export async function lookupMissingDois(
793
+ bibPath: string,
794
+ options: LookupMissingDoisOptions = {}
795
+ ): Promise<LookupMissingDoiResult[]> {
796
+ const { parallel = 3, onProgress } = options;
797
+
798
+ const entries = parseBibEntries(bibPath);
799
+ const missing = entries.filter(e =>
800
+ !e.doi &&
801
+ !e.skip &&
802
+ !NO_DOI_TYPES.has(e.type)
803
+ );
804
+
805
+ const results: LookupMissingDoiResult[] = [];
806
+
807
+ for (let i = 0; i < missing.length; i += parallel) {
808
+ const batch = missing.slice(i, i + parallel);
809
+
810
+ const batchResults = await Promise.all(
811
+ batch.map(async (entry) => {
812
+ // Extract first author's last name from the entry
813
+ // This is tricky because BibTeX author format varies
814
+ let author = '';
815
+ if (entry.authorRaw) {
816
+ // Try to get first author's last name
817
+ const firstAuthor = entry.authorRaw.split(' and ')[0];
818
+ if (firstAuthor) {
819
+ const parts = firstAuthor.split(',');
820
+ author = parts[0]?.trim() || '';
821
+ }
822
+ }
823
+
824
+ const result = await lookupDoi(entry.title, author, entry.year, entry.journal);
825
+
826
+ return {
827
+ key: entry.key,
828
+ title: entry.title,
829
+ type: entry.type,
830
+ journal: entry.journal,
831
+ result,
832
+ };
833
+ })
834
+ );
835
+
836
+ results.push(...batchResults);
837
+
838
+ if (onProgress) {
839
+ onProgress(Math.min(i + parallel, missing.length), missing.length);
840
+ }
841
+
842
+ // Rate limiting
843
+ if (i + parallel < missing.length) {
844
+ await new Promise(r => setTimeout(r, 300));
845
+ }
846
+ }
847
+
848
+ return results;
849
+ }
850
+
851
+ interface AddToBibResult {
852
+ success: boolean;
853
+ key?: string;
854
+ error?: string;
855
+ }
856
+
857
+ /**
858
+ * Add a BibTeX entry to a .bib file
859
+ */
860
+ export function addToBib(bibPath: string, bibtex: string): AddToBibResult {
861
+ // Extract key from BibTeX
862
+ const keyMatch = bibtex.match(/@\w+\s*\{\s*([^,\s]+)/);
863
+ if (!keyMatch) {
864
+ return { success: false, error: 'Could not extract citation key from BibTeX' };
865
+ }
866
+ const key = keyMatch[1];
867
+
868
+ // Check if key already exists
869
+ const existing = fs.existsSync(bibPath) ? fs.readFileSync(bibPath, 'utf-8') : '';
870
+ if (existing.includes(`{${key},`) || existing.includes(`{${key}\n`)) {
871
+ return { success: false, error: `Key "${key}" already exists in ${bibPath}` };
872
+ }
873
+
874
+ // Append to file
875
+ const newContent = existing.trim() + '\n\n' + bibtex + '\n';
876
+ fs.writeFileSync(bibPath, newContent, 'utf-8');
877
+
878
+ return { success: true, key };
879
+ }