@wwkit/harness 1.0.46 → 1.0.48

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 (119) hide show
  1. package/package.json +3 -4
  2. package/skills/pea/SKILL.md +14 -4
  3. package/skills/pea/references/tpl-prd/epic.md +7 -2
  4. package/skills/peago/SKILL.md +10 -2
  5. package/skills/peago/references/cleancode/languages/py-ut.md +88 -0
  6. package/skills/peago/references/cleancode/languages/py.md +222 -0
  7. package/skills/{blame-cleancode/references → peago/references/cleancode}/report_template.md +45 -12
  8. package/skills/peago/references/cleancode/rules-ut.md +133 -0
  9. package/skills/peago/references/cleancode/rules.md +477 -0
  10. package/skills/peago/references/cleancode/spec.md +204 -0
  11. package/skills/peago/references/lint/spec.md +160 -0
  12. package/skills/peago/references/test/languages/js.md +74 -0
  13. package/skills/peago/references/test/languages/py.md +68 -0
  14. package/skills/peago/references/test/spec.md +201 -0
  15. package/skills/peago/references/translate/scripts/check-paragraphs.js +71 -0
  16. package/skills/peago/references/translate/scripts/check-structure.js +118 -0
  17. package/skills/peago/references/translate/scripts/chunk-bilingual.js +123 -0
  18. package/skills/peago/references/translate/scripts/chunk-text.js +150 -0
  19. package/skills/peago/references/translate/scripts/clean-text.js +121 -0
  20. package/skills/peago/references/translate/scripts/count-terms.js +54 -0
  21. package/skills/peago/references/translate/scripts/extract-vision.js +267 -0
  22. package/skills/peago/references/translate/scripts/md-to-docx.js +381 -0
  23. package/skills/peago/references/translate/scripts/merge-format.js +110 -0
  24. package/skills/peago/references/translate/scripts/merge-pages.js +202 -0
  25. package/skills/peago/references/translate/scripts/merge-result.js +113 -0
  26. package/skills/peago/references/translate/scripts/verify-chunk.js +200 -0
  27. package/skills/peago/references/translate/spec.md +14 -6
  28. package/skills/better-class/SKILL.md +0 -48
  29. package/skills/better-class/references/planning_spec.md +0 -91
  30. package/skills/better-class/references/report-template.md +0 -65
  31. package/skills/better-class/references/sprint_for_eo.md +0 -83
  32. package/skills/better-class/references/sprint_for_report.md +0 -22
  33. package/skills/better-class/references/subagent-prompt.md +0 -47
  34. package/skills/better-class/references/workflow.md +0 -75
  35. package/skills/better-class/scripts/check-syntax.js +0 -112
  36. package/skills/better-class/scripts/check_input_vars.js +0 -52
  37. package/skills/better-class/scripts/init.js +0 -88
  38. package/skills/better-class/scripts/resolve_run_vars.js +0 -96
  39. package/skills/better-class/scripts/run-tests.js +0 -108
  40. package/skills/better-cleancode/SKILL.md +0 -157
  41. package/skills/better-ut/SKILL.md +0 -236
  42. package/skills/blame-class/SKILL.md +0 -78
  43. package/skills/blame-class/references/report_template.md +0 -98
  44. package/skills/blame-class/references/rules.md +0 -40
  45. package/skills/blame-cleancode/SKILL.md +0 -105
  46. package/skills/blame-cleancode/plan.md +0 -1408
  47. package/skills/blame-cleancode/references/rules.md +0 -630
  48. package/skills/blame-ut/SKILL.md +0 -113
  49. package/skills/blame-ut/references/report_template.md +0 -102
  50. package/skills/blame-ut/references/rules.md +0 -197
  51. package/skills/convert-files/SKILL.md +0 -37
  52. package/skills/convert-files/package.json +0 -11
  53. package/skills/convert-files/references/sprint_for_conversion.md +0 -17
  54. package/skills/convert-files/scripts/check_input_vars.js +0 -54
  55. package/skills/convert-files/scripts/convert.js +0 -331
  56. package/skills/convert-files/scripts/init.js +0 -75
  57. package/skills/convert-files/scripts/resolve_run_vars.js +0 -124
  58. package/skills/create-ppt/SKILL.md +0 -47
  59. package/skills/create-ppt/package.json +0 -9
  60. package/skills/create-ppt/references/ppt-styles.md +0 -287
  61. package/skills/create-ppt/references/sprint_for_ppt_generation.md +0 -81
  62. package/skills/create-ppt/references/sprint_for_source_discovery.md +0 -18
  63. package/skills/create-ppt/scripts/check_input_vars.js +0 -57
  64. package/skills/create-ppt/scripts/find-source-files.js +0 -98
  65. package/skills/create-ppt/scripts/init.js +0 -96
  66. package/skills/create-ppt/scripts/md-to-pptx.js +0 -579
  67. package/skills/create-ppt/scripts/resolve_run_vars.js +0 -91
  68. package/skills/jstest/SKILL.md +0 -561
  69. package/skills/jstest/references/case-create.md +0 -327
  70. package/skills/jstest/references/case-fix.md +0 -273
  71. package/skills/jstest/references/config.md +0 -148
  72. package/skills/jstest/references/coverage-analyze.md +0 -247
  73. package/skills/jstest/references/env-ensure.md +0 -210
  74. package/skills/jstest/references/execute.md +0 -168
  75. package/skills/jstest/references/sample.md +0 -166
  76. package/skills/jstest/references/scoring-rules.md +0 -75
  77. package/skills/jstest/references/suitability-check.md +0 -232
  78. package/skills/jstest/references/test-standards.md +0 -288
  79. package/skills/lint/SKILL.md +0 -440
  80. package/skills/lint/references/ai-fix.md +0 -138
  81. package/skills/lint/references/config-setup.md +0 -103
  82. package/skills/lint/references/config.md +0 -65
  83. package/skills/lint/references/env-ensure.md +0 -89
  84. package/skills/lint/references/language-detect.md +0 -76
  85. package/skills/lint/references/rules-analyze.md +0 -126
  86. package/skills/lint/references/suitability-check.md +0 -82
  87. package/skills/lint/references/tool-fix.md +0 -91
  88. package/skills/peago/references/extract/baseline.md +0 -17
  89. package/skills/peago/references/extract/spec.md +0 -117
  90. package/skills/pytest/SKILL.md +0 -556
  91. package/skills/pytest/references/case-create.md +0 -325
  92. package/skills/pytest/references/case-fix.md +0 -272
  93. package/skills/pytest/references/config.md +0 -145
  94. package/skills/pytest/references/coverage-analyze.md +0 -224
  95. package/skills/pytest/references/env-ensure.md +0 -196
  96. package/skills/pytest/references/execute.md +0 -153
  97. package/skills/pytest/references/sample.md +0 -160
  98. package/skills/pytest/references/scoring-rules.md +0 -57
  99. package/skills/pytest/references/suitability-check.md +0 -221
  100. package/skills/pytest/references/test-standards.md +0 -244
  101. package/skills/query/SKILL.md +0 -72
  102. package/skills/step-extract/SKILL.md +0 -205
  103. /package/skills/{lint/references → peago/references/lint}/languages/js.md +0 -0
  104. /package/skills/{lint/references → peago/references/lint}/languages/py.md +0 -0
  105. /package/skills/{lint/references → peago/references/lint/scripts}/detect-language.js +0 -0
  106. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/Calculator.js +0 -0
  107. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/ConfigManager.js +0 -0
  108. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/FileProcessor.js +0 -0
  109. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/OrderService.js +0 -0
  110. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/TokenGenerator.js +0 -0
  111. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/UserService.js +0 -0
  112. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/index.js +0 -0
  113. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/Calculator.py +0 -0
  114. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/ConfigManager.py +0 -0
  115. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/FileProcessor.py +0 -0
  116. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/OrderService.py +0 -0
  117. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/TokenGenerator.py +0 -0
  118. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/UserService.py +0 -0
  119. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/__init__.py +0 -0
@@ -0,0 +1,267 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * extract-vision.js — 文本提取一体化脚本(ESM):三种输入 → 纯文本
4
+ *
5
+ * 三个独立入口(调用者按输入类型直接选用):
6
+ * 1. extractPdfText(pdfPath, outPath, opts) — PDF 有文本层 → 直接抽取
7
+ * 2. extractImageText(imgPath, outPath, opts) — 图片文件(.png/.jpg/.jpeg)→ 视觉转录
8
+ * 3. extractPdfVision(pdfPath, outPath, opts) — PDF 无文本层(纯图片/扫描件)→ 渲染 + 视觉转录
9
+ * 另有组合入口 extractAny(inputPath, outPath, opts):PDF 自动判定文本层走 1 或 3,图片走 2。
10
+ *
11
+ * 公共辅助(不导出):resolveOpts / countWords / writeLog / transcribeWithRetry / joinPages
12
+ * 导出的细粒度辅助:getPageCount / probeTextLayer / renderPage / transcribePage
13
+ *
14
+ * 转录输出约定:段落重建(段内换行合并、段间空行)、跨行断词合并、
15
+ * 上标脚注编号转 [^N]、页底脚注为 [^N]: 独立段;PDF 页间以 \f 分隔(供下游 merge-pages.js 定位接缝)。
16
+ * 失败页记入清单后继续,整体有终点;提取日志输出到 <out>.extract-log.md。
17
+ *
18
+ * 用法(CLI,走组合入口):
19
+ * node extract-vision.js <pdf-or-image> <output.txt> [--endpoint URL] [--model ID] [--dpi 150] [--timeout 120000]
20
+ * 端点/模型缺省取环境变量 EXTRACT_VL_ENDPOINT / EXTRACT_VL_MODEL,再缺省用内置值
21
+ *
22
+ * 依赖:pdftotext / pdftoppm / pdfinfo(poppler-utils,系统自带);视觉模型端点(OpenAI 兼容)
23
+ */
24
+
25
+ import { execFileSync } from 'child_process';
26
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
27
+ import { join, dirname, basename } from 'path';
28
+
29
+ const DEFAULT_ENDPOINT = 'http://10.88.233.28:31943/v1/chat/completions';
30
+ const DEFAULT_MODEL = 'codemate/Qwen3.6-27B-VL';
31
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg']);
32
+
33
+ // ---------- 导出的细粒度辅助 ----------
34
+
35
+ /** 统计 PDF 页数。 */
36
+ export function getPageCount(pdfPath) {
37
+ const out = execFileSync('pdfinfo', [pdfPath], { encoding: 'utf-8' });
38
+ const m = out.match(/^Pages:\s+(\d+)/m);
39
+ if (!m) throw new Error(`pdfinfo: no Pages line for ${pdfPath}`);
40
+ return Number(m[1]);
41
+ }
42
+
43
+ /**
44
+ * 判定 PDF 是否有文本层:pdftotext 抽取,去除空白与分页符后有效字符数 > 200 判定有。
45
+ * @returns {{ hasTextLayer: boolean, text: string }}
46
+ */
47
+ export function probeTextLayer(pdfPath) {
48
+ let text = '';
49
+ try {
50
+ text = execFileSync('pdftotext', [pdfPath, '-'], { encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 });
51
+ } catch {
52
+ return { hasTextLayer: false, text: '' };
53
+ }
54
+ const effective = text.replace(/[\f\s]/g, '').length;
55
+ return { hasTextLayer: effective > 200, text };
56
+ }
57
+
58
+ /** 渲染 PDF 单页为 PNG,返回文件路径。 */
59
+ export function renderPage(pdfPath, page, outDir, dpi) {
60
+ const prefix = join(outDir, 'page');
61
+ execFileSync('pdftoppm', ['-f', String(page), '-l', String(page), '-r', String(dpi), '-png', pdfPath, prefix]);
62
+ const num = String(page).padStart(2, '0');
63
+ for (const c of [`${prefix}-${num}.png`, `${prefix}-${page}.png`, `${prefix}-0${num}.png`]) {
64
+ if (existsSync(c)) return c;
65
+ }
66
+ throw new Error(`pdftoppm: rendered page ${page} not found in ${outDir}`);
67
+ }
68
+
69
+ /**
70
+ * 视觉转录单页图像(OpenAI 兼容 API,图片 base64)。
71
+ * @returns {Promise<string>} 转录文本
72
+ */
73
+ export async function transcribePage(imgPath, opts) {
74
+ const { endpoint, model, timeout } = resolveOpts(opts);
75
+ const b64 = readFileSync(imgPath).toString('base64');
76
+ const body = JSON.stringify({
77
+ model,
78
+ max_tokens: 8000,
79
+ temperature: 0,
80
+ messages: [{
81
+ role: 'user',
82
+ content: [
83
+ { type: 'image_url', image_url: { url: `data:image/png;base64,${b64}` } },
84
+ {
85
+ type: 'text',
86
+ text: '转录这张图片中的全部文字,忠实原文,不翻译、不摘要、不臆造。'
87
+ + '输出约定:段内换行合并为一段,段间以空行分隔;行尾连字符断词合并(如 arbi- 与 traire 合并为 arbitraire);'
88
+ + '上标脚注编号转为 [^N] 形式;页底脚注条目转为 "[^N]: " 开头的独立段;页眉、页脚与页码原样保留(由下游清洗处理)。'
89
+ + '只输出转录文本,不要任何解释或代码围栏。',
90
+ },
91
+ ],
92
+ }],
93
+ });
94
+ const ctrl = new AbortController();
95
+ const timer = setTimeout(() => ctrl.abort(), timeout);
96
+ try {
97
+ const resp = await fetch(endpoint, {
98
+ method: 'POST',
99
+ headers: { 'Authorization': 'Bearer none', 'Content-Type': 'application/json' },
100
+ body,
101
+ signal: ctrl.signal,
102
+ });
103
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
104
+ const data = await resp.json();
105
+ let content = data.choices?.[0]?.message?.content;
106
+ if (!content) throw new Error('response has no message.content');
107
+ content = content.replace(/^```[a-z]*\n?/m, '').replace(/\n?```\s*$/m, '').trim();
108
+ return content;
109
+ } finally {
110
+ clearTimeout(timer);
111
+ }
112
+ }
113
+
114
+ // ---------- 三个独立入口 ----------
115
+
116
+ /**
117
+ * 入口 1:PDF 文本层 → 纯文本(直接抽取,不经过视觉模型)。
118
+ * @returns {{ mode: 'pdf-text', pages: number, failed: number[], words: number }}
119
+ */
120
+ export function extractPdfText(pdfPath, outputPath, opts = {}) {
121
+ const pages = getPageCount(pdfPath);
122
+ const { hasTextLayer, text } = probeTextLayer(pdfPath);
123
+ if (!hasTextLayer) {
124
+ throw new Error(`extractPdfText: ${basename(pdfPath)} 无文本层(有效字符 ≤200),请改用 extractPdfVision`);
125
+ }
126
+ writeFileSync(outputPath, text, 'utf-8');
127
+ const words = countWords(text);
128
+ writeLog(outputPath, { mode: 'pdf-text', pages, failed: [], words });
129
+ return { mode: 'pdf-text', pages, failed: [], words };
130
+ }
131
+
132
+ /**
133
+ * 入口 2:图片文件(.png/.jpg/.jpeg)→ 纯文本(视觉转录)。
134
+ * @returns {{ mode: 'image', pages: 1, failed: number[], words: number }}
135
+ */
136
+ export async function extractImageText(imgPath, outputPath, opts = {}) {
137
+ const ext = imgPath.slice(imgPath.lastIndexOf('.')).toLowerCase();
138
+ if (!IMAGE_EXTS.has(ext)) {
139
+ throw new Error(`extractImageText: 不支持的图片扩展名 "${ext}"(支持 .png/.jpg/.jpeg)`);
140
+ }
141
+ if (!existsSync(imgPath)) throw new Error(`extractImageText: ${imgPath} 不存在`);
142
+ const { maxRetry } = resolveOpts(opts);
143
+ let text = '';
144
+ let lastErr = null;
145
+ for (let attempt = 1; attempt <= maxRetry; attempt++) {
146
+ try { text = await transcribePage(imgPath, opts); break; }
147
+ catch (e) { lastErr = e; }
148
+ }
149
+ const failed = text ? [] : [1];
150
+ if (!text) throw new Error(`extractImageText: 转录失败(重试 ${maxRetry} 次): ${lastErr?.message}`);
151
+ writeFileSync(outputPath, text + '\n', 'utf-8');
152
+ const words = countWords(text);
153
+ writeLog(outputPath, { mode: 'image', pages: 1, failed, words });
154
+ return { mode: 'image', pages: 1, failed, words };
155
+ }
156
+
157
+ /**
158
+ * 入口 3:PDF 无文本层(纯图片/扫描件)→ 纯文本(逐页渲染 + 视觉转录)。
159
+ * @returns {{ mode: 'pdf-vision', pages: number, failed: number[], words: number }}
160
+ */
161
+ export async function extractPdfVision(pdfPath, outputPath, opts = {}) {
162
+ const { dpi, maxRetry } = resolveOpts(opts);
163
+ const pages = getPageCount(pdfPath);
164
+ const imgDir = join(dirname(outputPath), '.' + basename(outputPath, '.txt') + '-pages');
165
+ mkdirSync(imgDir, { recursive: true });
166
+ const results = new Array(pages).fill('');
167
+ const failed = [];
168
+ const log = [];
169
+ for (let p = 1; p <= pages; p++) {
170
+ let ok = false;
171
+ for (let attempt = 1; attempt <= maxRetry && !ok; attempt++) {
172
+ try {
173
+ const png = renderPage(pdfPath, p, imgDir, dpi);
174
+ results[p - 1] = await transcribePage(png, opts);
175
+ ok = true;
176
+ log.push(`page ${p}: ok (attempt ${attempt}, ${countWords(results[p - 1])} words)`);
177
+ } catch (e) {
178
+ log.push(`page ${p}: attempt ${attempt} failed: ${e.message}`);
179
+ if (attempt === maxRetry) failed.push(p);
180
+ }
181
+ }
182
+ }
183
+ const full = joinPages(results);
184
+ writeFileSync(outputPath, full, 'utf-8');
185
+ const words = countWords(full);
186
+ writeLog(outputPath, { mode: 'pdf-vision', pages, failed, words, log });
187
+ return { mode: 'pdf-vision', pages, failed, words };
188
+ }
189
+
190
+ /**
191
+ * 组合入口:按输入类型自动路由——PDF 判定文本层走入口 1 或 3,图片走入口 2。
192
+ * @returns {{ mode: string, pages: number, failed: number[], words: number }}
193
+ */
194
+ export async function extractAny(inputPath, outputPath, opts = {}) {
195
+ const ext = inputPath.slice(inputPath.lastIndexOf('.')).toLowerCase();
196
+ if (IMAGE_EXTS.has(ext)) return extractImageText(inputPath, outputPath, opts);
197
+ if (ext === '.pdf') {
198
+ const { hasTextLayer } = probeTextLayer(inputPath);
199
+ return hasTextLayer
200
+ ? extractPdfText(inputPath, outputPath, opts)
201
+ : extractPdfVision(inputPath, outputPath, opts);
202
+ }
203
+ throw new Error(`extractAny: 不支持的输入 "${ext}"(支持 .pdf/.png/.jpg/.jpeg)`);
204
+ }
205
+
206
+ // ---------- 公共辅助(不导出) ----------
207
+
208
+ function resolveOpts(opts = {}) {
209
+ return {
210
+ dpi: opts.dpi || 150,
211
+ timeout: opts.timeout || 120000,
212
+ maxRetry: opts.maxRetry ?? 3,
213
+ endpoint: opts.endpoint || process.env.EXTRACT_VL_ENDPOINT || DEFAULT_ENDPOINT,
214
+ model: opts.model || process.env.EXTRACT_VL_MODEL || DEFAULT_MODEL,
215
+ };
216
+ }
217
+
218
+ function countWords(s) {
219
+ return s.trim().split(/\s+/).filter(Boolean).length;
220
+ }
221
+
222
+ /** 页间以 \f 分隔(供下游 merge-pages.js 定位接缝)。 */
223
+ function joinPages(texts) {
224
+ return texts.map(t => t.trim()).join('\f') + '\n';
225
+ }
226
+
227
+ function writeLog(outputPath, summary) {
228
+ const lines = [
229
+ `# 提取日志 — ${basename(outputPath)}`,
230
+ '',
231
+ `| 项 | 值 |`,
232
+ `|---|---|`,
233
+ `| 模式 | ${summary.mode}(pdf-text = 文本层抽取,image = 图片转录,pdf-vision = 扫描件逐页转录)|`,
234
+ `| 页数 | ${summary.pages} |`,
235
+ `| 词数 | ${summary.words} |`,
236
+ `| 失败页 | ${summary.failed.length ? summary.failed.join(', ') : '无'} |`,
237
+ '',
238
+ ...(summary.log?.length ? ['## 逐页记录', '', ...summary.log.map(l => `- ${l}`)] : []),
239
+ '',
240
+ ];
241
+ writeFileSync(outputPath.replace(/\.txt$/, '') + '.extract-log.md', lines.join('\n'), 'utf-8');
242
+ }
243
+
244
+ // ---------- CLI ----------
245
+
246
+ const isMain = !process.env.JEST_WORKER_ID && import.meta.url === `file://${process.argv[1]}`;
247
+
248
+ if (isMain) {
249
+ const argv = process.argv.slice(2);
250
+ if (argv.length < 2) {
251
+ console.error('usage: node extract-vision.js <pdf-or-image> <output.txt> [--endpoint URL] [--model ID] [--dpi N] [--timeout ms]');
252
+ process.exit(1);
253
+ }
254
+ const opts = {};
255
+ for (let i = 2; i < argv.length; i++) {
256
+ if (argv[i] === '--endpoint') opts.endpoint = argv[++i];
257
+ else if (argv[i] === '--model') opts.model = argv[++i];
258
+ else if (argv[i] === '--dpi') opts.dpi = Number(argv[++i]);
259
+ else if (argv[i] === '--timeout') opts.timeout = Number(argv[++i]);
260
+ }
261
+ extractAny(argv[0], argv[1], opts)
262
+ .then(r => {
263
+ console.log(`mode: ${r.mode}, pages: ${r.pages}, words: ${r.words}, failed: ${r.failed.length ? r.failed.join(',') : 0}`);
264
+ process.exit(r.failed.length ? 1 : 0);
265
+ })
266
+ .catch(e => { console.error(e.message); process.exit(1); });
267
+ }
@@ -0,0 +1,381 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * md-to-docx.js — Markdown 转 docx 脚本(ESM)
4
+ *
5
+ * 将 Markdown 内容/文件转换为 Microsoft Word (.docx)。
6
+ * 被 translate(Item 7 docx 生成)引用。
7
+ *
8
+ * 三道转换前/后修正(缺一不可,都针对 Word 打开 docx 报错):
9
+ * 1. sanitizeMarkdownUrls(转换前):把"裸 URL + 全角标点/CJK 紧贴"的畸形转成
10
+ * 标准 Markdown 链接,防止 marked 的 GFM autolink 把全角标点/中文吞入 href
11
+ * 生成非法 URI(Word 打开报超链接错误)。
12
+ * 2. normalizeFootnoteLabels(转换前):translate/translate-format 产物中每章脚注重新编号
13
+ * ([^1]..[^N]),全书 label 大量复用。markdown-docx 用 label 作 key,后章
14
+ * 定义覆盖前章定义,生成大量"孤儿定义 + 重复引用",Word 报成百上千个脚注
15
+ * 错误。本函数按"正文引用 → 之后最近的同 label 定义"配对,把 label 重写为
16
+ * 全局唯一 [^f1]..[^fN];同时给紧贴正文段落的定义行前补空行(否则 marked
17
+ * 的 paragraph tokenizer 会吞掉定义行,footnote 扩展匹配不到)。
18
+ * 3. rebuildFootnotes(转换后兜底):把 document.xml 每个脚注/尾注引用按出现
19
+ * 顺序分配唯一 id(同一旧 id 的重复引用拆分为独立定义,内容复制),重建
20
+ * footnotes.xml/endnotes.xml(保留 Word 规范的 separator id=-1 与
21
+ * continuationSeparator id=0,并保留 XML 声明与完整 xmlns——两者缺失都会让
22
+ * Word 报 xml parsing error),删除无引用的孤儿定义。
23
+ *
24
+ * 用法:node md-to-docx.js <input_dir|input.md> [--ignore-image]
25
+ * node md-to-docx.js --check # 仅检查 markdown-docx 依赖可用性
26
+ * - 目录模式:扫描 <input_dir>/dist/*-fmt.md(translate 的 -tsl-fmt.md)或 <input_dir>/*-fmt.md(translate-format 的 -fmt.md),逐个转同名 .docx
27
+ * - 文件模式:<input.md> → 同名 .docx
28
+ * 短路:输出 docx 已存在且非空 → 打印 skipped(避免重复创建)
29
+ * stdout: docx: <input> → <output> (bytes=N)
30
+ * 退出码:0 成功/短路 / 2 参数或输入错误 / 3 依赖缺失 / 1 转换或写入失败
31
+ */
32
+
33
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, readdirSync } from 'fs';
34
+ import { dirname, join, basename } from 'path';
35
+ import { createRequire } from 'module';
36
+ import JSZip from 'jszip';
37
+
38
+ const require = createRequire(import.meta.url);
39
+
40
+ // markdown-docx 默认选项:启用 GFM(脚注/表格/删除线等扩展语法依赖)
41
+ const DEFAULTS = { gfm: true };
42
+
43
+ /**
44
+ * 惰性加载 markdown-docx(依赖检查用)。
45
+ * @returns {{ default: Function, Packer: object }} markdown-docx 模块
46
+ * @throws {Error} markdown-docx 不可用时抛出,附带安装提示
47
+ */
48
+ function loadMarkdownDocx() {
49
+ try {
50
+ const mod = require('markdown-docx');
51
+ return { default: mod.default || mod, Packer: mod.Packer };
52
+ } catch {
53
+ throw new Error('ERROR: markdown-docx not available. Run: npm install (in skills/translate)');
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 将跨章节复用的脚注 label 归一化为全局唯一(转换前预处理)。
59
+ *
60
+ * 背景:translate/translate-format 产物中每章脚注重新编号([^1]..[^N]),全书 label 大量
61
+ * 复用(实测 141 个定义行只有 14 个唯一 label)。markdown-docx 的 label→id Map
62
+ * 被后章定义覆盖,导致前章脚注内容丢失、生成大量孤儿定义与重复引用,Word 打开
63
+ * 报"成百上千个脚注错误"。
64
+ *
65
+ * 配对规则:正文引用 [^x] 对应其"之后最近"的同 label 定义(translate-format 产物中
66
+ * 脚注定义位于各章末尾,正文引用在前)。定义在前、引用在后的罕见场景回退到
67
+ * "之前最近"的同 label 定义。无法配对的引用保留原样(不报错,按普通文本处理)。
68
+ *
69
+ * @param {string} markdown - 原始 Markdown 文本
70
+ * @returns {string} 归一化后的 Markdown(label 全部形如 [^f1]..[^fN])
71
+ */
72
+ export function normalizeFootnoteLabels(markdown) {
73
+ const lines = markdown.split('\n');
74
+ const defs = new Map(); // label -> [行号]
75
+ const defLines = new Set(); // 定义行号
76
+ let inCode = false;
77
+ lines.forEach((l, i) => {
78
+ if (/^\s*```/.test(l)) {
79
+ inCode = !inCode;
80
+ return;
81
+ }
82
+ if (inCode) return;
83
+ const m = l.match(/^\[\^([^\]\n]+)\]:/);
84
+ if (m) {
85
+ const label = m[1];
86
+ if (!defs.has(label)) defs.set(label, []);
87
+ defs.get(label).push(i);
88
+ defLines.add(i);
89
+ }
90
+ });
91
+
92
+ // 引用位置(跳过定义行与 ``` 代码块)
93
+ const refs = new Map(); // label -> [行号]
94
+ inCode = false;
95
+ lines.forEach((l, i) => {
96
+ if (/^\s*```/.test(l)) {
97
+ inCode = !inCode;
98
+ return;
99
+ }
100
+ if (inCode || defLines.has(i)) return;
101
+ for (const m of l.matchAll(/\[\^([^\]\n]+)\]/g)) {
102
+ const label = m[1];
103
+ if (!refs.has(label)) refs.set(label, []);
104
+ refs.get(label).push(i);
105
+ }
106
+ });
107
+
108
+ // 定义按文档顺序编号(1..N)
109
+ const defOrder = [];
110
+ for (const [label, positions] of defs) for (const li of positions) defOrder.push({ label, li });
111
+ defOrder.sort((a, b) => a.li - b.li);
112
+ const idxOf = new Map(); // `${label}#${行号}` -> 全局序号
113
+ defOrder.forEach((d, i) => idxOf.set(`${d.label}#${d.li}`, i + 1));
114
+
115
+ // 引用 → 定义映射(之后最近优先,回退之前最近)
116
+ const refIdx = new Map(); // `${label}#${行号}` -> 定义序号 | -1(无法配对)
117
+ for (const [label, rlines] of refs) {
118
+ const dlines = defs.get(label) || [];
119
+ for (const li of rlines) {
120
+ const later = dlines.find((d) => d > li);
121
+ if (later !== undefined) {
122
+ refIdx.set(`${label}#${li}`, idxOf.get(`${label}#${later}`));
123
+ } else {
124
+ const earlier = [...dlines].reverse().find((d) => d < li);
125
+ refIdx.set(`${label}#${li}`, earlier !== undefined ? idxOf.get(`${label}#${earlier}`) : -1);
126
+ }
127
+ }
128
+ }
129
+
130
+ return lines
131
+ .map((l, i) => {
132
+ if (defLines.has(i)) {
133
+ const rewritten = l.replace(/^\[\^([^\]\n]+)\]:/, (m, label) => `[^f${idxOf.get(`${label}#${i}`)}]:`);
134
+ // 定义行前补空行(若前一行非空且非文档开头):marked 的 paragraph tokenizer
135
+ // 会把紧贴正文段落(无空行分隔)的定义行吞进段落,footnote 扩展永远匹配不到。
136
+ return (i > 0 && lines[i - 1].trim() !== '' ? '\n' : '') + rewritten;
137
+ }
138
+ return l.replace(/\[\^([^\]\n]+)\]/g, (m, label) => {
139
+ const idx = refIdx.get(`${label}#${i}`);
140
+ return idx && idx > 0 ? `[^f${idx}]` : m;
141
+ });
142
+ })
143
+ .join('\n');
144
+ }
145
+
146
+ /**
147
+ * 解析 footnotes.xml / endnotes.xml,供 rebuildFootnotes 重建时复用。
148
+ *
149
+ * 返回对象字段:
150
+ * - decl:XML 声明(`<?xml ...?>`),重建时必须原样保留
151
+ * - rootOpen:根开标签(含全部 xmlns 声明),重建时必须原样保留
152
+ * - sep / contSep:separator / continuationSeparator 定义(Word 规范 id=-1 / 0)
153
+ * - defs:普通脚注定义 id → 内部 XML 的映射
154
+ * - tag / plural:元素名('footnote'/'footnotes' 或 'endnote'/'endnotes')
155
+ *
156
+ * @param {string} xml - footnotes.xml 或 endnotes.xml 文本
157
+ * @param {string} tag - 'footnote' | 'endnote'
158
+ */
159
+ function parseNotesXml(xml, tag) {
160
+ const plural = `${tag}s`;
161
+ // 必须保留 XML 声明(<?xml ...?>)与根开标签的完整 xmlns 声明:
162
+ // 若丢失,w: 前缀未绑定命名空间,Word 报 "xml parsing error"(行0,列0)。
163
+ const decl = xml.match(/^<\?xml[^>]*\?>/)?.[0] || '';
164
+ const rootOpen = xml.match(new RegExp(`<w:${plural}[^>]*>`))?.[0] || `<w:${plural}>`;
165
+ const sep = xml.match(new RegExp(`<w:${tag} w:type="separator"[^>]*>.*?</w:${tag}>`, 's'))?.[0] || '';
166
+ const contSep = xml.match(
167
+ new RegExp(`<w:${tag} w:type="continuationSeparator"[^>]*>.*?</w:${tag}>`, 's')
168
+ )?.[0] || '';
169
+ const defs = new Map();
170
+ const re = new RegExp(`<w:${tag} w:id="(\\d+)">(.*?)</w:${tag}>`, 'gs');
171
+ let m;
172
+ while ((m = re.exec(xml))) defs.set(parseInt(m[1], 10), m[2]);
173
+ return { decl, rootOpen, sep, contSep, defs, tag, plural };
174
+ }
175
+
176
+ /**
177
+ * 重建 docx 中的脚注/尾注结构(转换后兜底)。
178
+ *
179
+ * 保证每个引用在 document.xml 中有唯一定义且定义全部被引用,彻底消除
180
+ * "重复引用 + 孤儿定义"(Word 严格校验的报错来源);保留 Word 规范的
181
+ * separator(id=-1) / continuationSeparator(id=0) 以及 XML 声明与完整 xmlns
182
+ * 命名空间(缺失则 Word 报 xml parsing error 行0列0);普通脚注按引用出现
183
+ * 顺序分配连续 id(1..M)。同一旧 id 的重复引用拆分为独立定义(内容复制)。
184
+ *
185
+ * @param {Buffer} docxBuffer - 原始 docx buffer
186
+ * @returns {Promise<Buffer>} 重建后的 docx buffer
187
+ */
188
+ export async function rebuildFootnotes(docxBuffer) {
189
+ const zip = await JSZip.loadAsync(docxBuffer);
190
+ const docXml = await zip.file('word/document.xml').async('string');
191
+
192
+ // 引用按在 document.xml 中的出现顺序重编号为 1..M(每个引用一个唯一 id)
193
+ let fnCounter = 0;
194
+ let enCounter = 0;
195
+ const fnUses = []; // { oldId, newId }:脚注引用记录
196
+ const enUses = []; // { oldId, newId }:尾注引用记录
197
+ const newDocXml = docXml
198
+ .replace(/w:footnoteReference w:id="(-?\d+)"/g, (m, id) => {
199
+ fnCounter += 1;
200
+ fnUses.push({ oldId: parseInt(id, 10), newId: fnCounter });
201
+ return `w:footnoteReference w:id="${fnCounter}"`;
202
+ })
203
+ .replace(/w:endnoteReference w:id="(-?\d+)"/g, (m, id) => {
204
+ enCounter += 1;
205
+ enUses.push({ oldId: parseInt(id, 10), newId: enCounter });
206
+ return `w:endnoteReference w:id="${enCounter}"`;
207
+ });
208
+
209
+ // 按引用记录重建 notes XML:声明 + 根开标签 + 两个特殊定义 + 普通定义
210
+ const buildNotes = (notes, uses) => {
211
+ const { decl, rootOpen, sep, contSep, defs, tag, plural } = notes;
212
+ let body = '';
213
+ for (const { oldId, newId } of uses) {
214
+ // 引用无对应定义时用空段落占位(正常流程不会发生,仅为结构兜底)
215
+ const inner = defs.get(oldId) || '<w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>';
216
+ body += `<w:${tag} w:id="${newId}">${inner}</w:${tag}>`;
217
+ }
218
+ return `${decl}${rootOpen}${sep}${contSep}${body}</w:${plural}>`;
219
+ };
220
+
221
+ if (zip.file('word/footnotes.xml')) {
222
+ const fnXml = await zip.file('word/footnotes.xml').async('string');
223
+ zip.file('word/footnotes.xml', buildNotes(parseNotesXml(fnXml, 'footnote'), fnUses));
224
+ }
225
+ if (zip.file('word/endnotes.xml')) {
226
+ const enXml = await zip.file('word/endnotes.xml').async('string');
227
+ zip.file('word/endnotes.xml', buildNotes(parseNotesXml(enXml, 'endnote'), enUses));
228
+ }
229
+ zip.file('word/document.xml', newDocXml);
230
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
231
+ }
232
+
233
+ /**
234
+ * 裸 URL 匹配:https?:// 或 www. 开头,到空白/尖括号/全角标点/CJK 为止。
235
+ * 前缀排除半角 ( 和 ] —— 已是标准链接目标 `[text](url)` 的 URL 不被处理。
236
+ */
237
+ const BARE_URL_RE = /(^|[^(\]])((?:https?:\/\/|www\.)[^\s<()《》“”‘’!?,。;:、\u4e00-\u9fff]+)/g;
238
+
239
+ /** URL 尾部回退的半角标点(与 marked _backpedal 一致)。 */
240
+ const TRAILING_ASCII_PUNCT = /[?!.,:;*_'"~)]+$/;
241
+
242
+ /**
243
+ * 清洗 Markdown 中的畸形裸 URL。
244
+ *
245
+ * 背景:marked 的 GFM autolink 对裸 URL 只回退半角尾部标点,
246
+ * 全角标点()、。,等)与 CJK 字符会被吞入 href,生成的 docx 超链接
247
+ * URI 非法,Word 打开时报错。本函数在转换前把畸形裸 URL 转为标准
248
+ * Markdown 链接 [url](url),URL 后的全角标点/中文保持在链接外。
249
+ *
250
+ * @param {string} markdown - 原始 Markdown 文本
251
+ * @returns {string} 清洗后的 Markdown 文本
252
+ */
253
+ export function sanitizeMarkdownUrls(markdown) {
254
+ return markdown.replace(BARE_URL_RE, (match, prefix, url) => {
255
+ // 回退 URL 尾部半角标点(如 `pdf.` → url=`pdf`,`.` 放回链接外)
256
+ const cleaned = url.replace(TRAILING_ASCII_PUNCT, '');
257
+ if (cleaned.length === 0) return match;
258
+ const rest = url.slice(cleaned.length);
259
+ return `${prefix}[${cleaned}](${cleaned})${rest}`;
260
+ });
261
+ }
262
+
263
+ /**
264
+ * 将 Markdown 内容转换为 docx Buffer。
265
+ * 流程:sanitizeMarkdownUrls(畸形 URL 清洗)→ normalizeFootnoteLabels(脚注
266
+ * label 全局唯一化)→ markdown-docx 转换 → rebuildFootnotes(脚注结构兜底重建)。
267
+ * @param {string} markdown - Markdown 文本内容
268
+ * @param {object} [options] - markdown-docx 转换选项
269
+ * @returns {Promise<Buffer>} docx 文件 buffer
270
+ */
271
+ export async function mdToDocxBuffer(markdown, options = {}) {
272
+ const { default: markdownDocx, Packer } = loadMarkdownDocx();
273
+ const cleaned = normalizeFootnoteLabels(sanitizeMarkdownUrls(markdown));
274
+ const doc = await markdownDocx(cleaned, { ...DEFAULTS, ...options });
275
+ const rawBuf = await Packer.toBuffer(doc);
276
+ return rebuildFootnotes(rawBuf);
277
+ }
278
+
279
+ /**
280
+ * 将 Markdown 文件转换为 docx 文件。
281
+ * @param {string} inputPath - 输入 .md 文件路径
282
+ * @param {string} outputPath - 输出 .docx 文件路径(父目录不存在时自动创建)
283
+ * @param {object} [options] - markdown-docx 转换选项
284
+ * @returns {Promise<{ inputPath: string, outputPath: string, bytes: number }>}
285
+ * @throws {Error} 参数缺失 / 输入文件不存在 / 转换或写入失败
286
+ */
287
+ export async function mdToDocx(inputPath, outputPath, options = {}) {
288
+ if (!inputPath || !outputPath) {
289
+ throw new Error('Usage: node md-to-docx.js <input.md> <output.docx>');
290
+ }
291
+ if (!existsSync(inputPath)) {
292
+ throw new Error(`ERROR: input file not found: ${inputPath}`);
293
+ }
294
+ const markdown = readFileSync(inputPath, 'utf-8');
295
+ const buf = await mdToDocxBuffer(markdown, options);
296
+ mkdirSync(dirname(outputPath), { recursive: true });
297
+ writeFileSync(outputPath, buf);
298
+ return { inputPath, outputPath, bytes: buf.length };
299
+ }
300
+
301
+ // --- CLI entry point (only when run directly, not when imported) ---
302
+
303
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
304
+
305
+ if (isMain) {
306
+ const args = process.argv.slice(2);
307
+
308
+ // --check 模式:仅检查 markdown-docx 依赖可用性
309
+ if (args[0] === '--check') {
310
+ try {
311
+ loadMarkdownDocx();
312
+ console.log('markdown-docx: OK');
313
+ process.exit(0);
314
+ } catch {
315
+ console.error('ERROR: markdown-docx not available. Run: npm install (in skills/translate)');
316
+ process.exit(3);
317
+ }
318
+ }
319
+
320
+ const target = args[0];
321
+ const options = args.includes('--ignore-image') ? { ignoreImage: true } : {};
322
+
323
+ if (!target) {
324
+ console.error('Usage: node md-to-docx.js <input_dir|input.md> [--ignore-image]');
325
+ process.exit(2);
326
+ }
327
+
328
+ // 目录模式:扫描 <distDir>/*-fmt.md 批量转换(覆盖 translate 的 -tsl-fmt.md 与 translate-format 的 -fmt.md)
329
+ if (!target.endsWith('.md')) {
330
+ if (!existsSync(target) || !statSync(target).isDirectory()) {
331
+ console.error(`ERROR: input must be a .md file or directory: ${target}`);
332
+ process.exit(2);
333
+ }
334
+ const distDir = existsSync(join(target, 'dist')) ? join(target, 'dist') : target;
335
+ const mdFiles = readdirSync(distDir)
336
+ .filter((f) => f.endsWith('-fmt.md'))
337
+ .sort();
338
+ if (mdFiles.length === 0) {
339
+ console.error(`ERROR: no *-fmt.md found in ${distDir}`);
340
+ process.exit(2);
341
+ }
342
+ for (const f of mdFiles) {
343
+ const inputPath = join(distDir, f);
344
+ const outputPath = inputPath.replace(/\.md$/, '.docx');
345
+ if (existsSync(outputPath) && statSync(outputPath).size > 0) {
346
+ console.log(`skipped: ${outputPath} (bytes=${statSync(outputPath).size})`);
347
+ continue;
348
+ }
349
+ try {
350
+ const result = await mdToDocx(inputPath, outputPath, options);
351
+ console.log(`docx: ${result.inputPath} → ${result.outputPath} (bytes=${result.bytes})`);
352
+ } catch (e) {
353
+ console.error(e.message);
354
+ process.exit(1);
355
+ }
356
+ }
357
+ process.exit(0);
358
+ }
359
+
360
+ // 单文件模式:输出 = 输入同名 .docx
361
+ const inputPath = target;
362
+ const outputPath = inputPath.replace(/\.md$/, '.docx');
363
+ if (!existsSync(inputPath)) {
364
+ console.error(`ERROR: input file not found: ${inputPath}`);
365
+ process.exit(2);
366
+ }
367
+
368
+ // 短路:输出 docx 已存在且非空 → 跳过(避免重复创建)
369
+ if (existsSync(outputPath) && statSync(outputPath).size > 0) {
370
+ console.log(`skipped: ${outputPath} (bytes=${statSync(outputPath).size})`);
371
+ process.exit(0);
372
+ }
373
+
374
+ try {
375
+ const result = await mdToDocx(inputPath, outputPath, options);
376
+ console.log(`docx: ${result.inputPath} → ${result.outputPath} (bytes=${result.bytes})`);
377
+ } catch (e) {
378
+ console.error(e.message);
379
+ process.exit(1);
380
+ }
381
+ }