@shuji-bonji/pdf-reader-mcp 0.6.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/README.ja.md +8 -3
- package/README.md +9 -3
- package/dist/schemas/tier2.d.ts +18 -0
- package/dist/schemas/tier2.d.ts.map +1 -1
- package/dist/schemas/tier2.js +13 -0
- package/dist/schemas/tier2.js.map +1 -1
- package/dist/services/pdfjs-service.d.ts +81 -4
- package/dist/services/pdfjs-service.d.ts.map +1 -1
- package/dist/services/pdfjs-service.js +232 -57
- package/dist/services/pdfjs-service.js.map +1 -1
- package/dist/services/pdflib-service.d.ts +21 -0
- package/dist/services/pdflib-service.d.ts.map +1 -1
- package/dist/services/pdflib-service.js +123 -46
- package/dist/services/pdflib-service.js.map +1 -1
- package/dist/services/struct-tree-service.d.ts +149 -0
- package/dist/services/struct-tree-service.d.ts.map +1 -0
- package/dist/services/struct-tree-service.js +459 -0
- package/dist/services/struct-tree-service.js.map +1 -0
- package/dist/services/validation-service.d.ts +15 -0
- package/dist/services/validation-service.d.ts.map +1 -1
- package/dist/services/validation-service.js +62 -16
- package/dist/services/validation-service.js.map +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/tier1/read-images.d.ts.map +1 -1
- package/dist/tools/tier1/read-images.js +8 -2
- package/dist/tools/tier1/read-images.js.map +1 -1
- package/dist/tools/tier2/extract-structured-text.d.ts +6 -0
- package/dist/tools/tier2/extract-structured-text.d.ts.map +1 -0
- package/dist/tools/tier2/extract-structured-text.js +82 -0
- package/dist/tools/tier2/extract-structured-text.js.map +1 -0
- package/dist/tools/tier2/inspect-tags.js +1 -1
- package/dist/tools/tier2/inspect-tags.js.map +1 -1
- package/dist/tools/tier3/validate-metadata.d.ts.map +1 -1
- package/dist/tools/tier3/validate-metadata.js +22 -7
- package/dist/tools/tier3/validate-metadata.js.map +1 -1
- package/dist/tools/tier3/validate-tagged.d.ts.map +1 -1
- package/dist/tools/tier3/validate-tagged.js +17 -2
- package/dist/tools/tier3/validate-tagged.js.map +1 -1
- package/dist/types.d.ts +56 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/formatter.d.ts +8 -1
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +46 -0
- package/dist/utils/formatter.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structure tree walker.
|
|
3
|
+
*
|
|
4
|
+
* Walks the document's logical structure hierarchy from the catalog's
|
|
5
|
+
* `StructTreeRoot`, depth-first — which is exactly how ISO 32000-2 §14.8.2.5
|
|
6
|
+
* defines logical content order:
|
|
7
|
+
*
|
|
8
|
+
* > Logical content order – the ordering for semantic purposes – shall be
|
|
9
|
+
* > defined by a depth-first traversal of the document's logical structure
|
|
10
|
+
* > hierarchy.
|
|
11
|
+
*
|
|
12
|
+
* ## Why not `page.getStructTree()`?
|
|
13
|
+
*
|
|
14
|
+
* pdfjs only offers a per-page view. Merging those per page — which is what
|
|
15
|
+
* `extract_tables` and `inspect_tags` do — cannot produce logical content order,
|
|
16
|
+
* because §14.8.2.5 NOTE 2 allows a single logical object to span pages:
|
|
17
|
+
*
|
|
18
|
+
* > A logical object can extend over more than one PDF page …
|
|
19
|
+
*
|
|
20
|
+
* Measured on `tests/fixtures/structured.pdf` (one paragraph and one list, each
|
|
21
|
+
* split across two pages):
|
|
22
|
+
*
|
|
23
|
+
* | | this walker | per-page merge |
|
|
24
|
+
* |---|---|---|
|
|
25
|
+
* | `Document` | 1 | 2 (duplicated per page) |
|
|
26
|
+
* | `L` | 1 (with 2 `LI`) | 2 (with 1 `LI` each) |
|
|
27
|
+
*
|
|
28
|
+
* pdfjs's per-page nodes carry no element identity (`role` + `children` only),
|
|
29
|
+
* so once merged there is no way to recover that page 1's `L` and page 2's `L`
|
|
30
|
+
* are the same list. Walking the document tree keeps them whole.
|
|
31
|
+
*
|
|
32
|
+
* ## Division of labour
|
|
33
|
+
*
|
|
34
|
+
* This module uses pdf-lib and returns *structure* plus the marked-content
|
|
35
|
+
* references that locate the text. It does not read text — resolving MCIDs to
|
|
36
|
+
* strings needs pdfjs, and lives in `pdfjs-service.ts`. Structure from pdf-lib,
|
|
37
|
+
* text from pdfjs.
|
|
38
|
+
*/
|
|
39
|
+
import { PDFArray, PDFDict, PDFHexString, PDFName, PDFNumber, PDFRef, PDFString, } from 'pdf-lib';
|
|
40
|
+
import { resolvePageNumbers } from '../utils/pdf-helpers.js';
|
|
41
|
+
import { buildDocumentIdToTextMap, LINE_BREAK, loadDocument, resolveLineBreaks, } from './pdfjs-service.js';
|
|
42
|
+
import { loadWithPdfLib } from './pdflib-service.js';
|
|
43
|
+
/**
|
|
44
|
+
* Build the pdfjs marked-content id for a `/Pg` + `/MCID` pair.
|
|
45
|
+
*
|
|
46
|
+
* pdfjs names marked content `p{pageObjectNumber}R_mc{mcid}` — verified against
|
|
47
|
+
* pdfjs-dist in `tests/tier1/struct-tree-service.test.ts`. Note it drops the
|
|
48
|
+
* generation number (`p7R`, not `p7_0R`).
|
|
49
|
+
*
|
|
50
|
+
* This format is pdfjs's internal convention, not a published contract, so the
|
|
51
|
+
* test asserts it against real pdfjs output: if a pdfjs upgrade renames these,
|
|
52
|
+
* the test fails rather than the tool silently returning empty text. (D-2 was
|
|
53
|
+
* caused by hardcoding pdfjs constants without such a guard.)
|
|
54
|
+
*/
|
|
55
|
+
export function pdfjsMarkedContentId(ref) {
|
|
56
|
+
return `p${ref.pageObjNum}R_mc${ref.mcid}`;
|
|
57
|
+
}
|
|
58
|
+
/** Resolve a value that may be an indirect reference. */
|
|
59
|
+
function deref(doc, obj) {
|
|
60
|
+
return obj instanceof PDFRef ? doc.context.lookup(obj) : obj;
|
|
61
|
+
}
|
|
62
|
+
/** Read a text-ish value (`PDFString` / `PDFHexString`) from a dictionary. */
|
|
63
|
+
function textEntry(doc, dict, key) {
|
|
64
|
+
const value = deref(doc, dict.get(PDFName.of(key)));
|
|
65
|
+
if (value instanceof PDFString || value instanceof PDFHexString)
|
|
66
|
+
return value.decodeText();
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
/** Normalise `/K` — it may be absent, a single object, or an array. */
|
|
70
|
+
function kidsOf(doc, dict) {
|
|
71
|
+
const k = deref(doc, dict.get(PDFName.of('K')));
|
|
72
|
+
if (k === undefined || k === null)
|
|
73
|
+
return [];
|
|
74
|
+
if (k instanceof PDFArray)
|
|
75
|
+
return k.asArray();
|
|
76
|
+
return [k];
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Walk one structure element.
|
|
80
|
+
*
|
|
81
|
+
* `/K` is polymorphic (§14.7.2 Table 355) and every form has to be handled:
|
|
82
|
+
*
|
|
83
|
+
* - **integer** — an MCID on the element's own (possibly inherited) `/Pg`
|
|
84
|
+
* - **MCR dict** — an MCID with its own `/Pg`, which is how an element points
|
|
85
|
+
* at content on a page other than its own. This is the page-spanning case.
|
|
86
|
+
* - **OBJR dict** — a reference to an annotation or form field. Skipped: it
|
|
87
|
+
* owns no page text.
|
|
88
|
+
* - **StructElem dict** — a child element, recursed into
|
|
89
|
+
*
|
|
90
|
+
* `/Pg` is inherited: an element without one uses its nearest ancestor's.
|
|
91
|
+
*/
|
|
92
|
+
function walkElement(doc, dict, inheritedPg) {
|
|
93
|
+
const s = deref(doc, dict.get(PDFName.of('S')));
|
|
94
|
+
if (!(s instanceof PDFName))
|
|
95
|
+
return null;
|
|
96
|
+
const pgValue = dict.get(PDFName.of('Pg'));
|
|
97
|
+
const pg = pgValue instanceof PDFRef ? pgValue : inheritedPg;
|
|
98
|
+
const element = {
|
|
99
|
+
role: s.decodeText(),
|
|
100
|
+
actualText: textEntry(doc, dict, 'ActualText'),
|
|
101
|
+
alt: textEntry(doc, dict, 'Alt'),
|
|
102
|
+
lang: textEntry(doc, dict, 'Lang'),
|
|
103
|
+
contentRefs: [],
|
|
104
|
+
children: [],
|
|
105
|
+
};
|
|
106
|
+
for (const kid of kidsOf(doc, dict)) {
|
|
107
|
+
// An MCID written directly, on this element's page.
|
|
108
|
+
if (kid instanceof PDFNumber) {
|
|
109
|
+
if (pg)
|
|
110
|
+
element.contentRefs.push({ pageObjNum: pg.objectNumber, mcid: kid.asNumber() });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const resolved = deref(doc, kid);
|
|
114
|
+
if (!(resolved instanceof PDFDict))
|
|
115
|
+
continue;
|
|
116
|
+
const type = resolved.get(PDFName.of('Type'));
|
|
117
|
+
const typeName = type instanceof PDFName ? type.decodeText() : null;
|
|
118
|
+
if (typeName === 'MCR') {
|
|
119
|
+
const mcid = deref(doc, resolved.get(PDFName.of('MCID')));
|
|
120
|
+
const mcrPgValue = resolved.get(PDFName.of('Pg'));
|
|
121
|
+
const mcrPg = mcrPgValue instanceof PDFRef ? mcrPgValue : pg;
|
|
122
|
+
if (mcid instanceof PDFNumber && mcrPg) {
|
|
123
|
+
element.contentRefs.push({ pageObjNum: mcrPg.objectNumber, mcid: mcid.asNumber() });
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
// OBJR points at an annotation or form field, which carries no page text.
|
|
128
|
+
if (typeName === 'OBJR')
|
|
129
|
+
continue;
|
|
130
|
+
// Anything with an /S is a child structure element. Checking /S rather than
|
|
131
|
+
// Type == StructElem on purpose: Type is optional in practice and plenty of
|
|
132
|
+
// producers omit it.
|
|
133
|
+
if (resolved.get(PDFName.of('S'))) {
|
|
134
|
+
const child = walkElement(doc, resolved, pg);
|
|
135
|
+
if (child)
|
|
136
|
+
element.children.push(child);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return element;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Walk the document's structure tree from the catalog.
|
|
143
|
+
*
|
|
144
|
+
* Returns the top-level structure elements in document order, or `null` when the
|
|
145
|
+
* catalog has no `StructTreeRoot` (an untagged document, or one whose structure
|
|
146
|
+
* tree is unreachable).
|
|
147
|
+
*
|
|
148
|
+
* Note this reads only `StructTreeRoot`; it needs neither `/ParentTree` nor
|
|
149
|
+
* `/StructParents`, which pdfjs's per-page `getStructTree()` does require.
|
|
150
|
+
*/
|
|
151
|
+
export function walkStructTree(doc) {
|
|
152
|
+
const root = deref(doc, doc.catalog.get(PDFName.of('StructTreeRoot')));
|
|
153
|
+
if (!(root instanceof PDFDict))
|
|
154
|
+
return null;
|
|
155
|
+
const elements = [];
|
|
156
|
+
for (const kid of kidsOf(doc, root)) {
|
|
157
|
+
const resolved = deref(doc, kid);
|
|
158
|
+
if (resolved instanceof PDFDict && resolved.get(PDFName.of('S'))) {
|
|
159
|
+
const element = walkElement(doc, resolved, undefined);
|
|
160
|
+
if (element)
|
|
161
|
+
elements.push(element);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return elements;
|
|
165
|
+
}
|
|
166
|
+
/** Collect every content reference under an element, in document order. */
|
|
167
|
+
export function collectContentRefs(element, into = []) {
|
|
168
|
+
into.push(...element.contentRefs);
|
|
169
|
+
for (const child of element.children)
|
|
170
|
+
collectContentRefs(child, into);
|
|
171
|
+
return into;
|
|
172
|
+
}
|
|
173
|
+
// ─── Structured text (M-8) ───────────────────────────────
|
|
174
|
+
/**
|
|
175
|
+
* Roles whose children are structural scaffolding rather than prose, and whose
|
|
176
|
+
* text therefore should not be rolled up from descendants.
|
|
177
|
+
*
|
|
178
|
+
* `Table` gets `rows` instead (it is two-dimensional; `depth` cannot express
|
|
179
|
+
* "row 2, column 3"), and `L` / `LI` have their items emitted separately.
|
|
180
|
+
*/
|
|
181
|
+
const CONTAINER_ROLES = new Set([
|
|
182
|
+
'Document',
|
|
183
|
+
'Part',
|
|
184
|
+
'Art',
|
|
185
|
+
'Sect',
|
|
186
|
+
'Div',
|
|
187
|
+
'Table',
|
|
188
|
+
'L',
|
|
189
|
+
'LI',
|
|
190
|
+
'TR',
|
|
191
|
+
]);
|
|
192
|
+
/** `Lbl` is a list label ("•", "1."), not body text — reported separately. */
|
|
193
|
+
const LABEL_ROLE = 'Lbl';
|
|
194
|
+
/**
|
|
195
|
+
* Assemble the text of an element from its marked content.
|
|
196
|
+
*
|
|
197
|
+
* `/ActualText` wins when present: ISO 32000-2 §14.9.4 says it "shall be used as
|
|
198
|
+
* a **replacement**, not a description, for the content". `/Alt` is deliberately
|
|
199
|
+
* NOT consulted here — it is a description of content that has no text (§14.9.3),
|
|
200
|
+
* so treating it as text would inject a caption into the body.
|
|
201
|
+
*
|
|
202
|
+
* When an element's content continues on another page, the page boundary is a
|
|
203
|
+
* line break in the original layout and is treated as one. pdfjs emits no EOL
|
|
204
|
+
* marker at the start of a page, so without this a paragraph split across pages
|
|
205
|
+
* extracts as "…page oneand continues…" — and for Japanese the same boundary
|
|
206
|
+
* must produce no space at all, which `resolveLineBreaks` decides.
|
|
207
|
+
*/
|
|
208
|
+
function textOf(element, idToText, includeDescendants) {
|
|
209
|
+
if (element.actualText !== null)
|
|
210
|
+
return element.actualText;
|
|
211
|
+
const refs = includeDescendants ? collectContentRefs(element) : element.contentRefs;
|
|
212
|
+
let assembled = '';
|
|
213
|
+
let previousPage;
|
|
214
|
+
for (const ref of refs) {
|
|
215
|
+
if (assembled !== '' && previousPage !== undefined && previousPage !== ref.pageObjNum) {
|
|
216
|
+
assembled += LINE_BREAK;
|
|
217
|
+
}
|
|
218
|
+
assembled += idToText.get(pdfjsMarkedContentId(ref)) ?? '';
|
|
219
|
+
previousPage = ref.pageObjNum;
|
|
220
|
+
}
|
|
221
|
+
return resolveLineBreaks(assembled);
|
|
222
|
+
}
|
|
223
|
+
/** Collapse whitespace runs and trim. Line breaks were already resolved upstream. */
|
|
224
|
+
function tidy(text) {
|
|
225
|
+
return text.replace(/[\s ]+/g, ' ').trim();
|
|
226
|
+
}
|
|
227
|
+
/** Pages an element's content lives on, in order of first appearance. */
|
|
228
|
+
function pagesOf(element, pageNumByObjNum) {
|
|
229
|
+
const seen = [];
|
|
230
|
+
for (const ref of collectContentRefs(element)) {
|
|
231
|
+
const pageNum = pageNumByObjNum.get(ref.pageObjNum);
|
|
232
|
+
if (pageNum !== undefined && !seen.includes(pageNum))
|
|
233
|
+
seen.push(pageNum);
|
|
234
|
+
}
|
|
235
|
+
return seen.sort((a, b) => a - b);
|
|
236
|
+
}
|
|
237
|
+
/** Build `rows` for a `Table` element by walking TR → TH/TD. */
|
|
238
|
+
function tableRows(element, idToText) {
|
|
239
|
+
const rows = [];
|
|
240
|
+
const visitRow = (row) => {
|
|
241
|
+
const cells = [];
|
|
242
|
+
for (const cell of row.children) {
|
|
243
|
+
if (cell.role === 'TH' || cell.role === 'TD') {
|
|
244
|
+
cells.push({ text: tidy(textOf(cell, idToText, true)), isHeader: cell.role === 'TH' });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (cells.length > 0)
|
|
248
|
+
rows.push(cells);
|
|
249
|
+
};
|
|
250
|
+
const visit = (node) => {
|
|
251
|
+
for (const child of node.children) {
|
|
252
|
+
if (child.role === 'TR')
|
|
253
|
+
visitRow(child);
|
|
254
|
+
// THead / TBody / TFoot wrap rows; TR may also sit directly under Table.
|
|
255
|
+
else
|
|
256
|
+
visit(child);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
visit(element);
|
|
260
|
+
return rows;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Flatten the structure tree into logical content order.
|
|
264
|
+
*
|
|
265
|
+
* Flat + `depth` rather than nested: a depth-first pre-order plus depth encodes
|
|
266
|
+
* the tree exactly (it is an indented outline), the main consumer walks it
|
|
267
|
+
* linearly to emit Markdown, and it can be truncated at any point without
|
|
268
|
+
* producing broken JSON. `Table` is the exception — see `rows`.
|
|
269
|
+
*/
|
|
270
|
+
function flatten(element, depth, idToText, pageNumByObjNum, out) {
|
|
271
|
+
// A list label belongs to its LI, not to the flow of text.
|
|
272
|
+
if (element.role === LABEL_ROLE)
|
|
273
|
+
return;
|
|
274
|
+
const isContainer = CONTAINER_ROLES.has(element.role);
|
|
275
|
+
const isTable = element.role === 'Table';
|
|
276
|
+
const entry = {
|
|
277
|
+
role: element.role,
|
|
278
|
+
depth,
|
|
279
|
+
text: null,
|
|
280
|
+
pages: pagesOf(element, pageNumByObjNum),
|
|
281
|
+
};
|
|
282
|
+
if (isTable) {
|
|
283
|
+
entry.rows = tableRows(element, idToText);
|
|
284
|
+
}
|
|
285
|
+
else if (!isContainer) {
|
|
286
|
+
// A leaf rolls up its descendants' text (e.g. LBody under LI, Span under P).
|
|
287
|
+
const text = tidy(textOf(element, idToText, true));
|
|
288
|
+
entry.text = text === '' ? null : text;
|
|
289
|
+
}
|
|
290
|
+
if (element.role === 'LI') {
|
|
291
|
+
const label = element.children.find((c) => c.role === LABEL_ROLE);
|
|
292
|
+
if (label) {
|
|
293
|
+
const labelText = tidy(textOf(label, idToText, true));
|
|
294
|
+
if (labelText)
|
|
295
|
+
entry.label = labelText;
|
|
296
|
+
}
|
|
297
|
+
// The LI's text is its LBody; emit it here so consumers get one entry per item.
|
|
298
|
+
const body = element.children.filter((c) => c.role !== LABEL_ROLE);
|
|
299
|
+
if (body.length > 0) {
|
|
300
|
+
const text = tidy(body.map((b) => textOf(b, idToText, true)).join(''));
|
|
301
|
+
entry.text = text === '' ? null : text;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (element.alt !== null)
|
|
305
|
+
entry.alt = element.alt;
|
|
306
|
+
if (element.lang !== null)
|
|
307
|
+
entry.lang = element.lang;
|
|
308
|
+
out.push(entry);
|
|
309
|
+
// Table rows and LI bodies are already represented; don't emit them again.
|
|
310
|
+
if (isTable || element.role === 'LI')
|
|
311
|
+
return;
|
|
312
|
+
for (const child of element.children) {
|
|
313
|
+
flatten(child, depth + 1, idToText, pageNumByObjNum, out);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Turn a walked structure tree into the flattened, text-bearing result.
|
|
318
|
+
*
|
|
319
|
+
* `pageNumByObjNum` maps page object numbers (as seen in `/Pg`) to 1-based page
|
|
320
|
+
* numbers, so the output speaks in page numbers rather than object numbers.
|
|
321
|
+
*/
|
|
322
|
+
export function buildStructuredText(roots, idToText, pageNumByObjNum, options = {}) {
|
|
323
|
+
const out = [];
|
|
324
|
+
for (const root of roots)
|
|
325
|
+
flatten(root, 0, idToText, pageNumByObjNum, out);
|
|
326
|
+
let filtered = out;
|
|
327
|
+
if (options.roles && options.roles.length > 0) {
|
|
328
|
+
const wanted = new Set(options.roles);
|
|
329
|
+
filtered = filtered.filter((e) => wanted.has(e.role));
|
|
330
|
+
}
|
|
331
|
+
if (options.pages && options.pages.length > 0) {
|
|
332
|
+
const wanted = new Set(options.pages);
|
|
333
|
+
// An element that touches the range at all is kept whole — splitting a
|
|
334
|
+
// page-spanning element is precisely what this tool exists to avoid.
|
|
335
|
+
filtered = filtered.filter((e) => e.pages.length === 0 || e.pages.some((p) => wanted.has(p)));
|
|
336
|
+
}
|
|
337
|
+
return filtered;
|
|
338
|
+
}
|
|
339
|
+
// ─── inspect_tags (C-1) ──────────────────────────────────
|
|
340
|
+
/** Convert a walked structure element to a `TagNode` for inspect_tags. */
|
|
341
|
+
function toTagNode(element, roleCounts) {
|
|
342
|
+
roleCounts[element.role] = (roleCounts[element.role] ?? 0) + 1;
|
|
343
|
+
return {
|
|
344
|
+
role: element.role,
|
|
345
|
+
children: element.children.map((child) => toTagNode(child, roleCounts)),
|
|
346
|
+
contentCount: element.contentRefs.length,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
function tagDepth(node) {
|
|
350
|
+
if (node.children.length === 0)
|
|
351
|
+
return 1;
|
|
352
|
+
return 1 + Math.max(...node.children.map(tagDepth));
|
|
353
|
+
}
|
|
354
|
+
function tagCount(node) {
|
|
355
|
+
return 1 + node.children.reduce((sum, child) => sum + tagCount(child), 0);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Build the inspect_tags analysis from the document's structure tree.
|
|
359
|
+
*
|
|
360
|
+
* C-1: the previous implementation walked `page.getStructTree()` per page and
|
|
361
|
+
* hung all of them under a synthetic `StructTreeRoot` node — so a two-page
|
|
362
|
+
* document reported TWO `Document` roots, and any element spanning pages was
|
|
363
|
+
* duplicated. That is a merge artifact, not the document's structure, and
|
|
364
|
+
* "reporting the structure tree is a fact and reader's job" (family M-2) only
|
|
365
|
+
* holds if the reported tree is the real one. Here `StructTreeRoot` is the
|
|
366
|
+
* actual root of the actual tree: one `Document`, page-spanning elements whole.
|
|
367
|
+
*/
|
|
368
|
+
export function analyzeTagsFromStructTree(roots, isTagged) {
|
|
369
|
+
if (!isTagged || !roots || roots.length === 0) {
|
|
370
|
+
return { isTagged, rootTag: null, maxDepth: 0, totalElements: 0, roleCounts: {} };
|
|
371
|
+
}
|
|
372
|
+
const roleCounts = {};
|
|
373
|
+
const children = roots.map((root) => toTagNode(root, roleCounts));
|
|
374
|
+
const rootTag = { role: 'StructTreeRoot', children, contentCount: 0 };
|
|
375
|
+
return {
|
|
376
|
+
isTagged: true,
|
|
377
|
+
rootTag,
|
|
378
|
+
// The StructTreeRoot node itself is one level; tagDepth counts from a child.
|
|
379
|
+
maxDepth: children.length > 0 ? 1 + Math.max(...children.map(tagDepth)) : 1,
|
|
380
|
+
totalElements: children.reduce((sum, child) => sum + tagCount(child), 0),
|
|
381
|
+
roleCounts,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Analyze a Tagged PDF's structure tree for inspect_tags.
|
|
386
|
+
*
|
|
387
|
+
* Uses the document's `StructTreeRoot` (pdf-lib), not per-page trees — see
|
|
388
|
+
* `analyzeTagsFromStructTree`.
|
|
389
|
+
*/
|
|
390
|
+
export async function analyzeTags(filePath) {
|
|
391
|
+
const doc = await loadWithPdfLib(filePath);
|
|
392
|
+
const markInfo = deref(doc, doc.catalog.get(PDFName.of('MarkInfo')));
|
|
393
|
+
const marked = markInfo instanceof PDFDict ? deref(doc, markInfo.get(PDFName.of('Marked'))) : undefined;
|
|
394
|
+
const isTagged = String(marked) === 'true';
|
|
395
|
+
return analyzeTagsFromStructTree(walkStructTree(doc), isTagged);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Extract structured text — the `extract_structured_text` service entry point.
|
|
399
|
+
*
|
|
400
|
+
* Reads the document twice on purpose, once per library, because each answers a
|
|
401
|
+
* different question:
|
|
402
|
+
*
|
|
403
|
+
* - **pdf-lib** — the structure: `StructTreeRoot`, depth-first, with element
|
|
404
|
+
* identity intact across pages.
|
|
405
|
+
* - **pdfjs** — the text: marked content resolved to strings.
|
|
406
|
+
*
|
|
407
|
+
* Untagged documents return `isTagged: false` with a reason and no elements.
|
|
408
|
+
* Nothing is guessed: §14.8.2.5 NOTE 1 is explicit that page content order need
|
|
409
|
+
* not match logical content order, so clustering by coordinates would be an
|
|
410
|
+
* invention, not an observation — and reader reports observations.
|
|
411
|
+
*/
|
|
412
|
+
export async function extractStructuredText(filePath, options = {}) {
|
|
413
|
+
const libDoc = await loadWithPdfLib(filePath);
|
|
414
|
+
const markInfo = deref(libDoc, libDoc.catalog.get(PDFName.of('MarkInfo')));
|
|
415
|
+
const marked = markInfo instanceof PDFDict ? deref(libDoc, markInfo.get(PDFName.of('Marked'))) : undefined;
|
|
416
|
+
const isTagged = String(marked) === 'true';
|
|
417
|
+
const roots = walkStructTree(libDoc);
|
|
418
|
+
if (!isTagged || !roots || roots.length === 0) {
|
|
419
|
+
return {
|
|
420
|
+
isTagged: false,
|
|
421
|
+
lang: null,
|
|
422
|
+
elements: [],
|
|
423
|
+
note: 'This document is not tagged (no MarkInfo/Marked=true or no reachable StructTreeRoot), ' +
|
|
424
|
+
'so its logical content order cannot be determined. ISO 32000-2 §14.8.2.5 defines logical ' +
|
|
425
|
+
'content order as a depth-first traversal of the structure hierarchy; without one, any ' +
|
|
426
|
+
'ordering would be inferred from coordinates and could not be trusted. ' +
|
|
427
|
+
'To add a structure scaffold, use pdf-writer-mcp `ensure_tagged`, then retry.',
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
const langEntry = deref(libDoc, libDoc.catalog.get(PDFName.of('Lang')));
|
|
431
|
+
const lang = langEntry instanceof PDFString || langEntry instanceof PDFHexString
|
|
432
|
+
? langEntry.decodeText()
|
|
433
|
+
: null;
|
|
434
|
+
const jsDoc = await loadDocument(filePath);
|
|
435
|
+
try {
|
|
436
|
+
const idToText = await buildDocumentIdToTextMap(jsDoc);
|
|
437
|
+
// Map page object numbers (what /Pg holds) to 1-based page numbers.
|
|
438
|
+
const pageNumByObjNum = new Map();
|
|
439
|
+
const pages = libDoc.getPages();
|
|
440
|
+
for (let i = 0; i < pages.length; i++) {
|
|
441
|
+
pageNumByObjNum.set(pages[i].ref.objectNumber, i + 1);
|
|
442
|
+
}
|
|
443
|
+
const pageFilter = options.pages
|
|
444
|
+
? resolvePageNumbers(options.pages, jsDoc.numPages)
|
|
445
|
+
: undefined;
|
|
446
|
+
return {
|
|
447
|
+
isTagged: true,
|
|
448
|
+
lang,
|
|
449
|
+
elements: buildStructuredText(roots, idToText, pageNumByObjNum, {
|
|
450
|
+
roles: options.roles,
|
|
451
|
+
pages: pageFilter,
|
|
452
|
+
}),
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
finally {
|
|
456
|
+
await jsDoc.destroy();
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
//# sourceMappingURL=struct-tree-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"struct-tree-service.js","sourceRoot":"","sources":["../../src/services/struct-tree-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EACL,QAAQ,EACR,OAAO,EAEP,YAAY,EACZ,OAAO,EACP,SAAS,EACT,MAAM,EACN,SAAS,GACV,MAAM,SAAS,CAAC;AAQjB,OAAO,EA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AE,EAAE,CAAC;YACtC,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QACxD,CAAC;QAED,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK;YAC9B,CAAC,CAAC,kBAAkB,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC;YACnD,CAAC,CAAC,SAAS,CAAC;QAEd,OAAO;YACL,QAAQ,EAAE,IAAI;YACd,IAAI;YACJ,QAAQ,EAAE,mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE;gBAC9D,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,KAAK,EAAE,UAAU;aAClB,CAAC;SACH,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;AACH,CAAC"}
|
|
@@ -46,4 +46,19 @@ export declare function validateMetadata(filePath: string): Promise<MetadataVali
|
|
|
46
46
|
* - Fonts used (set difference)
|
|
47
47
|
*/
|
|
48
48
|
export declare function compareStructure(filePath1: string, filePath2: string): Promise<StructureComparison>;
|
|
49
|
+
/**
|
|
50
|
+
* Check if a date string is a valid PDF date.
|
|
51
|
+
*
|
|
52
|
+
* ISO 32000-2 §7.9.4: `(D:YYYYMMDDHHmmSSOHH'mm)`. The `D:` prefix and `YYYY`
|
|
53
|
+
* are required; every later field may be omitted only if all preceding ones are
|
|
54
|
+
* present (SS excepted — see `PDF_DATE_PATTERN`). `O` is `+`, `-`, or `Z`.
|
|
55
|
+
*
|
|
56
|
+
* Also accepts ISO 8601 (`YYYY-MM-DDTHH:mm:ss`), which is a tolerance rather
|
|
57
|
+
* than conformance — such a string does not satisfy §7.9.4.
|
|
58
|
+
*
|
|
59
|
+
* Exported for unit testing: the pattern is dense enough that it hid two bugs
|
|
60
|
+
* (a character range masquerading as a class, and a welded HH/mm offset), and
|
|
61
|
+
* exercising it through `validateMetadata` would need a fixture per date form.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isValidPdfDate(dateStr: string): boolean;
|
|
49
64
|
//# sourceMappingURL=validation-service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-service.d.ts","sourceRoot":"","sources":["../../src/services/validation-service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EAEnB,gBAAgB,EAEjB,MAAM,aAAa,CAAC;AAYrB;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAgShF;AAID;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA8PpF;AAID;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CACpC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,mBAAmB,CAAC,CAyF9B"}
|
|
1
|
+
{"version":3,"file":"validation-service.d.ts","sourceRoot":"","sources":["../../src/services/validation-service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EAEnB,gBAAgB,EAEjB,MAAM,aAAa,CAAC;AAYrB;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAgShF;AAID;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA8PpF;AAID;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CACpC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,mBAAmB,CAAC,CAyF9B;AAqED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEvD"}
|
|
@@ -646,25 +646,71 @@ function addDiff(diffs, property, val1, val2) {
|
|
|
646
646
|
status: val1 === val2 ? 'match' : 'differ',
|
|
647
647
|
});
|
|
648
648
|
}
|
|
649
|
+
// ─── PDF date format (ISO 32000-2 §7.9.4) ────────────────
|
|
650
|
+
//
|
|
651
|
+
// Built up from the clause's own field definitions rather than written as one
|
|
652
|
+
// opaque expression, because the previous one-liner hid two bugs (see below).
|
|
653
|
+
//
|
|
654
|
+
// (D:YYYYMMDDHHmmSSOHH'mm)
|
|
655
|
+
//
|
|
656
|
+
// Value ranges are from the clause text; checking them is what separates
|
|
657
|
+
// "looks like a date" from "is a date" — the old pattern accepted month 13.
|
|
658
|
+
const D_YYYY = '\\d{4}';
|
|
659
|
+
const D_MM = '(?:0[1-9]|1[0-2])'; // "MM shall be the month (01–12)"
|
|
660
|
+
const D_DD = '(?:0[1-9]|[12]\\d|3[01])'; // "DD shall be the day (01–31)"
|
|
661
|
+
const D_HH = '(?:[01]\\d|2[0-3])'; // "HH shall be the hour (00–23)"
|
|
662
|
+
const D_MIN = '[0-5]\\d'; // "mm shall be the minute (00–59)"
|
|
663
|
+
const D_SS = '[0-5]\\d'; // "SS shall be the second (00–59)"
|
|
664
|
+
// O and the UT offset.
|
|
665
|
+
//
|
|
666
|
+
// BUG 1 (fixed): the old class was `[+-Z]`, which a regex reads as the RANGE
|
|
667
|
+
// U+002B(+) … U+005A(Z) — it accepted `,-./0-9:;<=>?@A-Z`. So `D:...A09'00` and
|
|
668
|
+
// `D:...509'00` were reported as valid dates. The clause admits exactly three
|
|
669
|
+
// characters: PLUS SIGN (+), HYPHEN-MINUS (-), LATIN CAPITAL LETTER Z (Z).
|
|
670
|
+
//
|
|
671
|
+
// BUG 2 (fixed): the old offset was `(\d{2}'\d{2}'?)?`, welding HH and mm
|
|
672
|
+
// together, so the valid `D:...-09'` (hours, no minutes) was rejected. The
|
|
673
|
+
// clause: "The APOSTROPHE … shall only be present if the HH field is present.
|
|
674
|
+
// The minute offset field (mm) shall only be present if the APOSTROPHE … is
|
|
675
|
+
// present." — mm is independently optional.
|
|
676
|
+
//
|
|
677
|
+
// The optional trailing apostrophe is the PDF 1.7 convention; NOTE 2 recommends
|
|
678
|
+
// that processors keep accepting it. NOTE 3 allows Z to carry offsets too
|
|
679
|
+
// ("The letter Z can optionally be followed by hour and minute offsets"), which
|
|
680
|
+
// falls out of treating all three O characters alike.
|
|
681
|
+
const D_OFFSET = `[+\\-Z](?:${D_HH}'(?:${D_MIN}'?)?)?`;
|
|
682
|
+
// "the year field (YYYY) shall be present and all other fields may be present
|
|
683
|
+
// but only if all of their preceding fields are also present" — hence the
|
|
684
|
+
// nesting: each field encloses the next rather than being independently optional.
|
|
685
|
+
//
|
|
686
|
+
// SS is the one deliberate exception. The clause's own EXAMPLE —
|
|
687
|
+
//
|
|
688
|
+
// "December 23, 1998, at 7:52 PM, U.S. Pacific Standard Time" → D:199812231952-08'00
|
|
689
|
+
//
|
|
690
|
+
// omits SS while still carrying the offset, which the sentence above forbids.
|
|
691
|
+
// This is not a version difference: ISO 32000-1:2008 §7.9.4 carries the *same*
|
|
692
|
+
// normative sentence and the *same* example, so it is a long-standing defect in
|
|
693
|
+
// the specification. Producers copy the example, and rejecting the standard's
|
|
694
|
+
// own example in a warning-level check would be indefensible — so we accept an
|
|
695
|
+
// omitted SS. Everything else follows the normative sentence.
|
|
696
|
+
const PDF_DATE_PATTERN = new RegExp(`^D:${D_YYYY}(?:${D_MM}(?:${D_DD}(?:${D_HH}(?:${D_MIN}(?:${D_SS})?(?:${D_OFFSET})?)?)?)?)?$`);
|
|
697
|
+
/** ISO 8601 — not a PDF date, but tolerated from non-conforming producers. */
|
|
698
|
+
const ISO_8601_PATTERN = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2})?(?:[+-]\d{2}:?\d{2}|Z)?)?$/;
|
|
649
699
|
/**
|
|
650
|
-
* Check if a date string
|
|
700
|
+
* Check if a date string is a valid PDF date.
|
|
651
701
|
*
|
|
652
|
-
*
|
|
653
|
-
*
|
|
654
|
-
*
|
|
655
|
-
* O is the timezone indicator: +, -, or Z.
|
|
702
|
+
* ISO 32000-2 §7.9.4: `(D:YYYYMMDDHHmmSSOHH'mm)`. The `D:` prefix and `YYYY`
|
|
703
|
+
* are required; every later field may be omitted only if all preceding ones are
|
|
704
|
+
* present (SS excepted — see `PDF_DATE_PATTERN`). `O` is `+`, `-`, or `Z`.
|
|
656
705
|
*
|
|
657
|
-
* Also accepts ISO 8601
|
|
706
|
+
* Also accepts ISO 8601 (`YYYY-MM-DDTHH:mm:ss`), which is a tolerance rather
|
|
707
|
+
* than conformance — such a string does not satisfy §7.9.4.
|
|
708
|
+
*
|
|
709
|
+
* Exported for unit testing: the pattern is dense enough that it hid two bugs
|
|
710
|
+
* (a character range masquerading as a class, and a welded HH/mm offset), and
|
|
711
|
+
* exercising it through `validateMetadata` would need a fixture per date form.
|
|
658
712
|
*/
|
|
659
|
-
function isValidPdfDate(dateStr) {
|
|
660
|
-
|
|
661
|
-
if (/^D:\d{4}(\d{2}(\d{2}(\d{2}(\d{2}(\d{2}([+-Z](\d{2}'\d{2}'?)?)?)?)?)?)?)?$/.test(dateStr)) {
|
|
662
|
-
return true;
|
|
663
|
-
}
|
|
664
|
-
// ISO 8601 dates: YYYY-MM-DD with optional time
|
|
665
|
-
if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?([+-]\d{2}:?\d{2}|Z)?)?$/.test(dateStr)) {
|
|
666
|
-
return true;
|
|
667
|
-
}
|
|
668
|
-
return false;
|
|
713
|
+
export function isValidPdfDate(dateStr) {
|
|
714
|
+
return PDF_DATE_PATTERN.test(dateStr) || ISO_8601_PATTERN.test(dateStr);
|
|
669
715
|
}
|
|
670
716
|
//# sourceMappingURL=validation-service.js.map
|