dsh-doc-anchor-viewer 0.2.0 → 0.3.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/lib/index.js CHANGED
@@ -16,6 +16,7 @@ import path from 'node:path'
16
16
 
17
17
  import { readZipBuffer } from './ooxml.js'
18
18
  import { parseParagraphs, parseStyles, buildOutline, occurrenceMap } from './docparse.js'
19
+ import { parsePdf } from './pdfparse.js'
19
20
  import { DocStore, resolveDataDir } from './store.js'
20
21
 
21
22
  /**
@@ -48,6 +49,8 @@ export const Config = {
48
49
  value: {
49
50
  dataDir: typeof v.dataDir === 'string' ? v.dataDir.trim() : '',
50
51
  maxDocxMb: num('maxDocxMb', 30, 1, 200),
52
+ // PDF 通常比 docx 大得多(扫描件动辄几十 MB),单独给一个上限
53
+ maxPdfMb: num('maxPdfMb', 60, 1, 300),
51
54
  },
52
55
  }
53
56
  },
@@ -262,6 +265,22 @@ export class DocAnchorViewer {
262
265
  }
263
266
  }
264
267
 
268
+ /**
269
+ * 按文件类型分派解析。docx 走 ZIP+OOXML,pdf 走 PDF.js。
270
+ *
271
+ * 两条管线产出**同构**的结构(paragraphs / outline / occurrence / stats),
272
+ * 所以后面的存储、标记、大纲、工具接口完全不用区分格式。
273
+ *
274
+ * @param {string} filePath
275
+ * @param {Buffer} buf
276
+ * @returns {Promise<object>}
277
+ */
278
+ async _analyzeAny(filePath, buf) {
279
+ const ext = path.extname(filePath).toLowerCase()
280
+ if (ext === '.pdf') return parsePdf(buf)
281
+ return this._analyze(buf)
282
+ }
283
+
265
284
  /**
266
285
  * 由一条记录组装落盘文档。
267
286
  * @param {object} input
@@ -270,12 +289,15 @@ export class DocAnchorViewer {
270
289
  async _persist(input) {
271
290
  const { filePath, buf, stat } = input
272
291
  const docId = makeDocId(filePath, stat.mtimeMs)
273
- const analysis = this._analyze(buf)
292
+ const analysis = await this._analyzeAny(filePath, buf)
293
+ const kind = path.extname(filePath).toLowerCase() === '.pdf' ? 'pdf' : 'docx'
274
294
 
275
295
  const prev = await this.store.readDoc(docId)
276
296
  const doc = {
277
297
  schemaVersion: 1,
278
298
  id: docId,
299
+ // kind 决定浏览器侧用哪个渲染器;老记录没有这个字段,按 docx 处理
300
+ kind,
279
301
  path: filePath,
280
302
  title: input.title || path.basename(filePath, path.extname(filePath)),
281
303
  size: stat.size,
@@ -290,9 +312,14 @@ export class DocAnchorViewer {
290
312
  norm: p.norm,
291
313
  heading: p.heading,
292
314
  level: p.level,
315
+ // PDF 段落带页码与坐标;docx 没有这两项,undefined 不会写进 JSON
316
+ ...(p.page ? { page: p.page } : {}),
317
+ ...(p.rect ? { rect: p.rect } : {}),
293
318
  })),
294
319
  outline: analysis.outline,
295
320
  occurrence: analysis.occurrence,
321
+ // PDF 独有:每页尺寸与每段的 PDF 坐标,客户端用来在 canvas 上摆锚点
322
+ ...(analysis.pageSizes ? { pageSizes: analysis.pageSizes } : {}),
296
323
  // 标记是用户的,重复登记同一份文件时要保住
297
324
  marks: Array.isArray(prev?.marks) ? prev.marks : [],
298
325
  }
@@ -311,6 +338,7 @@ export class DocAnchorViewer {
311
338
  ok: true,
312
339
  dataDir: this.dataDir,
313
340
  maxDocxMb: this.config.maxDocxMb,
341
+ maxPdfMb: this.config.maxPdfMb,
314
342
  store: await this.store.diagnostics(),
315
343
  }
316
344
  }
@@ -347,9 +375,28 @@ export class DocAnchorViewer {
347
375
  */
348
376
  async openDoc(request) {
349
377
  const input = unwrapArg(request)
350
- const maxBytes = Number(this.config.maxDocxMb ?? 30) * 1024 * 1024
351
378
 
379
+ /**
380
+ * 判格式**只看真实文件名**,不能用显示名。
381
+ *
382
+ * ⚠️ PR review 抓到:以前用 `fileName ?? title` 判格式,而 title 只是
383
+ * 给人看的显示名——40MB 的 PDF 配个 title「Report」就会按 docx 的
384
+ * 30MB 上限被拒;反过来 docx 叫「Report.pdf」又拿到了 PDF 的宽松上限。
385
+ *
386
+ * 有 filePath 时**一律以它的扩展名为准**;fileName/title 只在
387
+ * 上传(没有路径、字节是 base64)时才有意义——那时它们就是文件的真名。
388
+ */
352
389
  let filePath = stripQuotes(input.filePath)
390
+ const nameHint = filePath
391
+ ? path.basename(filePath)
392
+ : stripQuotes(input.fileName ?? input.title ?? '')
393
+ const hintExt = path.extname(nameHint).toLowerCase()
394
+ const isPdfHint = hintExt === '.pdf'
395
+ const maxMb = isPdfHint
396
+ ? Number(this.config.maxPdfMb ?? 60)
397
+ : Number(this.config.maxDocxMb ?? 30)
398
+ const maxBytes = maxMb * 1024 * 1024
399
+
353
400
  let buf = null
354
401
  let stat = null
355
402
 
@@ -359,11 +406,12 @@ export class DocAnchorViewer {
359
406
  return fail('doc/file-not-found', '文件不存在:' + filePath)
360
407
  }
361
408
  if (!st.isFile()) return fail('doc/not-a-file', '路径不是文件:' + filePath)
362
- if (path.extname(filePath).toLowerCase() !== '.docx') {
363
- return fail('doc/unsupported-format', '只支持 .docx;旧版 .doc 请先用 Word 另存为 .docx')
409
+ const ext = path.extname(filePath).toLowerCase()
410
+ if (ext !== '.docx' && ext !== '.pdf') {
411
+ return fail('doc/unsupported-format', '只支持 .docx 与 .pdf;旧版 .doc 请先用 Word 另存为 .docx')
364
412
  }
365
413
  if (st.size > maxBytes) {
366
- return fail('doc/file-too-large', `文件 ${(st.size / 1048576).toFixed(1)}MB 超过上限 ${this.config.maxDocxMb}MB`)
414
+ return fail('doc/file-too-large', `文件 ${(st.size / 1048576).toFixed(1)}MB 超过上限 ${maxMb}MB`)
367
415
  }
368
416
  buf = fs.readFileSync(filePath)
369
417
  stat = { size: st.size, mtimeMs: st.mtimeMs }
@@ -371,14 +419,14 @@ export class DocAnchorViewer {
371
419
  const b64 = String(input.base64 ?? '')
372
420
  if (!b64) return fail('doc/invalid-input', '需要 filePath 或 base64 之一')
373
421
  if (b64.length > maxBytes * 1.4) {
374
- return fail('doc/file-too-large', `上传内容超过上限 ${this.config.maxDocxMb}MB`)
422
+ return fail('doc/file-too-large', `上传内容超过上限 ${maxMb}MB`)
375
423
  }
376
424
  buf = Buffer.from(b64, 'base64')
377
425
  if (!buf.length) return fail('doc/invalid-input', 'base64 解码为空,文件可能没读全')
378
426
  if (buf.length > maxBytes) {
379
- return fail('doc/file-too-large', `文件 ${(buf.length / 1048576).toFixed(1)}MB 超过上限 ${this.config.maxDocxMb}MB`)
427
+ return fail('doc/file-too-large', `文件 ${(buf.length / 1048576).toFixed(1)}MB 超过上限 ${maxMb}MB`)
380
428
  }
381
- const name = String(input.fileName ?? input.title ?? 'uploaded.docx')
429
+ const name = String(input.fileName ?? input.title ?? (isPdfHint ? 'uploaded.pdf' : 'uploaded.docx'))
382
430
  // 上传的文件没有稳定路径。用内容哈希当路径标识,保证同一份文件重复打开命中同一条记录。
383
431
  const hash = createHash('sha1').update(buf).digest('hex').slice(0, 16)
384
432
  filePath = path.join(this.dataDir, 'uploads', hash + '-' + path.basename(name))
@@ -399,6 +447,9 @@ export class DocAnchorViewer {
399
447
  } catch (e) {
400
448
  const msg = String(e?.message ?? e)
401
449
  if (msg.startsWith('DOCX_NO_DOCUMENT_XML')) return fail('doc/not-a-docx', '这不是有效的 .docx(缺少 word/document.xml)')
450
+ if (/Invalid PDF|PasswordException|Unable to parse PDF|format error/i.test(msg)) {
451
+ return fail('doc/not-a-pdf', '这不是有效的 PDF,或文件已加密:' + msg)
452
+ }
402
453
  // 压缩炸弹 / 条目过大:给一句用户看得懂的话,而不是把 zlib 内部话端出去
403
454
  // (条目名来自不可信的 ZIP,绝不能原样透出到界面或日志)。
404
455
  if (msg.startsWith('ZIP_ENTRY_TOO_LARGE') || msg.startsWith('ZIP_TOTAL_TOO_LARGE')) {
@@ -433,6 +484,7 @@ export class DocAnchorViewer {
433
484
  if (!docId) return fail('doc/invalid-input', '缺少或非法的 docId')
434
485
  const doc = await this.store.readDoc(docId)
435
486
  if (!doc) return fail('doc/not-found', '文档不存在:' + docId)
487
+ const kind = doc.kind ?? 'docx'
436
488
  return {
437
489
  ok: true,
438
490
  doc: {
@@ -442,8 +494,17 @@ export class DocAnchorViewer {
442
494
  size: doc.size,
443
495
  openedAt: doc.openedAt,
444
496
  stats: doc.stats,
497
+ kind,
445
498
  outline: doc.outline ?? [],
446
499
  marks: doc.marks ?? [],
500
+ // PDF 渲染器需要每页尺寸与段落坐标来摆锚点;docx 没有这些字段。
501
+ // 只传 anchor 相关的轻量元数据,不把全文 paragraph 再传一遍(getDigest 才是干那个的)。
502
+ ...(doc.pageSizes ? { pageSizes: doc.pageSizes } : {}),
503
+ ...(kind === 'pdf' ? {
504
+ paragraphMeta: (doc.paragraphs ?? [])
505
+ .filter((p) => p.rect)
506
+ .map((p) => ({ index: p.index, page: p.page, rect: p.rect, text: p.text })),
507
+ } : {}),
447
508
  },
448
509
  }
449
510
  }
@@ -554,15 +615,17 @@ export class DocAnchorViewer {
554
615
  }
555
616
 
556
617
  /**
557
- * 取原始 docx 字节(base64),供浏览器端 docx-preview 渲染。
618
+ * 取原始文件字节(base64),供浏览器端渲染器使用。
619
+ *
620
+ * 为什么必须是原始字节:docx-preview / PDF.js 都自己解文件格式、
621
+ * 还原版式,给它们「已解析的中间结构」反而还原不出原样。
558
622
  *
559
- * 为什么必须是原始字节:docx-preview 自己解 ZIP、还原字体/编号/分页/表格,
560
- * 给它任何「已解析的中间结构」都还原不出 Word 的样子。
623
+ * docx 与 pdf 都走这个方法;返回的 kind 告诉客户端用哪个渲染器。
561
624
  *
562
625
  * @param {object} request { docId }
563
626
  * @returns {Promise<object>}
564
627
  */
565
- async getDocxBytes(request) {
628
+ async getSourceBytes(request) {
566
629
  const docId = safeDocId(unwrapArg(request).docId)
567
630
  if (!docId) return fail('doc/invalid-input', '缺少或非法的 docId')
568
631
  const doc = await this.store.readDoc(docId)
@@ -570,16 +633,30 @@ export class DocAnchorViewer {
570
633
  if (!doc.path || !fs.existsSync(doc.path)) {
571
634
  return fail('doc/file-missing', '源文件已不在原位置:' + (doc.path || '(未记录)'))
572
635
  }
573
- const maxBytes = Number(this.config.maxDocxMb ?? 30) * 1024 * 1024
636
+ const kind = doc.kind === 'pdf' ? 'pdf' : 'docx'
637
+ const maxMb = kind === 'pdf'
638
+ ? Number(this.config.maxPdfMb ?? 60)
639
+ : Number(this.config.maxDocxMb ?? 30)
574
640
  let buf
575
641
  try { buf = fs.readFileSync(doc.path) } catch (e) {
576
642
  return fail('doc/read-failed', '读取源文件失败:' + String(e?.message ?? e))
577
643
  }
578
- if (buf.length > maxBytes) {
579
- return fail('doc/file-too-large', `文件 ${(buf.length / 1048576).toFixed(1)}MB 超过上限 ${this.config.maxDocxMb}MB`)
644
+ if (buf.length > maxMb * 1024 * 1024) {
645
+ return fail('doc/file-too-large', `文件 ${(buf.length / 1048576).toFixed(1)}MB 超过上限 ${maxMb}MB`)
580
646
  }
581
647
  const hash = createHash('sha1').update(buf).digest('hex')
582
- return { ok: true, docId: doc.id, title: doc.title, size: buf.length, sha1: hash, base64: buf.toString('base64') }
648
+ return {
649
+ ok: true, docId: doc.id, title: doc.title, kind,
650
+ size: buf.length, sha1: hash, base64: buf.toString('base64'),
651
+ }
652
+ }
653
+
654
+ /**
655
+ * 向后兼容的别名:老的 docx 专用端点维持可用,内部走通用方法。
656
+ * @param {object} request
657
+ */
658
+ async getDocxBytes(request) {
659
+ return this.getSourceBytes(request)
583
660
  }
584
661
 
585
662
  /* ---------------- Remote / 工具:标记 ---------------- */
@@ -614,17 +691,34 @@ export class DocAnchorViewer {
614
691
  const paras = doc.paragraphs ?? []
615
692
  const outline = doc.outline ?? []
616
693
 
617
- // 章节边界:大纲条目各自的 index。没有大纲时整篇当一节。
618
- const bounds = outline.length
619
- ? outline.map((o) => o.index)
620
- : [paras[0]?.index ?? 0]
694
+ /**
695
+ * 章节边界:大纲条目各自的 index。没有大纲时整篇当一节。
696
+ *
697
+ * ⚠️ PR review 抓到:PDF 书签可能产生**乱序**或**重复**的段落 index
698
+ * (刚才的坐标/标题匹配就会这样)。若直接拿 outline 的顺序当边界,
699
+ * [10, 0] 会让第一节 end=0 < start=10 → 空节且内容分组全错;
700
+ * 两条书签指向同一段会产生 start===end 的空节。
701
+ *
702
+ * 所以:复制一份按 index 排序、去重后作为**分节边界**,
703
+ * 同时保留每个边界对应的大纲条目(标题/level/norm)。
704
+ * 原 outline 原样返回给客户端做导航,这里不改动它。
705
+ */
706
+ const boundaryList = outline.length
707
+ ? outline
708
+ .map((o, order) => ({ head: o, index: Number(o.index), order }))
709
+ .filter((x) => Number.isFinite(x.index) && x.index >= 0)
710
+ .sort((a, b) => a.index - b.index || a.order - b.order)
711
+ .filter((x, i, arr) => i === 0 || x.index !== arr[i - 1].index)
712
+ : [{ head: null, index: paras[0]?.index ?? 0 }]
713
+
714
+ const bounds = boundaryList.map((x) => x.index)
621
715
 
622
716
  const sections = []
623
717
  let used = 0
624
718
  for (let s = 0; s < bounds.length && sections.length < maxSections; s++) {
625
719
  const start = bounds[s]
626
720
  const end = s + 1 < bounds.length ? bounds[s + 1] : paras.length
627
- const head = outline[s] ?? null
721
+ const head = boundaryList[s].head
628
722
  const body = []
629
723
  let secUsed = 0
630
724
  for (let i = start; i < end; i++) {
@@ -911,6 +1005,7 @@ export const REMOTE_METHODS = [
911
1005
  'getDocByPath',
912
1006
  'getOutline',
913
1007
  'readSection',
1008
+ 'getSourceBytes',
914
1009
  'getDocxBytes',
915
1010
  'getDigest',
916
1011
  'addMark',
@@ -1101,7 +1196,9 @@ export function buildDocTools(ctx, svc) {
1101
1196
 
1102
1197
  disposers.push(tools.register({
1103
1198
  name: 'doc_viewer',
1104
- description: '文档锚点视图(通用):打开 docx 并按 Word 版式在面板里预览,附带可跳转的大纲锚点与自定义标记。'
1199
+ description: '文档锚点视图(通用):打开 .docx 或 .pdf 并按原版式在面板里预览,附带可跳转的大纲锚点与自定义标记。'
1200
+ + '两种格式共用同一套大纲、锚点与标记机制——docx 用 docx-preview 渲染,pdf 用 PDF.js 渲染;'
1201
+ + 'PDF 的大纲优先取书签,没有书签时按字号推断。'
1105
1202
  + '标记是通用的——严重程度与分类都是**自由文本**,不限于招投标;合同审阅、方案评审、病历批注、'
1106
1203
  + '会议纪要都能用同一套机制。'
1107
1204
  + '通读一篇文档的标准走法:open → get_digest(按大纲分节、每节带好锚点的压缩底稿)→ 写出要点/判定 → '
@@ -1113,12 +1210,12 @@ export function buildDocTools(ctx, svc) {
1113
1210
  type: 'string',
1114
1211
  required: true,
1115
1212
  enum: ['open', 'list_docs', 'get_outline', 'get_digest', 'read_section', 'add_mark', 'set_marks', 'list_marks', 'remove_mark', 'remove_doc', 'diagnostics'],
1116
- description: 'open=登记并预览一篇 docx;list_docs=已登记文档;get_outline=取大纲锚点;'
1213
+ description: 'open=登记并预览一篇 docx 或 pdf;list_docs=已登记文档;get_outline=取大纲锚点;'
1117
1214
  + 'get_digest=取用于总结的压缩底稿(按大纲分段、每节截断,带每节的段落序号);'
1118
1215
  + 'read_section=按锚点读原文段落;add_mark=加一条标记;set_marks=批量写标记(总结后一次落锚用这个);'
1119
1216
  + 'list_marks/remove_mark=读写标记;remove_doc=移除登记;diagnostics=诊断',
1120
1217
  },
1121
- filePath: { type: 'string', description: 'open 时必填:docx 的绝对路径' },
1218
+ filePath: { type: 'string', description: 'open 时必填:.docx 或 .pdf 的绝对路径' },
1122
1219
  docId: { type: 'string', description: '除 open / list_docs / diagnostics 外必填:文档 id(由 open 返回)' },
1123
1220
  title: { type: 'string', description: 'open 时可选:显示名,默认取文件名' },
1124
1221
  index: { type: 'number', description: 'read_section 时可选:从哪一段开始(大纲里的 index)' },
@@ -0,0 +1,344 @@
1
+ /**
2
+ * PDF 解析层 · Node 侧
3
+ *
4
+ * 职责:用 PDF.js 把 PDF 抽成与 docx **同构**的结构:
5
+ * · paragraphs: [{ index, text, norm, heading, level, page }]
6
+ * · outline: [{ index, title, text, norm, occurrence, level, page }]
7
+ *
8
+ * 为什么要自己抽、不用浏览器侧的结果:
9
+ * docx 那条路已证明——Host 与浏览器各读各的,锚点必须有一份**稳定、
10
+ * 可序列化**的表示。PDF 更甚:浏览器里只有 canvas 位图 + 可选文本层,
11
+ * 文本层还是按「视觉行」切分的,直接用它做锚点会得到一堆半截句子。
12
+ * Node 侧按 PDF.js 的 getTextContent 聚合,能把散落的 span 拼回完整的行。
13
+ *
14
+ * 大纲来源有两条,按优先级:
15
+ * 1. **PDF 书签**(getOutline)——最可靠,是作者显式标注的结构
16
+ * 2. **字号启发式**——没有书签时,把明显大于正文的行视为标题
17
+ * (真实文档里很多 PDF 没书签,这一步让大纲不至于空着)
18
+ *
19
+ * 零第三方运行时依赖之外只依赖 pdfjs-dist,且只用它做**文本解析**,
20
+ * 不做渲染——渲染在浏览器侧,见 client.js。
21
+ */
22
+
23
+ import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs'
24
+
25
+ /**
26
+ * 归一化:去掉所有空白。与 Host 的 normText / Client 的 normAnchor 必须一致,
27
+ * 否则同一个段落两边算出的键不同,锚点永远对不上。
28
+ * @param {string} s
29
+ * @returns {string}
30
+ */
31
+ export function normText(s) {
32
+ return String(s ?? '').replace(/\s+/g, '').trim()
33
+ }
34
+
35
+ /**
36
+ * PDF.js 的文本项 → 按视觉行聚合。
37
+ *
38
+ * getTextContent 返回的是一个个 span(有时一个汉字一个 span),带 transform
39
+ * 与 height。真正有意义的单位是「视觉行」:y 坐标相近、在同一页上的 span
40
+ * 合并成一段。这样锚点落在整行上,而不是落在半个词上。
41
+ *
42
+ * @param {Array} items getTextContent().items
43
+ * @returns {Array<{text:string, y:number, h:number, x:number}>}
44
+ */
45
+ export function groupLines(items) {
46
+ const lines = []
47
+ let cur = null
48
+ for (const it of items) {
49
+ // ⚠️ PR review 抓到:这里原来写 `!it.str.trim()`,把纯空白 span 也丢了。
50
+ // 但 PDF 里的 " " 常常是**词间分隔符**——"Hello" + " " + "world"
51
+ // 会拼成 "Helloworld",getDigest / readSection 读到的原文就不可读了。
52
+ // 只跳过真正的空串;空白保留在 text 里,归一化(normText)时才去掉。
53
+ if (typeof it.str !== 'string' || it.str.length === 0) continue
54
+ const tf = it.transform || [1, 0, 0, 1, 0, 0]
55
+ // PDF 的 y 轴向上,transform[5] 是基线位置
56
+ const y = Math.round(tf[5] * 10) / 10
57
+ const h = Math.round((it.height || Math.abs(tf[3]) || 12) * 10) / 10
58
+ const x = tf[4]
59
+
60
+ if (!cur || Math.abs(cur.y - y) > Math.max(2, cur.h * 0.45)) {
61
+ cur = { parts: [], y, h, x, right: x }
62
+ lines.push(cur)
63
+ }
64
+ cur.parts.push(it.str)
65
+ cur.h = Math.max(cur.h, h)
66
+ cur.x = Math.min(cur.x, x)
67
+ // 粗略估算宽度:字宽约为字高的 0.55 倍(CJK 更接近 1.0,但取小值
68
+ // 只影响锚点热区宽度,宁可窄一点也不要盖住相邻行)
69
+ cur.right = Math.max(cur.right, x + (it.width || String(it.str).length * h * 0.55))
70
+ }
71
+ return lines.map((l) => ({
72
+ text: l.parts.join('').trim(),
73
+ y: l.y, h: l.h, x: l.x,
74
+ w: Math.max(l.h, l.right - l.x),
75
+ })).filter((l) => l.text.length > 0)
76
+ }
77
+
78
+ /**
79
+ * 把 PDF 书签的 dest 解析成页码 + 目标坐标。
80
+ *
81
+ * dest 有两种形态:已解析的数组 `[ref, {name:'XYZ'}, x, y, z]`,
82
+ * 或未解析的命名目标字符串(要再调 getDestination)。
83
+ *
84
+ * ⚠️ PR review 抓到:以前只取页码就丢了 XYZ 里的 y 坐标。
85
+ * 同一页上有两个同名标题(都叫「Overview」)时,两个书签按标题匹配
86
+ * 都会落到第一个(occurrence 0),第二个书签就跳错了。
87
+ * y 是 PDF 页面坐标(原点左下),和段落 rect.y 同一空间,可直接比距离。
88
+ *
89
+ * @param {object} doc PDFDocumentProxy
90
+ * @param {any} dest
91
+ * @returns {Promise<{pageIdx:number, x:number|null, y:number|null}>}
92
+ */
93
+ async function destInfo(doc, dest) {
94
+ const none = { pageIdx: -1, x: null, y: null }
95
+ try {
96
+ let d = dest
97
+ if (typeof d === 'string') d = await doc.getDestination(d)
98
+ if (!Array.isArray(d) || !d[0] || typeof d[0] !== 'object') return none
99
+ const pageIdx = await doc.getPageIndex(d[0])
100
+ if (pageIdx < 0) return none
101
+ // 只有 XYZ/FitH/FitBH 之类带 y 的才有位置;z(缩放)我们不用
102
+ const y = typeof d[3] === 'number' ? d[3] : null
103
+ const x = typeof d[2] === 'number' ? d[2] : null
104
+ return { pageIdx, x, y }
105
+ } catch {
106
+ return none
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 解析整份 PDF。
112
+ *
113
+ * @param {Buffer|Uint8Array} buf PDF 字节
114
+ * @returns {Promise<{paragraphs:Array, outline:Array, occurrence:Object, stats:object, pageCount:number}>}
115
+ */
116
+ export async function parsePdf(buf) {
117
+ // ⚠️ PDF.js 用 `data.constructor === Uint8Array` 做严格校验,而 Buffer 是
118
+ // Uint8Array 的子类 —— 直接传 Buffer 会被拒。必须显式复制一份。
119
+ // 复制还有个附带好处:调用方之后改动 buffer 不会影响正在解析的文档。
120
+ const data = new Uint8Array(buf.byteLength ?? buf.length)
121
+ data.set(buf)
122
+ const doc = await getDocument({
123
+ data,
124
+ useSystemFonts: true,
125
+ isEvalSupported: false,
126
+ // 不要字体数据:只抽文本,字体字形表对结果没贡献,还会拖慢速度
127
+ fontData: false,
128
+ }).promise
129
+
130
+ try {
131
+ const pageCount = doc.numPages
132
+ const paragraphs = []
133
+ const pageStarts = [] // 每页第一个段落的 index,书签定位要用
134
+ const pageSizes = [] // 每页的 PDF 尺寸(pt),客户端摆锚点要用
135
+
136
+ for (let pn = 0; pn < pageCount; pn++) {
137
+ const page = await doc.getPage(pn + 1)
138
+ const vp = page.getViewport({ scale: 1 })
139
+ pageSizes.push({ width: vp.width, height: vp.height })
140
+ const tc = await page.getTextContent()
141
+ const lines = groupLines(tc.items)
142
+ pageStarts.push(paragraphs.length)
143
+ for (const line of lines) {
144
+ paragraphs.push({
145
+ index: paragraphs.length,
146
+ text: line.text,
147
+ norm: normText(line.text),
148
+ heading: false,
149
+ level: 0,
150
+ fontSize: Math.round(line.h * 10) / 10,
151
+ page: pn + 1, // 1 起页码,给用户看
152
+ // PDF 坐标(pt,原点在左下)。客户端把 canvas 画出来后,
153
+ // 用这几个数把 data-anchor 精确定位到这行文字上面——
154
+ // PDF 渲染结果是 canvas,没有 <p> 可以像 docx 那样直接打锚点。
155
+ rect: {
156
+ x: Math.round(line.x * 10) / 10,
157
+ y: Math.round(line.y * 10) / 10,
158
+ h: Math.round(line.h * 10) / 10,
159
+ w: Math.round(line.w * 10) / 10,
160
+ },
161
+ })
162
+ }
163
+ page.cleanup()
164
+ }
165
+
166
+ // ---- 大纲:优先书签 ----
167
+ let rawOutline = []
168
+ try { rawOutline = (await doc.getOutline()) ?? [] } catch { /* 没书签很正常 */ }
169
+
170
+ /**
171
+ * 书签 → 段落锚点。
172
+ *
173
+ * PR review 抓到两个问题,现在都处理:
174
+ * · 以前只按页 + 标题匹配,书签里的 XYZ 坐标被丢弃 →
175
+ * 同页两个同名标题会都落到第一个(occurrence 0)
176
+ * · 以前只遍历一层子书签,三级以上全丢
177
+ *
178
+ * 坐标与标题怎么配合(实测后的取舍):
179
+ * 单纯「坐标优先」会把「文档预处理后端接口」锚到它下面那行 URL——
180
+ * 因为 XYZ 的 y 常指向标题**上方空白**,不是标题基线本身。
181
+ * 所以反过来:**标题匹配定位置,坐标只用来在同名候选间消歧**:
182
+ * 1. 算该页每段的标题匹配得分(完全相等 > 包含 > 逐字重合)
183
+ * 2. 取最高分的一批候选
184
+ * 3. 若有多个同分候选且有 y 坐标 → 选基线最接近 y 的那个
185
+ * (这正是「同页两个 Overview」的场景)
186
+ * 4. 若完全没有标题匹配(全 0 分)但有坐标 → 用坐标兜底
187
+ * 5. 都没有 → 该页第一段
188
+ *
189
+ * @param {string} title
190
+ * @param {{pageIdx:number, x:number|null, y:number|null}} info
191
+ */
192
+ const findAnchor = (title, info) => {
193
+ const pageIdx = info.pageIdx
194
+ const from = pageIdx >= 0 && pageStarts[pageIdx] !== undefined ? pageStarts[pageIdx] : 0
195
+ const to = pageIdx + 1 < pageStarts.length ? pageStarts[pageIdx + 1] : paragraphs.length
196
+ const hasY = typeof info.y === 'number'
197
+
198
+ const t = normText(title)
199
+ const candidates = []
200
+ for (let i = from; i < to; i++) {
201
+ const p = paragraphs[i]
202
+ if (!p.norm) continue
203
+ let score = 0
204
+ if (p.norm === t) score = 3
205
+ else if (p.norm.includes(t) || t.includes(p.norm)) score = 2
206
+ else {
207
+ let same = 0
208
+ for (const ch of t) if (p.norm.includes(ch)) same++
209
+ score = same / Math.max(1, t.length)
210
+ }
211
+ candidates.push({ index: i, score })
212
+ }
213
+ if (!candidates.length) return from
214
+
215
+ const maxScore = Math.max(...candidates.map((c) => c.score))
216
+ const top = candidates.filter((c) => c.score === maxScore)
217
+
218
+ // 同名多候选 + 有坐标:用 y 距离消歧
219
+ if (top.length > 1 && hasY) {
220
+ let best = top[0].index
221
+ let bestD = Infinity
222
+ for (const c of top) {
223
+ const p = paragraphs[c.index]
224
+ if (!p.rect || typeof p.rect.y !== 'number') continue
225
+ const d = Math.abs(p.rect.y - info.y)
226
+ if (d < bestD) { bestD = d; best = c.index }
227
+ }
228
+ if (bestD < Infinity) return best
229
+ }
230
+
231
+ // 完全没匹配上但有坐标:纯用坐标选行
232
+ if (maxScore === 0 && hasY) {
233
+ let best = from
234
+ let bestD = Infinity
235
+ for (let i = from; i < to; i++) {
236
+ const p = paragraphs[i]
237
+ if (!p.rect || typeof p.rect.y !== 'number') continue
238
+ const d = Math.abs(p.rect.y - info.y)
239
+ if (d < bestD) { bestD = d; best = i }
240
+ }
241
+ if (bestD < Infinity) return best
242
+ }
243
+
244
+ return top[0].index
245
+ }
246
+
247
+ const outline = []
248
+
249
+ /**
250
+ * 递归展开书签树,携带真实层级。
251
+ *
252
+ * @param {Array} nodes PDF.js 的 outline 节点
253
+ * @param {number} level 1 起层级
254
+ * @param {object|null} parentInfo 父书签的 dest(子书签坐标缺失时兜底)
255
+ */
256
+ const emitOutline = async (nodes, level, parentInfo) => {
257
+ for (const node of nodes ?? []) {
258
+ const info = await destInfo(doc, node.dest)
259
+ const effective = info.pageIdx >= 0 ? info : (parentInfo ?? info)
260
+ const idx = findAnchor(node.title, effective)
261
+ const norm = paragraphs[idx]?.norm ?? normText(node.title)
262
+ outline.push(makeOutline(node.title, level, idx, norm, paragraphs, effective.pageIdx + 1 || 1))
263
+ // 递归到任意深度,层级随递归递增
264
+ if (node.items?.length) await emitOutline(node.items, level + 1, effective)
265
+ }
266
+ }
267
+
268
+ if (rawOutline.length) {
269
+ await emitOutline(rawOutline, 1, null)
270
+ } else {
271
+ // ---- 没有书签:字号启发式 ----
272
+ // 取全文正文字号的中位数,明显大于它的行视为标题。
273
+ // 只认 >= 1.25 倍且 >= 12pt,避免把加粗的正文小标题都算进来。
274
+ const sizes = paragraphs.map((p) => p.fontSize).filter((n) => n > 0).sort((a, b) => a - b)
275
+ const median = sizes.length ? sizes[Math.floor(sizes.length / 2)] : 12
276
+ for (const p of paragraphs) {
277
+ if (p.fontSize >= Math.max(12, median * 1.25) && p.norm.length > 0 && p.norm.length <= 80) {
278
+ p.heading = true
279
+ // 粗略分级:字号越大级别越靠前
280
+ const ratio = p.fontSize / median
281
+ p.level = ratio >= 1.8 ? 1 : ratio >= 1.45 ? 2 : 3
282
+ outline.push({
283
+ index: p.index,
284
+ title: p.text.trim(),
285
+ text: p.text,
286
+ norm: p.norm,
287
+ level: p.level,
288
+ page: p.page,
289
+ })
290
+ }
291
+ }
292
+ }
293
+
294
+ // occurrence:与 docx 保持同一算法(全文统计,不只在大纲里数)
295
+ const seen = new Map()
296
+ const occurrence = {}
297
+ for (const p of paragraphs) {
298
+ const k = p.norm || ('\u0000' + p.index)
299
+ const n = seen.get(k) ?? 0
300
+ seen.set(k, n + 1)
301
+ occurrence[p.index] = n
302
+ }
303
+ for (const o of outline) o.occurrence = occurrence[o.index] ?? 0
304
+
305
+ return {
306
+ paragraphs,
307
+ outline,
308
+ occurrence,
309
+ pageCount,
310
+ pageSizes,
311
+ stats: {
312
+ paragraphs: paragraphs.length,
313
+ headings: outline.length,
314
+ chars: paragraphs.reduce((n, p) => n + p.text.length, 0),
315
+ pages: pageCount,
316
+ outlineSource: rawOutline.length ? 'bookmarks' : 'font-size',
317
+ },
318
+ }
319
+ } finally {
320
+ // PDF.js 6 的 PDFDocumentProxy 没有 destroy(),只有 cleanup;
321
+ // 不强依赖,有就调。
322
+ if (typeof doc.cleanup === 'function') await doc.cleanup()
323
+ }
324
+ }
325
+
326
+ /**
327
+ * 构造一条大纲记录。
328
+ * @param {string} title
329
+ * @param {number} level
330
+ * @param {number} index
331
+ * @param {string} norm
332
+ * @param {Array} paragraphs
333
+ * @param {number} page
334
+ */
335
+ function makeOutline(title, level, index, norm, paragraphs, page) {
336
+ return {
337
+ index,
338
+ title: String(title ?? '').trim(),
339
+ text: paragraphs[index]?.text ?? String(title ?? ''),
340
+ norm,
341
+ level,
342
+ page,
343
+ }
344
+ }
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Document anchor view",
4
- "description": "Renders a .docx with Word's own layout and turns its headings and your own marks into jump targets: pick an item on the left and the document scrolls to that spot. Severity and category are free text, so it is not tied to one industry — contract review, proposal review, clinical notes and code review all use the same mechanism. Ask the assistant to call doc_viewer to open a document, take a sectioned digest that already carries anchors, and write the key points back in one call. It only reads your documents and stores its index and marks inside its own data directory."
4
+ "description": "Renders .docx and .pdf in their own layout (docx-preview for Word, PDF.js for PDF) and turns headings and your own marks into jump targets: pick an item on the left and the document scrolls to that spot. Severity and category are free text, so it is not tied to one industry or file format. Ask the assistant to call doc_viewer to open a document, take a sectioned digest that already carries anchors, and write the key points back in one call. It only reads your documents and stores its index and marks inside its own data directory."
5
5
  },
6
6
  "panel": "Document anchor",
7
7
  "open": "Open",
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "文档锚点视图",
4
- "description": "把 .docx 按 Word 版式渲染出来,并把大纲与自定义标记做成可跳转的锚点:点左侧条目就跳到右侧文档的对应位置。标记的严重程度与分类都是自由文本,不限于某个行业——合同审阅、方案评审、病历批注、代码评审都能用。会话里让助手调用 doc_viewer 即可打开文档、取一份带锚点的压缩底稿来通读,再把要点批量写回成锚点。只读你的文档,只在插件自己的数据目录里存索引与标记。"
4
+ "description": "把 .docx 与 .pdf 按原版式渲染出来(docx 用 docx-preview,pdf 用 PDF.js),并把大纲与自定义标记做成可跳转的锚点:点左侧条目就跳到右侧文档的对应位置。标记的严重程度与分类都是自由文本,不限于某个行业或文件格式。会话里让助手调用 doc_viewer 即可打开文档、取一份带锚点的压缩底稿来通读,再把要点批量写回成锚点。只读你的文档,只在插件自己的数据目录里存索引与标记。"
5
5
  },
6
6
  "panel": "文档锚点",
7
7
  "open": "打开",