markdown-to-word 0.4.0 → 0.5.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.
@@ -22,19 +22,33 @@ const ATTEMPTS = 2;
22
22
  */
23
23
  const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
24
24
  const WEB_URL = /^https?:\/\//i;
25
- /** Leading bytes of the image formats Word embeds, for servers that don't say. */
25
+ /**
26
+ * Leading bytes of the bitmap formats Word embeds. An image is checked
27
+ * against them whatever its declared type: html-to-docx drops a file it can't
28
+ * read (with its alt text), and embeds a format Word can't show, such as
29
+ * HEIC, as a broken picture.
30
+ */
26
31
  const SIGNATURES = [
27
32
  ['image/png', [0x89, 0x50, 0x4e, 0x47]],
28
33
  ['image/jpeg', [0xff, 0xd8, 0xff]],
29
34
  ['image/gif', [0x47, 0x49, 0x46, 0x38]],
30
35
  ['image/bmp', [0x42, 0x4d]],
31
36
  ];
37
+ /** The other format Word embeds, recognized by its root element. */
38
+ const SVG_TYPE = 'image/svg+xml';
39
+ /** How far into a file to look for SVG_START. */
40
+ const SVG_SNIFF_BYTES = 4096;
41
+ /** `data:[type][;params][;base64],payload` */
42
+ const DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;
43
+ const PERCENT = 0x25;
32
44
  /**
33
45
  * Downloads each web image in `html` and swaps its `src` for a `data:` URI,
34
46
  * which html-to-docx embeds without downloading it again. An image that can't
35
47
  * be fetched becomes its alt text, linked to its URL, where html-to-docx would
36
48
  * drop it without a trace. Other sources it can't embed either, such as a
37
- * relative path, keep their alt text too.
49
+ * relative path, keep their alt text too. So does a `data:` URI that isn't a
50
+ * PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of
51
+ * the type its bytes show, which is the form html-to-docx reads.
38
52
  *
39
53
  * Each URL is fetched once, however many times it appears: at most
40
54
  * MAX_IMAGES of them, CONCURRENCY at a time.
@@ -60,9 +74,9 @@ export async function embedImages(html) {
60
74
  await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
61
75
  for (const image of images) {
62
76
  const src = image.getAttribute('src') ?? '';
63
- if (src.startsWith('data:'))
64
- continue;
65
- const dataUri = downloads.get(src);
77
+ const dataUri = /^data:/i.test(src)
78
+ ? checkDataUri(src)
79
+ : downloads.get(src);
66
80
  if (dataUri) {
67
81
  image.setAttribute('src', dataUri);
68
82
  }
@@ -72,6 +86,73 @@ export async function embedImages(html) {
72
86
  }
73
87
  return dom.body.innerHTML;
74
88
  }
89
+ /**
90
+ * `src`, a `data:` URI, as base64 of the image type its bytes show, or null
91
+ * if it's malformed, too large, or not an image Word embeds.
92
+ */
93
+ function checkDataUri(src) {
94
+ const match = DATA_URI.exec(src);
95
+ if (!match)
96
+ return null;
97
+ const [, type, base64, payload] = match;
98
+ // At most four characters of payload make one byte (an escaped base64
99
+ // character, %2B, is a quarter of three bytes), so one this long decodes
100
+ // to more than the limit: turn it away before decoding allocates it.
101
+ if (payload.length > MAX_IMAGE_BYTES * 4 + 4)
102
+ return null;
103
+ let bytes;
104
+ try {
105
+ bytes = base64 ? base64Decode(payload) : percentDecode(payload);
106
+ }
107
+ catch {
108
+ return null;
109
+ }
110
+ if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {
111
+ return null;
112
+ }
113
+ const actual = imageType(type, bytes);
114
+ if (!actual)
115
+ return null;
116
+ return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;
117
+ }
118
+ /**
119
+ * The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded
120
+ * as a browser does (the fetch spec's forgiving-base64): percent-escapes and
121
+ * whitespace are allowed, any other stray character fails. `Buffer.from`
122
+ * alone skips stray characters, which would embed a corrupted picture.
123
+ */
124
+ function base64Decode(payload) {
125
+ let text = new TextDecoder().decode(percentDecode(payload));
126
+ text = text.replace(/[\t\n\f\r ]+/g, '');
127
+ if (text.length % 4 === 0)
128
+ text = text.replace(/={1,2}$/, '');
129
+ if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text))
130
+ return null;
131
+ return Buffer.from(text, 'base64');
132
+ }
133
+ /**
134
+ * The bytes of a URL-encoded `data:` payload. A `%` without two hex digits
135
+ * after it stays a `%`, as in a browser, so `width="100%"` in an SVG works.
136
+ */
137
+ function percentDecode(payload) {
138
+ // `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.
139
+ const encoded = new TextEncoder().encode(payload);
140
+ const bytes = new Uint8Array(encoded.length);
141
+ let length = 0;
142
+ for (let index = 0; index < encoded.length; index++) {
143
+ const hex = encoded[index] === PERCENT
144
+ ? String.fromCharCode(...encoded.subarray(index + 1, index + 3))
145
+ : '';
146
+ if (/^[0-9a-f]{2}$/i.test(hex)) {
147
+ bytes[length++] = parseInt(hex, 16);
148
+ index += 2;
149
+ }
150
+ else {
151
+ bytes[length++] = encoded[index];
152
+ }
153
+ }
154
+ return bytes.subarray(0, length);
155
+ }
75
156
  function isFetchable(src) {
76
157
  return WEB_URL.test(src) && GENERATOR_URL.test(src);
77
158
  }
@@ -140,16 +221,66 @@ async function readBody(response, tooLarge) {
140
221
  return bytes;
141
222
  }
142
223
  /**
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.
224
+ * The image's media type, read from its first bytes: PNG, JPEG, GIF or BMP,
225
+ * whatever `declared` says, or SVG if it says so (or names no image type)
226
+ * and the file starts like one. Null for anything else, such as an error
227
+ * page served with 200, or HEIC, which html-to-docx would embed but Word
228
+ * can't show.
146
229
  */
147
- function imageType(contentType, bytes) {
148
- const declared = contentType?.split(';')[0].trim().toLowerCase();
149
- if (declared?.startsWith('image/'))
150
- return declared;
230
+ function imageType(declared, bytes) {
151
231
  const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
152
- return match?.[0] ?? null;
232
+ if (match)
233
+ return match[0];
234
+ const type = declared?.split(';')[0].trim().toLowerCase() ?? '';
235
+ if (type !== SVG_TYPE && type.startsWith('image/'))
236
+ return null;
237
+ const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));
238
+ return startsWithSvg(head) ? SVG_TYPE : null;
239
+ }
240
+ /**
241
+ * Whether `text` is an SVG file: `<svg` first, after at most a byte-order
242
+ * mark, an XML declaration, comments and a doctype. Anchored, so an HTML page
243
+ * with an inline icon doesn't count. A scan rather than one regular
244
+ * expression, which backtracks exponentially on input like
245
+ * `<!----><!----><!--...` (a comment's end can also be read as part of a
246
+ * longer comment).
247
+ */
248
+ function startsWithSvg(text) {
249
+ let at = text.startsWith('\uFEFF') ? 1 : 0;
250
+ const skipSpace = () => {
251
+ while (at < text.length && /\s/.test(text[at]))
252
+ at++;
253
+ };
254
+ const startsHere = (prefix) => text.slice(at, at + prefix.length).toLowerCase() === prefix;
255
+ /** Moves past `end`, searching from `from`; false if it never comes. */
256
+ const skipPast = (end, from) => {
257
+ const index = text.indexOf(end, from);
258
+ if (index === -1)
259
+ return false;
260
+ at = index + end.length;
261
+ return true;
262
+ };
263
+ skipSpace();
264
+ if (startsHere('<?xml')) {
265
+ if (!skipPast('>', at))
266
+ return false;
267
+ skipSpace();
268
+ }
269
+ for (;;) {
270
+ if (startsHere('<!--')) {
271
+ if (!skipPast('-->', at + 4))
272
+ return false;
273
+ }
274
+ else if (startsHere('<!doctype')) {
275
+ if (!skipPast('>', at))
276
+ return false;
277
+ }
278
+ else {
279
+ break;
280
+ }
281
+ skipSpace();
282
+ }
283
+ return startsHere('<svg') && /[\s>]/.test(text[at + 4] ?? '');
153
284
  }
154
285
  /**
155
286
  * Puts the image's alt text where it was, as a link to `src` when that's a web
@@ -1 +1 @@
1
- {"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;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,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"]}
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;;;;;GAKG;AACH,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,oEAAoE;AACpE,MAAM,QAAQ,GAAG,eAAe,CAAC;AAEjC,iDAAiD;AACjD,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,8CAA8C;AAC9C,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AAEpD,MAAM,OAAO,GAAG,IAAI,CAAC;AAErB;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY;IAC5C,MAAM,GAAG,GAAG,IAAI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AK,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/**\n * Leading bytes of the bitmap formats Word embeds. An image is checked\n * against them whatever its declared type: html-to-docx drops a file it can't\n * read (with its alt text), and embeds a format Word can't show, such as\n * HEIC, as a broken picture.\n */\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/** The other format Word embeds, recognized by its root element. */\nconst SVG_TYPE = 'image/svg+xml';\n\n/** How far into a file to look for SVG_START. */\nconst SVG_SNIFF_BYTES = 4096;\n\n/** `data:[type][;params][;base64],payload` */\nconst DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;\n\nconst PERCENT = 0x25;\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. So does a `data:` URI that isn't a\n * PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of\n * the type its bytes show, which is the form html-to-docx reads.\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 const dataUri = /^data:/i.test(src)\n ? checkDataUri(src)\n : 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\n/**\n * `src`, a `data:` URI, as base64 of the image type its bytes show, or null\n * if it's malformed, too large, or not an image Word embeds.\n */\nfunction checkDataUri(src: string): string | null {\n const match = DATA_URI.exec(src);\n if (!match) return null;\n const [, type, base64, payload] = match;\n // At most four characters of payload make one byte (an escaped base64\n // character, %2B, is a quarter of three bytes), so one this long decodes\n // to more than the limit: turn it away before decoding allocates it.\n if (payload.length > MAX_IMAGE_BYTES * 4 + 4) return null;\n let bytes: Uint8Array | null;\n try {\n bytes = base64 ? base64Decode(payload) : percentDecode(payload);\n } catch {\n return null;\n }\n if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {\n return null;\n }\n const actual = imageType(type, bytes);\n if (!actual) return null;\n return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;\n}\n\n/**\n * The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded\n * as a browser does (the fetch spec's forgiving-base64): percent-escapes and\n * whitespace are allowed, any other stray character fails. `Buffer.from`\n * alone skips stray characters, which would embed a corrupted picture.\n */\nfunction base64Decode(payload: string): Uint8Array | null {\n let text = new TextDecoder().decode(percentDecode(payload));\n text = text.replace(/[\\t\\n\\f\\r ]+/g, '');\n if (text.length % 4 === 0) text = text.replace(/={1,2}$/, '');\n if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text)) return null;\n return Buffer.from(text, 'base64');\n}\n\n/**\n * The bytes of a URL-encoded `data:` payload. A `%` without two hex digits\n * after it stays a `%`, as in a browser, so `width=\"100%\"` in an SVG works.\n */\nfunction percentDecode(payload: string): Uint8Array {\n // `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.\n const encoded = new TextEncoder().encode(payload);\n const bytes = new Uint8Array(encoded.length);\n let length = 0;\n for (let index = 0; index < encoded.length; index++) {\n const hex =\n encoded[index] === PERCENT\n ? String.fromCharCode(...encoded.subarray(index + 1, index + 3))\n : '';\n if (/^[0-9a-f]{2}$/i.test(hex)) {\n bytes[length++] = parseInt(hex, 16);\n index += 2;\n } else {\n bytes[length++] = encoded[index];\n }\n }\n return bytes.subarray(0, length);\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, read from its first bytes: PNG, JPEG, GIF or BMP,\n * whatever `declared` says, or SVG if it says so (or names no image type)\n * and the file starts like one. Null for anything else, such as an error\n * page served with 200, or HEIC, which html-to-docx would embed but Word\n * can't show.\n */\nfunction imageType(declared: string | null, bytes: Uint8Array): string | null {\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n if (match) return match[0];\n const type = declared?.split(';')[0].trim().toLowerCase() ?? '';\n if (type !== SVG_TYPE && type.startsWith('image/')) return null;\n const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));\n return startsWithSvg(head) ? SVG_TYPE : null;\n}\n\n/**\n * Whether `text` is an SVG file: `<svg` first, after at most a byte-order\n * mark, an XML declaration, comments and a doctype. Anchored, so an HTML page\n * with an inline icon doesn't count. A scan rather than one regular\n * expression, which backtracks exponentially on input like\n * `<!----><!----><!--...` (a comment's end can also be read as part of a\n * longer comment).\n */\nfunction startsWithSvg(text: string): boolean {\n let at = text.startsWith('\\uFEFF') ? 1 : 0;\n const skipSpace = (): void => {\n while (at < text.length && /\\s/.test(text[at] as string)) at++;\n };\n const startsHere = (prefix: string): boolean =>\n text.slice(at, at + prefix.length).toLowerCase() === prefix;\n /** Moves past `end`, searching from `from`; false if it never comes. */\n const skipPast = (end: string, from: number): boolean => {\n const index = text.indexOf(end, from);\n if (index === -1) return false;\n at = index + end.length;\n return true;\n };\n\n skipSpace();\n if (startsHere('<?xml')) {\n if (!skipPast('>', at)) return false;\n skipSpace();\n }\n for (;;) {\n if (startsHere('<!--')) {\n if (!skipPast('-->', at + 4)) return false;\n } else if (startsHere('<!doctype')) {\n if (!skipPast('>', at)) return false;\n } else {\n break;\n }\n skipSpace();\n }\n return startsHere('<svg') && /[\\s>]/.test(text[at + 4] ?? '');\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"]}
@@ -19,7 +19,16 @@ export interface DocumentStructure {
19
19
  * - Section properties: the generator writes the body's `<w:sectPr>` (page
20
20
  * size and margins) as its first child. The schema requires it last, and
21
21
  * strict readers ignore it elsewhere, so it's moved to the end.
22
+ * - Image content types: the generator declares only JPEG, PNG and SVG in
23
+ * `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
24
+ * declared type, and Word offers to repair a file that lacks one, so each
25
+ * image extension in `word/media/` gets a `<Default>`.
22
26
  */
23
27
  export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
28
+ /**
29
+ * Adds a `<Default>` to `typesXml` for each image extension among `paths`
30
+ * under `word/media/` that it doesn't declare yet. Exported for testing.
31
+ */
32
+ export declare function patchContentTypes(typesXml: string, paths: string[]): string;
24
33
  /** Exported for testing. */
25
34
  export declare function patchDocumentXml(documentXml: string, structure: DocumentStructure): string;
@@ -1,6 +1,17 @@
1
1
  import JSZip from 'jszip';
2
2
  import { RULE_TEXT } from './docx-html.js';
3
3
  import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
4
+ const CONTENT_TYPES = '[Content_Types].xml';
5
+ const CONTENT_TYPES_NS = 'http://schemas.openxmlformats.org/package/2006/content-types';
6
+ /** The media type of each image extension html-to-docx can write. */
7
+ const IMAGE_CONTENT_TYPES = {
8
+ png: 'image/png',
9
+ jpeg: 'image/jpeg',
10
+ jpg: 'image/jpeg',
11
+ gif: 'image/gif',
12
+ bmp: 'image/bmp',
13
+ svg: 'image/svg+xml',
14
+ };
4
15
  /**
5
16
  * Restores structure the generator drops or gets wrong:
6
17
  *
@@ -15,6 +26,10 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
15
26
  * - Section properties: the generator writes the body's `<w:sectPr>` (page
16
27
  * size and margins) as its first child. The schema requires it last, and
17
28
  * strict readers ignore it elsewhere, so it's moved to the end.
29
+ * - Image content types: the generator declares only JPEG, PNG and SVG in
30
+ * `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
31
+ * declared type, and Word offers to repair a file that lacks one, so each
32
+ * image extension in `word/media/` gets a `<Default>`.
18
33
  */
19
34
  export async function patchStructure(wordDocument, structure) {
20
35
  const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
@@ -24,14 +39,49 @@ export async function patchStructure(wordDocument, structure) {
24
39
  }
25
40
  const documentXml = await documentEntry.async('string');
26
41
  const patched = patchDocumentXml(documentXml, structure);
27
- if (patched === documentXml) {
42
+ const typesEntry = zip.file(CONTENT_TYPES);
43
+ const typesXml = typesEntry ? await typesEntry.async('string') : null;
44
+ const patchedTypes = typesXml === null
45
+ ? null
46
+ : patchContentTypes(typesXml, Object.keys(zip.files));
47
+ if (patched === documentXml && patchedTypes === typesXml) {
28
48
  return wordDocument;
29
49
  }
30
50
  zip.file('word/document.xml', patched);
51
+ if (patchedTypes !== null)
52
+ zip.file(CONTENT_TYPES, patchedTypes);
31
53
  return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {
32
54
  type: wordDocument.type,
33
55
  });
34
56
  }
57
+ /**
58
+ * Adds a `<Default>` to `typesXml` for each image extension among `paths`
59
+ * under `word/media/` that it doesn't declare yet. Exported for testing.
60
+ */
61
+ export function patchContentTypes(typesXml, paths) {
62
+ const dom = new DOMParser().parseFromString(typesXml, 'application/xml');
63
+ const types = dom.documentElement;
64
+ const declared = new Set(Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) => (d.getAttribute('Extension') ?? '').toLowerCase()));
65
+ let changed = false;
66
+ for (const path of paths) {
67
+ if (!path.startsWith('word/media/'))
68
+ continue;
69
+ const extension = /\.([^./]+)$/.exec(path)?.[1].toLowerCase();
70
+ const contentType = extension && IMAGE_CONTENT_TYPES[extension];
71
+ if (!contentType || declared.has(extension))
72
+ continue;
73
+ const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');
74
+ entry.setAttribute('Extension', extension);
75
+ entry.setAttribute('ContentType', contentType);
76
+ // Defaults come before Overrides in the schema.
77
+ types.insertBefore(entry, types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null);
78
+ declared.add(extension);
79
+ changed = true;
80
+ }
81
+ if (!changed)
82
+ return typesXml;
83
+ return keepXmlDeclaration(typesXml, new XMLSerializer().serializeToString(dom));
84
+ }
35
85
  /** Exported for testing. */
36
86
  export function patchDocumentXml(documentXml, structure) {
37
87
  const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
@@ -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;;;;;;;;;;;;;;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,CAAC,CAAC;AACL,CAAC;AAED,4BAA4B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AC,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"]}
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;AAE9E,MAAM,aAAa,GAAG,qBAAqB,CAAC;AAC5C,MAAM,gBAAgB,GACpB,8DAA8D,CAAC;AAEjE,qEAAqE;AACrE,MAAM,mBAAmB,GAA2B;IAClD,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,eAAe;CACrB,CAAC;AAUF;;;;;;;;;;;;;;;;;;GAkBG;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,I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7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,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\nconst CONTENT_TYPES = '[Content_Types].xml';\nconst CONTENT_TYPES_NS =\n 'http://schemas.openxmlformats.org/package/2006/content-types';\n\n/** The media type of each image extension html-to-docx can write. */\nconst IMAGE_CONTENT_TYPES: Record<string, string> = {\n png: 'image/png',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n};\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 * - Image content types: the generator declares only JPEG, PNG and SVG in\n * `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a\n * declared type, and Word offers to repair a file that lacks one, so each\n * image extension in `word/media/` gets a `<Default>`.\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 const typesEntry = zip.file(CONTENT_TYPES);\n const typesXml = typesEntry ? await typesEntry.async('string') : null;\n const patchedTypes =\n typesXml === null\n ? null\n : patchContentTypes(typesXml, Object.keys(zip.files));\n if (patched === documentXml && patchedTypes === typesXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n if (patchedTypes !== null) zip.file(CONTENT_TYPES, patchedTypes);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/**\n * Adds a `<Default>` to `typesXml` for each image extension among `paths`\n * under `word/media/` that it doesn't declare yet. Exported for testing.\n */\nexport function patchContentTypes(typesXml: string, paths: string[]): string {\n const dom = new DOMParser().parseFromString(typesXml, 'application/xml');\n const types = dom.documentElement;\n const declared = new Set(\n Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) =>\n (d.getAttribute('Extension') ?? '').toLowerCase()\n )\n );\n let changed = false;\n for (const path of paths) {\n if (!path.startsWith('word/media/')) continue;\n const extension = /\\.([^./]+)$/.exec(path)?.[1].toLowerCase();\n const contentType = extension && IMAGE_CONTENT_TYPES[extension];\n if (!contentType || declared.has(extension)) continue;\n const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');\n entry.setAttribute('Extension', extension);\n entry.setAttribute('ContentType', contentType);\n // Defaults come before Overrides in the schema.\n types.insertBefore(\n entry,\n types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null\n );\n declared.add(extension);\n changed = true;\n }\n if (!changed) return typesXml;\n return keepXmlDeclaration(\n typesXml,\n new XMLSerializer().serializeToString(dom)\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"]}
@@ -0,0 +1,4 @@
1
+ /** Word and other word-processor files: the reverse direction, word2md's job. */
2
+ export declare const WORD_FILE: RegExp;
3
+ /** A file that's mostly binary isn't Markdown. NUL never appears in text. */
4
+ export declare function looksBinary(text: string): boolean;
@@ -0,0 +1,9 @@
1
+ // Checks for input that isn't Markdown, shared by the page (src/index.ts) and
2
+ // the `md2w` CLI (src/cli.ts) so both refuse the same files.
3
+ /** Word and other word-processor files: the reverse direction, word2md's job. */
4
+ export const WORD_FILE = /\.(docx?|dotx?|odt|rtf)$/i;
5
+ /** A file that's mostly binary isn't Markdown. NUL never appears in text. */
6
+ export function looksBinary(text) {
7
+ return text.slice(0, 8192).includes('\u0000');
8
+ }
9
+ //# sourceMappingURL=input-checks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input-checks.js","sourceRoot":"","sources":["../src/input-checks.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6DAA6D;AAE7D,iFAAiF;AACjF,MAAM,CAAC,MAAM,SAAS,GAAG,2BAA2B,CAAC;AAErD,6EAA6E;AAC7E,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAChD,CAAC","sourcesContent":["// Checks for input that isn't Markdown, shared by the page (src/index.ts) and\n// the `md2w` CLI (src/cli.ts) so both refuse the same files.\n\n/** Word and other word-processor files: the reverse direction, word2md's job. */\nexport const WORD_FILE = /\\.(docx?|dotx?|odt|rtf)$/i;\n\n/** A file that's mostly binary isn't Markdown. NUL never appears in text. */\nexport function looksBinary(text: string): boolean {\n return text.slice(0, 8192).includes('\\u0000');\n}\n"]}
@@ -16,10 +16,11 @@ export declare function renderPreviewHtml(markdown: string): string;
16
16
  */
17
17
  export declare function extractTitle(markdown: string): string | null;
18
18
  /**
19
- * Convert a string into a URL/filename-safe slug.
20
- * Lowercases, replaces whitespace and underscores with hyphens,
21
- * strips characters that are not word characters (\w), whitespace, or hyphens,
22
- * and collapses consecutive hyphens. Note that \w includes [a-zA-Z0-9_] and
23
- * Unicode letters/digits, so accented characters are preserved.
19
+ * Convert a string into a URL/filename-safe slug, used to name the download.
20
+ * NFC-normalizes and lowercases, keeps letters, digits, and the combining
21
+ * marks attached to them in any script (so 关于开展2026年工作的通知,
22
+ * Привет мир, and Café survive), strips everything else, including punctuation and the characters file
23
+ * systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
24
+ * underscores, and hyphens into one hyphen.
24
25
  */
25
26
  export declare function slugify(text: string): string;
@@ -90,20 +90,26 @@ function plainText(tokens) {
90
90
  .join('');
91
91
  }
92
92
  /**
93
- * Convert a string into a URL/filename-safe slug.
94
- * Lowercases, replaces whitespace and underscores with hyphens,
95
- * strips characters that are not word characters (\w), whitespace, or hyphens,
96
- * and collapses consecutive hyphens. Note that \w includes [a-zA-Z0-9_] and
97
- * Unicode letters/digits, so accented characters are preserved.
93
+ * Convert a string into a URL/filename-safe slug, used to name the download.
94
+ * NFC-normalizes and lowercases, keeps letters, digits, and the combining
95
+ * marks attached to them in any script (so 关于开展2026年工作的通知,
96
+ * Привет мир, and Café survive), strips everything else, including punctuation and the characters file
97
+ * systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
98
+ * underscores, and hyphens into one hyphen.
98
99
  */
99
100
  export function slugify(text) {
100
- return text
101
+ return (text
102
+ .normalize('NFC')
101
103
  .toLowerCase()
102
104
  .trim()
103
- .replace(/[^\w\s-]/g, '')
105
+ // A mark left with nothing to attach to (the U+FE0F after an emoji) is
106
+ // invisible, and would keep an all-emoji title from falling back to
107
+ // "document".
108
+ .replace(/(?<![\p{L}\p{M}\p{N}])\p{M}+/gu, '')
109
+ .replace(/[^\p{L}\p{M}\p{N}\s_-]/gu, '')
104
110
  .replace(/[\s_]+/g, '-')
105
111
  .replace(/-+/g, '-')
106
- .replace(/^-+|-+$/g, '');
112
+ .replace(/^-+|-+$/g, ''));
107
113
  }
108
114
  const HTML_ESCAPES = {
109
115
  '&': '&amp;',
@@ -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;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;Y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AAG,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"]}
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,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;AAE7C;;;GAGG;AACH,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;AAE7C;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAgB;IAClD,IAAI,CAAC;QACH,OA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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;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAY;IAClC,OAAO,CACL,IAAI;SACD,SAAS,CAAC,KAAK,CAAC;SAChB,WAAW,EAAE;SACb,IAAI,EAAE;QACP,uEAAuE;QACvE,oEAAoE;QACpE,cAAc;SACb,OAAO,CAAC,gCAAgC,EAAE,EAAE,CAAC;SAC7C,OAAO,CAAC,0BAA0B,EAAE,EAAE,CAAC;SACvC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAC3B,CAAC;AACJ,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, used to name the download.\n * NFC-normalizes and lowercases, keeps letters, digits, and the combining\n * marks attached to them in any script (so 关于开展2026年工作的通知,\n * Привет мир, and Café survive), strips everything else, including punctuation and the characters file\n * systems reject (/ \\ : * ? \" < > |), then turns runs of whitespace,\n * underscores, and hyphens into one hyphen.\n */\nexport function slugify(text: string): string {\n return (\n text\n .normalize('NFC')\n .toLowerCase()\n .trim()\n // A mark left with nothing to attach to (the U+FE0F after an emoji) is\n // invisible, and would keep an all-emoji title from falling back to\n // \"document\".\n .replace(/(?<![\\p{L}\\p{M}\\p{N}])\\p{M}+/gu, '')\n .replace(/[^\\p{L}\\p{M}\\p{N}\\s_-]/gu, '')\n .replace(/[\\s_]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n );\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"]}
package/build/mcp.js CHANGED
@@ -45,6 +45,13 @@ function installGuards() {
45
45
  if (guarded)
46
46
  return;
47
47
  guarded = true;
48
+ // stdout carries only JSON-RPC messages, but html-to-docx logs debug lines
49
+ // with console.log (a broken data: image, say). Send all of it to stderr.
50
+ const error = console.error;
51
+ console.log =
52
+ console.info =
53
+ console.debug =
54
+ (...args) => error(...args);
48
55
  const warn = console.warn;
49
56
  console.warn = (...args) => {
50
57
  conversion