dsh-ppt 0.34.0 → 0.35.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.
@@ -0,0 +1,652 @@
1
+ /**
2
+ * deck-export.mjs —— 双向 Office 逆向导出引擎(零新增运行时依赖):
3
+ * 1. `renderDeckWorkbookXlsx(manifest)` —— 生成标准 OOXML `.xlsx` 工作簿(总览页 + 每页图表/表格/KPI 数据工作表,真数值单元格 `<c t="n">`)
4
+ * 2. `renderDeckReportDocx(manifest, lang)` —— 生成标准 OOXML `.docx` Word 正式汇报文档(标题层级、正文段落、原生 `<w:tbl>` 表格与 `[E1..En]` 溯源附录)
5
+ * 3. `renderDeckMemoMarkdown(manifest, lang)` —— 生成高管散文体备忘录 `.memo.md`(Amazon 6-Page 叙事风格)
6
+ * 4. `renderQaPrepMarkdown(manifest, lang)` —— 生成会前高管质询与答辩预案 `.qa-prep.md`(基于真实指标、超预算页、冲突/估算/预测证据自动出题与给答法)
7
+ */
8
+
9
+ import { deflateRawSync } from 'node:zlib'
10
+ import { stripInlineMarkdown } from './deck-layouts.mjs'
11
+ import { computePaceBudget } from './deck-delivery.mjs'
12
+ import { renderEvidenceHandoutSection } from './deck-evidence.mjs'
13
+
14
+ let CRC_TABLE = null
15
+ function crc32(buffer) {
16
+ if (CRC_TABLE === null) {
17
+ CRC_TABLE = new Int32Array(256)
18
+ for (let n = 0; n < 256; n += 1) {
19
+ let c = n
20
+ for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
21
+ CRC_TABLE[n] = c
22
+ }
23
+ }
24
+ let crc = 0xffffffff
25
+ for (let i = 0; i < buffer.length; i += 1) {
26
+ crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
27
+ }
28
+ return (crc ^ 0xffffffff) >>> 0
29
+ }
30
+
31
+ function createZipBuffer(entries) {
32
+ const chunks = []
33
+ const central = []
34
+ let offset = 0
35
+
36
+ for (const entry of entries) {
37
+ const entryOffset = offset
38
+ const name = Buffer.from(entry.name, 'utf8')
39
+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data), 'utf8')
40
+ const crc = crc32(data)
41
+ const compressed = deflateRawSync(data)
42
+ const method = 8
43
+ const nameLen = name.length
44
+
45
+ const localHeader = Buffer.alloc(30)
46
+ localHeader.writeUInt32LE(0x04034b50, 0)
47
+ localHeader.writeUInt16LE(20, 4)
48
+ localHeader.writeUInt16LE(0x0800, 6)
49
+ localHeader.writeUInt16LE(method, 8)
50
+ localHeader.writeUInt16LE(0, 10)
51
+ localHeader.writeUInt16LE(0x21, 12)
52
+ localHeader.writeUInt32LE(crc, 14)
53
+ localHeader.writeUInt32LE(compressed.length, 18)
54
+ localHeader.writeUInt32LE(data.length, 22)
55
+ localHeader.writeUInt16LE(nameLen, 26)
56
+ localHeader.writeUInt16LE(0, 28)
57
+
58
+ chunks.push(localHeader, name, compressed)
59
+ offset += 30 + nameLen + compressed.length
60
+
61
+ const centralHeader = Buffer.alloc(46)
62
+ centralHeader.writeUInt32LE(0x02014b50, 0)
63
+ centralHeader.writeUInt16LE(20, 4)
64
+ centralHeader.writeUInt16LE(20, 6)
65
+ centralHeader.writeUInt16LE(0x0800, 8)
66
+ centralHeader.writeUInt16LE(method, 10)
67
+ centralHeader.writeUInt16LE(0, 12)
68
+ centralHeader.writeUInt16LE(0x21, 14)
69
+ centralHeader.writeUInt32LE(crc, 16)
70
+ centralHeader.writeUInt32LE(compressed.length, 20)
71
+ centralHeader.writeUInt32LE(data.length, 24)
72
+ centralHeader.writeUInt16LE(nameLen, 28)
73
+ centralHeader.writeUInt16LE(0, 30)
74
+ centralHeader.writeUInt16LE(0, 32)
75
+ centralHeader.writeUInt16LE(0, 34)
76
+ centralHeader.writeUInt16LE(0, 36)
77
+ centralHeader.writeUInt32LE(0, 38)
78
+ centralHeader.writeUInt32LE(entryOffset, 42)
79
+ central.push(centralHeader, name)
80
+ }
81
+
82
+ const centralOffset = offset
83
+ const centralSize = central.reduce((sum, part) => sum + part.length, 0)
84
+ const end = Buffer.alloc(22)
85
+ end.writeUInt32LE(0x06054b50, 0)
86
+ end.writeUInt16LE(0, 4)
87
+ end.writeUInt16LE(0, 6)
88
+ end.writeUInt16LE(entries.length, 8)
89
+ end.writeUInt16LE(entries.length, 10)
90
+ end.writeUInt32LE(centralSize, 12)
91
+ end.writeUInt32LE(centralOffset, 16)
92
+ end.writeUInt16LE(0, 20)
93
+
94
+ chunks.push(...central, end)
95
+ return Buffer.concat(chunks)
96
+ }
97
+
98
+ function escapeXml(value) {
99
+ return String(value ?? '')
100
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
101
+ .replace(/&/g, '&amp;')
102
+ .replace(/</g, '&lt;')
103
+ .replace(/>/g, '&gt;')
104
+ .replace(/"/g, '&quot;')
105
+ .replace(/'/g, '&apos;')
106
+ }
107
+
108
+ function cleanText(value, maxLen = 4000) {
109
+ return stripInlineMarkdown(String(value ?? '')).replace(/\s+/g, ' ').trim().slice(0, maxLen)
110
+ }
111
+
112
+ function colIndexToLetters(idx) {
113
+ let n = idx + 1
114
+ let out = ''
115
+ while (n > 0) {
116
+ const rem = (n - 1) % 26
117
+ out = String.fromCharCode(65 + rem) + out
118
+ n = Math.floor((n - 1) / 26)
119
+ }
120
+ return out
121
+ }
122
+
123
+ function sanitizeSheetName(raw, usedNames) {
124
+ let base = cleanText(raw, 28).replace(/[\[\]:*?\/\\']/g, '').trim() || 'Sheet'
125
+ base = base.slice(0, 28)
126
+ let candidate = base
127
+ let seq = 2
128
+ while (usedNames.has(candidate.toLowerCase())) {
129
+ const suffix = `_${seq}`
130
+ candidate = base.slice(0, 31 - suffix.length) + suffix
131
+ seq += 1
132
+ }
133
+ usedNames.add(candidate.toLowerCase())
134
+ return candidate
135
+ }
136
+
137
+ function parseStrictNumeric(val) {
138
+ if (typeof val === 'number' && Number.isFinite(val)) return val
139
+ if (typeof val !== 'string') return null
140
+ const s = val.trim()
141
+ if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(s)) {
142
+ const n = Number(s)
143
+ return Number.isFinite(n) ? n : null
144
+ }
145
+ return null
146
+ }
147
+
148
+ function buildWorksheetXml(rows) {
149
+ const rowXmls = []
150
+ for (let r = 0; r < rows.length; r += 1) {
151
+ const row = Array.isArray(rows[r]) ? rows[r] : [rows[r]]
152
+ const cells = []
153
+ for (let c = 0; c < row.length; c += 1) {
154
+ const ref = `${colIndexToLetters(c)}${r + 1}`
155
+ const raw = row[c]
156
+ const num = r === 0 ? null : parseStrictNumeric(raw)
157
+ const styleAttr = r === 0 ? ' s="1"' : ''
158
+ if (num !== null) {
159
+ cells.push(`<c r="${ref}" t="n"><v>${num}</v></c>`)
160
+ } else {
161
+ const text = escapeXml(cleanText(raw ?? '', 2000))
162
+ cells.push(`<c r="${ref}"${styleAttr} t="inlineStr"><is><t>${text}</t></is></c>`)
163
+ }
164
+ }
165
+ rowXmls.push(`<row r="${r + 1}">${cells.join('')}</row>`)
166
+ }
167
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
168
+ '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
169
+ '<sheetData>' + rowXmls.join('') + '</sheetData>' +
170
+ '</worksheet>'
171
+ }
172
+
173
+ /**
174
+ * 逆向导出标准 `.xlsx` Excel 数据工作簿:
175
+ * - Sheet 1:演示文稿结构总览(页码 / 版式 / 标题 / 核心结论 / 出处);
176
+ * - 后续每个包含图表、表格、KPI、Treemap、Gauge、Pricing 或证据账本的页面均生成独立可运算数据工作表。
177
+ * @param {object} manifest
178
+ * @returns {Buffer}
179
+ */
180
+ export function renderDeckWorkbookXlsx(manifest) {
181
+ const slides = Array.isArray(manifest?.slides) ? manifest.slides : []
182
+ const en = (manifest?.language || 'zh') === 'en'
183
+ const usedNames = new Set()
184
+ const sheets = []
185
+
186
+ const summaryRows = [
187
+ en
188
+ ? ['Slide', 'Layout', 'Kicker', 'Title', 'Takeaway', 'Source']
189
+ : ['页码', '版式', '章节标签', '页面标题', '核心结论', '数据出处'],
190
+ ...slides.map((s, idx) => [
191
+ idx + 1,
192
+ s.variant ? `${s.layout}[${s.variant}]` : (s.layout || 'bullets'),
193
+ cleanText(s.kicker || ''),
194
+ cleanText(s.title || ''),
195
+ cleanText(s.takeaway || ''),
196
+ cleanText(s.source || ''),
197
+ ]),
198
+ ]
199
+ sheets.push({
200
+ name: sanitizeSheetName(en ? 'Summary' : '演示总览', usedNames),
201
+ rows: summaryRows,
202
+ })
203
+
204
+ slides.forEach((s, idx) => {
205
+ const prefix = `P${idx + 1}_${cleanText(s.kicker || s.title || s.layout, 18)}`
206
+ if (s.chart && Array.isArray(s.chart.series) && s.chart.series.length > 0) {
207
+ const cats = Array.isArray(s.chart.categories) ? s.chart.categories : []
208
+ const header = [en ? 'Category' : '类别', ...s.chart.series.map(ser => cleanText(ser.name || 'Series'))]
209
+ const maxLen = Math.max(cats.length, ...s.chart.series.map(ser => (ser.values || []).length))
210
+ const dataRows = []
211
+ for (let i = 0; i < maxLen; i += 1) {
212
+ dataRows.push([
213
+ cleanText(cats[i] ?? `#${i + 1}`),
214
+ ...s.chart.series.map(ser => {
215
+ const v = ser.values?.[i]
216
+ return typeof v === 'number' && Number.isFinite(v) ? v : cleanText(v ?? '')
217
+ }),
218
+ ])
219
+ }
220
+ sheets.push({ name: sanitizeSheetName(prefix, usedNames), rows: [header, ...dataRows] })
221
+ } else if (Array.isArray(s.rows) && s.rows.length >= 2) {
222
+ sheets.push({
223
+ name: sanitizeSheetName(prefix, usedNames),
224
+ rows: s.rows.map(r => (Array.isArray(r) ? r.map(c => cleanText(c)) : [cleanText(r)])),
225
+ })
226
+ } else if (['kpi', 'treemap', 'gauge', 'pricing', 'sankey'].includes(s.layout) && Array.isArray(s.items) && s.items.length > 0) {
227
+ const header = s.layout === 'gauge'
228
+ ? (en ? ['Metric', 'Actual', 'Target', 'Max', 'Unit', 'Delta'] : ['指标名称', '当前值', '目标值', '上限', '单位', '变动'])
229
+ : (en ? ['Tag', 'Title', 'Value', 'Unit', 'Delta', 'Detail'] : ['标签', '名称', '数值', '单位', '变动', '说明'])
230
+ const dataRows = s.items.map((it) => {
231
+ if (s.layout === 'gauge') {
232
+ return [
233
+ cleanText(it.title || it.tag || ''),
234
+ it.value ?? it.actual ?? '',
235
+ it.target ?? it.before ?? '',
236
+ it.max ?? '',
237
+ cleanText(it.unit || ''),
238
+ cleanText(it.delta || ''),
239
+ ]
240
+ }
241
+ return [
242
+ cleanText(it.tag || ''),
243
+ cleanText(it.title || ''),
244
+ it.value ?? '',
245
+ cleanText(it.unit || ''),
246
+ cleanText(it.delta || ''),
247
+ cleanText(it.text || (Array.isArray(it.bullets) ? it.bullets.join('; ') : '')),
248
+ ]
249
+ })
250
+ sheets.push({ name: sanitizeSheetName(prefix, usedNames), rows: [header, ...dataRows] })
251
+ }
252
+ })
253
+
254
+ if (Array.isArray(manifest?.evidence) && manifest.evidence.length > 0) {
255
+ const evRows = [
256
+ en
257
+ ? ['ID', 'Origin', 'Tier', 'Claim', 'Source', 'Date', 'Scope', 'Confidence', 'URL']
258
+ : ['编号', '来源类别', '权威等级', '核验事实', '一手出处', '年份', '口径', '核验状态', '链接'],
259
+ ...manifest.evidence.map((e) => [
260
+ cleanText(e.id),
261
+ cleanText(e.origin || ''),
262
+ e.tier ? `T${e.tier}` : '',
263
+ cleanText(e.claim),
264
+ cleanText(e.source),
265
+ cleanText(e.date || ''),
266
+ cleanText(e.scope || ''),
267
+ cleanText(e.confidence || ''),
268
+ cleanText(e.url || ''),
269
+ ]),
270
+ ]
271
+ sheets.push({
272
+ name: sanitizeSheetName(en ? 'Evidence_Ledger' : '事实溯源台账', usedNames),
273
+ rows: evRows,
274
+ })
275
+ }
276
+
277
+ const sheetOverrides = sheets.map((_, i) =>
278
+ `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
279
+ ).join('')
280
+ const contentTypes = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
281
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
282
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
283
+ '<Default Extension="xml" ContentType="application/xml"/>' +
284
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
285
+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
286
+ sheetOverrides +
287
+ '</Types>'
288
+
289
+ const rootRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
290
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
291
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
292
+ '</Relationships>'
293
+
294
+ const workbookSheetsXml = sheets.map((sh, i) =>
295
+ `<sheet name="${escapeXml(sh.name)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`
296
+ ).join('')
297
+ const workbookXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
298
+ '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
299
+ `<sheets>${workbookSheetsXml}</sheets>` +
300
+ '</workbook>'
301
+
302
+ const wbRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
303
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
304
+ sheets.map((_, i) =>
305
+ `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`
306
+ ).join('') +
307
+ `<Relationship Id="rId${sheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
308
+ '</Relationships>'
309
+
310
+ const stylesXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
311
+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
312
+ '<fonts count="2">' +
313
+ '<font><sz val="11"/><name val="Calibri"/></font>' +
314
+ '<font><b/><sz val="11"/><color rgb="FF0F172A"/><name val="Calibri"/></font>' +
315
+ '</fonts>' +
316
+ '<fills count="3">' +
317
+ '<fill><patternFill patternType="none"/></fill>' +
318
+ '<fill><patternFill patternType="gray125"/></fill>' +
319
+ '<fill><patternFill patternType="solid"><fgColor rgb="FFE2E8F0"/></patternFill></fill>' +
320
+ '</fills>' +
321
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
322
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
323
+ '<cellXfs count="2">' +
324
+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
325
+ '<xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' +
326
+ '</cellXfs>' +
327
+ '</styleSheet>'
328
+
329
+ return createZipBuffer([
330
+ { name: '[Content_Types].xml', data: contentTypes },
331
+ { name: '_rels/.rels', data: rootRels },
332
+ { name: 'xl/workbook.xml', data: workbookXml },
333
+ { name: 'xl/_rels/workbook.xml.rels', data: wbRels },
334
+ { name: 'xl/styles.xml', data: stylesXml },
335
+ ...sheets.map((sh, i) => ({
336
+ name: `xl/worksheets/sheet${i + 1}.xml`,
337
+ data: buildWorksheetXml(sh.rows),
338
+ })),
339
+ ])
340
+ }
341
+
342
+ // ---------------------------------------------------------------------------
343
+ // Reverse Word (.docx) Formal Report Export
344
+ // ---------------------------------------------------------------------------
345
+
346
+ function docxPara(text, style = '', bold = false) {
347
+ const pPr = style ? `<w:pPr><w:pStyle w:val="${escapeXml(style)}"/></w:pPr>` : ''
348
+ const rPr = bold ? '<w:rPr><w:b/></w:rPr>' : ''
349
+ return `<w:p>${pPr}<w:r>${rPr}<w:t xml:space="preserve">${escapeXml(text)}</w:t></w:r></w:p>`
350
+ }
351
+
352
+ function docxTable(rows) {
353
+ if (!Array.isArray(rows) || rows.length === 0) return ''
354
+ const colCount = Math.max(1, ...rows.map(r => (Array.isArray(r) ? r.length : 1)))
355
+ const tblPr = '<w:tblPr><w:tblBorders>' +
356
+ '<w:top w:val="single" w:sz="6" w:color="334155"/>' +
357
+ '<w:bottom w:val="single" w:sz="6" w:color="334155"/>' +
358
+ '<w:insideH w:val="single" w:sz="4" w:color="CBD5E1"/>' +
359
+ '<w:left w:val="none"/><w:right w:val="none"/><w:insideV w:val="none"/>' +
360
+ '</w:tblBorders></w:tblPr>'
361
+ const trs = rows.map((row, rIdx) => {
362
+ const arr = Array.isArray(row) ? row : [row]
363
+ const cells = Array.from({ length: colCount }, (_, ci) => {
364
+ const txt = cleanText(arr[ci] ?? '')
365
+ const shd = rIdx === 0 ? '<w:tcPr><w:shd w:val="clear" w:fill="EEF2F7"/></w:tcPr>' : ''
366
+ return `<w:tc>${shd}${docxPara(txt, '', rIdx === 0)}</w:tc>`
367
+ }).join('')
368
+ return `<w:tr>${cells}</w:tr>`
369
+ }).join('')
370
+ return `<w:tbl>${tblPr}${trs}</w:tbl>`
371
+ }
372
+
373
+ /**
374
+ * 逆向导出标准 `.docx` Word 正式汇报文档(支持 Word 直接编辑与二次导入闭环)。
375
+ * @param {object} manifest
376
+ * @param {string} [language]
377
+ * @returns {Buffer}
378
+ */
379
+ export function renderDeckReportDocx(manifest, language) {
380
+ const en = (language || manifest?.language || 'zh') === 'en'
381
+ const slides = Array.isArray(manifest?.slides) ? manifest.slides : []
382
+ const title = cleanText(manifest?.title || (en ? 'Executive Report' : '汇报文档'))
383
+ const cover = slides.find(s => s.layout === 'cover')
384
+ const bodyBlocks = []
385
+
386
+ bodyBlocks.push(docxPara(title, 'Title'))
387
+ if (cover?.subtitle) bodyBlocks.push(docxPara(cleanText(cover.subtitle), 'Subtitle'))
388
+ bodyBlocks.push(docxPara(
389
+ en
390
+ ? `Theme: ${manifest?.theme || 'consulting'} · Slides: ${slides.length} · Generated by dsh-ppt`
391
+ : `主题风格:${manifest?.theme || 'consulting'} | 共 ${slides.length} 页 | 由 dsh-ppt 自动转为正式 Word 文档`,
392
+ ))
393
+
394
+ let secIdx = 0
395
+ for (const s of slides) {
396
+ if (s.layout === 'cover') continue
397
+ secIdx += 1
398
+ const headingStyle = s.layout === 'section' ? 'Heading1' : 'Heading2'
399
+ const secTitle = cleanText(s.title || (en ? `Section ${secIdx}` : `第 ${secIdx} 节`))
400
+ bodyBlocks.push(docxPara(`${secIdx}. ${secTitle}`, headingStyle))
401
+
402
+ if (s.subtitle) bodyBlocks.push(docxPara(cleanText(s.subtitle)))
403
+ if (s.text) bodyBlocks.push(docxPara(cleanText(s.text)))
404
+ if (s.formula) bodyBlocks.push(docxPara(`$${String(s.formula).trim()}$`))
405
+
406
+ if (Array.isArray(s.bullets) && s.bullets.length > 0) {
407
+ for (const b of s.bullets) {
408
+ const line = cleanText(b)
409
+ if (line) bodyBlocks.push(docxPara(`• ${line}`, 'ListParagraph'))
410
+ }
411
+ }
412
+
413
+ if (Array.isArray(s.items) && s.items.length > 0) {
414
+ if (['kpi', 'gauge', 'treemap', 'pricing', 'sankey'].includes(s.layout)) {
415
+ const tblRows = [
416
+ en ? ['Tag', 'Item', 'Value', 'Delta / Note'] : ['标签', '核心项', '关键数值', '变化 / 说明'],
417
+ ...s.items.map(it => [
418
+ cleanText(it.tag || ''),
419
+ cleanText(it.title || ''),
420
+ cleanText(`${it.value ?? ''}${it.unit ?? ''}`),
421
+ cleanText([it.delta, it.text, ...(Array.isArray(it.bullets) ? it.bullets : [])].filter(Boolean).join(';')),
422
+ ]),
423
+ ]
424
+ bodyBlocks.push(docxTable(tblRows))
425
+ } else {
426
+ for (const it of s.items) {
427
+ const head = [cleanText(it.tag), cleanText(it.title)].filter(Boolean).join(' · ')
428
+ const body = [cleanText(it.value), cleanText(it.delta), cleanText(it.text), ...(Array.isArray(it.bullets) ? it.bullets.map(cleanText) : [])].filter(Boolean).join(' — ')
429
+ const line = [head, body].filter(Boolean).join(':')
430
+ if (line) bodyBlocks.push(docxPara(`• ${line}`, 'ListParagraph'))
431
+ }
432
+ }
433
+ }
434
+
435
+ if (Array.isArray(s.rows) && s.rows.length >= 2) bodyBlocks.push(docxTable(s.rows))
436
+
437
+ if (s.chart && Array.isArray(s.chart.series) && s.chart.series.length > 0) {
438
+ const cats = Array.isArray(s.chart.categories) ? s.chart.categories : []
439
+ const header = [en ? 'Category' : '类别', ...s.chart.series.map(ser => cleanText(ser.name || 'Series'))]
440
+ const rows = [header]
441
+ const maxLen = Math.max(cats.length, ...s.chart.series.map(ser => (ser.values || []).length))
442
+ for (let i = 0; i < maxLen; i += 1) {
443
+ rows.push([cleanText(cats[i] ?? `#${i + 1}`), ...s.chart.series.map(ser => String(ser.values?.[i] ?? ''))])
444
+ }
445
+ bodyBlocks.push(docxTable(rows))
446
+ }
447
+
448
+ if (s.takeaway) bodyBlocks.push(docxPara((en ? 'Key Takeaway: ' : '核心结论:') + cleanText(s.takeaway), '', true))
449
+ if (s.source) bodyBlocks.push(docxPara((en ? 'Source: ' : '数据来源:') + cleanText(s.source)))
450
+ }
451
+
452
+ if (Array.isArray(manifest?.evidence) && manifest.evidence.length > 0) {
453
+ bodyBlocks.push(docxPara(en ? 'Verified Evidence Ledger & Sources' : '事实核验与证据溯源清单', 'Heading1'))
454
+ const evTbl = [
455
+ en ? ['ID', 'Origin', 'Verified Claim', 'Primary Source & Date', 'Status'] : ['编号', '来源类别', '核验事实', '一手出处与年份', '状态'],
456
+ ...manifest.evidence.map(e => [
457
+ cleanText(e.id),
458
+ cleanText(e.origin === 'local-file' ? (en ? 'Internal' : '内部资料') : (e.tier ? `T${e.tier}` : (en ? 'External' : '权威外源'))),
459
+ cleanText(e.claim),
460
+ cleanText(`${e.source}${e.date ? ` (${e.date})` : ''}`),
461
+ cleanText(e.confidence || 'verified'),
462
+ ]),
463
+ ]
464
+ bodyBlocks.push(docxTable(evTbl))
465
+ }
466
+
467
+ const documentXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
468
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
469
+ '<w:body>' + bodyBlocks.join('') +
470
+ '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>' +
471
+ '</w:body></w:document>'
472
+
473
+ const stylesXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
474
+ '<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
475
+ '<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:b/><w:sz w:val="44"/></w:rPr></w:style>' +
476
+ '<w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:rPr><w:color w:val="475569"/><w:sz w:val="26"/></w:rPr></w:style>' +
477
+ '<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:color w:val="0F172A"/><w:sz w:val="32"/></w:rPr></w:style>' +
478
+ '<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:rPr><w:b/><w:color w:val="1E3A8A"/><w:sz w:val="26"/></w:rPr></w:style>' +
479
+ '<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:pPr><w:ind w:left="360"/></w:pPr></w:style>' +
480
+ '</w:styles>'
481
+
482
+ const contentTypes = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
483
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
484
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
485
+ '<Default Extension="xml" ContentType="application/xml"/>' +
486
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
487
+ '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
488
+ '</Types>'
489
+
490
+ const rootRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
491
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
492
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
493
+ '</Relationships>'
494
+
495
+ const docRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
496
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
497
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
498
+ '</Relationships>'
499
+
500
+ return createZipBuffer([
501
+ { name: '[Content_Types].xml', data: contentTypes },
502
+ { name: '_rels/.rels', data: rootRels },
503
+ { name: 'word/document.xml', data: documentXml },
504
+ { name: 'word/styles.xml', data: stylesXml },
505
+ { name: 'word/_rels/document.xml.rels', data: docRels },
506
+ ])
507
+ }
508
+
509
+ /**
510
+ * 导出高管散文体阅读备忘录(`.memo.md`,Amazon Narrative Memo 风格)。
511
+ */
512
+ export function renderDeckMemoMarkdown(manifest, language) {
513
+ const en = (language || manifest?.language || 'zh') === 'en'
514
+ const slides = Array.isArray(manifest?.slides) ? manifest.slides : []
515
+ const title = cleanText(manifest?.title || (en ? 'Executive Memo' : '高管阅读备忘录'))
516
+ const cover = slides.find(s => s.layout === 'cover')
517
+ const takeaways = slides.map(s => cleanText(s.takeaway)).filter(Boolean)
518
+
519
+ const lines = [
520
+ `# ${title} — ${en ? 'Executive Narrative Memo' : '高管会前阅读备忘录'}`,
521
+ '',
522
+ `> **${en ? 'Core Thesis' : '核心论点'}**:${cleanText(cover?.subtitle || takeaways[0] || title)}`,
523
+ '',
524
+ `## ${en ? '1. Executive Summary' : '一、核心结论摘要'}`,
525
+ '',
526
+ ...(takeaways.length > 0
527
+ ? takeaways.slice(0, 6).map((tk, i) => `${i + 1}. ${tk}`)
528
+ : slides.filter(s => !['cover', 'closing', 'section', 'agenda'].includes(s.layout)).slice(0, 6).map((s, i) => `${i + 1}. **${cleanText(s.title)}**`)),
529
+ '',
530
+ `## ${en ? '2. Detailed Argumentation' : '二、分章论证与关键事实'}`,
531
+ '',
532
+ ]
533
+
534
+ let part = 0
535
+ for (const s of slides) {
536
+ if (['cover', 'agenda'].includes(s.layout)) continue
537
+ part += 1
538
+ lines.push(`### ${part}. ${cleanText(s.title)}`)
539
+ const paraParts = []
540
+ if (s.subtitle) paraParts.push(cleanText(s.subtitle))
541
+ if (s.text) paraParts.push(cleanText(s.text))
542
+ if (Array.isArray(s.bullets) && s.bullets.length) paraParts.push(s.bullets.map(cleanText).join(en ? ' ' : ';'))
543
+ if (Array.isArray(s.items) && s.items.length) {
544
+ paraParts.push(s.items.map(it => {
545
+ const val = it.value !== undefined && it.value !== '' ? `(${cleanText(it.value)}${cleanText(it.unit || '')}${it.delta ? ',' + cleanText(it.delta) : ''})` : ''
546
+ return `${cleanText(it.title || it.tag || '')}${val}${it.text ? ':' + cleanText(it.text) : ''}`
547
+ }).join(en ? '; ' : ';'))
548
+ }
549
+ if (paraParts.length) {
550
+ lines.push('')
551
+ lines.push(paraParts.join(en ? ' ' : '。') + (en ? '' : '。'))
552
+ }
553
+ if (s.takeaway) {
554
+ lines.push('')
555
+ lines.push(`**${en ? 'Implication' : '决策含义'}**:${cleanText(s.takeaway)}`)
556
+ }
557
+ if (s.source) lines.push(`_${en ? 'Source' : '依据'}:${cleanText(s.source)}_`)
558
+ lines.push('')
559
+ }
560
+
561
+ const evSec = renderEvidenceHandoutSection(manifest, en ? 'en' : 'zh')
562
+ if (evSec) lines.push(evSec)
563
+ return lines.join('\n')
564
+ }
565
+
566
+ /**
567
+ * 确定性会前高管质询与答辩预案(`.qa-prep.md`)。
568
+ */
569
+ export function renderQaPrepMarkdown(manifest, language) {
570
+ const en = (language || manifest?.language || 'zh') === 'en'
571
+ const slides = Array.isArray(manifest?.slides) ? manifest.slides : []
572
+ const ledger = Array.isArray(manifest?.evidence) ? manifest.evidence : []
573
+ const pace = computePaceBudget(manifest)
574
+ const title = cleanText(manifest?.title || (en ? 'Presentation' : '汇报材料'))
575
+
576
+ const kpiClaims = []
577
+ slides.forEach((s, idx) => {
578
+ if (s.layout === 'kpi' && Array.isArray(s.items)) {
579
+ for (const it of s.items.slice(0, 4)) {
580
+ if (it.value) kpiClaims.push({ slide: idx + 1, label: cleanText(it.title || it.tag || ''), value: `${cleanText(it.value)}${cleanText(it.unit || '')}`, delta: cleanText(it.delta || ''), source: cleanText(s.source || '') })
581
+ }
582
+ }
583
+ })
584
+
585
+ const riskyEvidence = ledger.filter(e =>
586
+ e.confidence === 'conflicting' ||
587
+ e.confidence === 'estimated' ||
588
+ e.confidence === 'unverified' ||
589
+ e.claimType === 'forecast' ||
590
+ e.tier === 3
591
+ )
592
+
593
+ const lines = [
594
+ `# ${title} — ${en ? 'Executive Q&A & Tough-Question Prep Sheet' : '会前高管质询与答辩预案(Q&A Prep)'}`,
595
+ '',
596
+ `- **${en ? 'Total Slides & Pace' : '页数与演讲配速'}**:${slides.length} ${en ? 'slides' : '页'} · ${en ? 'Est.' : '预计'} ${pace.estimatedMinutes} ${en ? 'min' : '分钟'}`,
597
+ `- **${en ? 'High-Scrutiny Evidence Items' : '高风险/待解释证据条目'}**:${riskyEvidence.length} ${en ? 'item(s)' : '项'}`,
598
+ `- **${en ? 'Over-Budget Slides' : '节奏超预算预警页'}**:${pace.overBudgetSlides.length > 0 ? pace.overBudgetSlides.map(n => `P${n}`).join(', ') : (en ? 'None' : '无')}`,
599
+ '',
600
+ `## ${en ? '1. Data & Evidence Challenge Defense' : '一、数据口径与事实证据质询预案'}`,
601
+ '',
602
+ ]
603
+
604
+ if (riskyEvidence.length > 0) {
605
+ riskyEvidence.forEach((e, idx) => {
606
+ const reason = e.confidence === 'conflicting'
607
+ ? (en ? 'Conflicting agency estimates' : '不同权威机构口径存在分歧')
608
+ : e.claimType === 'forecast'
609
+ ? (en ? 'Forward-looking forecast assumption' : '属于前瞻预测值而非历史实绩')
610
+ : e.tier === 3
611
+ ? (en ? 'Tier 3 / secondary relay source' : '属于三级/媒体转引信源')
612
+ : (en ? `Status: ${e.confidence}` : `核验状态:${e.confidence}`)
613
+ lines.push(`### Q${idx + 1} [${e.id}] · ${reason}`)
614
+ lines.push(`- **${en ? 'Likely Executive Pushback' : '高管可能追问'}**:${en ? `"How solid is '${cleanText(e.claim)}' from ${cleanText(e.source)}? What if downside materializes?"` : `“关于「${cleanText(e.claim)}」(出处:${cleanText(e.source)}),这个口径够扎实吗?如果按保守口径算结论还成立吗?”`}`)
615
+ lines.push(`- **${en ? 'Recommended Defense' : '建议答复口径'}**:${en ? `State period/scope (${[e.date, e.scope].filter(Boolean).join(' · ') || 'specify scope'}). ${e.note || 'Frame as a bounded range and highlight downside resilience.'}` : `先明确时间与统计口径(${[e.date, e.scope].filter(Boolean).join(' · ') || '补充说明口径'}),${e.note || '用保守/中性/乐观三档区间回应,并强调在保守下限下核心决策依然成立。'}`}`)
616
+ lines.push('')
617
+ })
618
+ } else {
619
+ lines.push(en
620
+ ? '- All indexed evidence items are verified (internal files or Tier 1/2 sources). Keep raw dates and scopes handy in speaker notes (`P` Presenter Console).'
621
+ : '- 当前证据账本条目均已标为已核验(含内部原始文件或 T1/T2 权威外源);答辩时可直接打开 HTML 按 `P` 键在提词台备查每页原文链接与年份口径。')
622
+ lines.push('')
623
+ }
624
+
625
+ lines.push(`## ${en ? '2. Headline KPI & ROI Interrogation' : '二、核心 KPI 与投入产出(ROI)追问准备'}`)
626
+ lines.push('')
627
+ if (kpiClaims.length > 0) {
628
+ kpiClaims.slice(0, 5).forEach((k) => {
629
+ lines.push(`- **P${k.slide} · ${k.label} = ${k.value}${k.delta ? ` (${k.delta})` : ''}**:${en ? `Be ready to break down denominator, baseline period, and source (${k.source || 'internal ledger'}).` : `提前准备该指标的分母定义、对比基期与拆分结构(依据:${k.source || '见演讲备注'})。`}`)
630
+ })
631
+ } else {
632
+ lines.push(en
633
+ ? '- Prepare 2–3 quantitative guardrails (investment cap, breakeven timeline, primary downside risk).'
634
+ : '- 建议提前备好 3 组兜底数字:总投入预算上限、盈亏平衡/里程碑节点、最大下行风险的止损阈值。')
635
+ }
636
+ lines.push('')
637
+
638
+ lines.push(`## ${en ? '3. Pacing & Delivery Risk Checks' : '三、演讲节奏与删减预案'}`)
639
+ lines.push('')
640
+ if (pace.overBudgetSlides.length > 0) {
641
+ lines.push(en
642
+ ? `- Slides **${pace.overBudgetSlides.map(n => `P${n}`).join(', ')}** exceed time budget. If cut short, speak only Action Title + Takeaway.`
643
+ : `- 第 **${pace.overBudgetSlides.map(n => `P${n}`).join('、')}** 页信息密度偏高/超预算;若现场时间被压缩,直接口述该页顶部 Action Title 与底部 Takeaway,细节留给问答环节。`)
644
+ } else {
645
+ lines.push(en
646
+ ? `- Pacing is balanced (~${pace.estimatedMinutes} min across ${slides.length} slides). Use \`ppt_edit({ remixPreset: "exec-5min" })\` for a 5-min executive flash brief.`
647
+ : `- 全篇节奏均衡(共 ${slides.length} 页,预计 ${pace.estimatedMinutes} 分钟);若临时被压缩成 5 分钟电梯汇报,可一键调用 \`ppt_edit({ remixPreset: "exec-5min" })\` 生成无损精简版。`)
648
+ }
649
+ lines.push('')
650
+
651
+ return lines.join('\n')
652
+ }