markdown-to-word 0.2.0 → 0.4.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.
package/README.md CHANGED
@@ -17,18 +17,20 @@ The document is named after its first heading, which also becomes its title.
17
17
 
18
18
  ## What converts
19
19
 
20
- | Markdown | In Word |
21
- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
22
- | `#` to `######` headings | Heading 1–6 styles |
23
- | `**bold**`, `*italic*`, `~~strikethrough~~` | The same formatting |
24
- | Bulleted and numbered lists, nested | Word lists |
25
- | `- [x]` task lists | ☒ (done) and ☐ (to do) items, since Word can't show checkboxes from HTML |
26
- | Tables | Thin borders, a bold header row that repeats on each page, and the column alignment from the Markdown |
27
- | `[links](https://example.com)` | Clickable hyperlinks |
28
- | `` `inline code` `` and fenced code blocks | Monospace; code blocks keep their line breaks |
29
- | `> block quotes` | Indented paragraphs |
30
- | `---` horizontal rules | A line across the page |
31
- | `![images](https://example.com/a.png)` | Embedded, when the browser can fetch them (see [Limitations](#limitations)) |
20
+ | Markdown | In Word |
21
+ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
22
+ | `#` to `######` headings | Heading 1–6 styles |
23
+ | `**bold**`, `*italic*`, `~~strikethrough~~` | The same formatting |
24
+ | Bulleted and numbered lists, nested | Word lists |
25
+ | `- [x]` task lists | ☒ (done) and ☐ (to do) items, since Word can't show checkboxes from HTML |
26
+ | Tables | Thin borders, a bold header row that repeats on each page, and the column alignment from the Markdown |
27
+ | `[links](https://example.com)` | Clickable hyperlinks |
28
+ | `` `inline code` `` and fenced code blocks | Monospace; code blocks keep their line breaks |
29
+ | `> block quotes` | Left-aligned paragraphs, indented one step per level of nesting |
30
+ | `---` horizontal rules | A line across the page |
31
+ | `[^1]` footnotes | Superscript numbers, with the notes as a numbered list after a line at the end of the document (not Word footnotes) |
32
+ | `![images](https://example.com/a.png)` | Embedded, when the browser can fetch them; otherwise the alt text, linked to the image (see [Limitations](#limitations)) |
33
+ | `<kbd>`, `<mark>`, `<abbr>` and other inline HTML | The text, with `<kbd>` in the code font and `<mark>` highlighted |
32
34
 
33
35
  As on GitHub, a single newline inside a paragraph is joined into the same line, so hard-wrapped files convert to normal paragraphs. End a line with two spaces or a backslash to force a line break.
34
36
 
@@ -84,11 +86,83 @@ Conversion happens entirely in your browser: your Markdown and the Word document
84
86
 
85
87
  ## Limitations
86
88
 
87
- - Images are embedded only when the browser can fetch them: `data:` URIs, and web URLs whose server allows cross-origin requests (most image hosts and CDNs do). Other images, images under 1 KB (html-to-docx's minimum), and local file paths are left out.
89
+ - Images are embedded only when the browser can fetch them: `data:` URIs, and web URLs whose server allows cross-origin requests (most image hosts and CDNs do). Any other image, including a local file path, becomes its alt text, linked to the image's URL when it has one.
90
+ - Footnotes come out as a numbered list of notes at the end of the document, not as Word footnotes at the foot of each page.
91
+ - Math stays as the literal text: `$x^2$` comes out as `$x^2$`, not an equation.
92
+ - Emoji shortcodes such as `:tada:` aren't converted; paste the emoji itself instead.
93
+ - Links to headings in the same document (`[see below](#usage)`) don't jump anywhere in Word.
94
+ - `<details>` sections are flattened: the summary and the hidden content both show, as ordinary paragraphs.
88
95
  - Complex raw HTML inside Markdown may not convert cleanly, and advanced Word features (comments, tracked changes, page layout) aren't produced.
89
96
  - Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
90
97
  - The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
91
98
 
99
+ ## Command line
100
+
101
+ Run it directly with `npx` (downloads and runs the latest published version):
102
+
103
+ ```console
104
+ npx markdown-to-word report.md
105
+ ```
106
+
107
+ Or install it globally to get the `md2w` command:
108
+
109
+ ```console
110
+ npm install -g markdown-to-word
111
+ md2w report.md
112
+ ```
113
+
114
+ It writes the `.docx` next to the input with the same name (`report.md` becomes `report.docx`), replacing any file already there, and prints where it wrote it to **stderr**. It needs Node 22.12 or later, and exits with status 1 and a message if the file is missing or empty.
115
+
116
+ To read the Markdown from **stdin**, pass `-` as the file, or leave it out and pipe the Markdown in. There's no file name to go on then, so `-o` is required:
117
+
118
+ ```console
119
+ cat reply.md | md2w -o reply.docx
120
+ md2w - -o - < report.md > report.docx
121
+ ```
122
+
123
+ Options:
124
+
125
+ - `-o, --output <file>`: write the `.docx` to `<file>`, creating folders as needed. `-o -` writes it to stdout.
126
+ - `--font-preset <name>`: restyle the document with a font preset. `chinese-official` is the Chinese official document (公文) style described in [Optional Font Presets](#optional-font-presets).
127
+ - `-q, --quiet`: print nothing to stderr except errors.
128
+ - `-V, --version`: print the version.
129
+
130
+ ## MCP server
131
+
132
+ `md2w mcp` runs a local [Model Context Protocol](https://modelcontextprotocol.io) server on stdio, so AI agents can turn Markdown into Word documents on your machine. Like the website, it never uploads anything: the server converts in-process and writes the `.docx` to disk.
133
+
134
+ Add it to Claude Code:
135
+
136
+ ```console
137
+ claude mcp add markdown-to-word -- npx -y markdown-to-word mcp
138
+ ```
139
+
140
+ Or to any MCP client that takes a JSON config:
141
+
142
+ ```json
143
+ {
144
+ "mcpServers": {
145
+ "markdown-to-word": {
146
+ "command": "npx",
147
+ "args": ["-y", "markdown-to-word", "mcp"]
148
+ }
149
+ }
150
+ }
151
+ ```
152
+
153
+ It has one tool, `convert_markdown_to_word`:
154
+
155
+ - `markdown` or `path` (exactly one): the Markdown as a string, or the path of a Markdown file (`.md`, `.markdown`, `.mdown`, or `.txt`). Prefer absolute paths; relative ones resolve against the server's working directory.
156
+ - `output_path` (required): where to write the `.docx`; it must end in `.docx`. Missing folders are created.
157
+ - `overwrite`: replace `output_path` if it already exists. Off by default, so the tool refuses to clobber an existing file and says so.
158
+ - `font_preset`: `chinese-official` for the 公文 style; omit for Word's default styling.
159
+
160
+ It returns the `output_path`, the file's size in `bytes`, and any `warnings` (remote images it didn't download, or a `.docx` patch that had to be skipped), also as structured content.
161
+
162
+ An agent may be following instructions from a document or web page it read, so the tool limits what it can be talked into: it reads only Markdown files, writes only `.docx` files, never writes through a symlink, and never replaces a file unless asked. It also never downloads remote images, since a URL in a document could point anywhere, your own network included: they appear in the document as links. An agent that wants an image embedded can fetch it itself and put it in the Markdown as a `data:` URI. The CLI, run by you, has none of these limits and embeds remote images like the website.
163
+
164
+ In the browser, md2word.app registers the same conversion as a [WebMCP](https://webmachinelearning.github.io/webmcp/) tool, `convert_markdown_to_docx` (`markdown`, plus optional `filename` and `font_preset`), for agents in browsers that support it. It runs in the tab like a paste, shows the result on the page, and returns the `.docx` as base64. The page also tries to download the file, which a browser may block when no one clicked.
165
+
92
166
  ## Use it from code
93
167
 
94
168
  The converter is also on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word), for Node 22.12+ and for browsers through a bundler (Vite, webpack, esbuild):
@@ -115,7 +189,7 @@ The converter needs the DOM's `DOMParser` and `XMLSerializer`. Browsers have the
115
189
 
116
190
  The package also exports `parseMarkdownToHtml`, `extractTitle`, the `FONT_PRESETS` (see [Optional Font Presets](#optional-font-presets)), and their TypeScript types. `parseMarkdownToHtml` passes raw HTML through unsanitized, so sanitize its output (for example with [DOMPurify](https://github.com/cure53/DOMPurify)) before putting it in a page.
117
191
 
118
- On a server, treat Markdown from users as untrusted: the converter downloads each remote image (`![](https://…)`) to embed it, so the request comes from your server. Strip or allowlist image URLs first if the server can reach internal addresses.
192
+ On a server, treat Markdown from users as untrusted: the converter downloads each remote image (`![](https://…)`) to embed it, so the request comes from your server (up to 100 distinct `http(s)` URLs per document, 10 MB each, 4 at a time). Strip or allowlist image URLs first if the server can reach internal addresses.
119
193
 
120
194
  ## Development
121
195
 
package/build/cli.js ADDED
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env node
2
+ // The `md2w` command (also installed as `markdown-to-word`): converts a
3
+ // Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's
4
+ // `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node
5
+ // entry, which supplies the DOM APIs the converter needs.
6
+ import { Command, Option } from 'commander';
7
+ import { createRequire } from 'module';
8
+ import { mkdir, readFile, writeFile } from 'fs/promises';
9
+ import path from 'path';
10
+ import { convertMarkdownToWord, FONT_PRESETS } from './node.js';
11
+ // Read our own version from package.json. createRequire resolves relative to
12
+ // this module, so `../package.json` points at the package root both from the
13
+ // TypeScript source (src/) and the compiled CLI (build/) after publish.
14
+ const require = createRequire(import.meta.url);
15
+ const { version } = require('../package.json');
16
+ async function readStdin() {
17
+ const chunks = [];
18
+ for await (const chunk of process.stdin)
19
+ chunks.push(chunk);
20
+ return Buffer.concat(chunks).toString('utf8');
21
+ }
22
+ /** `notes.md` → `notes.docx`, next to the input. */
23
+ function defaultOutputPath(input) {
24
+ const { dir, name } = path.parse(input);
25
+ return path.join(dir, `${name}.docx`);
26
+ }
27
+ const EXAMPLES = `
28
+ Examples:
29
+ $ md2w report.md # writes report.docx
30
+ $ md2w report.md -o out/report.docx
31
+ $ md2w --font-preset chinese-official notice.md
32
+ $ cat reply.md | md2w -o reply.docx
33
+ $ md2w - -o - < report.md > report.docx`;
34
+ const program = new Command();
35
+ program.name('md2w');
36
+ program.description('Convert Markdown to a formatted Word (.docx) document');
37
+ program.version(version);
38
+ program.addHelpText('after', `\nRun "md2w convert --help" for all conversion options.\n${EXAMPLES}`);
39
+ program
40
+ .command('mcp')
41
+ .description('Run a local MCP server on stdio so AI agents can convert Markdown to ' +
42
+ '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +
43
+ 'npx -y markdown-to-word mcp)')
44
+ .action(async () => {
45
+ // Loaded only here, so conversions never pay for the MCP SDK.
46
+ const { startMcpServer } = await import('./mcp.js');
47
+ await startMcpServer(version);
48
+ });
49
+ const convert = program
50
+ .command('convert', { isDefault: true })
51
+ .argument('[file]', 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +
52
+ 'in) to read from stdin.')
53
+ .option('-o, --output <file>', 'Write the .docx to <file> (- means stdout). Defaults to the input ' +
54
+ 'file name with .docx; required when reading stdin.')
55
+ .addOption(new Option('--font-preset <name>', 'Restyle the document with a font preset, e.g. chinese-official for ' +
56
+ 'a Chinese official document (公文) after GB/T 9704-2012').choices(Object.keys(FONT_PRESETS)))
57
+ .option('-q, --quiet', 'Print nothing to stderr except errors')
58
+ .addHelpText('after', EXAMPLES)
59
+ .action(async (file, options) => {
60
+ const note = (message) => {
61
+ if (!options.quiet)
62
+ console.error(message);
63
+ };
64
+ try {
65
+ // An explicit `-`, or no file with something piped in, reads stdin. No
66
+ // file at an interactive terminal would just hang, so ask for one.
67
+ const fromStdin = file === '-' || (!file && !process.stdin.isTTY);
68
+ if (!file && !fromStdin) {
69
+ convert.help({ error: true });
70
+ }
71
+ if (fromStdin && !options.output) {
72
+ throw new Error('Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).');
73
+ }
74
+ const markdown = fromStdin
75
+ ? await readStdin()
76
+ : await readFile(file, 'utf8').catch((error) => {
77
+ if (error.code === 'ENOENT') {
78
+ throw new Error(`${file} was not found.`);
79
+ }
80
+ throw error;
81
+ });
82
+ if (markdown.trim() === '') {
83
+ throw new Error(fromStdin
84
+ ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'
85
+ : `${file} is empty.`);
86
+ }
87
+ const blob = await convertMarkdownToWord(markdown, {
88
+ fontPreset: options.fontPreset
89
+ ? FONT_PRESETS[options.fontPreset]
90
+ : undefined,
91
+ });
92
+ const bytes = Buffer.from(await blob.arrayBuffer());
93
+ const output = options.output ?? defaultOutputPath(file);
94
+ if (output === '-') {
95
+ process.stdout.write(bytes);
96
+ }
97
+ else {
98
+ await mkdir(path.dirname(output), { recursive: true });
99
+ await writeFile(output, bytes);
100
+ note(`Wrote ${output}`);
101
+ }
102
+ }
103
+ catch (error) {
104
+ console.error('Error:', error instanceof Error ? error.message : String(error));
105
+ process.exit(1);
106
+ }
107
+ });
108
+ await program.parseAsync();
109
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/c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AO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CACX,QAAQ,EACR,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CACvD,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n\n// The `md2w` command (also installed as `markdown-to-word`): converts a\n// Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's\n// `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node\n// entry, which supplies the DOM APIs the converter needs.\n\nimport { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { mkdir, readFile, writeFile } from 'fs/promises';\nimport path from 'path';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\n\n// Read our own version from package.json. createRequire resolves relative to\n// this module, so `../package.json` points at the package root both from the\n// TypeScript source (src/) and the compiled CLI (build/) after publish.\nconst require = createRequire(import.meta.url);\nconst { version } = require('../package.json') as { version: string };\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n\n/** `notes.md` → `notes.docx`, next to the input. */\nfunction defaultOutputPath(input: string): string {\n const { dir, name } = path.parse(input);\n return path.join(dir, `${name}.docx`);\n}\n\nconst EXAMPLES = `\nExamples:\n $ md2w report.md # writes report.docx\n $ md2w report.md -o out/report.docx\n $ md2w --font-preset chinese-official notice.md\n $ cat reply.md | md2w -o reply.docx\n $ md2w - -o - < report.md > report.docx`;\n\nconst program = new Command();\nprogram.name('md2w');\nprogram.description('Convert Markdown to a formatted Word (.docx) document');\nprogram.version(version);\nprogram.addHelpText(\n 'after',\n `\\nRun \"md2w convert --help\" for all conversion options.\\n${EXAMPLES}`\n);\nprogram\n .command('mcp')\n .description(\n 'Run a local MCP server on stdio so AI agents can convert Markdown to ' +\n '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +\n 'npx -y markdown-to-word mcp)'\n )\n .action(async () => {\n // Loaded only here, so conversions never pay for the MCP SDK.\n const { startMcpServer } = await import('./mcp.js');\n await startMcpServer(version);\n });\nconst convert = program\n .command('convert', { isDefault: true })\n .argument(\n '[file]',\n 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +\n 'in) to read from stdin.'\n )\n .option(\n '-o, --output <file>',\n 'Write the .docx to <file> (- means stdout). Defaults to the input ' +\n 'file name with .docx; required when reading stdin.'\n )\n .addOption(\n new Option(\n '--font-preset <name>',\n 'Restyle the document with a font preset, e.g. chinese-official for ' +\n 'a Chinese official document (公文) after GB/T 9704-2012'\n ).choices(Object.keys(FONT_PRESETS))\n )\n .option('-q, --quiet', 'Print nothing to stderr except errors')\n .addHelpText('after', EXAMPLES)\n .action(async (file: string | undefined, options) => {\n const note = (message: string): void => {\n if (!options.quiet) console.error(message);\n };\n try {\n // An explicit `-`, or no file with something piped in, reads stdin. No\n // file at an interactive terminal would just hang, so ask for one.\n const fromStdin = file === '-' || (!file && !process.stdin.isTTY);\n if (!file && !fromStdin) {\n convert.help({ error: true });\n }\n if (fromStdin && !options.output) {\n throw new Error(\n 'Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).'\n );\n }\n\n const markdown = fromStdin\n ? await readStdin()\n : await readFile(file as string, 'utf8').catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${file} was not found.`);\n }\n throw error;\n });\n if (markdown.trim() === '') {\n throw new Error(\n fromStdin\n ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'\n : `${file} is empty.`\n );\n }\n\n const blob = await convertMarkdownToWord(markdown, {\n fontPreset: options.fontPreset\n ? FONT_PRESETS[options.fontPreset]\n : undefined,\n });\n const bytes = Buffer.from(await blob.arrayBuffer());\n\n const output: string = options.output ?? defaultOutputPath(file!);\n if (output === '-') {\n process.stdout.write(bytes);\n } else {\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, bytes);\n note(`Wrote ${output}`);\n }\n } catch (error) {\n console.error(\n 'Error:',\n error instanceof Error ? error.message : String(error)\n );\n process.exit(1);\n }\n });\n\nawait program.parseAsync();\n"]}
@@ -2,6 +2,7 @@
2
2
  import './buffer-global.js';
3
3
  import HTMLtoDOCX from '@turbodocx/html-to-docx';
4
4
  import { prepareHtmlForDocx } from './docx-html.js';
5
+ import { embedImages } from './docx-images.js';
5
6
  import { mmToTwips } from './font-presets.js';
6
7
  import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
7
8
  /**
@@ -9,7 +10,13 @@ import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
9
10
  */
10
11
  export async function convertMarkdownToWord(markdown, options = {}) {
11
12
  try {
12
- const html = parseMarkdownToHtml(markdown);
13
+ let html = parseMarkdownToHtml(markdown);
14
+ // Case-insensitive: raw HTML in the Markdown can say <IMG>, and an image
15
+ // this skips is left for html-to-docx to download on its own.
16
+ if (/<img/i.test(html)) {
17
+ // Before generation, so a failed image can keep its alt text.
18
+ html = await embedImages(html);
19
+ }
13
20
  const documentOptions = {
14
21
  // The generator's default border size is 0, so tables had no grid lines.
15
22
  // A thin light gray rule (size in eighths of a point) matches how
@@ -46,7 +53,9 @@ export async function convertMarkdownToWord(markdown, options = {}) {
46
53
  // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js
47
54
  const generated = result instanceof Blob ? result : new Blob([result]);
48
55
  // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own
49
- // copy, so ours is a second one; load it only when a patch actually applies.
56
+ // copy, so ours is a second one, in the patch chunks. The structure patch
57
+ // runs on every document, so it always loads; the others only when they
58
+ // apply.
50
59
  // Code blocks are broken in the generator output itself, so they are fixed
51
60
  // whether or not a font preset is requested.
52
61
  let wordDocument = generated;
@@ -57,13 +66,13 @@ export async function convertMarkdownToWord(markdown, options = {}) {
57
66
  return formatCodeBlocks(document, codeBlocks);
58
67
  });
59
68
  }
60
- if (html.includes('<hr') || html.includes('<table')) {
61
- const structure = documentStructure(html);
62
- wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {
63
- const { patchStructure } = await import('./docx-structure.js');
64
- return patchStructure(document, structure);
65
- });
66
- }
69
+ // Every document: the generator writes <w:sectPr> first in the body, and
70
+ // the schema wants it last.
71
+ const structure = documentStructure(html);
72
+ wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {
73
+ const { patchStructure } = await import('./docx-structure.js');
74
+ return patchStructure(document, structure);
75
+ });
67
76
  const { fontPreset } = options;
68
77
  if (fontPreset) {
69
78
  wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {
@@ -85,12 +94,16 @@ function codeBlockTexts(html) {
85
94
  }
86
95
  /** The rules and table header rows in `html`, for the structure patch. */
87
96
  function documentStructure(html) {
97
+ if (!html.includes('<hr') && !html.includes('<table')) {
98
+ return { rules: 0, headerRows: [] };
99
+ }
88
100
  const dom = new DOMParser().parseFromString(html, 'text/html');
89
101
  return {
90
102
  rules: dom.querySelectorAll('hr').length,
91
103
  headerRows: Array.from(dom.querySelectorAll('table'), (table) => {
92
104
  const firstRow = table.querySelector('tr');
93
- return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);
105
+ return (Boolean(table.tHead) ||
106
+ Boolean(firstRow && firstRow.querySelector('td') === null));
94
107
  }),
95
108
  };
96
109
  }
@@ -1 +1 @@
1
- {"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,oBAAoB,CAAC;AAC5B,OAAO,UAAU,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAiBzE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,QAAgB,EAChB,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAE3C,MAAM,eAAe,GAA+B;YAClD,yEAAyE;YACzE,kEAAkE;YAClE,uBAAuB;YACvB,KAAK,EAAE,EAAE,aAAa,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;SACzE,CAAC;QAEF,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;QACrC,IAAI,KAAK,EAAE,CAAC;YACV,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;QAChC,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC;QACtC,IAAI,IAAI,EAAE,CAAC;YACT,eAAe,CAAC,QAAQ,GAAG;gBACzB,KAAK,EAAE,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC;gBAC9B,MAAM,EAAE,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC;aACjC,CAAC;YACF,eAAe,CAAC,OAAO,GAAG;gBACxB,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,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/D,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;AACjF,CAAC;AAED,0EAA0E;AAC1E,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,GAAG,GAAG,IAAI,SAAS,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAC/D,OAAO;QACL,KAAK,EAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,MAAM;QACxC,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC3C,OAAO,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;QAC5F,CAAC,CAAC;KACH,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,WAAW,CACxB,YAAkB,EAClB,IAAY,EACZ,KAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,eAAe,IAAI,yCAAyC,EAAE,KAAK,CAAC,CAAC;QAClF,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n const html = parseMarkdownToHtml(markdown);\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(prepareHtmlForDocx(html), null, documentOptions);\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one; load it only when a patch actually applies.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(wordDocument, 'code block', async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n });\n }\n\n if (html.includes('<hr') || html.includes('<table')) {\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(wordDocument, 'structure', async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n });\n }\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(wordDocument, 'font preset', async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n });\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(dom.querySelectorAll('pre'), (pre) => pre.textContent ?? '');\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return Boolean(table.tHead) || Boolean(firstRow && firstRow.querySelector('td') === null);\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(`Skipped the ${name} patch; keeping the unpatched document:`, error);\n return wordDocument;\n }\n}"]}
1
+ {"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;A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tB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport { embedImages } from './docx-images.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n let html = parseMarkdownToHtml(markdown);\n // Case-insensitive: raw HTML in the Markdown can say <IMG>, and an image\n // this skips is left for html-to-docx to download on its own.\n if (/<img/i.test(html)) {\n // Before generation, so a failed image can keep its alt text.\n html = await embedImages(html);\n }\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(\n prepareHtmlForDocx(html),\n null,\n documentOptions\n );\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one, in the patch chunks. The structure patch\n // runs on every document, so it always loads; the others only when they\n // apply.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'code block',\n async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n }\n );\n }\n\n // Every document: the generator writes <w:sectPr> first in the body, and\n // the schema wants it last.\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'structure',\n async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n }\n );\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(\n wordDocument,\n 'font preset',\n async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n }\n );\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(\n dom.querySelectorAll('pre'),\n (pre) => pre.textContent ?? ''\n );\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n if (!html.includes('<hr') && !html.includes('<table')) {\n return { rules: 0, headerRows: [] };\n }\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return (\n Boolean(table.tHead) ||\n Boolean(firstRow && firstRow.querySelector('td') === null)\n );\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(\n `Skipped the ${name} patch; keeping the unpatched document:`,\n error\n );\n return wordDocument;\n }\n}\n"]}
@@ -3,7 +3,12 @@ import { CODE_FONT } from './docx-html.js';
3
3
  import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS, XML_NS, } from './xml-part.js';
4
4
  export { CODE_FONT };
5
5
  /** Theme slots WinWord prefers over explicitly named fonts. */
6
- const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
6
+ const THEME_FONT_ATTRIBUTES = [
7
+ 'asciiTheme',
8
+ 'eastAsiaTheme',
9
+ 'hAnsiTheme',
10
+ 'cstheme',
11
+ ];
7
12
  /**
8
13
  * Makes code blocks survive in Word, regardless of the font preset:
9
14
  *
@@ -54,7 +59,8 @@ export function formatDocumentXml(documentXml, codeBlocks) {
54
59
  if (pending.length === 0) {
55
60
  break;
56
61
  }
57
- if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {
62
+ if (compact(paragraphText(paragraph)) === pending[0] &&
63
+ hasExplicitFonts(paragraph)) {
58
64
  pending.shift();
59
65
  setCodeFont(paragraph);
60
66
  changed = true;
@@ -1 +1 @@
1
- {"version":3,"file":"docx-code-blocks.js","sourceRoot":"","sources":["../src/docx-code-blocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAA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ML_NS,\n} from './xml-part.js';\n\nexport { CODE_FONT };\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * Makes code blocks survive in Word, regardless of the font preset:\n *\n * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare\n * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become\n * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a\n * bare `LF` is the bug's own signature and needs no other marker.\n * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments\n * fell through to the body font. Code paragraphs are found by their text,\n * matched in order against `codeBlocks`, and get the monospace face in all\n * three slots. Keying on the generator's hardcoded code font instead would\n * also catch any inline `font-family` that names the same font.\n * - Indent: the same paragraphs get an explicit zero first-line indent, so a\n * preset that indents body text (the 公文 one) leaves the first code line\n * aligned with the rest.\n *\n * @param codeBlocks The text content of each `<pre>` in the source HTML, in\n * document order.\n */\nexport async function formatCodeBlocks(wordDocument: Blob, codeBlocks: string[]): 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 format code blocks: document contains no word/document.xml');\n }\n\n const documentXml = await documentEntry.async('string');\n const formatted = formatDocumentXml(documentXml, codeBlocks);\n if (formatted === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', formatted);\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/** Exported for testing. */\nexport function formatDocumentXml(documentXml: string, codeBlocks: string[]): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n // The generator emits one paragraph per <pre>, in source order, so a single\n // forward pass pairs each code block with the next paragraph of equal text.\n // Whitespace is ignored because the generator may trim or collapse it. A\n // plain paragraph can repeat a code block's text, so a match also needs every\n // run to name a font, as the generator does for <pre> but not for body text.\n // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the\n // generator never uses for <pre>, so those runs don't count.\n const pending = codeBlocks.map(compact).filter((text) => text !== '');\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (pending.length === 0) {\n break;\n }\n if (compact(paragraphText(paragraph)) === pending[0] && hasExplicitFonts(paragraph)) {\n pending.shift();\n setCodeFont(paragraph);\n changed = true;\n }\n }\n\n for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {\n changed = expandLineBreaks(text) || changed;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction compact(text: string): string {\n return text.replace(/\\s+/g, '');\n}\n\nfunction paragraphText(paragraph: Element): string {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((text) => text.textContent ?? '')\n .join('');\n}\n\nfunction hasExplicitFonts(paragraph: Element): boolean {\n return textRuns(paragraph).every((run) => {\n const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(W_NS, 'rFonts')[0];\n const font = rFonts?.getAttributeNS(W_NS, 'ascii');\n return Boolean(font) && font !== CODE_FONT;\n });\n}\n\nfunction textRuns(paragraph: Element): Element[] {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter(\n (run) => run.getElementsByTagNameNS(W_NS, 't').length > 0\n );\n}\n\nfunction setCodeFont(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n\n let pPr = firstChild(paragraph, 'pPr');\n if (!pPr) {\n pPr = paragraph.insertBefore(document.createElementNS(W_NS, 'w:pPr'), paragraph.firstChild);\n }\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n\n for (const run of textRuns(paragraph)) {\n let rPr = firstChild(run, 'rPr');\n if (!rPr) {\n rPr = run.insertBefore(document.createElementNS(W_NS, 'w:rPr'), run.firstChild);\n }\n\n // <w:rFonts> comes first in <w:rPr>.\n let rFonts = firstChild(rPr, 'rFonts');\n if (!rFonts) {\n rFonts = rPr.insertBefore(document.createElementNS(W_NS, 'w:rFonts'), rPr.firstChild);\n }\n\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia'] as const) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);\n }\n }\n}\n\nfunction firstChild(parent: Element, localName: string): Element | undefined {\n return Array.from(parent.children).find(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n\n/**\n * Replaces one `<w:t>a\\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.\n * Returns whether anything changed.\n */\nfunction expandLineBreaks(text: Element): boolean {\n const lines = (text.textContent ?? '').split('\\n');\n if (lines.length < 2) {\n return false;\n }\n\n const document = text.ownerDocument;\n const run = text.parentNode as Element;\n\n for (const [index, line] of lines.entries()) {\n if (index > 0) {\n run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);\n }\n if (line !== '') {\n const textElement = document.createElementNS(W_NS, 'w:t');\n textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n textElement.textContent = line;\n run.insertBefore(textElement, text);\n }\n }\n\n run.removeChild(text);\n return true;\n}\n"]}
1
+ {"version":3,"file":"docx-code-blocks.js","sourceRoot":"","sources":["../src/docx-code-blocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,EACzB,MAAM,GACP,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,eAAe;IACf,YAAY;IACZ,SAAS;CACV,CAAC;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MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;IACpC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAqB,CAAC;IAEvC,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;QAC5C,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACd,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;QACjE,CAAC;QACD,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;YAChB,MAAM,WAAW,GAAG,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC1D,WAAW,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;YAC5D,WAAW,CAAC,WAAW,GAAG,IAAI,CAAC;YAC/B,GAAG,CAAC,YAAY,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IACtB,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { CODE_FONT } from './docx-html.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n XML_NS,\n} from './xml-part.js';\n\nexport { CODE_FONT };\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = [\n 'asciiTheme',\n 'eastAsiaTheme',\n 'hAnsiTheme',\n 'cstheme',\n];\n\n/**\n * Makes code blocks survive in Word, regardless of the font preset:\n *\n * - Line breaks: the generator keeps the source newlines of a `<pre>` as bare\n * `LF` inside `<w:t>`, which WinWord renders as whitespace; they become\n * `<w:br/>` here. Everywhere else the generator emits `<w:br/>` itself, so a\n * bare `LF` is the bug's own signature and needs no other marker.\n * - Typeface: the generator sets only `w:ascii`/`w:hAnsi`, so Chinese comments\n * fell through to the body font. Code paragraphs are found by their text,\n * matched in order against `codeBlocks`, and get the monospace face in all\n * three slots. Keying on the generator's hardcoded code font instead would\n * also catch any inline `font-family` that names the same font.\n * - Indent: the same paragraphs get an explicit zero first-line indent, so a\n * preset that indents body text (the 公文 one) leaves the first code line\n * aligned with the rest.\n *\n * @param codeBlocks The text content of each `<pre>` in the source HTML, in\n * document order.\n */\nexport async function formatCodeBlocks(\n wordDocument: Blob,\n codeBlocks: string[]\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 format code blocks: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const formatted = formatDocumentXml(documentXml, codeBlocks);\n if (formatted === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', formatted);\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/** Exported for testing. */\nexport function formatDocumentXml(\n documentXml: string,\n codeBlocks: string[]\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n // The generator emits one paragraph per <pre>, in source order, so a single\n // forward pass pairs each code block with the next paragraph of equal text.\n // Whitespace is ignored because the generator may trim or collapse it. A\n // plain paragraph can repeat a code block's text, so a match also needs every\n // run to name a font, as the generator does for <pre> but not for body text.\n // Inline code names CODE_FONT itself (see prepareHtmlForDocx), which the\n // generator never uses for <pre>, so those runs don't count.\n const pending = codeBlocks.map(compact).filter((text) => text !== '');\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (pending.length === 0) {\n break;\n }\n if (\n compact(paragraphText(paragraph)) === pending[0] &&\n hasExplicitFonts(paragraph)\n ) {\n pending.shift();\n setCodeFont(paragraph);\n changed = true;\n }\n }\n\n for (const text of Array.from(dom.getElementsByTagNameNS(W_NS, 't'))) {\n changed = expandLineBreaks(text) || changed;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction compact(text: string): string {\n return text.replace(/\\s+/g, '');\n}\n\nfunction paragraphText(paragraph: Element): string {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((text) => text.textContent ?? '')\n .join('');\n}\n\nfunction hasExplicitFonts(paragraph: Element): boolean {\n return textRuns(paragraph).every((run) => {\n const rFonts = firstChild(run, 'rPr')?.getElementsByTagNameNS(\n W_NS,\n 'rFonts'\n )[0];\n const font = rFonts?.getAttributeNS(W_NS, 'ascii');\n return Boolean(font) && font !== CODE_FONT;\n });\n}\n\nfunction textRuns(paragraph: Element): Element[] {\n return Array.from(paragraph.getElementsByTagNameNS(W_NS, 'r')).filter(\n (run) => run.getElementsByTagNameNS(W_NS, 't').length > 0\n );\n}\n\nfunction setCodeFont(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n\n let pPr = firstChild(paragraph, 'pPr');\n if (!pPr) {\n pPr = paragraph.insertBefore(\n document.createElementNS(W_NS, 'w:pPr'),\n paragraph.firstChild\n );\n }\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n\n for (const run of textRuns(paragraph)) {\n let rPr = firstChild(run, 'rPr');\n if (!rPr) {\n rPr = run.insertBefore(\n document.createElementNS(W_NS, 'w:rPr'),\n run.firstChild\n );\n }\n\n // <w:rFonts> comes first in <w:rPr>.\n let rFonts = firstChild(rPr, 'rFonts');\n if (!rFonts) {\n rFonts = rPr.insertBefore(\n document.createElementNS(W_NS, 'w:rFonts'),\n rPr.firstChild\n );\n }\n\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia'] as const) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, CODE_FONT);\n }\n }\n}\n\nfunction firstChild(parent: Element, localName: string): Element | undefined {\n return Array.from(parent.children).find(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n\n/**\n * Replaces one `<w:t>a\\nb</w:t>` with `<w:t>a</w:t><w:br/><w:t>b</w:t>`.\n * Returns whether anything changed.\n */\nfunction expandLineBreaks(text: Element): boolean {\n const lines = (text.textContent ?? '').split('\\n');\n if (lines.length < 2) {\n return false;\n }\n\n const document = text.ownerDocument;\n const run = text.parentNode as Element;\n\n for (const [index, line] of lines.entries()) {\n if (index > 0) {\n run.insertBefore(document.createElementNS(W_NS, 'w:br'), text);\n }\n if (line !== '') {\n const textElement = document.createElementNS(W_NS, 'w:t');\n textElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n textElement.textContent = line;\n run.insertBefore(textElement, text);\n }\n }\n\n run.removeChild(text);\n return true;\n}\n"]}
@@ -1,7 +1,12 @@
1
1
  import JSZip from 'jszip';
2
- import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS } from './xml-part.js';
2
+ import { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS, } from './xml-part.js';
3
3
  /** Theme slots WinWord prefers over explicitly named fonts. */
4
- const THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];
4
+ const THEME_FONT_ATTRIBUTES = [
5
+ 'asciiTheme',
6
+ 'eastAsiaTheme',
7
+ 'hAnsiTheme',
8
+ 'cstheme',
9
+ ];
5
10
  /**
6
11
  * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240
7
12
  * twips, so the preset writes the pair Word itself produces.
@@ -139,7 +144,7 @@ export function patchDocumentXml(documentXml, preset) {
139
144
  * itself sets up with GB/T 9704 margins, this reproduces its linePitch="579"
140
145
  * and charSpace="-834".
141
146
  */
142
- function measureGrid(sectPr, { linesPerPage, charsPerLine }, bodySizePt) {
147
+ function measureGrid(sectPr, { linesPerPage, charsPerLine, }, bodySizePt) {
143
148
  const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');
144
149
  const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');
145
150
  const twips = (element, attribute) => {