dsh-ppt 0.21.0 → 0.22.1

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 (49) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.en.md +18 -17
  3. package/README.md +16 -15
  4. package/docs/COACHING.md +14 -13
  5. package/docs/DATA.md +8 -8
  6. package/docs/REFERENCE.en.md +17 -19
  7. package/docs/REFERENCE.zh.md +16 -18
  8. package/docs/USAGE.en.md +107 -60
  9. package/docs/USAGE.md +115 -84
  10. package/docs/VALIDATION.md +2 -0
  11. package/docs/VISUAL.md +27 -20
  12. package/docs/WORKBENCH.md +17 -6
  13. package/docs/assets/intro/screen-en.webp +0 -0
  14. package/docs/assets/intro/screen-zh.webp +0 -0
  15. package/lib/client.js +941 -132
  16. package/lib/coaching.d.ts +1 -1
  17. package/lib/coaching.js +25 -12
  18. package/lib/config.d.ts +2 -0
  19. package/lib/config.js +30 -2
  20. package/lib/execution.d.ts +2 -1
  21. package/lib/execution.js +21 -1
  22. package/lib/tools.d.ts +1 -1
  23. package/lib/tools.js +151 -24
  24. package/lib/types.d.ts +108 -8
  25. package/lib/visual.d.ts +3 -1
  26. package/lib/visual.js +40 -13
  27. package/lib/workbench-language.js +45 -9
  28. package/lib/workbench.d.ts +5 -0
  29. package/lib/workbench.js +485 -9
  30. package/package.json +9 -4
  31. package/skills/dsh-ppt/SKILL.md +56 -54
  32. package/skills/dsh-ppt/package.json +1 -1
  33. package/skills/dsh-ppt/references/advanced.md +122 -41
  34. package/skills/dsh-ppt/references/copywriting.md +63 -41
  35. package/skills/dsh-ppt/references/data.md +83 -36
  36. package/skills/dsh-ppt/references/syntax.md +157 -28
  37. package/skills/dsh-ppt/references/themes.md +90 -41
  38. package/skills/dsh-ppt/references/troubleshooting.md +21 -16
  39. package/skills/dsh-ppt/scripts/build-deck.mjs +67 -28
  40. package/skills/dsh-ppt/scripts/deck-absorb.mjs +1029 -0
  41. package/skills/dsh-ppt/scripts/deck-advanced.mjs +406 -99
  42. package/skills/dsh-ppt/scripts/deck-core.mjs +568 -717
  43. package/skills/dsh-ppt/scripts/deck-data-view.mjs +30 -11
  44. package/skills/dsh-ppt/scripts/deck-data.mjs +35 -5
  45. package/skills/dsh-ppt/scripts/deck-director.mjs +1717 -0
  46. package/skills/dsh-ppt/scripts/deck-layouts.mjs +4557 -0
  47. package/skills/dsh-ppt/scripts/deck-media.mjs +1408 -86
  48. package/skills/dsh-ppt/scripts/deck-themes.mjs +1503 -0
  49. package/skills/dsh-ppt/scripts/deck-visual.mjs +133 -31
@@ -0,0 +1,1029 @@
1
+ /**
2
+ * deck-absorb.mjs —— 外部参考 .pptx 母版、主题、字体、Logo 与骨架版式只读提取与审美净化器。
3
+ *
4
+ * Phase 3 深度增强:
5
+ * - 解析 OOXML <a:schemeClr> / <a:srgbClr> 子变换(lumMod, lumOff, tint, shade, satMod, satOff)
6
+ * - 提取母版骨架特征 extractedSkeleton: { cornerStyle: 'sharp'|'rounded'|'soft', hasTopBanner, hasSideSpine, masterShapeCount }
7
+ * - 推荐 6 种母版骨架 chromeStyle (recommendedChrome)
8
+ * - 逐页推理版式骨架 slideSkeleton: Array<{ slideNumber, inferredLayout, variant?, titleSample? }>
9
+ *
10
+ * 严格约束:
11
+ * - 仅使用 Node 内置模块 + 动态加载的 @office-kit/pptx
12
+ * - 绝不直接导入 saxes 或 fflate,保证技能目录独立复制到任意 Agent 环境均可运行
13
+ * - 提取出的原始配色与字体统一经由 deck-themes.mjs 的 sanitizeAbsorbedTheme 进行 WCAG 对比度与高饱和底色净化
14
+ */
15
+
16
+ import { lstatSync, readFileSync } from 'node:fs'
17
+ import { resolve } from 'node:path'
18
+ import { inflateSync } from 'node:zlib'
19
+ import { sanitizeAbsorbedTheme, normalizeHex, hexToHsl } from './deck-themes.mjs'
20
+
21
+ const MAX_PPTX_BYTES = 64 * 1024 * 1024
22
+ const MAX_LOGO_BYTES = 2 * 1024 * 1024
23
+ const EMU_PER_INCH = 914400
24
+
25
+ const OFFICE_DEFAULT_ACCENTS = new Set(['#4F81BD', '#4472C4', '#156082', '#0F9ED5'])
26
+
27
+ /** 6 Chrome Style IDs matching deck-themes.mjs / deck-layouts.mjs */
28
+ export const CHROME_STYLE_IDS = Object.freeze([
29
+ 'consulting-classic',
30
+ 'keynote-spatial',
31
+ 'editorial-folio',
32
+ 'saas-bento',
33
+ 'academic-minimal',
34
+ 'gov-ceremonial',
35
+ ])
36
+
37
+ const SCHEME_PROP_MAP = {
38
+ dk1: 'dark1',
39
+ lt1: 'light1',
40
+ dk2: 'dark2',
41
+ lt2: 'light2',
42
+ bg1: 'light1',
43
+ tx1: 'dark1',
44
+ bg2: 'light2',
45
+ tx2: 'dark2',
46
+ dark1: 'dark1',
47
+ light1: 'light1',
48
+ dark2: 'dark2',
49
+ light2: 'light2',
50
+ accent1: 'accent1',
51
+ accent2: 'accent2',
52
+ accent3: 'accent3',
53
+ accent4: 'accent4',
54
+ accent5: 'accent5',
55
+ accent6: 'accent6',
56
+ hlink: 'hyperlink',
57
+ folHlink: 'followedHyperlink',
58
+ hyperlink: 'hyperlink',
59
+ followedHyperlink: 'followedHyperlink',
60
+ phClr: 'accent1',
61
+ }
62
+
63
+ function fail(zh, en) {
64
+ throw new Error('dsh-ppt:' + zh + (en ? ' / ' + en : ''))
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // OOXML DrawingML Color Modifier Resolver (ISO/IEC 29500)
69
+ // ---------------------------------------------------------------------------
70
+
71
+ function clamp01(v) {
72
+ return Math.max(0, Math.min(1, v))
73
+ }
74
+
75
+ function srgbToLinear(c) {
76
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
77
+ }
78
+
79
+ function linearToSrgb(c) {
80
+ const v = clamp01(c)
81
+ return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055
82
+ }
83
+
84
+ function rgbToHsl01(r, g, b) {
85
+ const max = Math.max(r, g, b)
86
+ const min = Math.min(r, g, b)
87
+ const l = (max + min) / 2
88
+ if (max === min) return [0, 0, l]
89
+ const d = max - min
90
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
91
+ let h
92
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0)
93
+ else if (max === g) h = (b - r) / d + 2
94
+ else h = (r - g) / d + 4
95
+ return [h / 6, s, l]
96
+ }
97
+
98
+ function hueToRgb(p, q, t) {
99
+ let u = t
100
+ if (u < 0) u += 1
101
+ if (u > 1) u -= 1
102
+ if (u < 1 / 6) return p + (q - p) * 6 * u
103
+ if (u < 1 / 2) return q
104
+ if (u < 2 / 3) return p + (q - p) * (2 / 3 - u) * 6
105
+ return p
106
+ }
107
+
108
+ function hslToRgb01(h, s, l) {
109
+ if (s === 0) return [l, l, l]
110
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s
111
+ const p = 2 * l - q
112
+ return [
113
+ hueToRgb(p, q, h + 1 / 3),
114
+ hueToRgb(p, q, h),
115
+ hueToRgb(p, q, h - 1 / 3),
116
+ ]
117
+ }
118
+
119
+ /**
120
+ * Resolve OOXML DrawingML color child modifiers (`lumMod`, `lumOff`, `tint`, `shade`, `satMod`, `satOff`)
121
+ * on a base `#RRGGBB` color string. Values are OOXML percentage units (`100000` = 100%).
122
+ */
123
+ export function resolveColorModifiers(baseHex, mods) {
124
+ const norm = normalizeHex(baseHex, '')
125
+ if (!norm) return baseHex
126
+ if (!mods || (Array.isArray(mods) && mods.length === 0) || (typeof mods === 'object' && Object.keys(mods).length === 0)) {
127
+ return norm
128
+ }
129
+
130
+ let r = parseInt(norm.slice(1, 3), 16) / 255
131
+ let g = parseInt(norm.slice(3, 5), 16) / 255
132
+ let b = parseInt(norm.slice(5, 7), 16) / 255
133
+
134
+ const steps = Array.isArray(mods)
135
+ ? mods
136
+ : Object.entries(mods).map(([kind, val]) => ({ kind, val }))
137
+
138
+ for (const step of steps) {
139
+ if (!step || typeof step.val !== 'number' || !Number.isFinite(step.val)) continue
140
+ const ratio = step.val / 100000
141
+ if (step.kind === 'tint') {
142
+ r = linearToSrgb(srgbToLinear(r) * ratio + (1 - ratio))
143
+ g = linearToSrgb(srgbToLinear(g) * ratio + (1 - ratio))
144
+ b = linearToSrgb(srgbToLinear(b) * ratio + (1 - ratio))
145
+ } else if (step.kind === 'shade') {
146
+ r = linearToSrgb(srgbToLinear(r) * ratio)
147
+ g = linearToSrgb(srgbToLinear(g) * ratio)
148
+ b = linearToSrgb(srgbToLinear(b) * ratio)
149
+ } else if (step.kind === 'lumMod' || step.kind === 'lumOff') {
150
+ const [h, s, l] = rgbToHsl01(r, g, b)
151
+ const nextL = clamp01(step.kind === 'lumMod' ? l * ratio : l + ratio)
152
+ ;[r, g, b] = hslToRgb01(h, s, nextL)
153
+ } else if (step.kind === 'satMod' || step.kind === 'satOff') {
154
+ const [h, s, l] = rgbToHsl01(r, g, b)
155
+ const nextS = clamp01(step.kind === 'satMod' ? s * ratio : s + ratio)
156
+ ;[r, g, b] = hslToRgb01(h, nextS, l)
157
+ }
158
+ }
159
+
160
+ const toHex = (v) => Math.round(clamp01(v) * 255).toString(16).padStart(2, '0').toUpperCase()
161
+ return '#' + toHex(r) + toHex(g) + toHex(b)
162
+ }
163
+
164
+ function parseXmlModifiers(innerXml) {
165
+ if (!innerXml) return []
166
+ const mods = []
167
+ const modRe = /<a:(lumMod|lumOff|tint|shade|satMod|satOff)\b[^>]*\bval=["'](-?\d+)["'][^>]*\/?>/g
168
+ for (const m of innerXml.matchAll(modRe)) {
169
+ mods.push({ kind: m[1], val: Number(m[2]) })
170
+ }
171
+ return mods
172
+ }
173
+
174
+ function lookupSchemeHex(slot, themeScheme, colorMap) {
175
+ if (!slot || !themeScheme) return null
176
+ const mapped = (colorMap && colorMap[slot]) || slot
177
+ const prop = SCHEME_PROP_MAP[mapped] || SCHEME_PROP_MAP[slot] || mapped
178
+ const candidate = themeScheme[prop]
179
+ if (candidate && /^#?[\da-f]{6}$/i.test(String(candidate))) {
180
+ return normalizeHex(candidate, '') || null
181
+ }
182
+ return null
183
+ }
184
+
185
+ /**
186
+ * Parse <a:srgbClr> or <a:schemeClr> (including child lumMod/lumOff/tint/shade/satMod) from an XML fragment.
187
+ */
188
+ export function resolveXmlColorElement(xmlFragment, themeScheme, colorMap) {
189
+ if (!xmlFragment || typeof xmlFragment !== 'string') return null
190
+ const match = /<a:(srgbClr|schemeClr)\b[^>]*\bval=["']([^"']+)["'][^>]*(?:\/>|>([\s\S]*?)<\/a:\1>)/.exec(xmlFragment)
191
+ if (!match) return null
192
+ const [, tag, val, inner] = match
193
+ let baseHex = null
194
+ if (tag === 'srgbClr') {
195
+ baseHex = normalizeHex(val, '') || null
196
+ } else {
197
+ baseHex = lookupSchemeHex(val.trim(), themeScheme, colorMap)
198
+ }
199
+ if (!baseHex) return null
200
+ const mods = parseXmlModifiers(inner)
201
+ return mods.length ? resolveColorModifiers(baseHex, mods) : baseHex
202
+ }
203
+
204
+ function resolveBackgroundFromXml(xmlStr, themeScheme, colorMap) {
205
+ if (!xmlStr) return null
206
+ const bgMatch = /<p:bg\b[^>]*>([\s\S]*?)<\/p:bg>/.exec(xmlStr)
207
+ if (!bgMatch) return null
208
+ const bgInner = bgMatch[1]
209
+ // Direct solidFill or gradFill stop inside p:bgPr
210
+ const solidMatch = /<a:solidFill\b[^>]*>([\s\S]*?)<\/a:solidFill>/.exec(bgInner)
211
+ if (solidMatch) {
212
+ const resolved = resolveXmlColorElement(solidMatch[1], themeScheme, colorMap)
213
+ if (resolved) return resolved
214
+ }
215
+ // bgRef referencing style matrix (e.g. <p:bgRef idx="1001"><a:schemeClr val="bg1">...</a:schemeClr></p:bgRef>)
216
+ const refMatch = /<p:bgRef\b[^>]*>([\s\S]*?)<\/p:bgRef>/.exec(bgInner)
217
+ if (refMatch) {
218
+ const resolved = resolveXmlColorElement(refMatch[1], themeScheme, colorMap)
219
+ if (resolved) return resolved
220
+ }
221
+ const gradMatch = /<a:gs\b[^>]*>([\s\S]*?)<\/a:gs>/.exec(bgInner)
222
+ if (gradMatch) {
223
+ const resolved = resolveXmlColorElement(gradMatch[1], themeScheme, colorMap)
224
+ if (resolved) return resolved
225
+ }
226
+ return null
227
+ }
228
+
229
+ function resolveShapeFillSafe(lib, pres, shape, themeScheme, colorMap) {
230
+ try {
231
+ const hex = lib.getShapeFillColorResolved(pres, shape)
232
+ if (hex && /^#[\da-f]{6}$/i.test(hex)) return hex.toUpperCase()
233
+ } catch { /* fallback to XML */ }
234
+ try {
235
+ const xml = lib.getShapeXmlString?.(shape)
236
+ if (xml) {
237
+ const spPrMatch = /<p:spPr\b[^>]*>([\s\S]*?)<\/p:spPr>/.exec(xml)
238
+ const solid = spPrMatch && /<a:solidFill\b[^>]*>([\s\S]*?)<\/a:solidFill>/.exec(spPrMatch[1])
239
+ if (solid) {
240
+ return resolveXmlColorElement(solid[1], themeScheme, colorMap)
241
+ }
242
+ }
243
+ } catch { /* ignore */ }
244
+ return null
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // Master Slide Skeleton Extraction
249
+ // ---------------------------------------------------------------------------
250
+
251
+ function classifyCornerFromShapes(lib, shapes, slideW) {
252
+ let hasRounded = false
253
+ let hasSoft = false
254
+ let hasSharpRect = false
255
+ for (const shape of shapes) {
256
+ try {
257
+ const bounds = lib.getShapeBounds(shape)
258
+ if (!bounds) continue
259
+ const relW = bounds.w / slideW
260
+ if (relW < 0.08) continue
261
+ const preset = String(lib.getShapePreset?.(shape) ?? '').toLowerCase()
262
+ const name = String(lib.getShapeName?.(shape) ?? '').toLowerCase()
263
+ if (preset === 'roundrect' || preset === 'round2samerect' || preset === 'round1rect' || name.includes('round')) {
264
+ let adjVal = 0
265
+ try {
266
+ const adjs = lib.getShapeAdjustValues?.(shape)
267
+ if (adjs && typeof adjs.adj === 'number') adjVal = adjs.adj
268
+ else if (Array.isArray(adjs)) {
269
+ const adjItem = adjs.find((a) => a?.name === 'adj')
270
+ if (adjItem && typeof adjItem.val === 'number') adjVal = adjItem.val
271
+ }
272
+ } catch { /* ignore */ }
273
+ if (adjVal >= 10000) hasSoft = true
274
+ else hasRounded = true
275
+ } else if (preset === 'ellipse' && relW > 0.12) {
276
+ hasSoft = true
277
+ } else if (preset === 'rect') {
278
+ hasSharpRect = true
279
+ }
280
+ } catch { /* ignore */ }
281
+ }
282
+ if (hasSoft) return 'soft'
283
+ if (hasRounded) return 'rounded'
284
+ if (hasSharpRect) return 'sharp'
285
+ return 'sharp'
286
+ }
287
+
288
+ function extractSkeletonFromShapes(lib, masterShapes, layoutShapes, sampleSlideShapes, slideW, slideH) {
289
+ const mShapes = Array.isArray(masterShapes) ? masterShapes : []
290
+ const lShapes = Array.isArray(layoutShapes) ? layoutShapes : []
291
+ const sShapes = Array.isArray(sampleSlideShapes) ? sampleSlideShapes : []
292
+ const inspectShapes = [...mShapes, ...lShapes, ...(mShapes.length + lShapes.length === 0 ? sShapes : [])]
293
+
294
+ let hasTopBanner = false
295
+ let hasSideSpine = false
296
+ let hasFooterRule = false
297
+ let doubleHeaderLines = 0
298
+
299
+ for (const shape of inspectShapes) {
300
+ try {
301
+ if (lib.hasShapeImage(shape)) continue
302
+ const bounds = lib.getShapeBounds(shape)
303
+ if (!bounds) continue
304
+ const relW = bounds.w / slideW
305
+ const relH = bounds.h / slideH
306
+ const relX = bounds.x / slideW
307
+ const relY = bounds.y / slideH
308
+ const name = String(lib.getShapeName?.(shape) ?? '').toLowerCase()
309
+
310
+ if (relY <= 0.08 && relW >= 0.65 && relH <= 0.22) {
311
+ hasTopBanner = true
312
+ if (relH <= 0.025) doubleHeaderLines += 1
313
+ }
314
+ if ((relX <= 0.06 || relX >= 0.90) && relW <= 0.10 && relH >= 0.45) {
315
+ hasSideSpine = true
316
+ }
317
+ if (relY >= 0.85 && relW >= 0.5 && relH <= 0.03) {
318
+ hasFooterRule = true
319
+ }
320
+ if (name.includes('header') && relW >= 0.6) {
321
+ hasTopBanner = true
322
+ }
323
+ } catch { /* ignore malformed shape */ }
324
+ }
325
+
326
+ const cornerStyle = classifyCornerFromShapes(lib, [...mShapes, ...lShapes, ...sShapes], slideW)
327
+ return {
328
+ cornerStyle,
329
+ hasTopBanner,
330
+ hasSideSpine,
331
+ masterShapeCount: mShapes.length,
332
+ _hasFooterRule: hasFooterRule,
333
+ _doubleHeaderLines: doubleHeaderLines,
334
+ }
335
+ }
336
+
337
+ function inferChromeStyle(skeleton, palette, fonts, dark, recommendedTheme) {
338
+ const fontText = [fonts.majorLatin, fonts.majorEastAsian, fonts.minorLatin, fonts.minorEastAsian].filter(Boolean).join(' ')
339
+ const isSerif = /(?:times|georgia|garamond|cambria|palatino|宋体|SimSun|Songti|Source\s*Serif|Noto\s*Serif)/i.test(fontText)
340
+
341
+ if (
342
+ recommendedTheme === 'exec-palace' ||
343
+ recommendedTheme === 'exec-jilan' ||
344
+ skeleton._doubleHeaderLines >= 2 ||
345
+ (palette.accent1 && /^#[89AB][0-9A-F]0{3}$/i.test(palette.accent1))
346
+ ) {
347
+ return 'gov-ceremonial'
348
+ }
349
+
350
+ if (
351
+ recommendedTheme === 'academic' ||
352
+ recommendedTheme === 'course-sage' ||
353
+ recommendedTheme === 'medical-clean' ||
354
+ (isSerif && !dark && (skeleton.hasTopBanner || skeleton._hasFooterRule))
355
+ ) {
356
+ return 'academic-minimal'
357
+ }
358
+
359
+ if (
360
+ recommendedTheme === 'keynote-light' ||
361
+ recommendedTheme === 'bold' ||
362
+ skeleton.cornerStyle === 'soft' ||
363
+ (!skeleton.hasTopBanner && !skeleton.hasSideSpine && !skeleton._hasFooterRule && skeleton.cornerStyle !== 'sharp' && !dark)
364
+ ) {
365
+ return 'keynote-spatial'
366
+ }
367
+
368
+ if (
369
+ skeleton.hasSideSpine ||
370
+ recommendedTheme === 'editorial-forest' ||
371
+ recommendedTheme === 'cartesian' ||
372
+ recommendedTheme === 'velvet' ||
373
+ recommendedTheme === 'luxury-noir'
374
+ ) {
375
+ return 'editorial-folio'
376
+ }
377
+
378
+ if (
379
+ recommendedTheme === 'linear-dark' ||
380
+ recommendedTheme === 'swiss' ||
381
+ recommendedTheme === 'data' ||
382
+ recommendedTheme === 'soft' ||
383
+ (skeleton.cornerStyle === 'rounded' && dark)
384
+ ) {
385
+ return 'saas-bento'
386
+ }
387
+
388
+ return 'consulting-classic'
389
+ }
390
+
391
+ // ---------------------------------------------------------------------------
392
+ // Per-Slide Layout Classification
393
+ // ---------------------------------------------------------------------------
394
+
395
+ function analyzeSlideLayout(lib, slide, slideIndex, totalSlides, slideW, slideH) {
396
+ const result = { slideNumber: slideIndex + 1, inferredLayout: 'bullets' }
397
+ try {
398
+ const shapes = lib.getSlideShapes(slide) ?? []
399
+ let layoutType = ''
400
+ try {
401
+ const sLayout = lib.getSlideLayout(slide)
402
+ if (sLayout) layoutType = String(lib.getSlideLayoutType(sLayout) ?? '').toLowerCase()
403
+ } catch { /* ignore */ }
404
+
405
+ let hasChart = false
406
+ let hasTable = false
407
+ try {
408
+ const charts = lib.getSlideCharts?.(slide)
409
+ if (Array.isArray(charts) && charts.length > 0) hasChart = true
410
+ } catch { /* ignore */ }
411
+ try {
412
+ const tables = lib.getSlideTables?.(slide)
413
+ if (Array.isArray(tables) && tables.length > 0) hasTable = true
414
+ } catch { /* ignore */ }
415
+
416
+ let titleText = ''
417
+ let titleFound = false
418
+ let imageCount = 0
419
+ let hasLeftHalfImage = false
420
+ let hasRightHalfImage = false
421
+ let nonTitleTextShapes = 0
422
+ let largeCardShapes = 0
423
+ let numericKpiShapes = 0
424
+ let harveyCells = false
425
+ const shapeCenters = []
426
+
427
+ for (const shape of shapes) {
428
+ try {
429
+ if (lib.isChartShape?.(shape)) hasChart = true
430
+ if (lib.isTableShape?.(shape)) hasTable = true
431
+
432
+ const name = String(lib.getShapeName?.(shape) ?? '').toLowerCase()
433
+ const phType = String(lib.getShapePlaceholderType?.(shape) ?? '').toLowerCase()
434
+ const bounds = lib.getShapeBounds(shape)
435
+ const text = String(lib.getShapeText?.(shape) ?? '').trim()
436
+
437
+ if (!hasChart && (name.includes('chart') || name.includes('diagram'))) hasChart = true
438
+ if (!hasTable && name.includes('table')) hasTable = true
439
+
440
+ if (phType === 'title' || phType === 'ctrtitle' || name.startsWith('title') || name.includes('标题')) {
441
+ titleFound = true
442
+ if (!titleText && text) titleText = text.replace(/\s+/g, ' ').slice(0, 80)
443
+ continue
444
+ }
445
+
446
+ if (lib.hasShapeImage(shape)) {
447
+ imageCount += 1
448
+ if (bounds) {
449
+ const relW = bounds.w / slideW
450
+ const relH = bounds.h / slideH
451
+ const relX = bounds.x / slideW
452
+ if (relW > 0.25 && relH > 0.3) {
453
+ if (relX < 0.35) hasLeftHalfImage = true
454
+ else if (relX >= 0.35) hasRightHalfImage = true
455
+ }
456
+ }
457
+ continue
458
+ }
459
+
460
+ if (!bounds) {
461
+ if (text) nonTitleTextShapes += 1
462
+ continue
463
+ }
464
+
465
+ const relW = bounds.w / slideW
466
+ const relH = bounds.h / slideH
467
+ const relX = bounds.x / slideW
468
+ const relY = bounds.y / slideH
469
+
470
+ if (!titleFound && relY < 0.22 && relW > 0.45 && relH < 0.22 && text) {
471
+ titleFound = true
472
+ titleText = text.replace(/\s+/g, ' ').slice(0, 80)
473
+ continue
474
+ }
475
+
476
+ const isChromeShape =
477
+ relY >= 0.88 ||
478
+ (relY <= 0.12 && relH <= 0.12) ||
479
+ /^(?:page number|footer|source|kicker|folio|beamer|header rule|takeaway)/i.test(name) ||
480
+ phType === 'ftr' || phType === 'sldnum' || phType === 'dt'
481
+ if (isChromeShape) continue
482
+
483
+ if (text) {
484
+ nonTitleTextShapes += 1
485
+ if (/^[+-]?\d[\d.,]*\s*[%%倍xX万亿千百kKmMbB+]*$/.test(text.split('\n')[0]?.trim() ?? '')) {
486
+ numericKpiShapes += 1
487
+ }
488
+ if (/[●◕◑◔○]/.test(text)) harveyCells = true
489
+ }
490
+
491
+ if (!lib.isChartShape?.(shape) && !lib.isTableShape?.(shape) && relW > 0.18 && relW < 0.65 && relH > 0.18) {
492
+ largeCardShapes += 1
493
+ shapeCenters.push({ x: relX + relW / 2, y: relY + relH / 2 })
494
+ }
495
+ } catch { /* ignore shape */ }
496
+ }
497
+
498
+ // Check charts & tables BEFORE shapeCount <= 2 so single-chart/single-table slides classify accurately!
499
+ if (harveyCells) {
500
+ result.inferredLayout = 'harvey'
501
+ } else if (hasChart) {
502
+ result.inferredLayout = nonTitleTextShapes >= 1 || largeCardShapes >= 1 ? 'chart-split' : 'chart'
503
+ } else if (hasTable) {
504
+ result.inferredLayout = 'table'
505
+ } else if (imageCount >= 2) {
506
+ result.inferredLayout = 'image'
507
+ result.variant = 'gallery'
508
+ } else if (imageCount === 1) {
509
+ if (hasLeftHalfImage && nonTitleTextShapes >= 1) result.inferredLayout = 'image-left'
510
+ else if (hasRightHalfImage && nonTitleTextShapes >= 1) result.inferredLayout = 'image-right'
511
+ else if (hasLeftHalfImage) result.inferredLayout = 'image-left'
512
+ else if (hasRightHalfImage) result.inferredLayout = 'image-right'
513
+ else result.inferredLayout = 'image'
514
+ } else if (
515
+ slideIndex === 0 &&
516
+ (layoutType === 'title' || (titleFound && nonTitleTextShapes <= 2 && largeCardShapes <= 1) || (nonTitleTextShapes <= 1 && shapes.length <= 3))
517
+ ) {
518
+ result.inferredLayout = 'cover'
519
+ } else if (
520
+ slideIndex === totalSlides - 1 &&
521
+ totalSlides >= 3 &&
522
+ (nonTitleTextShapes <= 1 && /谢谢|感谢|Q\s*&\s*A|Thank|Contact|Next/i.test(titleText))
523
+ ) {
524
+ result.inferredLayout = 'closing'
525
+ } else if (slideIndex > 0 && (layoutType === 'sechdr' || (nonTitleTextShapes === 0 && shapes.length <= 2))) {
526
+ result.inferredLayout = 'section'
527
+ } else if (numericKpiShapes >= 2) {
528
+ result.inferredLayout = 'kpi'
529
+ result.variant = 'grid'
530
+ } else if (largeCardShapes === 4 && shapeCenters.length === 4) {
531
+ const xs = shapeCenters.map((c) => c.x).sort((a, b) => a - b)
532
+ const ys = shapeCenters.map((c) => c.y).sort((a, b) => a - b)
533
+ const is2x2 = xs[2] - xs[1] > 0.15 && ys[2] - ys[1] > 0.15
534
+ result.inferredLayout = is2x2 ? 'matrix' : 'cards'
535
+ result.variant = is2x2 ? '2x2' : 'bento'
536
+ } else if (largeCardShapes >= 3) {
537
+ const ySpread = Math.max(...shapeCenters.map((c) => c.y)) - Math.min(...shapeCenters.map((c) => c.y))
538
+ if (ySpread < 0.12) {
539
+ result.inferredLayout = 'process'
540
+ result.variant = 'steps'
541
+ } else {
542
+ result.inferredLayout = 'cards'
543
+ result.variant = 'bento'
544
+ }
545
+ } else if (largeCardShapes === 2) {
546
+ result.inferredLayout = 'comparison'
547
+ result.variant = 'versus'
548
+ } else {
549
+ result.inferredLayout = 'bullets'
550
+ }
551
+
552
+ if (titleText) result.titleSample = titleText
553
+ } catch { /* ignore slide analysis error */ }
554
+
555
+ return result
556
+ }
557
+
558
+ // ---------------------------------------------------------------------------
559
+ // Background, Logo, Theme & Palette Extraction
560
+ // ---------------------------------------------------------------------------
561
+
562
+ function resolveBackgroundHex(bg, pres, slideOrLayout, themeScheme, colorMap, getGradFn, xmlStr = '') {
563
+ if (bg && typeof bg === 'object') {
564
+ let rawColor = null
565
+ if (bg.kind === 'solid' && typeof bg.color === 'string') {
566
+ rawColor = bg.color
567
+ } else if (bg.kind === 'gradient' && typeof getGradFn === 'function') {
568
+ try {
569
+ const grad = slideOrLayout !== undefined ? getGradFn(pres, slideOrLayout) : null
570
+ rawColor = grad?.stops?.[0]?.color ?? null
571
+ } catch {
572
+ try {
573
+ const grad = getGradFn(slideOrLayout)
574
+ rawColor = grad?.stops?.[0]?.color ?? null
575
+ } catch { /* ignore */ }
576
+ }
577
+ }
578
+ if (rawColor && typeof rawColor === 'string') {
579
+ if (/^#?[\da-f]{6}$/i.test(rawColor.trim())) {
580
+ return normalizeHex(rawColor.trim(), '') || null
581
+ }
582
+ if (rawColor.startsWith('scheme:') && themeScheme) {
583
+ const slot = rawColor.slice(7).trim()
584
+ const resolved = lookupSchemeHex(slot, themeScheme, colorMap)
585
+ if (resolved) return resolved
586
+ }
587
+ }
588
+ }
589
+ if (xmlStr) {
590
+ return resolveBackgroundFromXml(xmlStr, themeScheme, colorMap)
591
+ }
592
+ return null
593
+ }
594
+
595
+ function isValidRasterLogo(bytes, format) {
596
+ if (!bytes || bytes.byteLength < 24 || bytes.byteLength > MAX_LOGO_BYTES) return false
597
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
598
+ if (format === 'png') {
599
+ if (!buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return false
600
+ if (buf.length < 45 || buf.toString('ascii', 12, 16) !== 'IHDR') return false
601
+ const width = buf.readUInt32BE(16)
602
+ const height = buf.readUInt32BE(20)
603
+ if (!width || !height || width > 8000 || height > 8000) return false
604
+ let offset = 8
605
+ let ended = false
606
+ const compressed = []
607
+ while (offset + 12 <= buf.length) {
608
+ const length = buf.readUInt32BE(offset)
609
+ const type = buf.toString('ascii', offset + 4, offset + 8)
610
+ if (offset + length + 12 > buf.length) return false
611
+ if (type === 'IDAT') compressed.push(buf.subarray(offset + 8, offset + 8 + length))
612
+ if (type === 'IEND') { ended = true; break }
613
+ offset += length + 12
614
+ }
615
+ if (!ended || compressed.length === 0) return false
616
+ try {
617
+ inflateSync(Buffer.concat(compressed), { maxOutputLength: 32 * 1024 * 1024 })
618
+ return true
619
+ } catch {
620
+ return false
621
+ }
622
+ }
623
+ if (format === 'jpeg') {
624
+ if (buf[0] !== 0xff || buf[1] !== 0xd8) return false
625
+ if (!buf.subarray(-2).equals(Buffer.from([0xff, 0xd9]))) return false
626
+ return true
627
+ }
628
+ return false
629
+ }
630
+
631
+ function aspectLabel(widthEmu, heightEmu) {
632
+ if (!widthEmu || !heightEmu) return '16:9'
633
+ const ratio = widthEmu / heightEmu
634
+ if (Math.abs(ratio - 16 / 9) < 0.04) return '16:9'
635
+ if (Math.abs(ratio - 16 / 10) < 0.04) return '16:10'
636
+ if (Math.abs(ratio - 4 / 3) < 0.04) return '4:3'
637
+ return ratio.toFixed(2) + ':1'
638
+ }
639
+
640
+ function detectFullBleedShapeBg(lib, pres, shapes, slideW, slideH, themeScheme, colorMap) {
641
+ if (!Array.isArray(shapes) || !slideW || !slideH) return null
642
+ for (const shape of shapes) {
643
+ try {
644
+ if (lib.hasShapeImage(shape)) continue
645
+ const bounds = lib.getShapeBounds(shape)
646
+ if (!bounds) continue
647
+ if (bounds.w >= slideW * 0.78 && bounds.h >= slideH * 0.78 && bounds.x <= slideW * 0.12 && bounds.y <= slideH * 0.12) {
648
+ const fill = resolveShapeFillSafe(lib, pres, shape, themeScheme, colorMap)
649
+ if (fill && /^#[\da-f]{6}$/i.test(fill)) return fill.toUpperCase()
650
+ }
651
+ } catch { /* ignore individual malformed shape */ }
652
+ }
653
+ return null
654
+ }
655
+
656
+ function extractCandidateLogo(lib, pres, slides, layouts, slideW, slideH) {
657
+ const pools = []
658
+ for (const layout of layouts.slice(0, 6)) {
659
+ try { pools.push({ source: 'master', shapes: lib.getSlideMasterShapes(pres, layout) }) } catch { /* ignore */ }
660
+ try { pools.push({ source: 'layout', shapes: lib.getSlideLayoutShapes(pres, layout) }) } catch { /* ignore */ }
661
+ }
662
+ for (const slide of slides.slice(0, 2)) {
663
+ try { pools.push({ source: 'slide', shapes: lib.getSlideShapes(slide) }) } catch { /* ignore */ }
664
+ }
665
+
666
+ let best = null
667
+ for (const pool of pools) {
668
+ for (const shape of pool.shapes ?? []) {
669
+ try {
670
+ if (!lib.hasShapeImage(shape)) continue
671
+ const rawFmt = String(lib.getShapeImageFormat(shape) ?? '').toLowerCase()
672
+ const fmt = rawFmt === 'jpg' ? 'jpeg' : rawFmt
673
+ if (fmt !== 'png' && fmt !== 'jpeg') continue
674
+ const bounds = lib.getShapeBounds(shape)
675
+ if (!bounds || bounds.w <= 0 || bounds.h <= 0) continue
676
+
677
+ const nameText = [
678
+ lib.getShapeName?.(shape),
679
+ lib.getShapeDescription?.(shape),
680
+ lib.getShapeAltTitle?.(shape),
681
+ ].filter(Boolean).join(' ')
682
+ const namedLogo = /logo|brand|徽|标|院徽|校徽|台标/i.test(nameText)
683
+ const maxW = namedLogo ? slideW * 0.45 : slideW * 0.28
684
+ const maxH = namedLogo ? slideH * 0.35 : slideH * 0.20
685
+ if (bounds.w > maxW || bounds.h > maxH) continue
686
+
687
+ const nearCornerBand = bounds.y <= slideH * 0.24 || (bounds.y + bounds.h) >= slideH * 0.76
688
+ if (!namedLogo && pool.source === 'slide' && !nearCornerBand) continue
689
+
690
+ const bytes = lib.getShapeImageBytes(shape)
691
+ if (!isValidRasterLogo(bytes, fmt)) continue
692
+
693
+ const score = (namedLogo ? 100 : 0) + (pool.source === 'master' ? 40 : pool.source === 'layout' ? 25 : 10) + (nearCornerBand ? 15 : 0)
694
+ if (!best || score > best.score) {
695
+ const b64 = Buffer.from(bytes).toString('base64')
696
+ best = { score, dataUri: `data:image/${fmt};base64,${b64}` }
697
+ }
698
+ } catch { /* ignore shape read error */ }
699
+ }
700
+ }
701
+ return best?.dataUri ?? null
702
+ }
703
+
704
+ function safeReadXmlPart(lib, pres, partName) {
705
+ if (!partName) return ''
706
+ try {
707
+ const raw = lib.readPackagePart?.(pres, partName)
708
+ return raw ? Buffer.from(raw).toString('utf8') : ''
709
+ } catch {
710
+ return ''
711
+ }
712
+ }
713
+
714
+ /**
715
+ * 只读解析外部 .pptx 文件或字节流,提取并净化主题色板、中英文字体、母版 Logo、骨架特征与逐页版式分布。
716
+ */
717
+ export async function absorbPptx(options = {}) {
718
+ options.signal?.throwIfAborted()
719
+ const cwd = resolve(String(options.cwd ?? '.'))
720
+ const extractLogo = options.extractLogo !== false
721
+
722
+ let bytes
723
+ let resolvedPath
724
+ if (options.bytes instanceof Uint8Array) {
725
+ bytes = options.bytes
726
+ if (typeof options.pptxPath === 'string' && options.pptxPath.trim()) {
727
+ resolvedPath = resolve(cwd, options.pptxPath.trim())
728
+ }
729
+ } else {
730
+ if (typeof options.pptxPath !== 'string' || !options.pptxPath.trim()) {
731
+ fail('请提供参考 .pptx 文件路径 pptxPath', 'pptxPath is required')
732
+ }
733
+ resolvedPath = resolve(cwd, options.pptxPath.trim())
734
+ let stat
735
+ try {
736
+ stat = lstatSync(resolvedPath)
737
+ } catch {
738
+ fail('找不到参考 PPTX 文件:' + resolvedPath, 'Reference PPTX file not found: ' + resolvedPath)
739
+ }
740
+ if (!stat.isFile() || stat.isSymbolicLink()) {
741
+ fail('参考 PPTX 必须是普通文件(不支持目录或符号链接)', 'Reference PPTX must be a regular file')
742
+ }
743
+ if (stat.size < 22 || stat.size > MAX_PPTX_BYTES) {
744
+ fail('参考 PPTX 文件大小需在 64 MiB 以内', 'Reference PPTX must be up to 64 MiB')
745
+ }
746
+ bytes = readFileSync(resolvedPath)
747
+ }
748
+
749
+ if (!bytes || bytes.byteLength < 22 || bytes.byteLength > MAX_PPTX_BYTES || bytes[0] !== 0x50 || bytes[1] !== 0x4b) {
750
+ fail('文件不是有效的 .pptx 压缩包', 'Invalid .pptx archive')
751
+ }
752
+
753
+ options.signal?.throwIfAborted()
754
+ let lib
755
+ try {
756
+ lib = await import('@office-kit/pptx')
757
+ } catch (error) {
758
+ fail('解析参考 PPTX 需要 @office-kit/pptx@0.21.0。独立技能请在技能目录运行 npm install --ignore-scripts。' + error.message)
759
+ }
760
+ options.signal?.throwIfAborted()
761
+
762
+ let pres
763
+ try {
764
+ pres = await lib.loadPresentation(bytes)
765
+ } catch (error) {
766
+ fail('无法解析参考 PPTX 结构:' + error.message, 'Failed to parse PPTX: ' + error.message)
767
+ }
768
+ options.signal?.throwIfAborted()
769
+
770
+ const slides = lib.getSlides(pres)
771
+ const slideCount = slides.length
772
+ const rawSize = lib.getSlideSize(pres)
773
+ const widthEmu = rawSize?.width ?? 12192000
774
+ const heightEmu = rawSize?.height ?? 6858000
775
+ const slideSize = {
776
+ width: Number((widthEmu / EMU_PER_INCH).toFixed(3)),
777
+ height: Number((heightEmu / EMU_PER_INCH).toFixed(3)),
778
+ widthEmu,
779
+ heightEmu,
780
+ aspect: aspectLabel(widthEmu, heightEmu),
781
+ }
782
+
783
+ const rawTheme = lib.getPresentationTheme(pres) ?? {}
784
+ const rawFonts = lib.getPresentationFonts(pres) ?? {}
785
+ const layouts = lib.getSlideLayouts(pres) ?? []
786
+ const sampleSlide = slides[1] ?? slides[0] ?? null
787
+ const colorMap = sampleSlide ? lib.getEffectiveColorMap(sampleSlide) : null
788
+
789
+ let sampleLayout = null
790
+ if (sampleSlide) {
791
+ try { sampleLayout = lib.getSlideLayout(sampleSlide) } catch { /* ignore */ }
792
+ }
793
+ const firstLayout = sampleLayout ?? layouts[0] ?? null
794
+ let masterPartName = null
795
+ if (sampleSlide) {
796
+ try { masterPartName = lib.getSlideMasterPartName?.(sampleSlide) } catch { /* ignore */ }
797
+ }
798
+ if (!masterPartName) {
799
+ try { masterPartName = lib.getSlideMasterPartNames?.(pres)?.[0] ?? null } catch { /* ignore */ }
800
+ }
801
+ const masterXml = safeReadXmlPart(lib, pres, masterPartName)
802
+
803
+ let masterBg = null
804
+ if (firstLayout) {
805
+ try {
806
+ masterBg = resolveBackgroundHex(
807
+ lib.getSlideMasterBackground(pres, firstLayout),
808
+ pres,
809
+ firstLayout,
810
+ rawTheme,
811
+ colorMap,
812
+ lib.getSlideMasterBackgroundGradientFill,
813
+ masterXml,
814
+ )
815
+ } catch { /* ignore */ }
816
+ if (!masterBg) {
817
+ try {
818
+ masterBg = detectFullBleedShapeBg(lib, pres, lib.getSlideMasterShapes(pres, firstLayout), widthEmu, heightEmu, rawTheme, colorMap)
819
+ } catch { /* ignore */ }
820
+ }
821
+ } else if (masterXml) {
822
+ masterBg = resolveBackgroundFromXml(masterXml, rawTheme, colorMap)
823
+ }
824
+
825
+ let contentSlideBg = null
826
+ if (sampleSlide) {
827
+ const sampleXml = (() => { try { return lib.getSlideXmlString?.(sampleSlide) ?? '' } catch { return '' } })()
828
+ try {
829
+ contentSlideBg = resolveBackgroundHex(
830
+ lib.getSlideBackground(sampleSlide),
831
+ pres,
832
+ sampleSlide,
833
+ rawTheme,
834
+ colorMap,
835
+ lib.getSlideBackgroundGradientFill,
836
+ sampleXml,
837
+ )
838
+ } catch { /* ignore */ }
839
+ if (!contentSlideBg && sampleLayout) {
840
+ const layoutPartName = (() => { try { return lib.getSlideLayoutPartName?.(sampleLayout) } catch { return '' } })()
841
+ const layoutXml = safeReadXmlPart(lib, pres, layoutPartName)
842
+ try {
843
+ contentSlideBg = resolveBackgroundHex(
844
+ lib.getSlideLayoutBackground(sampleLayout),
845
+ pres,
846
+ sampleLayout,
847
+ rawTheme,
848
+ colorMap,
849
+ lib.getSlideLayoutBackgroundGradientFill,
850
+ layoutXml,
851
+ ) || detectFullBleedShapeBg(lib, pres, lib.getSlideLayoutShapes(pres, sampleLayout), widthEmu, heightEmu, rawTheme, colorMap)
852
+ } catch { /* ignore */ }
853
+ }
854
+ if (!contentSlideBg) {
855
+ try {
856
+ contentSlideBg = detectFullBleedShapeBg(lib, pres, lib.getSlideShapes(sampleSlide), widthEmu, heightEmu, rawTheme, colorMap)
857
+ } catch { /* ignore */ }
858
+ }
859
+ }
860
+ if (!contentSlideBg && slides[0] && slides[0] !== sampleSlide) {
861
+ const firstXml = (() => { try { return lib.getSlideXmlString?.(slides[0]) ?? '' } catch { return '' } })()
862
+ try {
863
+ contentSlideBg = resolveBackgroundHex(
864
+ lib.getSlideBackground(slides[0]),
865
+ pres,
866
+ slides[0],
867
+ rawTheme,
868
+ colorMap,
869
+ lib.getSlideBackgroundGradientFill,
870
+ firstXml,
871
+ ) || detectFullBleedShapeBg(lib, pres, lib.getSlideShapes(slides[0]), widthEmu, heightEmu, rawTheme, colorMap)
872
+ } catch { /* ignore */ }
873
+ }
874
+
875
+ let bodyTextColor = null
876
+ if (sampleSlide) {
877
+ try { bodyTextColor = lib.resolveDeckBodyTextColor(sampleSlide) } catch { /* ignore */ }
878
+ }
879
+
880
+ let shapeAccentCandidate = null
881
+ const rawAccent1 = rawTheme.accent1 ? normalizeHex(rawTheme.accent1, '') : ''
882
+ if (!rawAccent1 || OFFICE_DEFAULT_ACCENTS.has(rawAccent1)) {
883
+ const colorCounts = new Map()
884
+ const inspectPool = []
885
+ if (firstLayout) {
886
+ try { inspectPool.push(...lib.getSlideMasterShapes(pres, firstLayout)) } catch { /* ignore */ }
887
+ }
888
+ for (const slide of slides.slice(0, 6)) {
889
+ try { inspectPool.push(...lib.getSlideShapes(slide)) } catch { /* ignore */ }
890
+ }
891
+ for (const shape of inspectPool) {
892
+ try {
893
+ const b = lib.getShapeBounds(shape)
894
+ if (b && b.w >= widthEmu * 0.78 && b.h >= heightEmu * 0.78) continue
895
+ const hex = resolveShapeFillSafe(lib, pres, shape, rawTheme, colorMap)
896
+ if (!hex || !/^#[\da-f]{6}$/i.test(hex)) continue
897
+ const norm = hex.toUpperCase()
898
+ if (norm === '#FFFFFF' || norm === '#000000' || norm === (contentSlideBg ?? masterBg)) continue
899
+ colorCounts.set(norm, (colorCounts.get(norm) ?? 0) + 1)
900
+ } catch { /* ignore */ }
901
+ }
902
+ let topCount = 0
903
+ for (const [hex, count] of colorCounts.entries()) {
904
+ if (count > topCount) {
905
+ topCount = count
906
+ shapeAccentCandidate = hex
907
+ }
908
+ }
909
+ }
910
+
911
+ const extractedPalette = {}
912
+ for (const key of ['dark1', 'light1', 'dark2', 'light2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hyperlink', 'followedHyperlink']) {
913
+ if (typeof rawTheme[key] === 'string' && rawTheme[key]) {
914
+ extractedPalette[key] = normalizeHex(rawTheme[key], rawTheme[key])
915
+ }
916
+ }
917
+ if (masterBg) extractedPalette.masterBg = masterBg
918
+ if (contentSlideBg) extractedPalette.contentSlideBg = contentSlideBg
919
+ if (bodyTextColor) extractedPalette.bodyTextColor = normalizeHex(bodyTextColor, bodyTextColor)
920
+
921
+ const extractedFonts = {}
922
+ for (const key of ['majorLatin', 'majorEastAsian', 'minorLatin', 'minorEastAsian']) {
923
+ if (typeof rawFonts[key] === 'string' && rawFonts[key].trim()) {
924
+ extractedFonts[key] = rawFonts[key].trim()
925
+ }
926
+ }
927
+
928
+ const sanitized = sanitizeAbsorbedTheme({
929
+ palette: extractedPalette,
930
+ fonts: extractedFonts,
931
+ masterBg: masterBg ?? undefined,
932
+ contentSlideBg: contentSlideBg ?? masterBg ?? undefined,
933
+ textColor: bodyTextColor ?? undefined,
934
+ ...(shapeAccentCandidate ? { brandPrimary: shapeAccentCandidate } : {}),
935
+ })
936
+
937
+ const logoDataUri = extractLogo ? extractCandidateLogo(lib, pres, slides, layouts, widthEmu, heightEmu) : null
938
+ let coreTitle = ''
939
+ try {
940
+ const props = lib.getCoreProperties(pres)
941
+ if (typeof props?.title === 'string' && props.title.trim() && !/^PowerPoint 演示文稿$|^Presentation\d*$/i.test(props.title.trim())) {
942
+ coreTitle = props.title.trim().slice(0, 100)
943
+ }
944
+ } catch { /* ignore */ }
945
+
946
+ const sanitizedBrand = {
947
+ ...sanitized.sanitizedBrand,
948
+ ...(coreTitle ? { name: coreTitle } : {}),
949
+ ...(logoDataUri ? { logo: logoDataUri } : {}),
950
+ }
951
+ if (
952
+ sanitizedBrand.fontFamily &&
953
+ (
954
+ /^(?:SimSun|NSimSun|宋体|新宋体|FangSong|仿宋|Impact|Comic Sans MS)$/i.test(sanitizedBrand.fontFamily) ||
955
+ (/^(?:Calibri|Calibri Light|Aptos|Aptos Display)$/i.test(sanitizedBrand.fontFamily) &&
956
+ !extractedFonts.majorEastAsian &&
957
+ !extractedFonts.minorEastAsian)
958
+ )
959
+ ) {
960
+ delete sanitizedBrand.fontFamily
961
+ }
962
+
963
+ const layoutTypes = {}
964
+ for (const layout of layouts) {
965
+ try {
966
+ const t = lib.getSlideLayoutType(layout) || lib.getSlideLayoutName(layout) || 'custom'
967
+ layoutTypes[t] = (layoutTypes[t] ?? 0) + 1
968
+ } catch { /* ignore */ }
969
+ }
970
+ let chartCount = 0
971
+ let tableCount = 0
972
+ let mediaPartCount = 0
973
+ try { chartCount = lib.getAllCharts(pres).length } catch { /* ignore */ }
974
+ try { tableCount = lib.getAllTables(pres).length } catch { /* ignore */ }
975
+ try { mediaPartCount = lib.getMediaParts(pres).length } catch { /* ignore */ }
976
+
977
+ const layoutSummary = {
978
+ layoutCount: layouts.length,
979
+ slideCount,
980
+ chartCount,
981
+ tableCount,
982
+ mediaPartCount,
983
+ hasLogo: Boolean(logoDataUri),
984
+ layoutTypes,
985
+ }
986
+
987
+ // Deep Skeleton Extraction
988
+ let masterShapes = []
989
+ let layoutShapes = []
990
+ let sampleSlideShapes = []
991
+ if (firstLayout) {
992
+ try { masterShapes = lib.getSlideMasterShapes(pres, firstLayout) ?? [] } catch { /* ignore */ }
993
+ try { layoutShapes = lib.getSlideLayoutShapes(pres, firstLayout) ?? [] } catch { /* ignore */ }
994
+ }
995
+ if (sampleSlide) {
996
+ try { sampleSlideShapes = lib.getSlideShapes(sampleSlide) ?? [] } catch { /* ignore */ }
997
+ }
998
+
999
+ const rawSkeleton = extractSkeletonFromShapes(lib, masterShapes, layoutShapes, sampleSlideShapes, widthEmu, heightEmu)
1000
+ const recommendedChrome = inferChromeStyle(rawSkeleton, extractedPalette, extractedFonts, sanitized.dark, sanitized.recommendedTheme)
1001
+ const extractedSkeleton = {
1002
+ cornerStyle: rawSkeleton.cornerStyle,
1003
+ hasTopBanner: rawSkeleton.hasTopBanner,
1004
+ hasSideSpine: rawSkeleton.hasSideSpine,
1005
+ masterShapeCount: rawSkeleton.masterShapeCount,
1006
+ }
1007
+
1008
+ const slideSkeleton = slides.slice(0, 60).map((slide, idx) =>
1009
+ analyzeSlideLayout(lib, slide, idx, slides.length, widthEmu, heightEmu)
1010
+ )
1011
+
1012
+ return {
1013
+ ok: true,
1014
+ ...(resolvedPath ? { pptxPath: resolvedPath } : {}),
1015
+ slideCount,
1016
+ slideSize,
1017
+ extractedPalette,
1018
+ extractedFonts,
1019
+ sanitizedBrand,
1020
+ sanitizedTokens: sanitized.sanitizedTokens,
1021
+ recommendedTheme: sanitized.recommendedTheme,
1022
+ recommendedChrome,
1023
+ dark: sanitized.dark,
1024
+ warnings: sanitized.warnings,
1025
+ layoutSummary,
1026
+ extractedSkeleton,
1027
+ slideSkeleton,
1028
+ }
1029
+ }