markdown-to-word 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ import { Buffer } from 'buffer';
2
+ /** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */
3
+ export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
4
+ /**
5
+ * The most distinct image URLs fetched for one document: html-to-docx keeps
6
+ * at most this many in its image cache (imageProcessing.maxCacheEntries). The
7
+ * rest keep their alt text.
8
+ */
9
+ export const MAX_IMAGES = 100;
10
+ /**
11
+ * How many downloads run at once. html-to-docx fetched one at a time; a few
12
+ * in parallel is faster without opening a connection per image.
13
+ */
14
+ export const CONCURRENCY = 4;
15
+ /** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */
16
+ const TIMEOUT_MS = 5000;
17
+ const ATTEMPTS = 2;
18
+ /**
19
+ * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag
20
+ * that makes `test()` stateful), anchored so the whole `src` is the URL.
21
+ * Requiring both means this module never fetches what it wouldn't.
22
+ */
23
+ const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
24
+ const WEB_URL = /^https?:\/\//i;
25
+ /** Leading bytes of the image formats Word embeds, for servers that don't say. */
26
+ const SIGNATURES = [
27
+ ['image/png', [0x89, 0x50, 0x4e, 0x47]],
28
+ ['image/jpeg', [0xff, 0xd8, 0xff]],
29
+ ['image/gif', [0x47, 0x49, 0x46, 0x38]],
30
+ ['image/bmp', [0x42, 0x4d]],
31
+ ];
32
+ /**
33
+ * Downloads each web image in `html` and swaps its `src` for a `data:` URI,
34
+ * which html-to-docx embeds without downloading it again. An image that can't
35
+ * be fetched becomes its alt text, linked to its URL, where html-to-docx would
36
+ * drop it without a trace. Other sources it can't embed either, such as a
37
+ * relative path, keep their alt text too.
38
+ *
39
+ * Each URL is fetched once, however many times it appears: at most
40
+ * MAX_IMAGES of them, CONCURRENCY at a time.
41
+ */
42
+ export async function embedImages(html) {
43
+ const dom = new DOMParser().parseFromString(html, 'text/html');
44
+ const images = Array.from(dom.querySelectorAll('img'));
45
+ if (images.length === 0)
46
+ return html;
47
+ const urls = new Set();
48
+ for (const image of images) {
49
+ const src = image.getAttribute('src') ?? '';
50
+ if (isFetchable(src) && urls.size < MAX_IMAGES)
51
+ urls.add(src);
52
+ }
53
+ const queue = Array.from(urls);
54
+ const downloads = new Map();
55
+ const worker = async () => {
56
+ for (let url = queue.shift(); url !== undefined; url = queue.shift()) {
57
+ downloads.set(url, await fetchImage(url));
58
+ }
59
+ };
60
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
61
+ for (const image of images) {
62
+ const src = image.getAttribute('src') ?? '';
63
+ if (src.startsWith('data:'))
64
+ continue;
65
+ const dataUri = downloads.get(src);
66
+ if (dataUri) {
67
+ image.setAttribute('src', dataUri);
68
+ }
69
+ else {
70
+ replaceWithAltText(image, src);
71
+ }
72
+ }
73
+ return dom.body.innerHTML;
74
+ }
75
+ function isFetchable(src) {
76
+ return WEB_URL.test(src) && GENERATOR_URL.test(src);
77
+ }
78
+ /** The image at `url` as a `data:` URI, or null if it can't be fetched. */
79
+ async function fetchImage(url) {
80
+ for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
81
+ const tooLarge = new AbortController();
82
+ try {
83
+ const response = await fetch(url, {
84
+ signal: AbortSignal.any([
85
+ tooLarge.signal,
86
+ AbortSignal.timeout(TIMEOUT_MS * attempt),
87
+ ]),
88
+ });
89
+ // Not found, forbidden or too large won't change on a retry.
90
+ if (!response.ok)
91
+ return null;
92
+ if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {
93
+ tooLarge.abort();
94
+ return null;
95
+ }
96
+ const bytes = await readBody(response, tooLarge);
97
+ if (!bytes || bytes.length === 0)
98
+ return null;
99
+ const type = imageType(response.headers.get('content-type'), bytes);
100
+ if (!type)
101
+ return null;
102
+ return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;
103
+ }
104
+ catch {
105
+ if (tooLarge.signal.aborted)
106
+ return null;
107
+ // Offline, blocked by CORS or the CSP, or timed out: try once more.
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ /**
113
+ * The response body, read a chunk at a time so a server that sends more than
114
+ * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather
115
+ * than held in memory. Null if it was too large.
116
+ */
117
+ async function readBody(response, tooLarge) {
118
+ if (!response.body) {
119
+ const bytes = new Uint8Array(await response.arrayBuffer());
120
+ return bytes.length > MAX_IMAGE_BYTES ? null : bytes;
121
+ }
122
+ const reader = response.body.getReader();
123
+ const chunks = [];
124
+ let total = 0;
125
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
126
+ total += chunk.value.length;
127
+ if (total > MAX_IMAGE_BYTES) {
128
+ tooLarge.abort();
129
+ await reader.cancel().catch(() => { });
130
+ return null;
131
+ }
132
+ chunks.push(chunk.value);
133
+ }
134
+ const bytes = new Uint8Array(total);
135
+ let offset = 0;
136
+ for (const chunk of chunks) {
137
+ bytes.set(chunk, offset);
138
+ offset += chunk.length;
139
+ }
140
+ return bytes;
141
+ }
142
+ /**
143
+ * The image's media type: the server's, if it says it's an image, or else
144
+ * read from the file's first bytes. Null for anything else (an error page
145
+ * served with 200, say), which html-to-docx would fail to measure and drop.
146
+ */
147
+ function imageType(contentType, bytes) {
148
+ const declared = contentType?.split(';')[0].trim().toLowerCase();
149
+ if (declared?.startsWith('image/'))
150
+ return declared;
151
+ const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
152
+ return match?.[0] ?? null;
153
+ }
154
+ /**
155
+ * Puts the image's alt text where it was, as a link to `src` when that's a web
156
+ * URL and the image isn't already inside a link. With no alt text, the URL
157
+ * itself is the text.
158
+ */
159
+ function replaceWithAltText(image, src) {
160
+ const document = image.ownerDocument;
161
+ const isWebUrl = WEB_URL.test(src);
162
+ const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');
163
+ if (!text) {
164
+ image.remove();
165
+ return;
166
+ }
167
+ if (!isWebUrl || image.closest('a')) {
168
+ image.replaceWith(document.createTextNode(text));
169
+ return;
170
+ }
171
+ const link = document.createElement('a');
172
+ link.setAttribute('href', src);
173
+ link.textContent = text;
174
+ image.replaceWith(link);
175
+ }
176
+ //# sourceMappingURL=docx-images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE7B,iFAAiF;AACjF,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,QAAQ,GAAG,CAAC,CAAC;AAEnB;;;;GAIG;AACH,MAAM,aAAa,GACjB,+EAA+E,CAAC;AAClF,MAAM,OAAO,GAAG,eAAe,CAAC;AAEhC,kFAAkF;AAClF,MAAM,UAAU,GAAyB;IACvC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,WA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GAAG,KAAK,CAAC,aAAa,CAAC;IACrC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,MAAM,IAAI,GAAG,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACxE,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,KAAK,CAAC,MAAM,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/** Leading bytes of the image formats Word embeds, for servers that don't say. */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (src.startsWith('data:')) continue;\n const dataUri = downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type: the server's, if it says it's an image, or else\n * read from the file's first bytes. Null for anything else (an error page\n * served with 200, say), which html-to-docx would fail to measure and drop.\n */\nfunction imageType(\n contentType: string | null,\n bytes: Uint8Array\n): string | null {\n const declared = contentType?.split(';')[0].trim().toLowerCase();\n if (declared?.startsWith('image/')) return declared;\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n return match?.[0] ?? null;\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
@@ -16,6 +16,9 @@ export interface DocumentStructure {
16
16
  * it at the top of each page the table spans.
17
17
  * - Table grids: the generator writes a second `<w:tblGrid>` between rows,
18
18
  * which the schema doesn't allow; only the first is kept.
19
+ * - Section properties: the generator writes the body's `<w:sectPr>` (page
20
+ * size and margins) as its first child. The schema requires it last, and
21
+ * strict readers ignore it elsewhere, so it's moved to the end.
19
22
  */
20
23
  export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
21
24
  /** Exported for testing. */
@@ -12,6 +12,9 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
12
12
  * it at the top of each page the table spans.
13
13
  * - Table grids: the generator writes a second `<w:tblGrid>` between rows,
14
14
  * which the schema doesn't allow; only the first is kept.
15
+ * - Section properties: the generator writes the body's `<w:sectPr>` (page
16
+ * size and margins) as its first child. The schema requires it last, and
17
+ * strict readers ignore it elsewhere, so it's moved to the end.
15
18
  */
16
19
  export async function patchStructure(wordDocument, structure) {
17
20
  const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
@@ -56,6 +59,12 @@ export function patchDocumentXml(documentXml, structure) {
56
59
  changed = true;
57
60
  }
58
61
  }
62
+ const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];
63
+ const sectPr = body && children(body, 'sectPr')[0];
64
+ if (sectPr && body.lastElementChild !== sectPr) {
65
+ body.appendChild(sectPr);
66
+ changed = true;
67
+ }
59
68
  if (!changed) {
60
69
  return documentXml;
61
70
  }
@@ -66,7 +75,7 @@ function isRulePlaceholder(paragraph) {
66
75
  .map((t) => t.textContent ?? '')
67
76
  .join('');
68
77
  const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];
69
- return text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center';
78
+ return (text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center');
70
79
  }
71
80
  /** Replaces the paragraph's content with nothing but a bottom border. */
72
81
  function drawRule(paragraph) {
@@ -1 +1 @@
1
- {"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,YAAkB,EAClB,SAA4B;IAE5B,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACpF,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,SAAS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AC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error('Cannot patch structure: document contains no word/document.xml');\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n if (patched === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(documentXml: string, structure: DocumentStructure): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center';\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(document.createElementNS(W_NS, 'w:trPr'), row.firstChild);\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
1
+ {"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,YAAkB,EAClB,SAA4B;IAE5B,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACzD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;QAC5B,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,IAAI,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC,EAAE;QAClE,IAAI,EAAE,YAAY,CAAC,IAAI;KACxB,CAA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AAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n if (patched === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
@@ -14,14 +14,41 @@ export interface LevelStyle {
14
14
  /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */
15
15
  sizePt: number;
16
16
  bold: boolean;
17
+ /** Centers the paragraph, without the first-line indent. */
18
+ centered?: boolean;
17
19
  }
18
- /** Word line spacing rule. The presets only need single spacing so far. */
19
- export type LineSpacing = 'single';
20
+ /**
21
+ * Word line spacing rule:
22
+ *
23
+ * - `single`: single line spacing.
24
+ * - `grid`: exact line spacing at the line pitch of the page's document grid,
25
+ * with widow control off, so every full page holds `page.grid.linesPerPage`
26
+ * lines. Needs `page.grid`.
27
+ */
28
+ export type LineSpacing = 'single' | 'grid';
20
29
  export interface ParagraphStyle {
21
30
  /** Paragraph spacing before and after, in points. */
22
31
  beforePt: number;
23
32
  afterPt: number;
24
33
  lineSpacing: LineSpacing;
34
+ /** First-line indent, in characters of the body font size. */
35
+ firstLineIndentChars?: number;
36
+ }
37
+ /** Paper and text block, in millimeters. */
38
+ export interface PageLayout {
39
+ widthMm: number;
40
+ heightMm: number;
41
+ marginsMm: {
42
+ top: number;
43
+ right: number;
44
+ bottom: number;
45
+ left: number;
46
+ };
47
+ /** Word's document grid (文档网格): a fixed number of lines and characters. */
48
+ grid?: {
49
+ linesPerPage: number;
50
+ charsPerLine: number;
51
+ };
25
52
  }
26
53
  export interface FontPreset {
27
54
  body: LevelStyle;
@@ -29,20 +56,34 @@ export interface FontPreset {
29
56
  headings: LevelStyle[];
30
57
  /** Shared by the body text and every heading level. */
31
58
  paragraph: ParagraphStyle;
59
+ /**
60
+ * Page size and margins. Margins passed to `convertMarkdownToWord` as
61
+ * `pageMargins` take precedence.
62
+ */
63
+ page?: PageLayout;
32
64
  }
33
65
  /**
34
- * Fonts and sizes for Chinese official documents (公文):
66
+ * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
35
67
  *
36
68
  * - Body: FangSong (仿宋), size 3
37
- * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2
69
+ * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)
38
70
  * - Heading 2: SimHei (黑体), size 3
39
71
  * - Heading 3: KaiTi (楷体), size 3
40
- * - Heading 4 and below: bold FangSong, size 3
72
+ * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in
73
+ * plain 仿宋, but a bolded fourth level is how these documents are made.
74
+ * - Heading 5 and below: FangSong, size 3, not bold.
75
+ * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text
76
+ * block (5.1, 5.2.1)
77
+ * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact
78
+ * line spacing at its pitch
79
+ * - Paragraphs indented two characters (7.3.3), headings below the title too
41
80
  *
42
- * Every level uses Times New Roman for Latin text, no space before or after
43
- * paragraphs, and single line spacing.
81
+ * Every level uses Times New Roman for Latin text and no space before or after
82
+ * paragraphs. The standard names no Latin font; Times New Roman is common
83
+ * practice.
44
84
  */
45
85
  export declare const CHINESE_OFFICIAL_DOC_FONTS: FontPreset;
86
+ export declare function mmToTwips(mm: number): number;
46
87
  /** The presets offered in the UI, keyed by the value of their `<option>`. */
47
88
  export declare const FONT_PRESETS: Record<string, FontPreset>;
48
89
  /**
@@ -5,29 +5,65 @@ const SIZE_ER = 22;
5
5
  /** Chinese size 3 (三号). */
6
6
  const SIZE_SAN = 16;
7
7
  /**
8
- * Fonts and sizes for Chinese official documents (公文):
8
+ * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
9
9
  *
10
10
  * - Body: FangSong (仿宋), size 3
11
- * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2
11
+ * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)
12
12
  * - Heading 2: SimHei (黑体), size 3
13
13
  * - Heading 3: KaiTi (楷体), size 3
14
- * - Heading 4 and below: bold FangSong, size 3
14
+ * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in
15
+ * plain 仿宋, but a bolded fourth level is how these documents are made.
16
+ * - Heading 5 and below: FangSong, size 3, not bold.
17
+ * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text
18
+ * block (5.1, 5.2.1)
19
+ * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact
20
+ * line spacing at its pitch
21
+ * - Paragraphs indented two characters (7.3.3), headings below the title too
15
22
  *
16
- * Every level uses Times New Roman for Latin text, no space before or after
17
- * paragraphs, and single line spacing.
23
+ * Every level uses Times New Roman for Latin text and no space before or after
24
+ * paragraphs. The standard names no Latin font; Times New Roman is common
25
+ * practice.
18
26
  */
19
27
  export const CHINESE_OFFICIAL_DOC_FONTS = {
20
- body: { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
28
+ body: {
29
+ latin: LATIN_FONT,
30
+ eastAsia: BODY_FONT,
31
+ sizePt: SIZE_SAN,
32
+ bold: false,
33
+ },
21
34
  headings: [
22
- { latin: LATIN_FONT, eastAsia: '方正小标宋简体', sizePt: SIZE_ER, bold: false },
35
+ {
36
+ latin: LATIN_FONT,
37
+ eastAsia: '方正小标宋简体',
38
+ sizePt: SIZE_ER,
39
+ bold: false,
40
+ centered: true,
41
+ },
23
42
  { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },
24
43
  { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },
25
44
  { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
26
- { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
27
- { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },
45
+ { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
46
+ { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },
28
47
  ],
29
- paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'single' },
48
+ paragraph: {
49
+ beforePt: 0,
50
+ afterPt: 0,
51
+ lineSpacing: 'grid',
52
+ firstLineIndentChars: 2,
53
+ },
54
+ page: {
55
+ widthMm: 210,
56
+ heightMm: 297,
57
+ // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.
58
+ marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },
59
+ grid: { linesPerPage: 22, charsPerLine: 28 },
60
+ },
30
61
  };
62
+ /** Twips (1/20 point) per millimeter. */
63
+ const TWIPS_PER_MM = 1440 / 25.4;
64
+ export function mmToTwips(mm) {
65
+ return Math.round(mm * TWIPS_PER_MM);
66
+ }
31
67
  /** The presets offered in the UI, keyed by the value of their `<option>`. */
32
68
  export const FONT_PRESETS = {
33
69
  'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,
@@ -1 +1 @@
1
- {"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AAoCA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC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,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAEnF,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n}\n\n/** Word line spacing rule. The presets only need single spacing so far. */\nexport type LineSpacing = 'single';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Fonts and sizes for Chinese official documents (公文):\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1: FZXiaoBiaoSong (方正小标宋简体), size 2\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4 and below: bold FangSong, size 3\n *\n * Every level uses Times New Roman for Latin text, no space before or after\n * paragraphs, and single line spacing.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n headings: [\n { latin: LATIN_FONT, eastAsia: '方正小标宋简体', sizePt: SIZE_ER, bold: false },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n ],\n paragraph: { beforePt: 0, afterPt: 0, lineSpacing: 'single' },\n};\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana = text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
1
+ {"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AA6DA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,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MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;QACvD,IAAI,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE;KAC7C;CACF,CAAC;AAEF,yCAAyC;AACzC,MAAM,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;AAEjC,MAAM,UAAU,SAAS,CAAC,EAAU;IAClC,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,YAAY,CAAC,CAAC;AACvC,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,kBAAkB,EAAE,0BAA0B;CAC/C,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GACR,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAExE,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n /** Centers the paragraph, without the first-line indent. */\n centered?: boolean;\n}\n\n/**\n * Word line spacing rule:\n *\n * - `single`: single line spacing.\n * - `grid`: exact line spacing at the line pitch of the page's document grid,\n * with widow control off, so every full page holds `page.grid.linesPerPage`\n * lines. Needs `page.grid`.\n */\nexport type LineSpacing = 'single' | 'grid';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n /** First-line indent, in characters of the body font size. */\n firstLineIndentChars?: number;\n}\n\n/** Paper and text block, in millimeters. */\nexport interface PageLayout {\n widthMm: number;\n heightMm: number;\n marginsMm: { top: number; right: number; bottom: number; left: number };\n /** Word's document grid (文档网格): a fixed number of lines and characters. */\n grid?: { linesPerPage: number; charsPerLine: number };\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n /**\n * Page size and margins. Margins passed to `convertMarkdownToWord` as\n * `pageMargins` take precedence.\n */\n page?: PageLayout;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in\n * plain 仿宋, but a bolded fourth level is how these documents are made.\n * - Heading 5 and below: FangSong, size 3, not bold.\n * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text\n * block (5.1, 5.2.1)\n * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact\n * line spacing at its pitch\n * - Paragraphs indented two characters (7.3.3), headings below the title too\n *\n * Every level uses Times New Roman for Latin text and no space before or after\n * paragraphs. The standard names no Latin font; Times New Roman is common\n * practice.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: {\n latin: LATIN_FONT,\n eastAsia: BODY_FONT,\n sizePt: SIZE_SAN,\n bold: false,\n },\n headings: [\n {\n latin: LATIN_FONT,\n eastAsia: '方正小标宋简体',\n sizePt: SIZE_ER,\n bold: false,\n centered: true,\n },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n ],\n paragraph: {\n beforePt: 0,\n afterPt: 0,\n lineSpacing: 'grid',\n firstLineIndentChars: 2,\n },\n page: {\n widthMm: 210,\n heightMm: 297,\n // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.\n marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },\n grid: { linesPerPage: 22, charsPerLine: 28 },\n },\n};\n\n/** Twips (1/20 point) per millimeter. */\nconst TWIPS_PER_MM = 1440 / 25.4;\n\nexport function mmToTwips(mm: number): number {\n return Math.round(mm * TWIPS_PER_MM);\n}\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana =\n text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
package/build/main.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { convertMarkdownToWord, type ConversionOptions } from './converter.js';
2
2
  export { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';
3
- export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type ParagraphStyle, } from './font-presets.js';
3
+ export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type PageLayout, type ParagraphStyle, } from './font-presets.js';
package/build/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,YAAY,GAKb,MAAM,mBAAmB,CAAC","sourcesContent":["// The npm package's entry: the converter without the browser UI (index.ts).\n// Browsers and bundlers load this directly; Node loads node.ts, which supplies\n// the DOM APIs the converter needs first.\nexport { convertMarkdownToWord, type ConversionOptions } from './converter.js';\nexport { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';\nexport {\n CHINESE_OFFICIAL_DOC_FONTS,\n FONT_PRESETS,\n type FontPreset,\n type LevelStyle,\n type LineSpacing,\n type ParagraphStyle,\n} from './font-presets.js';\n"]}
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,YAAY,GAMb,MAAM,mBAAmB,CAAC","sourcesContent":["// The npm package's entry: the converter without the browser UI (index.ts).\n// Browsers and bundlers load this directly; Node loads node.ts, which supplies\n// the DOM APIs the converter needs first.\nexport { convertMarkdownToWord, type ConversionOptions } from './converter.js';\nexport { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';\nexport {\n CHINESE_OFFICIAL_DOC_FONTS,\n FONT_PRESETS,\n type FontPreset,\n type LevelStyle,\n type LineSpacing,\n type PageLayout,\n type ParagraphStyle,\n} from './font-presets.js';\n"]}
@@ -1,5 +1,6 @@
1
1
  import DOMPurify from 'dompurify';
2
2
  import { Marked } from 'marked';
3
+ import markedFootnote from 'marked-footnote';
3
4
  // Our own instance, not marked's shared default: as an npm package, configuring
4
5
  // that one would change how the consumer's own copy of marked renders.
5
6
  // GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,
@@ -11,11 +12,28 @@ marked.use({
11
12
  renderer: {
12
13
  code({ text, lang }) {
13
14
  const language = lang?.match(/^\S*/)?.[0];
14
- const className = language ? ` class="language-${escapeHtml(language)}"` : '';
15
+ const className = language
16
+ ? ` class="language-${escapeHtml(language)}"`
17
+ : '';
15
18
  return `<pre><code${className}>${escapeHtml(text)}</code></pre>\n`;
16
19
  },
17
20
  },
18
21
  });
22
+ // GitHub's `[^1]` footnotes: numbered superscript references, and the notes in
23
+ // a list after a rule at the end, much as GitHub shows them. prepareHtmlForDocx
24
+ // drops the parts that only work on a web page (the in-page links).
25
+ marked.use(markedFootnote({ footnoteDivider: true }));
26
+ /**
27
+ * extractTitle only lexes, and marked-footnote resets its per-document state
28
+ * while rendering, so lexing with `marked` would number the next document's
29
+ * footnotes wrong or throw. Titles get their own instance without it.
30
+ */
31
+ const titleLexer = new Marked({ gfm: true });
32
+ /**
33
+ * A `[^label]` footnote reference, which titleLexer leaves as text, or reads
34
+ * as a reference-style link when the note is defined.
35
+ */
36
+ const FOOTNOTE_REFERENCE = /\[\^[^\]\s]+\]/g;
19
37
  /**
20
38
  * Parse markdown text and return HTML
21
39
  */
@@ -43,10 +61,12 @@ export function renderPreviewHtml(markdown) {
43
61
  * Returns null if no H1 heading is found.
44
62
  */
45
63
  export function extractTitle(markdown) {
46
- const tokens = marked.lexer(markdown);
64
+ const tokens = titleLexer.lexer(markdown);
47
65
  for (const token of tokens) {
48
66
  if (token.type === 'heading' && token.depth === 1) {
49
- return plainText(token.tokens ?? []).trim();
67
+ return plainText(token.tokens ?? [])
68
+ .replace(FOOTNOTE_REFERENCE, '')
69
+ .trim();
50
70
  }
51
71
  }
52
72
  return null;
@@ -55,6 +75,10 @@ export function extractTitle(markdown) {
55
75
  function plainText(tokens) {
56
76
  return tokens
57
77
  .map((token) => {
78
+ if (token.type === 'link' &&
79
+ token.raw.match(FOOTNOTE_REFERENCE)?.[0] === token.raw) {
80
+ return '';
81
+ }
58
82
  if ('tokens' in token && token.tokens)
59
83
  return plainText(token.tokens);
60
84
  if (token.type === 'br')
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-parser.js","sourceRoot":"","sources":["../src/markdown-parser.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAc,MAAM,QAAQ,CAAC;AAE5C,gFAAgF;AAChF,uEAAuE;AACvE,+EAA+E;AAC/E,wEAAwE;AACxE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;AAEzC,+EAA+E;AAC/E,oEAAoE;AACpE,MAAM,CAAC,GAAG,CAAC;IACT,QAAQ,EAAE;QACR,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE;YACjB,MAAM,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAA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AI,KAAK,IAAI,KAAK,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACtE,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI;YAAE,OAAO,GAAG,CAAC;QACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,EAAE,CAAC;QACrC,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3C,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,OAAO,CAAC,IAAY;IAClC,OAAO,IAAI;SACR,WAAW,EAAE;SACb,IAAI,EAAE;SACN,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,YAAY,GAA2B;IAC3C,GAAG,EAAE,OAAO;IACZ,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,QAAQ;IACb,GAAG,EAAE,OAAO;CACb,CAAC;AAEF,sFAAsF;AACtF,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import DOMPurify from 'dompurify';\nimport { Marked, type Token } from 'marked';\n\n// Our own instance, not marked's shared default: as an npm package, configuring\n// that one would change how the consumer's own copy of marked renders.\n// GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,\n// and a single newline inside a paragraph is a space, not a line break.\nconst marked = new Marked({ gfm: true });\n\n// marked's default code renderer keeps the block's trailing newline, which the\n// .docx code block patch would turn into a blank last line in Word.\nmarked.use({\n renderer: {\n code({ text, lang }) {\n const language = lang?.match(/^\\S*/)?.[0];\n const className = language ? ` class=\"language-${escapeHtml(language)}\"` : '';\n return `<pre><code${className}>${escapeHtml(text)}</code></pre>\\n`;\n },\n },\n});\n\n/**\n * Parse markdown text and return HTML\n */\nexport function parseMarkdownToHtml(markdown: string): string {\n try {\n return marked.parse(markdown) as string;\n } catch (error) {\n console.error('Markdown parsing error:', error);\n throw new Error('Failed to parse markdown content', { cause: error });\n }\n}\n\n/**\n * Parse markdown into HTML that is safe to put in the page with innerHTML.\n * marked passes raw HTML through, so a shared .md file could otherwise run\n * script (e.g. `<img src=x onerror=...>`). The .docx path doesn't need this,\n * since html-to-docx never executes the HTML.\n */\nexport function renderPreviewHtml(markdown: string): string {\n return DOMPurify.sanitize(parseMarkdownToHtml(markdown));\n}\n\n/**\n * Extract the first H1 heading from markdown content as plain text, without\n * inline markup, since it becomes the Word document's title.\n * Returns null if no H1 heading is found.\n */\nexport function extractTitle(markdown: string): string | null {\n const tokens = marked.lexer(markdown);\n for (const token of tokens) {\n if (token.type === 'heading' && token.depth === 1) {\n return plainText(token.tokens ?? []).trim();\n }\n }\n return null;\n}\n\n/** The text of inline tokens with their markup (emphasis, links, code) removed. */\nfunction plainText(tokens: Token[]): string {\n return tokens\n .map((token) => {\n if ('tokens' in token && token.tokens) return plainText(token.tokens);\n if (token.type === 'br') return ' ';\n if (token.type === 'html') return '';\n return 'text' in token ? token.text : '';\n })\n .join('');\n}\n\n/**\n * Convert a string into a URL/filename-safe slug.\n * Lowercases, replaces whitespace and underscores with hyphens,\n * strips characters that are not word characters (\\w), whitespace, or hyphens,\n * and collapses consecutive hyphens. Note that \\w includes [a-zA-Z0-9_] and\n * Unicode letters/digits, so accented characters are preserved.\n */\nexport function slugify(text: string): string {\n return text\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n};\n\n/** Escape text for HTML without needing a DOM, so parsing works outside a browser. */\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char]);\n}"]}
1
+ {"version":3,"file":"markdown-parser.js","sourceRoot":"","sources":["../src/markdown-parser.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAc,MAAM,QAAQ,CAAC;AAC5C,OAAO,cAAc,MAAM,iBAAiB,CAAC;AAE7C,gFAAgF;AAChF,uEAAuE;AACvE,+EAA+E;AAC/E,wEAAwE;AACxE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;AAEzC,+EAA+E;AAC/E,oEAAoE;AACpE,MAAM,CAAC,GAAG,CAAC;IACT,QAAQ,EAAE;QACR,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE;YACjB,MAAM,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC1C,MAAM,SAAS,GAAG,QAAQ;gBACxB,CAAC,CAAC,oBAAoB,UAAU,CAAC,QAAQ,CAAC,GAAG;gBAC7C,CAAC,CAAC,EAAE,CAAC;YACP,OAAO,aAAa,SAAS,IAAI,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC;QACrE,CAAC;KACF;CACF,CAAC,CAAC;AAEH,+EAA+E;AAC/E,gFAAgF;AAChF,oEAAoE;AACpE,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAEtD;;;;GAIG;AACH,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,EAAE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AC,CAAC,CAAC,KAAK,KAAK,CAAC,GAAG,EACtD,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,IAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACtE,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI;YAAE,OAAO,GAAG,CAAC;QACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,EAAE,CAAC;QACrC,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3C,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,OAAO,CAAC,IAAY;IAClC,OAAO,IAAI;SACR,WAAW,EAAE;SACb,IAAI,EAAE;SACN,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,YAAY,GAA2B;IAC3C,GAAG,EAAE,OAAO;IACZ,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,QAAQ;IACb,GAAG,EAAE,OAAO;CACb,CAAC;AAEF,sFAAsF;AACtF,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import DOMPurify from 'dompurify';\nimport { Marked, type Token } from 'marked';\nimport markedFootnote from 'marked-footnote';\n\n// Our own instance, not marked's shared default: as an npm package, configuring\n// that one would change how the consumer's own copy of marked renders.\n// GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,\n// and a single newline inside a paragraph is a space, not a line break.\nconst marked = new Marked({ gfm: true });\n\n// marked's default code renderer keeps the block's trailing newline, which the\n// .docx code block patch would turn into a blank last line in Word.\nmarked.use({\n renderer: {\n code({ text, lang }) {\n const language = lang?.match(/^\\S*/)?.[0];\n const className = language\n ? ` class=\"language-${escapeHtml(language)}\"`\n : '';\n return `<pre><code${className}>${escapeHtml(text)}</code></pre>\\n`;\n },\n },\n});\n\n// GitHub's `[^1]` footnotes: numbered superscript references, and the notes in\n// a list after a rule at the end, much as GitHub shows them. prepareHtmlForDocx\n// drops the parts that only work on a web page (the in-page links).\nmarked.use(markedFootnote({ footnoteDivider: true }));\n\n/**\n * extractTitle only lexes, and marked-footnote resets its per-document state\n * while rendering, so lexing with `marked` would number the next document's\n * footnotes wrong or throw. Titles get their own instance without it.\n */\nconst titleLexer = new Marked({ gfm: true });\n\n/**\n * A `[^label]` footnote reference, which titleLexer leaves as text, or reads\n * as a reference-style link when the note is defined.\n */\nconst FOOTNOTE_REFERENCE = /\\[\\^[^\\]\\s]+\\]/g;\n\n/**\n * Parse markdown text and return HTML\n */\nexport function parseMarkdownToHtml(markdown: string): string {\n try {\n return marked.parse(markdown) as string;\n } catch (error) {\n console.error('Markdown parsing error:', error);\n throw new Error('Failed to parse markdown content', { cause: error });\n }\n}\n\n/**\n * Parse markdown into HTML that is safe to put in the page with innerHTML.\n * marked passes raw HTML through, so a shared .md file could otherwise run\n * script (e.g. `<img src=x onerror=...>`). The .docx path doesn't need this,\n * since html-to-docx never executes the HTML.\n */\nexport function renderPreviewHtml(markdown: string): string {\n return DOMPurify.sanitize(parseMarkdownToHtml(markdown));\n}\n\n/**\n * Extract the first H1 heading from markdown content as plain text, without\n * inline markup, since it becomes the Word document's title.\n * Returns null if no H1 heading is found.\n */\nexport function extractTitle(markdown: string): string | null {\n const tokens = titleLexer.lexer(markdown);\n for (const token of tokens) {\n if (token.type === 'heading' && token.depth === 1) {\n return plainText(token.tokens ?? [])\n .replace(FOOTNOTE_REFERENCE, '')\n .trim();\n }\n }\n return null;\n}\n\n/** The text of inline tokens with their markup (emphasis, links, code) removed. */\nfunction plainText(tokens: Token[]): string {\n return tokens\n .map((token) => {\n if (\n token.type === 'link' &&\n token.raw.match(FOOTNOTE_REFERENCE)?.[0] === token.raw\n ) {\n return '';\n }\n if ('tokens' in token && token.tokens) return plainText(token.tokens);\n if (token.type === 'br') return ' ';\n if (token.type === 'html') return '';\n return 'text' in token ? token.text : '';\n })\n .join('');\n}\n\n/**\n * Convert a string into a URL/filename-safe slug.\n * Lowercases, replaces whitespace and underscores with hyphens,\n * strips characters that are not word characters (\\w), whitespace, or hyphens,\n * and collapses consecutive hyphens. Note that \\w includes [a-zA-Z0-9_] and\n * Unicode letters/digits, so accented characters are preserved.\n */\nexport function slugify(text: string): string {\n return text\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n};\n\n/** Escape text for HTML without needing a DOM, so parsing works outside a browser. */\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char]);\n}\n"]}
@@ -7,3 +7,8 @@ export declare const XML_NS = "http://www.w3.org/XML/1998/namespace";
7
7
  * copied back from the source.
8
8
  */
9
9
  export declare function keepXmlDeclaration(original: string, serialized: string): string;
10
+ /**
11
+ * The `localName` child of a `<w:pPr>`, created in schema order if missing.
12
+ * WinWord rejects paragraph properties that are out of order.
13
+ */
14
+ export declare function paragraphProperty(pPr: Element, localName: string): Element;