docrev 0.10.0 → 0.10.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 (126) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -164
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/anchor-match.d.ts +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +17 -47
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/context.d.ts +1 -1
  16. package/dist/lib/commands/context.d.ts.map +1 -1
  17. package/dist/lib/commands/context.js +1 -1
  18. package/dist/lib/commands/context.js.map +1 -1
  19. package/dist/lib/commands/sections.js +7 -7
  20. package/dist/lib/commands/sections.js.map +1 -1
  21. package/dist/lib/commands/sync.d.ts.map +1 -1
  22. package/dist/lib/commands/sync.js +15 -14
  23. package/dist/lib/commands/sync.js.map +1 -1
  24. package/dist/lib/commands/utilities.js +164 -164
  25. package/dist/lib/commands/verify-anchors.js +6 -6
  26. package/dist/lib/commands/verify-anchors.js.map +1 -1
  27. package/dist/lib/commands/word-tools.js +8 -8
  28. package/dist/lib/grammar.js +3 -3
  29. package/dist/lib/macro-filter.lua +201 -201
  30. package/dist/lib/pdf-comments.js +44 -44
  31. package/dist/lib/plugins.js +57 -57
  32. package/dist/lib/pptx-color-filter.lua +37 -37
  33. package/dist/lib/pptx-themes.js +115 -115
  34. package/dist/lib/sections.d.ts +35 -0
  35. package/dist/lib/sections.d.ts.map +1 -1
  36. package/dist/lib/sections.js +81 -0
  37. package/dist/lib/sections.js.map +1 -1
  38. package/dist/lib/spelling.js +2 -2
  39. package/dist/lib/templates.js +387 -387
  40. package/dist/lib/themes.js +51 -51
  41. package/docs-src/build.py +113 -113
  42. package/docs-src/extra.css +208 -208
  43. package/docs-src/md-to-html.lua +6 -6
  44. package/docs-src/template.html +116 -116
  45. package/eslint.config.js +27 -27
  46. package/lib/anchor-match.ts +276 -308
  47. package/lib/annotations.ts +644 -644
  48. package/lib/build.ts +1766 -1766
  49. package/lib/citations.ts +160 -160
  50. package/lib/commands/build.ts +855 -855
  51. package/lib/commands/citations.ts +515 -515
  52. package/lib/commands/comments.ts +1050 -1050
  53. package/lib/commands/context.ts +176 -174
  54. package/lib/commands/core.ts +309 -309
  55. package/lib/commands/doi.ts +435 -435
  56. package/lib/commands/file-ops.ts +372 -372
  57. package/lib/commands/history.ts +320 -320
  58. package/lib/commands/index.ts +87 -87
  59. package/lib/commands/init.ts +259 -259
  60. package/lib/commands/merge-resolve.ts +378 -378
  61. package/lib/commands/preview.ts +178 -178
  62. package/lib/commands/project-info.ts +244 -244
  63. package/lib/commands/quality.ts +517 -517
  64. package/lib/commands/response.ts +454 -454
  65. package/lib/commands/section-boundaries.ts +82 -82
  66. package/lib/commands/sections.ts +451 -451
  67. package/lib/commands/sync.ts +709 -706
  68. package/lib/commands/text-ops.ts +449 -449
  69. package/lib/commands/utilities.ts +448 -448
  70. package/lib/commands/verify-anchors.ts +272 -272
  71. package/lib/commands/word-tools.ts +340 -340
  72. package/lib/comment-realign.ts +517 -517
  73. package/lib/config.ts +84 -84
  74. package/lib/crossref.ts +781 -781
  75. package/lib/csl.ts +191 -191
  76. package/lib/dependencies.ts +98 -98
  77. package/lib/diff-engine.ts +465 -465
  78. package/lib/doi-cache.ts +115 -115
  79. package/lib/doi.ts +897 -897
  80. package/lib/equations.ts +506 -506
  81. package/lib/errors.ts +346 -346
  82. package/lib/format.ts +541 -541
  83. package/lib/git.ts +326 -326
  84. package/lib/grammar.ts +303 -303
  85. package/lib/image-registry.ts +180 -180
  86. package/lib/import.ts +911 -911
  87. package/lib/journals.ts +543 -543
  88. package/lib/macro-filter.lua +201 -201
  89. package/lib/macros.ts +273 -273
  90. package/lib/merge.ts +633 -633
  91. package/lib/orcid.ts +144 -144
  92. package/lib/pdf-comments.ts +263 -263
  93. package/lib/pdf-import.ts +524 -524
  94. package/lib/plugins.ts +362 -362
  95. package/lib/postprocess.ts +188 -188
  96. package/lib/pptx-color-filter.lua +37 -37
  97. package/lib/pptx-template.ts +469 -469
  98. package/lib/pptx-themes.ts +483 -483
  99. package/lib/protect-restore.ts +520 -520
  100. package/lib/rate-limiter.ts +94 -94
  101. package/lib/response.ts +197 -197
  102. package/lib/restore-references.ts +240 -240
  103. package/lib/review.ts +327 -327
  104. package/lib/schema.ts +488 -488
  105. package/lib/scientific-words.ts +73 -73
  106. package/lib/sections.ts +425 -335
  107. package/lib/slides.ts +756 -756
  108. package/lib/spelling.ts +334 -334
  109. package/lib/templates.ts +526 -526
  110. package/lib/themes.ts +742 -742
  111. package/lib/trackchanges.ts +247 -247
  112. package/lib/tui.ts +450 -450
  113. package/lib/types.ts +550 -550
  114. package/lib/undo.ts +250 -250
  115. package/lib/utils.ts +69 -69
  116. package/lib/variables.ts +179 -179
  117. package/lib/word-extraction.ts +806 -806
  118. package/lib/word.ts +643 -643
  119. package/lib/wordcomments.ts +840 -840
  120. package/mkdocs.yml +64 -64
  121. package/package.json +137 -137
  122. package/scripts/postbuild.js +47 -47
  123. package/skill/REFERENCE.md +539 -539
  124. package/skill/SKILL.md +295 -295
  125. package/tsconfig.json +26 -26
  126. package/types/index.d.ts +525 -525
@@ -1,469 +1,469 @@
1
- /**
2
- * PPTX post-processing
3
- *
4
- * Pure TypeScript implementation using AdmZip for in-memory ZIP/PPTX manipulation.
5
- * No Python dependency required.
6
- */
7
-
8
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
- import { join } from 'node:path';
10
- import AdmZip from 'adm-zip';
11
-
12
- interface ThemeFonts {
13
- major?: string;
14
- minor?: string;
15
- }
16
-
17
- interface Theme {
18
- fonts?: ThemeFonts;
19
- }
20
-
21
- interface TemplateOptions {
22
- baseTemplate: string;
23
- outputPath: string;
24
- }
25
-
26
- interface BuildupConfig {
27
- default?: string;
28
- title?: string;
29
- grey?: string;
30
- accent?: string;
31
- enabled?: boolean;
32
- }
33
-
34
- // =============================================================================
35
- // Shared Helpers
36
- // =============================================================================
37
-
38
- function getSlideEntries(zip: AdmZip) {
39
- return zip.getEntries()
40
- .filter(e => /^ppt\/slides\/slide\d+\.xml$/.test(e.entryName))
41
- .sort((a, b) => {
42
- const na = parseInt(a.entryName.match(/slide(\d+)/)?.[1] || '0');
43
- const nb = parseInt(b.entryName.match(/slide(\d+)/)?.[1] || '0');
44
- return na - nb;
45
- });
46
- }
47
-
48
- function readEntry(zip: AdmZip, name: string): string {
49
- return zip.getEntry(name)?.getData().toString('utf-8') ?? '';
50
- }
51
-
52
- function updateEntry(zip: AdmZip, name: string, content: string): void {
53
- zip.updateFile(name, Buffer.from(content, 'utf-8'));
54
- }
55
-
56
- function findMaxId(xml: string): number {
57
- const ids = [...xml.matchAll(/id="(\d+)"/g)].map(m => parseInt(m[1]));
58
- return ids.length ? Math.max(...ids) : 0;
59
- }
60
-
61
- function findMaxRId(xml: string): number {
62
- const rids = [...xml.matchAll(/Id="rId(\d+)"/g)].map(m => parseInt(m[1]));
63
- return rids.length ? Math.max(...rids) : 0;
64
- }
65
-
66
- // =============================================================================
67
- // 1. Apply Theme Fonts
68
- // =============================================================================
69
-
70
- /**
71
- * Apply theme fonts to all text in a PPTX.
72
- * Pandoc generates slides with hardcoded fonts; this replaces them with theme font references.
73
- */
74
- export async function applyThemeFonts(pptxPath: string, theme: Theme): Promise<void> {
75
- if (!existsSync(pptxPath) || !theme || !theme.fonts) return;
76
-
77
- const { major, minor } = theme.fonts;
78
- if (!major && !minor) return;
79
-
80
- const zip = new AdmZip(pptxPath);
81
- const defaultFonts = ['Calibri', 'Arial', 'Helvetica', 'Times New Roman', 'Cambria'];
82
-
83
- for (const entry of getSlideEntries(zip)) {
84
- let text = entry.getData().toString('utf-8');
85
- for (const font of defaultFonts) {
86
- text = text.replace(
87
- new RegExp(`(<a:latin\\s+typeface=")${font}(")`, 'g'),
88
- '$1+mn-lt$2'
89
- );
90
- }
91
- updateEntry(zip, entry.entryName, text);
92
- }
93
-
94
- zip.writeZip(pptxPath);
95
- }
96
-
97
- // =============================================================================
98
- // 2. Apply Centering
99
- // =============================================================================
100
-
101
- /**
102
- * Apply horizontal centering to slides that have the .center class.
103
- */
104
- export async function applyCentering(pptxPath: string, centeredSlideIndices: number[]): Promise<void> {
105
- if (!existsSync(pptxPath) || !centeredSlideIndices || centeredSlideIndices.length === 0) return;
106
-
107
- const zip = new AdmZip(pptxPath);
108
- const centeredFiles = new Set(centeredSlideIndices.map(i => `ppt/slides/slide${i}.xml`));
109
-
110
- for (const entry of getSlideEntries(zip)) {
111
- if (!centeredFiles.has(entry.entryName)) continue;
112
-
113
- let text = entry.getData().toString('utf-8');
114
-
115
- // Process each shape separately to skip footer and slide number
116
- text = text.replace(/<p:sp>.*?<\/p:sp>/gs, (shape) => {
117
- // Skip footer and slide number placeholders
118
- if (shape.includes('type="sldNum"') || shape.includes('type="ftr"')) {
119
- return shape;
120
- }
121
-
122
- // Add algn="ctr" to existing <a:pPr> elements
123
- shape = shape.replace(
124
- /(<a:pPr)((?:[^/>]|\/(?!>))*)(\s*\/?>)/g,
125
- (_match: string, before: string, attrs: string, closing: string) => {
126
- attrs = attrs.trimEnd();
127
- let isSelfClosing = closing.includes('/');
128
-
129
- if (attrs.endsWith('/')) {
130
- attrs = attrs.slice(0, -1).trimEnd();
131
- isSelfClosing = true;
132
- }
133
-
134
- if (!attrs.includes('algn=')) {
135
- attrs += ' algn="ctr"';
136
- } else {
137
- attrs = attrs.replace(/algn="[^"]*"/, 'algn="ctr"');
138
- }
139
-
140
- return before + attrs + (isSelfClosing ? ' />' : '>');
141
- }
142
- );
143
-
144
- // Add <a:pPr algn="ctr"/> to paragraphs without pPr
145
- shape = shape.replace(/(<a:p>)(<a:r>)/g, '$1<a:pPr algn="ctr"/>$2');
146
-
147
- return shape;
148
- });
149
-
150
- updateEntry(zip, entry.entryName, text);
151
- }
152
-
153
- zip.writeZip(pptxPath);
154
- }
155
-
156
- // =============================================================================
157
- // 3. Inject Slide Numbers
158
- // =============================================================================
159
-
160
- function getSlideNumXml(maxId: number, num: number): string {
161
- return `<p:sp><p:nvSpPr><p:cNvPr id="${maxId}" name="Slide Number Placeholder ${maxId}"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="8610600" y="6581838"/><a:ext cx="2743200" cy="319024"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1600"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-GB" sz="1600" dirty="0"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:rPr><a:t>${num}</a:t></a:r></a:p></p:txBody></p:sp>`;
162
- }
163
-
164
- function isContentSlide(text: string): boolean {
165
- const hasFooter = text.includes('type="ftr"');
166
- const hasBody = text.includes('idx="1"') || text.includes('type="body"');
167
- return hasFooter && hasBody;
168
- }
169
-
170
- /**
171
- * Inject slide numbers into content slides of a PPTX.
172
- * Only adds numbers to slides that have a footer and body placeholder.
173
- * Title, section, and cover slides are skipped.
174
- */
175
- export async function injectSlideNumbers(pptxPath: string): Promise<void> {
176
- if (!existsSync(pptxPath)) return;
177
-
178
- const zip = new AdmZip(pptxPath);
179
- const slides = getSlideEntries(zip);
180
-
181
- // Pass 1: identify content slides and assign sequential numbers
182
- const slideNumbers = new Map<string, number>();
183
- let contentNum = 1;
184
-
185
- for (const entry of slides) {
186
- const text = entry.getData().toString('utf-8');
187
- if (isContentSlide(text) && !text.includes('type="sldNum"')) {
188
- slideNumbers.set(entry.entryName, contentNum);
189
- contentNum++;
190
- }
191
- }
192
-
193
- // Pass 2: inject numbers
194
- for (const entry of slides) {
195
- const num = slideNumbers.get(entry.entryName);
196
- if (num === undefined) continue;
197
-
198
- let text = entry.getData().toString('utf-8');
199
- const maxId = findMaxId(text) + 1;
200
- const slideNumXml = getSlideNumXml(maxId, num);
201
- text = text.replace('</p:spTree>', slideNumXml + '</p:spTree>');
202
- updateEntry(zip, entry.entryName, text);
203
- }
204
-
205
- zip.writeZip(pptxPath);
206
- }
207
-
208
- // =============================================================================
209
- // 4. Inject Logos Into Slides
210
- // =============================================================================
211
-
212
- /**
213
- * Inject logos into cover slide of a PPTX (matching ref.pptx style).
214
- */
215
- export async function injectLogosIntoSlides(pptxPath: string, mediaDir: string | null): Promise<void> {
216
- if (!mediaDir || !existsSync(mediaDir) || !existsSync(pptxPath)) return;
217
-
218
- const logoLeftPath = join(mediaDir, 'logo-left.png');
219
- const logoRightPath = join(mediaDir, 'logo-right.png');
220
- const hasLeft = existsSync(logoLeftPath);
221
- const hasRight = existsSync(logoRightPath);
222
-
223
- if (!hasLeft && !hasRight) return;
224
-
225
- const zip = new AdmZip(pptxPath);
226
-
227
- // Find next available image number
228
- let maxImgNum = 0;
229
- for (const entry of zip.getEntries()) {
230
- const m = entry.entryName.match(/^ppt\/media\/image(\d+)\./);
231
- if (m) maxImgNum = Math.max(maxImgNum, parseInt(m[1]));
232
- }
233
- const nextImg = maxImgNum + 1;
234
-
235
- const rightImgName = hasRight ? `ppt/media/image${nextImg}.png` : null;
236
- const leftImgName = hasLeft ? `ppt/media/image${nextImg + 1}.png` : null;
237
-
238
- // Update [Content_Types].xml to include png if needed
239
- const contentTypesXml = readEntry(zip, '[Content_Types].xml');
240
- if (contentTypesXml && !contentTypesXml.includes('Extension="png"')) {
241
- updateEntry(zip, '[Content_Types].xml',
242
- contentTypesXml.replace('</Types>', '<Default Extension="png" ContentType="image/png"/></Types>')
243
- );
244
- }
245
-
246
- // Update slide1.xml.rels to add image relationships
247
- let rightRid: string | null = null;
248
- let leftRid: string | null = null;
249
- const relsName = 'ppt/slides/_rels/slide1.xml.rels';
250
- let relsXml = readEntry(zip, relsName);
251
-
252
- if (relsXml) {
253
- let maxRid = findMaxRId(relsXml);
254
- const newRels: string[] = [];
255
-
256
- if (hasRight) {
257
- maxRid++;
258
- rightRid = `rId${maxRid}`;
259
- newRels.push(`<Relationship Id="${rightRid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image${nextImg}.png"/>`);
260
- }
261
-
262
- if (hasLeft) {
263
- maxRid++;
264
- leftRid = `rId${maxRid}`;
265
- newRels.push(`<Relationship Id="${leftRid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image${nextImg + 1}.png"/>`);
266
- }
267
-
268
- if (newRels.length > 0) {
269
- relsXml = relsXml.replace('</Relationships>', newRels.join('') + '</Relationships>');
270
- updateEntry(zip, relsName, relsXml);
271
- }
272
- }
273
-
274
- // Update slide1.xml to add picture elements
275
- let slide1Xml = readEntry(zip, 'ppt/slides/slide1.xml');
276
- if (slide1Xml) {
277
- let maxId = findMaxId(slide1Xml);
278
- const pics: string[] = [];
279
-
280
- if (hasRight && rightRid) {
281
- maxId++;
282
- pics.push(`<p:pic><p:nvPicPr><p:cNvPr id="${maxId}" name="Picture ${maxId}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="${rightRid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm><a:off x="9492000" y="5742001"/><a:ext cx="2700000" cy="1115999"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`);
283
- }
284
-
285
- if (hasLeft && leftRid) {
286
- maxId++;
287
- pics.push(`<p:pic><p:nvPicPr><p:cNvPr id="${maxId}" name="Picture ${maxId}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="${leftRid}"/><a:srcRect t="22495" b="27262"/><a:stretch/></p:blipFill><p:spPr><a:xfrm><a:off x="0" y="5904608"/><a:ext cx="3794408" cy="954349"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`);
288
- }
289
-
290
- if (pics.length > 0) {
291
- slide1Xml = slide1Xml.replace('</p:spTree>', pics.join('') + '</p:spTree>');
292
- updateEntry(zip, 'ppt/slides/slide1.xml', slide1Xml);
293
- }
294
- }
295
-
296
- // Add logo image files
297
- if (hasRight && rightImgName) {
298
- zip.addFile(rightImgName, readFileSync(logoRightPath));
299
- }
300
- if (hasLeft && leftImgName) {
301
- zip.addFile(leftImgName, readFileSync(logoLeftPath));
302
- }
303
-
304
- zip.writeZip(pptxPath);
305
- }
306
-
307
- // =============================================================================
308
- // 5. Apply Buildup Colors
309
- // =============================================================================
310
-
311
- function applyColorToPara(para: string, color: string): string {
312
- const fill = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`;
313
-
314
- // Replace bare <a:rPr/> with colored version
315
- let result = para.replace(/<a:rPr\s*\/>/g, `<a:rPr>${fill}</a:rPr>`);
316
-
317
- // Replace <a:rPr attrs/> (self-closing with attributes) with colored version
318
- result = result.replace(/<a:rPr\s+([^>]+?)\s*\/>/g, (_: string, attrs: string) => {
319
- return `<a:rPr ${attrs.trim()}>${fill}</a:rPr>`;
320
- });
321
-
322
- return result;
323
- }
324
-
325
- function isBuildupSlide(xml: string): boolean {
326
- return xml.includes('animEffect') || xml.includes('<a:bldLst>');
327
- }
328
-
329
- function getBulletParagraphs(body: string): {
330
- bulletIndices: number[];
331
- paras: { start: number; end: number; text: string }[];
332
- } {
333
- const paraRegex = /<a:p>.*?<\/a:p>/gs;
334
- const paras: { start: number; end: number; text: string }[] = [];
335
- let m: RegExpExecArray | null;
336
- while ((m = paraRegex.exec(body)) !== null) {
337
- paras.push({ start: m.index, end: m.index + m[0].length, text: m[0] });
338
- }
339
-
340
- const bulletIndices: number[] = [];
341
- for (let i = 0; i < paras.length; i++) {
342
- const paraText = paras[i].text;
343
- if (paraText.includes('lvl="0"') && !paraText.includes('<a:buNone')) {
344
- bulletIndices.push(i);
345
- }
346
- }
347
-
348
- return { bulletIndices, paras };
349
- }
350
-
351
- function colorContentPlaceholder(
352
- xml: string,
353
- defaultColor: string,
354
- greyColor: string,
355
- accentColor: string
356
- ): string {
357
- const pattern = /(<p:sp>.*?<p:ph idx="1"[^/]*\/?>.*?<p:txBody>)(.*?)(<\/p:txBody>.*?<\/p:sp>)/s;
358
- const match = pattern.exec(xml);
359
-
360
- if (!match) return xml;
361
-
362
- const beforeBody = match[1];
363
- const body = match[2];
364
- const afterBody = match[3];
365
-
366
- const { bulletIndices, paras } = getBulletParagraphs(body);
367
- const isBuildup = isBuildupSlide(xml);
368
-
369
- let newBody = body;
370
- let offset = 0;
371
-
372
- for (let i = 0; i < paras.length; i++) {
373
- const para = paras[i];
374
- const start = para.start + offset;
375
- const end = para.end + offset;
376
- const paraText = para.text;
377
-
378
- let color: string;
379
- if (bulletIndices.includes(i) && isBuildup) {
380
- color = (i === bulletIndices[bulletIndices.length - 1]) ? accentColor : greyColor;
381
- } else {
382
- color = defaultColor;
383
- }
384
-
385
- const newPara = applyColorToPara(paraText, color);
386
- newBody = newBody.slice(0, start) + newPara + newBody.slice(end);
387
- offset += newPara.length - paraText.length;
388
- }
389
-
390
- return xml.slice(0, match.index) + beforeBody + newBody + afterBody + xml.slice(match.index + match[0].length);
391
- }
392
-
393
- function colorTitlePlaceholder(xml: string, titleColor: string): string {
394
- const pattern = /(<p:sp>.*?<p:ph[^>]*type="(?:title|ctrTitle)"[^/]*\/?>.*?<p:txBody>)(.*?)(<\/p:txBody>.*?<\/p:sp>)/s;
395
- const match = pattern.exec(xml);
396
-
397
- if (!match) return xml;
398
-
399
- const beforeBody = match[1];
400
- const body = match[2];
401
- const afterBody = match[3];
402
-
403
- const paraRegex = /<a:p>.*?<\/a:p>/gs;
404
- const paras: { start: number; end: number; text: string }[] = [];
405
- let m: RegExpExecArray | null;
406
- while ((m = paraRegex.exec(body)) !== null) {
407
- paras.push({ start: m.index, end: m.index + m[0].length, text: m[0] });
408
- }
409
-
410
- let newBody = body;
411
- let offset = 0;
412
-
413
- for (const para of paras) {
414
- const start = para.start + offset;
415
- const end = para.end + offset;
416
- const newPara = applyColorToPara(para.text, titleColor);
417
- newBody = newBody.slice(0, start) + newPara + newBody.slice(end);
418
- offset += newPara.length - para.text.length;
419
- }
420
-
421
- return xml.slice(0, match.index) + beforeBody + newBody + afterBody + xml.slice(match.index + match[0].length);
422
- }
423
-
424
- /**
425
- * Apply buildup greying to slides with buildup content.
426
- * Greys out all bullet items except the last one, which gets the accent color.
427
- * Only affects actual bullet items (not intro text with buNone).
428
- */
429
- export async function applyBuildupColors(pptxPath: string, config: BuildupConfig = {}): Promise<void> {
430
- if (!existsSync(pptxPath)) return;
431
- if (config.enabled === false) return;
432
-
433
- const defaultColor = (config.default || '608C32').replace(/^#/, '');
434
- const titleColor = (config.title || defaultColor).replace(/^#/, '');
435
- const greyColor = (config.grey || '888888').replace(/^#/, '');
436
- const accentColor = (config.accent || defaultColor).replace(/^#/, '');
437
-
438
- const zip = new AdmZip(pptxPath);
439
-
440
- for (const entry of getSlideEntries(zip)) {
441
- let text = entry.getData().toString('utf-8');
442
- text = colorContentPlaceholder(text, defaultColor, greyColor, accentColor);
443
- text = colorTitlePlaceholder(text, titleColor);
444
- updateEntry(zip, entry.entryName, text);
445
- }
446
-
447
- zip.writeZip(pptxPath);
448
- }
449
-
450
- // =============================================================================
451
- // Legacy Exports (signatures preserved for build.ts compatibility)
452
- // =============================================================================
453
-
454
- export async function generatePptxTemplate(options: TemplateOptions): Promise<string | null> {
455
- const { baseTemplate, outputPath } = options;
456
- if (baseTemplate && existsSync(baseTemplate)) {
457
- writeFileSync(outputPath, readFileSync(baseTemplate));
458
- return outputPath;
459
- }
460
- return null;
461
- }
462
-
463
- export function templateNeedsRegeneration(templatePath: string, mediaDir: string, baseTemplate: string): boolean {
464
- return false;
465
- }
466
-
467
- export async function injectMediaIntoPptx(pptxPath: string, mediaDir: string): Promise<void> {
468
- return injectLogosIntoSlides(pptxPath, mediaDir);
469
- }
1
+ /**
2
+ * PPTX post-processing
3
+ *
4
+ * Pure TypeScript implementation using AdmZip for in-memory ZIP/PPTX manipulation.
5
+ * No Python dependency required.
6
+ */
7
+
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import AdmZip from 'adm-zip';
11
+
12
+ interface ThemeFonts {
13
+ major?: string;
14
+ minor?: string;
15
+ }
16
+
17
+ interface Theme {
18
+ fonts?: ThemeFonts;
19
+ }
20
+
21
+ interface TemplateOptions {
22
+ baseTemplate: string;
23
+ outputPath: string;
24
+ }
25
+
26
+ interface BuildupConfig {
27
+ default?: string;
28
+ title?: string;
29
+ grey?: string;
30
+ accent?: string;
31
+ enabled?: boolean;
32
+ }
33
+
34
+ // =============================================================================
35
+ // Shared Helpers
36
+ // =============================================================================
37
+
38
+ function getSlideEntries(zip: AdmZip) {
39
+ return zip.getEntries()
40
+ .filter(e => /^ppt\/slides\/slide\d+\.xml$/.test(e.entryName))
41
+ .sort((a, b) => {
42
+ const na = parseInt(a.entryName.match(/slide(\d+)/)?.[1] || '0');
43
+ const nb = parseInt(b.entryName.match(/slide(\d+)/)?.[1] || '0');
44
+ return na - nb;
45
+ });
46
+ }
47
+
48
+ function readEntry(zip: AdmZip, name: string): string {
49
+ return zip.getEntry(name)?.getData().toString('utf-8') ?? '';
50
+ }
51
+
52
+ function updateEntry(zip: AdmZip, name: string, content: string): void {
53
+ zip.updateFile(name, Buffer.from(content, 'utf-8'));
54
+ }
55
+
56
+ function findMaxId(xml: string): number {
57
+ const ids = [...xml.matchAll(/id="(\d+)"/g)].map(m => parseInt(m[1]));
58
+ return ids.length ? Math.max(...ids) : 0;
59
+ }
60
+
61
+ function findMaxRId(xml: string): number {
62
+ const rids = [...xml.matchAll(/Id="rId(\d+)"/g)].map(m => parseInt(m[1]));
63
+ return rids.length ? Math.max(...rids) : 0;
64
+ }
65
+
66
+ // =============================================================================
67
+ // 1. Apply Theme Fonts
68
+ // =============================================================================
69
+
70
+ /**
71
+ * Apply theme fonts to all text in a PPTX.
72
+ * Pandoc generates slides with hardcoded fonts; this replaces them with theme font references.
73
+ */
74
+ export async function applyThemeFonts(pptxPath: string, theme: Theme): Promise<void> {
75
+ if (!existsSync(pptxPath) || !theme || !theme.fonts) return;
76
+
77
+ const { major, minor } = theme.fonts;
78
+ if (!major && !minor) return;
79
+
80
+ const zip = new AdmZip(pptxPath);
81
+ const defaultFonts = ['Calibri', 'Arial', 'Helvetica', 'Times New Roman', 'Cambria'];
82
+
83
+ for (const entry of getSlideEntries(zip)) {
84
+ let text = entry.getData().toString('utf-8');
85
+ for (const font of defaultFonts) {
86
+ text = text.replace(
87
+ new RegExp(`(<a:latin\\s+typeface=")${font}(")`, 'g'),
88
+ '$1+mn-lt$2'
89
+ );
90
+ }
91
+ updateEntry(zip, entry.entryName, text);
92
+ }
93
+
94
+ zip.writeZip(pptxPath);
95
+ }
96
+
97
+ // =============================================================================
98
+ // 2. Apply Centering
99
+ // =============================================================================
100
+
101
+ /**
102
+ * Apply horizontal centering to slides that have the .center class.
103
+ */
104
+ export async function applyCentering(pptxPath: string, centeredSlideIndices: number[]): Promise<void> {
105
+ if (!existsSync(pptxPath) || !centeredSlideIndices || centeredSlideIndices.length === 0) return;
106
+
107
+ const zip = new AdmZip(pptxPath);
108
+ const centeredFiles = new Set(centeredSlideIndices.map(i => `ppt/slides/slide${i}.xml`));
109
+
110
+ for (const entry of getSlideEntries(zip)) {
111
+ if (!centeredFiles.has(entry.entryName)) continue;
112
+
113
+ let text = entry.getData().toString('utf-8');
114
+
115
+ // Process each shape separately to skip footer and slide number
116
+ text = text.replace(/<p:sp>.*?<\/p:sp>/gs, (shape) => {
117
+ // Skip footer and slide number placeholders
118
+ if (shape.includes('type="sldNum"') || shape.includes('type="ftr"')) {
119
+ return shape;
120
+ }
121
+
122
+ // Add algn="ctr" to existing <a:pPr> elements
123
+ shape = shape.replace(
124
+ /(<a:pPr)((?:[^/>]|\/(?!>))*)(\s*\/?>)/g,
125
+ (_match: string, before: string, attrs: string, closing: string) => {
126
+ attrs = attrs.trimEnd();
127
+ let isSelfClosing = closing.includes('/');
128
+
129
+ if (attrs.endsWith('/')) {
130
+ attrs = attrs.slice(0, -1).trimEnd();
131
+ isSelfClosing = true;
132
+ }
133
+
134
+ if (!attrs.includes('algn=')) {
135
+ attrs += ' algn="ctr"';
136
+ } else {
137
+ attrs = attrs.replace(/algn="[^"]*"/, 'algn="ctr"');
138
+ }
139
+
140
+ return before + attrs + (isSelfClosing ? ' />' : '>');
141
+ }
142
+ );
143
+
144
+ // Add <a:pPr algn="ctr"/> to paragraphs without pPr
145
+ shape = shape.replace(/(<a:p>)(<a:r>)/g, '$1<a:pPr algn="ctr"/>$2');
146
+
147
+ return shape;
148
+ });
149
+
150
+ updateEntry(zip, entry.entryName, text);
151
+ }
152
+
153
+ zip.writeZip(pptxPath);
154
+ }
155
+
156
+ // =============================================================================
157
+ // 3. Inject Slide Numbers
158
+ // =============================================================================
159
+
160
+ function getSlideNumXml(maxId: number, num: number): string {
161
+ return `<p:sp><p:nvSpPr><p:cNvPr id="${maxId}" name="Slide Number Placeholder ${maxId}"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="8610600" y="6581838"/><a:ext cx="2743200" cy="319024"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1600"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:r><a:rPr lang="en-GB" sz="1600" dirty="0"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:rPr><a:t>${num}</a:t></a:r></a:p></p:txBody></p:sp>`;
162
+ }
163
+
164
+ function isContentSlide(text: string): boolean {
165
+ const hasFooter = text.includes('type="ftr"');
166
+ const hasBody = text.includes('idx="1"') || text.includes('type="body"');
167
+ return hasFooter && hasBody;
168
+ }
169
+
170
+ /**
171
+ * Inject slide numbers into content slides of a PPTX.
172
+ * Only adds numbers to slides that have a footer and body placeholder.
173
+ * Title, section, and cover slides are skipped.
174
+ */
175
+ export async function injectSlideNumbers(pptxPath: string): Promise<void> {
176
+ if (!existsSync(pptxPath)) return;
177
+
178
+ const zip = new AdmZip(pptxPath);
179
+ const slides = getSlideEntries(zip);
180
+
181
+ // Pass 1: identify content slides and assign sequential numbers
182
+ const slideNumbers = new Map<string, number>();
183
+ let contentNum = 1;
184
+
185
+ for (const entry of slides) {
186
+ const text = entry.getData().toString('utf-8');
187
+ if (isContentSlide(text) && !text.includes('type="sldNum"')) {
188
+ slideNumbers.set(entry.entryName, contentNum);
189
+ contentNum++;
190
+ }
191
+ }
192
+
193
+ // Pass 2: inject numbers
194
+ for (const entry of slides) {
195
+ const num = slideNumbers.get(entry.entryName);
196
+ if (num === undefined) continue;
197
+
198
+ let text = entry.getData().toString('utf-8');
199
+ const maxId = findMaxId(text) + 1;
200
+ const slideNumXml = getSlideNumXml(maxId, num);
201
+ text = text.replace('</p:spTree>', slideNumXml + '</p:spTree>');
202
+ updateEntry(zip, entry.entryName, text);
203
+ }
204
+
205
+ zip.writeZip(pptxPath);
206
+ }
207
+
208
+ // =============================================================================
209
+ // 4. Inject Logos Into Slides
210
+ // =============================================================================
211
+
212
+ /**
213
+ * Inject logos into cover slide of a PPTX (matching ref.pptx style).
214
+ */
215
+ export async function injectLogosIntoSlides(pptxPath: string, mediaDir: string | null): Promise<void> {
216
+ if (!mediaDir || !existsSync(mediaDir) || !existsSync(pptxPath)) return;
217
+
218
+ const logoLeftPath = join(mediaDir, 'logo-left.png');
219
+ const logoRightPath = join(mediaDir, 'logo-right.png');
220
+ const hasLeft = existsSync(logoLeftPath);
221
+ const hasRight = existsSync(logoRightPath);
222
+
223
+ if (!hasLeft && !hasRight) return;
224
+
225
+ const zip = new AdmZip(pptxPath);
226
+
227
+ // Find next available image number
228
+ let maxImgNum = 0;
229
+ for (const entry of zip.getEntries()) {
230
+ const m = entry.entryName.match(/^ppt\/media\/image(\d+)\./);
231
+ if (m) maxImgNum = Math.max(maxImgNum, parseInt(m[1]));
232
+ }
233
+ const nextImg = maxImgNum + 1;
234
+
235
+ const rightImgName = hasRight ? `ppt/media/image${nextImg}.png` : null;
236
+ const leftImgName = hasLeft ? `ppt/media/image${nextImg + 1}.png` : null;
237
+
238
+ // Update [Content_Types].xml to include png if needed
239
+ const contentTypesXml = readEntry(zip, '[Content_Types].xml');
240
+ if (contentTypesXml && !contentTypesXml.includes('Extension="png"')) {
241
+ updateEntry(zip, '[Content_Types].xml',
242
+ contentTypesXml.replace('</Types>', '<Default Extension="png" ContentType="image/png"/></Types>')
243
+ );
244
+ }
245
+
246
+ // Update slide1.xml.rels to add image relationships
247
+ let rightRid: string | null = null;
248
+ let leftRid: string | null = null;
249
+ const relsName = 'ppt/slides/_rels/slide1.xml.rels';
250
+ let relsXml = readEntry(zip, relsName);
251
+
252
+ if (relsXml) {
253
+ let maxRid = findMaxRId(relsXml);
254
+ const newRels: string[] = [];
255
+
256
+ if (hasRight) {
257
+ maxRid++;
258
+ rightRid = `rId${maxRid}`;
259
+ newRels.push(`<Relationship Id="${rightRid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image${nextImg}.png"/>`);
260
+ }
261
+
262
+ if (hasLeft) {
263
+ maxRid++;
264
+ leftRid = `rId${maxRid}`;
265
+ newRels.push(`<Relationship Id="${leftRid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image${nextImg + 1}.png"/>`);
266
+ }
267
+
268
+ if (newRels.length > 0) {
269
+ relsXml = relsXml.replace('</Relationships>', newRels.join('') + '</Relationships>');
270
+ updateEntry(zip, relsName, relsXml);
271
+ }
272
+ }
273
+
274
+ // Update slide1.xml to add picture elements
275
+ let slide1Xml = readEntry(zip, 'ppt/slides/slide1.xml');
276
+ if (slide1Xml) {
277
+ let maxId = findMaxId(slide1Xml);
278
+ const pics: string[] = [];
279
+
280
+ if (hasRight && rightRid) {
281
+ maxId++;
282
+ pics.push(`<p:pic><p:nvPicPr><p:cNvPr id="${maxId}" name="Picture ${maxId}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="${rightRid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm><a:off x="9492000" y="5742001"/><a:ext cx="2700000" cy="1115999"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`);
283
+ }
284
+
285
+ if (hasLeft && leftRid) {
286
+ maxId++;
287
+ pics.push(`<p:pic><p:nvPicPr><p:cNvPr id="${maxId}" name="Picture ${maxId}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="${leftRid}"/><a:srcRect t="22495" b="27262"/><a:stretch/></p:blipFill><p:spPr><a:xfrm><a:off x="0" y="5904608"/><a:ext cx="3794408" cy="954349"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`);
288
+ }
289
+
290
+ if (pics.length > 0) {
291
+ slide1Xml = slide1Xml.replace('</p:spTree>', pics.join('') + '</p:spTree>');
292
+ updateEntry(zip, 'ppt/slides/slide1.xml', slide1Xml);
293
+ }
294
+ }
295
+
296
+ // Add logo image files
297
+ if (hasRight && rightImgName) {
298
+ zip.addFile(rightImgName, readFileSync(logoRightPath));
299
+ }
300
+ if (hasLeft && leftImgName) {
301
+ zip.addFile(leftImgName, readFileSync(logoLeftPath));
302
+ }
303
+
304
+ zip.writeZip(pptxPath);
305
+ }
306
+
307
+ // =============================================================================
308
+ // 5. Apply Buildup Colors
309
+ // =============================================================================
310
+
311
+ function applyColorToPara(para: string, color: string): string {
312
+ const fill = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`;
313
+
314
+ // Replace bare <a:rPr/> with colored version
315
+ let result = para.replace(/<a:rPr\s*\/>/g, `<a:rPr>${fill}</a:rPr>`);
316
+
317
+ // Replace <a:rPr attrs/> (self-closing with attributes) with colored version
318
+ result = result.replace(/<a:rPr\s+([^>]+?)\s*\/>/g, (_: string, attrs: string) => {
319
+ return `<a:rPr ${attrs.trim()}>${fill}</a:rPr>`;
320
+ });
321
+
322
+ return result;
323
+ }
324
+
325
+ function isBuildupSlide(xml: string): boolean {
326
+ return xml.includes('animEffect') || xml.includes('<a:bldLst>');
327
+ }
328
+
329
+ function getBulletParagraphs(body: string): {
330
+ bulletIndices: number[];
331
+ paras: { start: number; end: number; text: string }[];
332
+ } {
333
+ const paraRegex = /<a:p>.*?<\/a:p>/gs;
334
+ const paras: { start: number; end: number; text: string }[] = [];
335
+ let m: RegExpExecArray | null;
336
+ while ((m = paraRegex.exec(body)) !== null) {
337
+ paras.push({ start: m.index, end: m.index + m[0].length, text: m[0] });
338
+ }
339
+
340
+ const bulletIndices: number[] = [];
341
+ for (let i = 0; i < paras.length; i++) {
342
+ const paraText = paras[i].text;
343
+ if (paraText.includes('lvl="0"') && !paraText.includes('<a:buNone')) {
344
+ bulletIndices.push(i);
345
+ }
346
+ }
347
+
348
+ return { bulletIndices, paras };
349
+ }
350
+
351
+ function colorContentPlaceholder(
352
+ xml: string,
353
+ defaultColor: string,
354
+ greyColor: string,
355
+ accentColor: string
356
+ ): string {
357
+ const pattern = /(<p:sp>.*?<p:ph idx="1"[^/]*\/?>.*?<p:txBody>)(.*?)(<\/p:txBody>.*?<\/p:sp>)/s;
358
+ const match = pattern.exec(xml);
359
+
360
+ if (!match) return xml;
361
+
362
+ const beforeBody = match[1];
363
+ const body = match[2];
364
+ const afterBody = match[3];
365
+
366
+ const { bulletIndices, paras } = getBulletParagraphs(body);
367
+ const isBuildup = isBuildupSlide(xml);
368
+
369
+ let newBody = body;
370
+ let offset = 0;
371
+
372
+ for (let i = 0; i < paras.length; i++) {
373
+ const para = paras[i];
374
+ const start = para.start + offset;
375
+ const end = para.end + offset;
376
+ const paraText = para.text;
377
+
378
+ let color: string;
379
+ if (bulletIndices.includes(i) && isBuildup) {
380
+ color = (i === bulletIndices[bulletIndices.length - 1]) ? accentColor : greyColor;
381
+ } else {
382
+ color = defaultColor;
383
+ }
384
+
385
+ const newPara = applyColorToPara(paraText, color);
386
+ newBody = newBody.slice(0, start) + newPara + newBody.slice(end);
387
+ offset += newPara.length - paraText.length;
388
+ }
389
+
390
+ return xml.slice(0, match.index) + beforeBody + newBody + afterBody + xml.slice(match.index + match[0].length);
391
+ }
392
+
393
+ function colorTitlePlaceholder(xml: string, titleColor: string): string {
394
+ const pattern = /(<p:sp>.*?<p:ph[^>]*type="(?:title|ctrTitle)"[^/]*\/?>.*?<p:txBody>)(.*?)(<\/p:txBody>.*?<\/p:sp>)/s;
395
+ const match = pattern.exec(xml);
396
+
397
+ if (!match) return xml;
398
+
399
+ const beforeBody = match[1];
400
+ const body = match[2];
401
+ const afterBody = match[3];
402
+
403
+ const paraRegex = /<a:p>.*?<\/a:p>/gs;
404
+ const paras: { start: number; end: number; text: string }[] = [];
405
+ let m: RegExpExecArray | null;
406
+ while ((m = paraRegex.exec(body)) !== null) {
407
+ paras.push({ start: m.index, end: m.index + m[0].length, text: m[0] });
408
+ }
409
+
410
+ let newBody = body;
411
+ let offset = 0;
412
+
413
+ for (const para of paras) {
414
+ const start = para.start + offset;
415
+ const end = para.end + offset;
416
+ const newPara = applyColorToPara(para.text, titleColor);
417
+ newBody = newBody.slice(0, start) + newPara + newBody.slice(end);
418
+ offset += newPara.length - para.text.length;
419
+ }
420
+
421
+ return xml.slice(0, match.index) + beforeBody + newBody + afterBody + xml.slice(match.index + match[0].length);
422
+ }
423
+
424
+ /**
425
+ * Apply buildup greying to slides with buildup content.
426
+ * Greys out all bullet items except the last one, which gets the accent color.
427
+ * Only affects actual bullet items (not intro text with buNone).
428
+ */
429
+ export async function applyBuildupColors(pptxPath: string, config: BuildupConfig = {}): Promise<void> {
430
+ if (!existsSync(pptxPath)) return;
431
+ if (config.enabled === false) return;
432
+
433
+ const defaultColor = (config.default || '608C32').replace(/^#/, '');
434
+ const titleColor = (config.title || defaultColor).replace(/^#/, '');
435
+ const greyColor = (config.grey || '888888').replace(/^#/, '');
436
+ const accentColor = (config.accent || defaultColor).replace(/^#/, '');
437
+
438
+ const zip = new AdmZip(pptxPath);
439
+
440
+ for (const entry of getSlideEntries(zip)) {
441
+ let text = entry.getData().toString('utf-8');
442
+ text = colorContentPlaceholder(text, defaultColor, greyColor, accentColor);
443
+ text = colorTitlePlaceholder(text, titleColor);
444
+ updateEntry(zip, entry.entryName, text);
445
+ }
446
+
447
+ zip.writeZip(pptxPath);
448
+ }
449
+
450
+ // =============================================================================
451
+ // Legacy Exports (signatures preserved for build.ts compatibility)
452
+ // =============================================================================
453
+
454
+ export async function generatePptxTemplate(options: TemplateOptions): Promise<string | null> {
455
+ const { baseTemplate, outputPath } = options;
456
+ if (baseTemplate && existsSync(baseTemplate)) {
457
+ writeFileSync(outputPath, readFileSync(baseTemplate));
458
+ return outputPath;
459
+ }
460
+ return null;
461
+ }
462
+
463
+ export function templateNeedsRegeneration(templatePath: string, mediaDir: string, baseTemplate: string): boolean {
464
+ return false;
465
+ }
466
+
467
+ export async function injectMediaIntoPptx(pptxPath: string, mediaDir: string): Promise<void> {
468
+ return injectLogosIntoSlides(pptxPath, mediaDir);
469
+ }