dsh-mineru 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/anchors.js ADDED
@@ -0,0 +1,522 @@
1
+ /**
2
+ * Page-anchored Markdown for precision-API results (pure functions, no host
3
+ * dependencies).
4
+ *
5
+ * `document.md` is an opt-in companion to the untouched `full.md`: the same
6
+ * blocks in `content_list.json` order, each preceded by one HTML comment
7
+ * anchor so a reader (or an agent) can cite the page a sentence came from:
8
+ *
9
+ * ```
10
+ * <!-- p12 b3 -->
11
+ * 君子务本,本立而道生。
12
+ * ```
13
+ *
14
+ * Two rules drive everything here:
15
+ *
16
+ * - **`page_idx` is a request-relative index.** When `page_ranges` is set the
17
+ * cloud renumbers the requested subset from 0, so `requestedPages[page_idx]`
18
+ * is the only correct way back to the original page — an offset alone breaks
19
+ * on discrete ranges such as `"2,4-6"`;
20
+ * - **`bK` counts blocks inside their page, in content-list order.** Auxiliary
21
+ * blocks (`header` / `footer` / `page_number` / `aside_text`) are left out of
22
+ * the body stream but still occupy their number, so `bK` always points at the
23
+ * K-th block of that page in `content_list.json` (a gap is expected, not a
24
+ * bug).
25
+ *
26
+ * A block whose page cannot be resolved keeps its anchor as `<!-- p? bK -->`
27
+ * instead of being dropped.
28
+ *
29
+ * `pN` is the **physical page order of this file** (1-based, cover and front
30
+ * matter included) — not the page number printed on the page. When the result
31
+ * carries readable `page_number` blocks the renderer compares the two on a
32
+ * best-effort basis and reports a constant or non-constant difference (see
33
+ * `pageNumbers` on the result); the anchors themselves never change.
34
+ * @module dsh-mineru/anchors
35
+ */
36
+ import { readFile } from 'node:fs/promises';
37
+
38
+ /** Block types rendered into the body stream. */
39
+ export const BODY_TYPES = Object.freeze([
40
+ 'text', 'title', 'paragraph_title', 'list', 'code', 'ref_text',
41
+ 'equation', 'table', 'chart', 'image',
42
+ ]);
43
+
44
+ /** Page furniture: kept out of the body stream, but still counted. */
45
+ export const AUX_TYPES = Object.freeze(['header', 'footer', 'page_number', 'aside_text']);
46
+
47
+ /** Cloud marker for a block it could not read. */
48
+ export const UNREADABLE_MARKER = '[Unreadable]';
49
+
50
+ const AUX_SET = new Set(AUX_TYPES);
51
+
52
+ /** Key order used to pull a block's text out of V1 / V2 shapes. */
53
+ const CONTENT_KEYS = Object.freeze([
54
+ 'text',
55
+ 'content',
56
+ 'table_body',
57
+ 'html',
58
+ 'math_content',
59
+ 'paragraph_content',
60
+ 'item_content',
61
+ 'list_items',
62
+ ]);
63
+
64
+ /**
65
+ * Flatten a block field into plain text, falling back across the known keys.
66
+ * @param {unknown} node
67
+ * @returns {string}
68
+ */
69
+ export function extractText(node) {
70
+ if (node === null || node === undefined) return '';
71
+ if (typeof node === 'string') return node;
72
+ if (typeof node === 'number' || typeof node === 'boolean') return String(node);
73
+ if (Array.isArray(node)) {
74
+ return node.map(extractText).filter((part) => part !== '').join('\n');
75
+ }
76
+ if (typeof node === 'object') {
77
+ for (const key of CONTENT_KEYS) {
78
+ if (key in node) {
79
+ const value = extractText(node[key]);
80
+ if (value !== '') return value;
81
+ }
82
+ }
83
+ }
84
+ return '';
85
+ }
86
+
87
+ /**
88
+ * @param {unknown} type
89
+ * @returns {'body' | 'aux' | 'other'}
90
+ */
91
+ export function classifyBlockType(type) {
92
+ if (typeof type !== 'string' || type === '') return 'other';
93
+ if (AUX_SET.has(type)) return 'aux';
94
+ return BODY_TYPES.includes(type) ? 'body' : 'other';
95
+ }
96
+
97
+ /**
98
+ * True when a block carries nothing but the cloud's unreadable marker.
99
+ * @param {string} text
100
+ * @returns {boolean}
101
+ */
102
+ export function isUnreadableText(text) {
103
+ if (typeof text !== 'string' || text === '') return false;
104
+ return text.split(UNREADABLE_MARKER).join('').trim() === '';
105
+ }
106
+
107
+ /** Roman numeral values, for front matter printed with Roman numerals. */
108
+ const ROMAN_VALUES = Object.freeze({ i: 1, v: 5, x: 10, l: 50, c: 100, d: 500, m: 1000 });
109
+
110
+ /**
111
+ * Parse a simple Roman numeral such as `iv` / `IX`.
112
+ *
113
+ * Printed front matter often numbers its pages this way, so the self-check has
114
+ * to read them too. Only the seven classic letters are accepted (either case)
115
+ * and the subtractive rule is applied left to right; shapes the Romans never
116
+ * wrote (`iix`) are accepted rather than rejected, because this value only
117
+ * ever feeds a best-effort comparison with the physical page order.
118
+ *
119
+ * @param {unknown} text
120
+ * @returns {number|null} the value, or null when `text` is not a Roman numeral
121
+ */
122
+ export function parseRomanNumeral(text) {
123
+ if (typeof text !== 'string') return null;
124
+ const token = text.trim().toLowerCase();
125
+ if (token === '' || !/^[ivxlcdm]+$/.test(token)) return null;
126
+ let total = 0;
127
+ for (let index = 0; index < token.length; index += 1) {
128
+ const value = ROMAN_VALUES[token[index]];
129
+ const next = index + 1 < token.length ? ROMAN_VALUES[token[index + 1]] : 0;
130
+ total += value < next ? -value : value;
131
+ }
132
+ return total > 0 ? total : null;
133
+ }
134
+
135
+ /**
136
+ * Parse the text of a `page_number` block into a printed page number.
137
+ *
138
+ * Accepts Arabic digits and Roman numerals. Everything else — empty text, the
139
+ * cloud's `[Unreadable]` marker, running heads like `第 3 页`, `1 / 200` — is
140
+ * not a printed page number we can compare, so it yields null and the page is
141
+ * simply left out of the self-check.
142
+ *
143
+ * @param {unknown} text
144
+ * @returns {number|null}
145
+ */
146
+ export function parsePrintedPageNumber(text) {
147
+ if (typeof text !== 'string') return null;
148
+ const token = text.trim();
149
+ if (token === '' || isUnreadableText(token)) return null;
150
+ if (/^\d+$/.test(token)) {
151
+ const value = Number(token);
152
+ return value > 0 ? value : null;
153
+ }
154
+ return parseRomanNumeral(token);
155
+ }
156
+
157
+ /** Signed offset for user-facing messages: `+3` / `-2` / `0`. */
158
+ function formatPageOffset(offset) {
159
+ return offset > 0 ? '+' + offset : String(offset);
160
+ }
161
+
162
+ /** @param {unknown} value @returns {string} */
163
+ function scalar(value) {
164
+ if (typeof value === 'string') return value;
165
+ return extractText(value);
166
+ }
167
+
168
+ /** Markdown heading prefix from the cloud's heading level, when it gives one. */
169
+ function headingPrefix(block) {
170
+ const level = Number.isInteger(block.text_level) ? block.text_level : null;
171
+ if (level !== null && level >= 1 && level <= 6) return '#'.repeat(level) + ' ';
172
+ return '';
173
+ }
174
+
175
+ /** The cloud's table caption arrives as an array of strings (or a string). */
176
+ function captionText(block) {
177
+ const raw = Array.isArray(block.table_caption) ? block.table_caption : [block.table_caption];
178
+ return raw.map(scalar).filter((part) => part !== '').join(' ');
179
+ }
180
+
181
+ /**
182
+ * Render one block's body (the anchor line is added by the caller).
183
+ * @param {Record<string, unknown>} block
184
+ * @param {string} text flattened block text
185
+ * @param {(message: string) => void} warn
186
+ * @returns {string}
187
+ */
188
+ function renderBlock(block, text, warn) {
189
+ const type = String(block.type);
190
+ const unreadable = isUnreadableText(text);
191
+
192
+ if (type === 'table') {
193
+ const parts = [];
194
+ const caption = captionText(block);
195
+ if (caption !== '') parts.push('**' + caption + '**');
196
+ const html = scalar(block.table_body) || scalar(block.html);
197
+ if (html !== '') {
198
+ parts.push(html);
199
+ } else if (typeof block.img_path === 'string' && block.img_path !== '') {
200
+ // Always the reference the cloud itself gave; never build *_body_* names.
201
+ parts.push('![table](' + block.img_path + ')');
202
+ } else {
203
+ // Keep the anchor: an unreadable table is a finding, not a reason to drop it.
204
+ parts.push(UNREADABLE_MARKER);
205
+ warn('表格块既没有 table_body 也没有 img_path,已保留锚点与占位');
206
+ }
207
+ return parts.join('\n\n');
208
+ }
209
+
210
+ if (type === 'image' || type === 'chart') {
211
+ if (typeof block.img_path === 'string' && block.img_path !== '') {
212
+ return '![' + type + '](' + block.img_path + ')';
213
+ }
214
+ warn(type + ' 块没有 img_path,已保留锚点与占位');
215
+ return UNREADABLE_MARKER;
216
+ }
217
+
218
+ if (type === 'equation') {
219
+ const language = typeof block.text_format === 'string' && block.text_format !== ''
220
+ ? block.text_format
221
+ : 'latex';
222
+ if (unreadable || text === '') return UNREADABLE_MARKER;
223
+ return '```' + language + '\n' + text + '\n```';
224
+ }
225
+
226
+ if (unreadable) return UNREADABLE_MARKER;
227
+ return headingPrefix(block) + text;
228
+ }
229
+
230
+ /**
231
+ * Parse a MinerU `page_ranges` string into the ordered list of pages the
232
+ * request actually asked for.
233
+ *
234
+ * Needed because `page_idx` in the returned `content_list.json` is an index
235
+ * into *this* request's subset. Supports the official syntax: `2`, `4-6`,
236
+ * and negative indexes such as `2--2` (which resolve against `totalPages`).
237
+ *
238
+ * @param {string} spec e.g. `"2,4-6"`
239
+ * @param {{totalPages?: number|null}} [options]
240
+ * @returns {{
241
+ * pages: number[],
242
+ * canonical: string,
243
+ * unresolvedNegative: boolean,
244
+ * offset: number,
245
+ * warnings: string[],
246
+ * }}
247
+ */
248
+ export function parseRequestedPages(spec, options = {}) {
249
+ if (typeof spec !== 'string' || spec.trim() === '') {
250
+ throw new TypeError('spec must be a non-empty page-ranges string');
251
+ }
252
+ const totalPages = Number.isInteger(options.totalPages) && options.totalPages > 0
253
+ ? options.totalPages
254
+ : null;
255
+ const warnings = [];
256
+ const seen = new Set();
257
+ let unresolvedNegative = false;
258
+ let firstPositivePage = null;
259
+ const tokens = spec.split(',').map((token) => token.trim()).filter((token) => token !== '');
260
+
261
+ for (const token of tokens) {
262
+ const negative = /^-\d+$/.test(token);
263
+ const range = /^(\d+)-(-?\d+)$/.exec(token);
264
+ const single = /^(\d+)$/.exec(token);
265
+ let start = null;
266
+ let end = null;
267
+ if (range) {
268
+ start = Number(range[1]);
269
+ end = Number(range[2]);
270
+ } else if (single) {
271
+ start = Number(single[1]);
272
+ end = start;
273
+ } else if (negative) {
274
+ start = Number(token);
275
+ end = start;
276
+ } else {
277
+ warnings.push('无法识别的页码范围片段「' + token + '」,已忽略');
278
+ continue;
279
+ }
280
+ if (start > 0 && (firstPositivePage === null || start < firstPositivePage)) {
281
+ firstPositivePage = start;
282
+ }
283
+ const resolve = (value) => {
284
+ if (value > 0) return value;
285
+ if (totalPages === null) { unresolvedNegative = true; return null; }
286
+ const page = totalPages + value + 1;
287
+ return page >= 1 ? page : null;
288
+ };
289
+ if (start <= 0 && end <= 0) {
290
+ const a = resolve(start);
291
+ const b = resolve(end);
292
+ if (a === null || b === null) { unresolvedNegative = true; continue; }
293
+ for (let page = Math.min(a, b); page <= Math.max(a, b); page += 1) seen.add(page);
294
+ continue;
295
+ }
296
+ if (end < 0) {
297
+ const b = resolve(end);
298
+ if (b === null) { unresolvedNegative = true; continue; }
299
+ for (let page = start; page <= b; page += 1) seen.add(page);
300
+ continue;
301
+ }
302
+ for (let page = start; page <= end; page += 1) seen.add(page);
303
+ }
304
+
305
+ const pages = [...seen].sort((a, b) => a - b);
306
+ if (pages.length === 0) {
307
+ warnings.push('页码清单「' + spec + '」没有解析出可用的正数页码,锚点将无法映射回原文页码');
308
+ unresolvedNegative = true;
309
+ }
310
+ if (unresolvedNegative) {
311
+ warnings.push('页码范围「' + spec + '」含倒数页码,但本次结果无法确定文档总页数:锚点按「首个正数页码」推算,倒数码之后的页可能偏移,请核对');
312
+ }
313
+ // canonical is only meaningful for a resolved, ascending page list.
314
+ const ranges = [];
315
+ for (const page of pages) {
316
+ const last = ranges[ranges.length - 1];
317
+ if (last && page === last[1] + 1) last[1] = page;
318
+ else ranges.push([page, page]);
319
+ }
320
+ return {
321
+ pages,
322
+ canonical: ranges.map(([a, b]) => (a === b ? String(a) : a + '-' + b)).join(','),
323
+ unresolvedNegative,
324
+ firstPositivePage,
325
+ offset: firstPositivePage === null ? 0 : firstPositivePage - 1,
326
+ warnings,
327
+ };
328
+ }
329
+
330
+ /**
331
+ * Build the page-anchored Markdown for one precision result.
332
+ *
333
+ * @param {Array<Record<string, unknown>>} contentList `content_list.json`
334
+ * @param {{
335
+ * pageNumbers?: number[] | null,
336
+ * pageOffset?: number,
337
+ * pageRanges?: string | null,
338
+ * }} [options]
339
+ * `pageNumbers` / `pageOffset` say how to turn a request-relative `page_idx`
340
+ * into an original 1-based page; `pageRanges` (the raw request string) is
341
+ * only used to derive them when neither is given.
342
+ * @returns {{
343
+ * markdown: string,
344
+ * anchors: Array<{ page: number|null, index: number, type: string, kind: string, emitted: boolean }>,
345
+ * stats: Record<string, unknown>,
346
+ * pageNumbers: { detected: number, total: number, offsets: number[] },
347
+ * warnings: string[],
348
+ * }}
349
+ * `pageNumbers` is the best-effort self-check of the printed page numbers
350
+ * found in the `page_number` blocks against the physical page order:
351
+ * `detected` counted pages, `total` rendered pages, `offsets` the distinct
352
+ * printed-minus-physical differences (sorted, ascending).
353
+ */
354
+ export function synthesizeDocument(contentList, options = {}) {
355
+ if (!Array.isArray(contentList)) throw new TypeError('contentList must be an array');
356
+
357
+ const warnings = [];
358
+ const warningSeen = new Set();
359
+ const warn = (message) => {
360
+ if (warningSeen.has(message)) return;
361
+ warningSeen.add(message);
362
+ warnings.push(message);
363
+ };
364
+
365
+ const hasPageNumbers = Array.isArray(options.pageNumbers) && options.pageNumbers.length > 0;
366
+ let pageNumbers = hasPageNumbers ? options.pageNumbers : null;
367
+ let pageOffset = Number.isInteger(options.pageOffset) && options.pageOffset >= 0
368
+ ? options.pageOffset
369
+ : 0;
370
+
371
+ if (!pageNumbers && typeof options.pageRanges === 'string' && options.pageRanges.trim() !== '') {
372
+ // totalPages is deliberately not guessed from the result: the content list
373
+ // only covers the requested subset, so its highest page_idx says nothing
374
+ // about the document length. Without a real total, negative indexes fall
375
+ // back to the first positive page and the warning below says so.
376
+ const parsed = parseRequestedPages(options.pageRanges);
377
+ for (const message of parsed.warnings) warn(message);
378
+ if (parsed.pages.length > 0 && !parsed.unresolvedNegative) {
379
+ pageNumbers = parsed.pages;
380
+ } else if (parsed.firstPositivePage !== null && options.pageOffset === undefined) {
381
+ // Negative indexes with an unknown total: the subset still starts at a
382
+ // known page, so an offset is the best available mapping (and the
383
+ // warning above says so). An explicit caller-supplied offset wins.
384
+ pageOffset = parsed.offset;
385
+ }
386
+ }
387
+ if (pageNumbers && !pageNumbers.every((page) => Number.isInteger(page) && page >= 1)) {
388
+ throw new TypeError('pageNumbers must be an array of 1-based integers');
389
+ }
390
+
391
+ const pageOf = (rawPageIdx) => {
392
+ if (pageNumbers) return pageNumbers[rawPageIdx] ?? null;
393
+ return rawPageIdx + pageOffset + 1;
394
+ };
395
+
396
+ const counters = new Map();
397
+ const anchors = [];
398
+ const chunks = [];
399
+ const textByPage = new Map();
400
+ // Physical page -> printed page number, first readable candidate wins.
401
+ const printedByPage = new Map();
402
+ let missingPageIdx = 0;
403
+ let outOfRange = 0;
404
+ let auxBlocks = 0;
405
+ let unknownTypes = 0;
406
+ let unreadableBlocks = 0;
407
+
408
+ for (const block of contentList) {
409
+ if (block === null || typeof block !== 'object' || Array.isArray(block)) {
410
+ warn('content_list 里出现了非对象记录,已跳过');
411
+ continue;
412
+ }
413
+ const rawPage = block.page_idx;
414
+ const hasPage = Number.isInteger(rawPage) && rawPage >= 0;
415
+ if (!hasPage) missingPageIdx += 1;
416
+ const page = hasPage ? pageOf(rawPage) : null;
417
+ if (hasPage && page === null) outOfRange += 1;
418
+
419
+ // The in-page counter advances for every block, including the auxiliary
420
+ // ones we do not render, so bK keeps pointing at the same record in
421
+ // content_list.json regardless of what this renderer chooses to show.
422
+ const key = page === null ? '?' : String(page);
423
+ const index = (counters.get(key) ?? 0) + 1;
424
+ counters.set(key, index);
425
+ const type = typeof block.type === 'string' && block.type !== '' ? block.type : '(missing type)';
426
+ const kind = classifyBlockType(block.type);
427
+ const text = extractText(block);
428
+ if (isUnreadableText(text)) unreadableBlocks += 1;
429
+
430
+ if (kind === 'aux') {
431
+ auxBlocks += 1;
432
+ // The printed page number lives in an auxiliary block, and the physical
433
+ // page it sits on comes from the same mapping the anchors use — never a
434
+ // second derivation, or the self-check would compare two different things.
435
+ if (type === 'page_number' && page !== null && !printedByPage.has(page)) {
436
+ const printed = parsePrintedPageNumber(text);
437
+ if (printed !== null) printedByPage.set(page, printed);
438
+ }
439
+ anchors.push({ page, index, type, kind, emitted: false });
440
+ continue;
441
+ }
442
+ if (kind === 'other') {
443
+ unknownTypes += 1;
444
+ warn('content_list 里出现了未收录的块类型「' + type + '」,已按正文渲染');
445
+ }
446
+ if (page !== null) {
447
+ textByPage.set(page, (textByPage.get(page) ?? '') + text);
448
+ }
449
+ anchors.push({ page, index, type, kind, emitted: true });
450
+ chunks.push('<!-- p' + (page === null ? '?' : page) + ' b' + index + ' -->\n' + renderBlock(block, text, warn));
451
+ }
452
+
453
+ if (missingPageIdx > 0) warn('有 ' + missingPageIdx + ' 个块缺少 page_idx,锚点降级为 p?');
454
+ if (outOfRange > 0) warn('有 ' + outOfRange + ' 个块的 page_idx 超出请求页码清单,锚点降级为 p?');
455
+ if (unreadableBlocks > 0) {
456
+ warn('有 ' + unreadableBlocks + ' 个块被云端标为不可读(' + UNREADABLE_MARKER + '),已保留锚点与占位');
457
+ }
458
+
459
+ const pageList = [...new Set(anchors.map((anchor) => anchor.page).filter((page) => page !== null))]
460
+ .sort((a, b) => a - b);
461
+ const charCountByPage = pageList.map((page) => ({
462
+ page,
463
+ chars: [...(textByPage.get(page) ?? '')].length,
464
+ }));
465
+
466
+ const detectedOffsets = [...printedByPage.entries()]
467
+ .map(([page, printed]) => printed - page)
468
+ .sort((a, b) => a - b);
469
+ const offsets = [...new Set(detectedOffsets)];
470
+ const pageNumberCheck = { detected: detectedOffsets.length, total: pageList.length, offsets };
471
+
472
+ if (offsets.length === 1 && offsets[0] !== 0) {
473
+ warn('印刷页码与物理页序整体相差 ' + formatPageOffset(offsets[0])
474
+ + '(前言用罗马数字,或用析出文献保留原刊页码,都会造成整体偏移);'
475
+ + '锚点仍用物理页序,可用页码映射声明两者的对应关系');
476
+ } else if (offsets.length > 1) {
477
+ warn('检测到多套偏移(' + offsets.map(formatPageOffset).join('、')
478
+ + '),锚点仍用物理页序,请按页码映射逐页核对印刷页码');
479
+ }
480
+
481
+ return {
482
+ markdown: chunks.length === 0 ? '' : chunks.join('\n\n') + '\n',
483
+ anchors,
484
+ stats: {
485
+ blocks: anchors.length,
486
+ pages: pageList.length,
487
+ pageNumbers: pageList,
488
+ bodyBlocks: anchors.filter((anchor) => anchor.emitted).length,
489
+ auxBlocks,
490
+ unknownTypes,
491
+ unreadableBlocks,
492
+ missingPageIdx,
493
+ outOfRange,
494
+ charCountByPage,
495
+ },
496
+ pageNumbers: pageNumberCheck,
497
+ warnings,
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Read a `content_list.json` from an extracted run directory.
503
+ *
504
+ * Accepts the array shape the API returns today and the `{ content_list: [...] }`
505
+ * wrapper some MinerU exports use; a leading BOM is tolerated.
506
+ *
507
+ * @param {string} filePath
508
+ * @returns {Promise<Array<Record<string, unknown>>>}
509
+ */
510
+ export async function readContentListFile(filePath) {
511
+ const raw = await readFile(filePath, 'utf8');
512
+ const text = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
513
+ let parsed;
514
+ try {
515
+ parsed = JSON.parse(text);
516
+ } catch (err) {
517
+ throw new Error('content_list.json 不是合法 JSON: ' + (err?.message ?? String(err)));
518
+ }
519
+ const list = Array.isArray(parsed) ? parsed : parsed?.content_list;
520
+ if (!Array.isArray(list)) throw new Error('content_list.json 既不是数组也不含 content_list 数组');
521
+ return list;
522
+ }
package/lib/artifacts.js CHANGED
@@ -114,6 +114,26 @@ export class ArtifactManager {
114
114
  return { dir, relDir: join('artifacts', runName), runName };
115
115
  }
116
116
 
117
+ /**
118
+ * List run directory names under artifacts/ (run names carry a timestamp
119
+ * prefix, so lexical-descending is newest first). A missing/empty artifacts
120
+ * dir returns [].
121
+ * @returns {Promise<string[]>}
122
+ */
123
+ async listRunDirs() {
124
+ let entries;
125
+ try {
126
+ entries = await readdir(join(this.rootDir, 'artifacts'), { withFileTypes: true });
127
+ } catch {
128
+ return [];
129
+ }
130
+ return entries
131
+ .filter((entry) => entry.isDirectory())
132
+ .map((entry) => entry.name)
133
+ .sort()
134
+ .reverse();
135
+ }
136
+
117
137
  /** rel path of an artifact inside its run dir. */
118
138
  relIn(relDir, fileName) {
119
139
  return join(relDir, fileName);
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Merging per-chunk results back into one document (pure functions).
3
+ *
4
+ * A request split by `page_ranges` comes back renumbered: the cloud counts the
5
+ * requested subset from 0, so a two-page request for pages 3-4 returns
6
+ * `page_idx` 0 and 1. A block's original page is therefore
7
+ * `requestedPages[page_idx] - 1` (0-based, matching what an unsplit request
8
+ * returns), and every consumer downstream can read the merged file exactly like
9
+ * a single-request result.
10
+ * @module dsh-mineru/chunk-merge
11
+ */
12
+
13
+ /**
14
+ * Remap one chunk's `content_list.json` blocks onto original page indexes.
15
+ *
16
+ * Blocks whose integer `page_idx` does not land inside the requested page list
17
+ * keep every other field but lose `page_idx`: a page number that does not exist
18
+ * is worse than no page number, because nothing downstream can tell it is wrong.
19
+ * A block without an integer `page_idx` (the cloud emits plain strings for some
20
+ * list items) is passed through untouched.
21
+ *
22
+ * @param {unknown[]} blocks parsed `content_list.json` of one chunk
23
+ * @param {number[]} requestedPages the 1-based page list that chunk was requested with
24
+ * @returns {{blocks: unknown[], outOfRange: number}} mapped blocks and how many
25
+ * blocks lost their `page_idx`
26
+ */
27
+ export function remapChunkPages(blocks, requestedPages) {
28
+ if (!Array.isArray(blocks)) throw new TypeError('blocks must be an array');
29
+ if (!Array.isArray(requestedPages) || requestedPages.length === 0) {
30
+ throw new TypeError('requestedPages must be a non-empty array');
31
+ }
32
+ const out = [];
33
+ let outOfRange = 0;
34
+ for (const block of blocks) {
35
+ // Non-object entries (the cloud emits plain strings for some list items)
36
+ // carry no page index and are passed through untouched.
37
+ if (block === null || typeof block !== 'object' || Array.isArray(block)) {
38
+ out.push(block);
39
+ continue;
40
+ }
41
+ const localPage = block.page_idx;
42
+ if (!Number.isInteger(localPage) || localPage < 0) {
43
+ out.push(block);
44
+ continue;
45
+ }
46
+ const original = requestedPages[localPage];
47
+ if (!Number.isInteger(original)) {
48
+ const rest = { ...block };
49
+ delete rest.page_idx;
50
+ outOfRange += 1;
51
+ out.push(rest);
52
+ continue;
53
+ }
54
+ out.push({ ...block, page_idx: original - 1 });
55
+ }
56
+ return { blocks: out, outOfRange };
57
+ }
58
+
59
+ /**
60
+ * Concatenate per-chunk Markdown with a provenance line before each segment.
61
+ *
62
+ * `full.md` is plain Markdown, so stitching the segments preserves the
63
+ * structure; the comment names the chunk and its page range so a reader can see
64
+ * where one request ended and the next began.
65
+ *
66
+ * @param {Array<{note: string, markdown: string}>} segments in submission order
67
+ * @returns {string}
68
+ */
69
+ export function mergeChunksMarkdown(segments) {
70
+ if (!Array.isArray(segments) || segments.length === 0) {
71
+ throw new TypeError('segments must be a non-empty array');
72
+ }
73
+ const parts = [];
74
+ for (const segment of segments) {
75
+ const body = String(segment?.markdown ?? '').replace(/\s+$/, '');
76
+ parts.push('<!-- ' + String(segment?.note ?? '') + ' -->');
77
+ if (body !== '') parts.push('', body);
78
+ }
79
+ return parts.join('\n') + '\n';
80
+ }