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 +88 -14
- package/build/cli.js +109 -0
- package/build/cli.js.map +1 -0
- package/build/converter.js +23 -10
- package/build/converter.js.map +1 -1
- package/build/docx-code-blocks.js +8 -2
- package/build/docx-code-blocks.js.map +1 -1
- package/build/docx-font-preset.js +8 -3
- package/build/docx-font-preset.js.map +1 -1
- package/build/docx-html.d.ts +10 -0
- package/build/docx-html.js +106 -1
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +24 -0
- package/build/docx-images.js +176 -0
- package/build/docx-images.js.map +1 -0
- package/build/docx-structure.d.ts +3 -0
- package/build/docx-structure.js +10 -1
- package/build/docx-structure.js.map +1 -1
- package/build/font-presets.js +12 -2
- package/build/font-presets.js.map +1 -1
- package/build/markdown-parser.js +27 -3
- package/build/markdown-parser.js.map +1 -1
- package/build/mcp.js +233 -0
- package/build/mcp.js.map +1 -0
- package/build/xml-part.js +2 -1
- package/build/xml-part.js.map +1 -1
- package/package.json +22 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAEjG,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG,CAAC,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAiBrD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,YAAkB,EAAE,MAAkB;IAC1E,MAA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;QACb,MAAM,IAAI,KAAK,CAAC,kDAAkD,SAAS,WAAW,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, ParagraphStyle } from './font-presets.js';\nimport { keepXmlDeclaration, paragraphProperty, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = ['asciiTheme', 'eastAsiaTheme', 'hAnsiTheme', 'cstheme'];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing and page grid of an already\n * generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(wordDocument: Blob, preset: FontPreset): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error('Cannot apply font preset: document contains no word/styles.xml');\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error('Cannot apply font preset: document contains no word/document.xml');\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(paragraphPropertiesOf(docDefaults), 'widowControl').setAttributeNS(\n W_NS,\n 'w:val',\n '0'\n );\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(style.getAttributeNS(W_NS, 'styleId') ?? '');\n if (heading) {\n applyLevelStyle(style, preset.headings[Number(heading[1]) - 1], preset.paragraph, layout);\n }\n }\n\n return keepXmlDeclaration(stylesXml, new XMLSerializer().serializeToString(dom));\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n if (lineSpacing === 'grid' && !grid) {\n throw new Error(\"Cannot apply font preset: lineSpacing 'grid' needs page.grid\");\n }\n return {\n spacing:\n lineSpacing === 'grid' && grid\n ? { line: String(grid.linePitch), rule: 'exact' }\n : SINGLE_SPACING,\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(dom.getElementsByTagNameNS(W_NS, 'sectPr'))) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n\n if (gridSpacing) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing = pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n return {\n xml: keepXmlDeclaration(documentXml, new XMLSerializer().serializeToString(dom)),\n grid,\n };\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n { linesPerPage, charsPerLine }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`Cannot apply font preset: section has no page ${attribute}`);\n }\n return value;\n };\n\n const textHeight = twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth = twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find((child) => child.localName === 'printerSettings');\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(rPr.ownerDocument.createElementNS(W_NS, 'w:b'), rFonts.nextSibling);\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter((child) => child.namespaceURI === W_NS);\n}\n\nfunction childOrCreate(parent: Element, localName: string, position: 'first' | 'last'): Element {\n const existing = children(parent).find((child) => child.localName === localName);\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(`Cannot apply font preset: styles.xml has no <w:${localName}> element`);\n }\n return element;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,iBAAi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OAAO;QACzB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,kDAAkD,SAAS,WAAW,CACvE,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, ParagraphStyle } from './font-presets.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n} from './xml-part.js';\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 * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing and page grid of an already\n * generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(\n wordDocument: Blob,\n preset: FontPreset\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/styles.xml'\n );\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/document.xml'\n );\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(\n paragraphPropertiesOf(docDefaults),\n 'widowControl'\n ).setAttributeNS(W_NS, 'w:val', '0');\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(\n style.getAttributeNS(W_NS, 'styleId') ?? ''\n );\n if (heading) {\n applyLevelStyle(\n style,\n preset.headings[Number(heading[1]) - 1],\n preset.paragraph,\n layout\n );\n }\n }\n\n return keepXmlDeclaration(\n stylesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n if (lineSpacing === 'grid' && !grid) {\n throw new Error(\n \"Cannot apply font preset: lineSpacing 'grid' needs page.grid\"\n );\n }\n return {\n spacing:\n lineSpacing === 'grid' && grid\n ? { line: String(grid.linePitch), rule: 'exact' }\n : SINGLE_SPACING,\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(\n dom.getElementsByTagNameNS(W_NS, 'sectPr')\n )) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n\n if (gridSpacing) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing =\n pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n return {\n xml: keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n ),\n grid,\n };\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n {\n linesPerPage,\n charsPerLine,\n }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Cannot apply font preset: section has no page ${attribute}`\n );\n }\n return value;\n };\n\n const textHeight =\n twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth =\n twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find(\n (child) => child.localName === 'printerSettings'\n );\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(\n rPr.ownerDocument.createElementNS(W_NS, 'w:b'),\n rFonts.nextSibling\n );\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter(\n (child) => child.namespaceURI === W_NS\n );\n}\n\nfunction childOrCreate(\n parent: Element,\n localName: string,\n position: 'first' | 'last'\n): Element {\n const existing = children(parent).find(\n (child) => child.localName === localName\n );\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(\n `Cannot apply font preset: styles.xml has no <w:${localName}> element`\n );\n }\n return element;\n}\n"]}
|
package/build/docx-html.d.ts
CHANGED
|
@@ -23,6 +23,16 @@ export declare const RULE_TEXT = "* * *";
|
|
|
23
23
|
* the same value as a `text-align` style is honored.
|
|
24
24
|
* - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
|
|
25
25
|
* paragraph for the structure patch to draw as a rule.
|
|
26
|
+
* - Block quotes: the generator joins everything in a `<blockquote>` into one
|
|
27
|
+
* justified paragraph. Its paragraphs and headings are kept apart instead,
|
|
28
|
+
* left aligned and indented one step per level of nesting.
|
|
29
|
+
* - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
|
|
30
|
+
* text is dropped, so each is replaced by a span or `<em>` (see
|
|
31
|
+
* UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
|
|
32
|
+
* - Footnotes: the reference and back links point into the page, which a
|
|
33
|
+
* Word reader can't follow, so references keep only their number and the
|
|
34
|
+
* back links (↩) go. So does the footnotes heading, which the page only
|
|
35
|
+
* shows to screen readers.
|
|
26
36
|
*
|
|
27
37
|
* Only the HTML bound for the .docx changes; the preview keeps the original.
|
|
28
38
|
*/
|
package/build/docx-html.js
CHANGED
|
@@ -20,6 +20,38 @@ export const RULE_TEXT = '* * *';
|
|
|
20
20
|
* serialized tags, where the CSP doesn't reach.
|
|
21
21
|
*/
|
|
22
22
|
const STYLE_PLACEHOLDER = 'data-docx-style';
|
|
23
|
+
/** How far each level of block quote is indented. */
|
|
24
|
+
const QUOTE_INDENT_INCHES = 0.5;
|
|
25
|
+
/** Block quote children that become indented paragraphs. */
|
|
26
|
+
const QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
|
|
27
|
+
/**
|
|
28
|
+
* Inline elements the generator doesn't know, whose text it drops. Each is
|
|
29
|
+
* replaced by what a browser shows: a span (in the code font, for the ones a
|
|
30
|
+
* browser draws in monospace), emphasis, or quotation marks.
|
|
31
|
+
*/
|
|
32
|
+
const UNKNOWN_INLINE = {
|
|
33
|
+
kbd: 'code',
|
|
34
|
+
samp: 'code',
|
|
35
|
+
tt: 'code',
|
|
36
|
+
var: 'em',
|
|
37
|
+
cite: 'em',
|
|
38
|
+
dfn: 'em',
|
|
39
|
+
q: 'quote',
|
|
40
|
+
abbr: 'text',
|
|
41
|
+
acronym: 'text',
|
|
42
|
+
bdi: 'text',
|
|
43
|
+
bdo: 'text',
|
|
44
|
+
big: 'text',
|
|
45
|
+
data: 'text',
|
|
46
|
+
font: 'text',
|
|
47
|
+
label: 'text',
|
|
48
|
+
small: 'text',
|
|
49
|
+
time: 'text',
|
|
50
|
+
};
|
|
51
|
+
/** `Node.TEXT_NODE`, which Node's globals lack. */
|
|
52
|
+
const TEXT_NODE = 3;
|
|
53
|
+
/** The highlight browsers give `<mark>`; the generator drops it. */
|
|
54
|
+
const MARK_COLOR = '#FFFF00';
|
|
23
55
|
/**
|
|
24
56
|
* Adjusts the parser's HTML for html-to-docx, which drops or flattens some of
|
|
25
57
|
* what the browser preview renders:
|
|
@@ -33,13 +65,25 @@ const STYLE_PLACEHOLDER = 'data-docx-style';
|
|
|
33
65
|
* the same value as a `text-align` style is honored.
|
|
34
66
|
* - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
|
|
35
67
|
* paragraph for the structure patch to draw as a rule.
|
|
68
|
+
* - Block quotes: the generator joins everything in a `<blockquote>` into one
|
|
69
|
+
* justified paragraph. Its paragraphs and headings are kept apart instead,
|
|
70
|
+
* left aligned and indented one step per level of nesting.
|
|
71
|
+
* - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
|
|
72
|
+
* text is dropped, so each is replaced by a span or `<em>` (see
|
|
73
|
+
* UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
|
|
74
|
+
* - Footnotes: the reference and back links point into the page, which a
|
|
75
|
+
* Word reader can't follow, so references keep only their number and the
|
|
76
|
+
* back links (↩) go. So does the footnotes heading, which the page only
|
|
77
|
+
* shows to screen readers.
|
|
36
78
|
*
|
|
37
79
|
* Only the HTML bound for the .docx changes; the preview keeps the original.
|
|
38
80
|
*/
|
|
39
81
|
export function prepareHtmlForDocx(html) {
|
|
40
82
|
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
41
83
|
for (const input of Array.from(dom.querySelectorAll('input[type="checkbox"]'))) {
|
|
42
|
-
const box = input.hasAttribute('checked')
|
|
84
|
+
const box = input.hasAttribute('checked')
|
|
85
|
+
? CHECKBOX.checked
|
|
86
|
+
: CHECKBOX.unchecked;
|
|
43
87
|
input.replaceWith(dom.createTextNode(box));
|
|
44
88
|
}
|
|
45
89
|
for (const code of Array.from(dom.querySelectorAll('code'))) {
|
|
@@ -63,6 +107,44 @@ export function prepareHtmlForDocx(html) {
|
|
|
63
107
|
cell.append(strong);
|
|
64
108
|
}
|
|
65
109
|
}
|
|
110
|
+
for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {
|
|
111
|
+
// Outermost first; each one unwraps its nested quotes as it goes.
|
|
112
|
+
if (quote.isConnected)
|
|
113
|
+
unwrapQuote(quote, 1);
|
|
114
|
+
}
|
|
115
|
+
for (const element of Array.from(dom.body.querySelectorAll('*'))) {
|
|
116
|
+
const kind = UNKNOWN_INLINE[element.localName];
|
|
117
|
+
if (!kind || element.closest('pre'))
|
|
118
|
+
continue;
|
|
119
|
+
if (kind === 'quote') {
|
|
120
|
+
element.replaceWith('“', ...Array.from(element.childNodes), '”');
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');
|
|
124
|
+
if (kind === 'code') {
|
|
125
|
+
replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);
|
|
126
|
+
}
|
|
127
|
+
replacement.append(...Array.from(element.childNodes));
|
|
128
|
+
element.replaceWith(replacement);
|
|
129
|
+
}
|
|
130
|
+
for (const mark of Array.from(dom.querySelectorAll('mark'))) {
|
|
131
|
+
const span = dom.createElement('span');
|
|
132
|
+
span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);
|
|
133
|
+
span.append(...Array.from(mark.childNodes));
|
|
134
|
+
mark.replaceWith(span);
|
|
135
|
+
}
|
|
136
|
+
for (const reference of Array.from(dom.querySelectorAll('a[data-footnote-ref]'))) {
|
|
137
|
+
reference.replaceWith(...Array.from(reference.childNodes));
|
|
138
|
+
}
|
|
139
|
+
for (const backReference of Array.from(dom.querySelectorAll('a[data-footnote-backref]'))) {
|
|
140
|
+
// The space before it, too, so the note doesn't end in one.
|
|
141
|
+
const before = backReference.previousSibling;
|
|
142
|
+
if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {
|
|
143
|
+
before.textContent = before.textContent.slice(0, -1);
|
|
144
|
+
}
|
|
145
|
+
backReference.remove();
|
|
146
|
+
}
|
|
147
|
+
dom.querySelector('section[data-footnotes] > h2')?.remove();
|
|
66
148
|
for (const rule of Array.from(dom.querySelectorAll('hr'))) {
|
|
67
149
|
const paragraph = dom.createElement('p');
|
|
68
150
|
paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');
|
|
@@ -72,4 +154,27 @@ export function prepareHtmlForDocx(html) {
|
|
|
72
154
|
// Only inside tags: text can't contain a raw `<`, so it's never touched.
|
|
73
155
|
return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) => tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='));
|
|
74
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Replaces `quote` with its children, indenting its paragraphs and headings
|
|
159
|
+
* `depth` steps. Other blocks (lists, code, tables) keep their own layout, and
|
|
160
|
+
* so does a quote in a list item: the generator indents that paragraph for the
|
|
161
|
+
* list already, and a second indent would be invalid or move the bullet.
|
|
162
|
+
*/
|
|
163
|
+
function unwrapQuote(quote, depth) {
|
|
164
|
+
const inList = quote.closest('li') !== null;
|
|
165
|
+
for (const child of Array.from(quote.children)) {
|
|
166
|
+
if (child.localName === 'blockquote') {
|
|
167
|
+
unwrapQuote(child, depth + 1);
|
|
168
|
+
}
|
|
169
|
+
else if (QUOTE_PARAGRAPHS.has(child.localName)) {
|
|
170
|
+
const align = 'text-align: left';
|
|
171
|
+
const layout = inList
|
|
172
|
+
? align
|
|
173
|
+
: `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;
|
|
174
|
+
const style = child.getAttribute(STYLE_PLACEHOLDER);
|
|
175
|
+
child.setAttribute(STYLE_PLACEHOLDER, style ? `${style}; ${layout}` : layout);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
quote.replaceWith(...Array.from(quote.childNodes));
|
|
179
|
+
}
|
|
75
180
|
//# sourceMappingURL=docx-html.js.map
|
package/build/docx-html.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY;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AAC;QAChC,CAAC;QACD,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI,IAAI,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;YACxD,MAAM,MAAM,GAAG,GAAG,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;YAC3C,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;YAC9C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;QAC1D,MAAM,SAAS,GAAG,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QACzC,SAAS,CAAC,YAAY,CAAC,iBAAiB,EAAE,oBAAoB,CAAC,CAAC;QAChE,SAAS,CAAC,WAAW,GAAG,SAAS,CAAC;QAClC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;IAC9B,CAAC;IAED,yEAAyE;IACzE,OAAO,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE,CACpD,GAAG,CAAC,OAAO,CAAC,IAAI,iBAAiB,GAAG,EAAE,SAAS,CAAC,CACjD,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(dom.querySelectorAll('input[type=\"checkbox\"]'))) {\n const box = input.hasAttribute('checked') ? CHECKBOX.checked : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,qDAAqD;AACrD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,4DAA4D;AAC5D,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAE5E;;;;GAIG;AACH,MAAM,cAAc,GAAqD;IACvE,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,EAAE,EAAE,MAAM;IACV,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,CAAC,EAAE,OAAO;IACV,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,MAAM;IACf,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,MAAM;IACb,KAAK,EAAE,MAAM;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AC;aAAM,IAAI,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;YACjD,MAAM,KAAK,GAAG,kBAAkB,CAAC;YACjC,MAAM,MAAM,GAAG,MAAM;gBACnB,CAAC,CAAC,KAAK;gBACP,CAAC,CAAC,gBAAgB,KAAK,GAAG,mBAAmB,OAAO,KAAK,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,CAAC;YACpD,KAAK,CAAC,YAAY,CAChB,iBAAiB,EACjB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CACvC,CAAC;QACJ,CAAC;IACH,CAAC;IACD,KAAK,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span (in the code font, for the ones a\n * browser draws in monospace), emphasis, or quotation marks.\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote' | 'text'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n abbr: 'text',\n acronym: 'text',\n bdi: 'text',\n bdo: 'text',\n big: 'text',\n data: 'text',\n font: 'text',\n label: 'text',\n small: 'text',\n time: 'text',\n};\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their\n * text is dropped, so each is replaced by a span or `<em>` (see\n * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n for (const element of Array.from(dom.body.querySelectorAll('*'))) {\n const kind = UNKNOWN_INLINE[element.localName];\n if (!kind || element.closest('pre')) continue;\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */
|
|
2
|
+
export declare const MAX_IMAGE_BYTES: number;
|
|
3
|
+
/**
|
|
4
|
+
* The most distinct image URLs fetched for one document: html-to-docx keeps
|
|
5
|
+
* at most this many in its image cache (imageProcessing.maxCacheEntries). The
|
|
6
|
+
* rest keep their alt text.
|
|
7
|
+
*/
|
|
8
|
+
export declare const MAX_IMAGES = 100;
|
|
9
|
+
/**
|
|
10
|
+
* How many downloads run at once. html-to-docx fetched one at a time; a few
|
|
11
|
+
* in parallel is faster without opening a connection per image.
|
|
12
|
+
*/
|
|
13
|
+
export declare const CONCURRENCY = 4;
|
|
14
|
+
/**
|
|
15
|
+
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
16
|
+
* which html-to-docx embeds without downloading it again. An image that can't
|
|
17
|
+
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
18
|
+
* drop it without a trace. Other sources it can't embed either, such as a
|
|
19
|
+
* relative path, keep their alt text too.
|
|
20
|
+
*
|
|
21
|
+
* Each URL is fetched once, however many times it appears: at most
|
|
22
|
+
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
23
|
+
*/
|
|
24
|
+
export declare function embedImages(html: string): Promise<string>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { Buffer } from 'buffer';
|
|
2
|
+
/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */
|
|
3
|
+
export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
4
|
+
/**
|
|
5
|
+
* The most distinct image URLs fetched for one document: html-to-docx keeps
|
|
6
|
+
* at most this many in its image cache (imageProcessing.maxCacheEntries). The
|
|
7
|
+
* rest keep their alt text.
|
|
8
|
+
*/
|
|
9
|
+
export const MAX_IMAGES = 100;
|
|
10
|
+
/**
|
|
11
|
+
* How many downloads run at once. html-to-docx fetched one at a time; a few
|
|
12
|
+
* in parallel is faster without opening a connection per image.
|
|
13
|
+
*/
|
|
14
|
+
export const CONCURRENCY = 4;
|
|
15
|
+
/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */
|
|
16
|
+
const TIMEOUT_MS = 5000;
|
|
17
|
+
const ATTEMPTS = 2;
|
|
18
|
+
/**
|
|
19
|
+
* The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag
|
|
20
|
+
* that makes `test()` stateful), anchored so the whole `src` is the URL.
|
|
21
|
+
* Requiring both means this module never fetches what it wouldn't.
|
|
22
|
+
*/
|
|
23
|
+
const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
|
|
24
|
+
const WEB_URL = /^https?:\/\//i;
|
|
25
|
+
/** Leading bytes of the image formats Word embeds, for servers that don't say. */
|
|
26
|
+
const SIGNATURES = [
|
|
27
|
+
['image/png', [0x89, 0x50, 0x4e, 0x47]],
|
|
28
|
+
['image/jpeg', [0xff, 0xd8, 0xff]],
|
|
29
|
+
['image/gif', [0x47, 0x49, 0x46, 0x38]],
|
|
30
|
+
['image/bmp', [0x42, 0x4d]],
|
|
31
|
+
];
|
|
32
|
+
/**
|
|
33
|
+
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
34
|
+
* which html-to-docx embeds without downloading it again. An image that can't
|
|
35
|
+
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
36
|
+
* drop it without a trace. Other sources it can't embed either, such as a
|
|
37
|
+
* relative path, keep their alt text too.
|
|
38
|
+
*
|
|
39
|
+
* Each URL is fetched once, however many times it appears: at most
|
|
40
|
+
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
41
|
+
*/
|
|
42
|
+
export async function embedImages(html) {
|
|
43
|
+
const dom = new DOMParser().parseFromString(html, 'text/html');
|
|
44
|
+
const images = Array.from(dom.querySelectorAll('img'));
|
|
45
|
+
if (images.length === 0)
|
|
46
|
+
return html;
|
|
47
|
+
const urls = new Set();
|
|
48
|
+
for (const image of images) {
|
|
49
|
+
const src = image.getAttribute('src') ?? '';
|
|
50
|
+
if (isFetchable(src) && urls.size < MAX_IMAGES)
|
|
51
|
+
urls.add(src);
|
|
52
|
+
}
|
|
53
|
+
const queue = Array.from(urls);
|
|
54
|
+
const downloads = new Map();
|
|
55
|
+
const worker = async () => {
|
|
56
|
+
for (let url = queue.shift(); url !== undefined; url = queue.shift()) {
|
|
57
|
+
downloads.set(url, await fetchImage(url));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
|
|
61
|
+
for (const image of images) {
|
|
62
|
+
const src = image.getAttribute('src') ?? '';
|
|
63
|
+
if (src.startsWith('data:'))
|
|
64
|
+
continue;
|
|
65
|
+
const dataUri = downloads.get(src);
|
|
66
|
+
if (dataUri) {
|
|
67
|
+
image.setAttribute('src', dataUri);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
replaceWithAltText(image, src);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return dom.body.innerHTML;
|
|
74
|
+
}
|
|
75
|
+
function isFetchable(src) {
|
|
76
|
+
return WEB_URL.test(src) && GENERATOR_URL.test(src);
|
|
77
|
+
}
|
|
78
|
+
/** The image at `url` as a `data:` URI, or null if it can't be fetched. */
|
|
79
|
+
async function fetchImage(url) {
|
|
80
|
+
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
|
|
81
|
+
const tooLarge = new AbortController();
|
|
82
|
+
try {
|
|
83
|
+
const response = await fetch(url, {
|
|
84
|
+
signal: AbortSignal.any([
|
|
85
|
+
tooLarge.signal,
|
|
86
|
+
AbortSignal.timeout(TIMEOUT_MS * attempt),
|
|
87
|
+
]),
|
|
88
|
+
});
|
|
89
|
+
// Not found, forbidden or too large won't change on a retry.
|
|
90
|
+
if (!response.ok)
|
|
91
|
+
return null;
|
|
92
|
+
if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {
|
|
93
|
+
tooLarge.abort();
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const bytes = await readBody(response, tooLarge);
|
|
97
|
+
if (!bytes || bytes.length === 0)
|
|
98
|
+
return null;
|
|
99
|
+
const type = imageType(response.headers.get('content-type'), bytes);
|
|
100
|
+
if (!type)
|
|
101
|
+
return null;
|
|
102
|
+
return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
if (tooLarge.signal.aborted)
|
|
106
|
+
return null;
|
|
107
|
+
// Offline, blocked by CORS or the CSP, or timed out: try once more.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The response body, read a chunk at a time so a server that sends more than
|
|
114
|
+
* MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather
|
|
115
|
+
* than held in memory. Null if it was too large.
|
|
116
|
+
*/
|
|
117
|
+
async function readBody(response, tooLarge) {
|
|
118
|
+
if (!response.body) {
|
|
119
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
120
|
+
return bytes.length > MAX_IMAGE_BYTES ? null : bytes;
|
|
121
|
+
}
|
|
122
|
+
const reader = response.body.getReader();
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let total = 0;
|
|
125
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
126
|
+
total += chunk.value.length;
|
|
127
|
+
if (total > MAX_IMAGE_BYTES) {
|
|
128
|
+
tooLarge.abort();
|
|
129
|
+
await reader.cancel().catch(() => { });
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
chunks.push(chunk.value);
|
|
133
|
+
}
|
|
134
|
+
const bytes = new Uint8Array(total);
|
|
135
|
+
let offset = 0;
|
|
136
|
+
for (const chunk of chunks) {
|
|
137
|
+
bytes.set(chunk, offset);
|
|
138
|
+
offset += chunk.length;
|
|
139
|
+
}
|
|
140
|
+
return bytes;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The image's media type: the server's, if it says it's an image, or else
|
|
144
|
+
* read from the file's first bytes. Null for anything else (an error page
|
|
145
|
+
* served with 200, say), which html-to-docx would fail to measure and drop.
|
|
146
|
+
*/
|
|
147
|
+
function imageType(contentType, bytes) {
|
|
148
|
+
const declared = contentType?.split(';')[0].trim().toLowerCase();
|
|
149
|
+
if (declared?.startsWith('image/'))
|
|
150
|
+
return declared;
|
|
151
|
+
const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
|
|
152
|
+
return match?.[0] ?? null;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Puts the image's alt text where it was, as a link to `src` when that's a web
|
|
156
|
+
* URL and the image isn't already inside a link. With no alt text, the URL
|
|
157
|
+
* itself is the text.
|
|
158
|
+
*/
|
|
159
|
+
function replaceWithAltText(image, src) {
|
|
160
|
+
const document = image.ownerDocument;
|
|
161
|
+
const isWebUrl = WEB_URL.test(src);
|
|
162
|
+
const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');
|
|
163
|
+
if (!text) {
|
|
164
|
+
image.remove();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!isWebUrl || image.closest('a')) {
|
|
168
|
+
image.replaceWith(document.createTextNode(text));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const link = document.createElement('a');
|
|
172
|
+
link.setAttribute('href', src);
|
|
173
|
+
link.textContent = text;
|
|
174
|
+
image.replaceWith(link);
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=docx-images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE7B,iFAAiF;AACjF,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB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,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/** Leading bytes of the image formats Word embeds, for servers that don't say. */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (src.startsWith('data:')) continue;\n const dataUri = downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type: the server's, if it says it's an image, or else\n * read from the file's first bytes. Null for anything else (an error page\n * served with 200, say), which html-to-docx would fail to measure and drop.\n */\nfunction imageType(\n contentType: string | null,\n bytes: Uint8Array\n): string | null {\n const declared = contentType?.split(';')[0].trim().toLowerCase();\n if (declared?.startsWith('image/')) return declared;\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n return match?.[0] ?? null;\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
@@ -16,6 +16,9 @@ export interface DocumentStructure {
|
|
|
16
16
|
* it at the top of each page the table spans.
|
|
17
17
|
* - Table grids: the generator writes a second `<w:tblGrid>` between rows,
|
|
18
18
|
* which the schema doesn't allow; only the first is kept.
|
|
19
|
+
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
20
|
+
* size and margins) as its first child. The schema requires it last, and
|
|
21
|
+
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
19
22
|
*/
|
|
20
23
|
export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
|
|
21
24
|
/** Exported for testing. */
|
package/build/docx-structure.js
CHANGED
|
@@ -12,6 +12,9 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
|
12
12
|
* it at the top of each page the table spans.
|
|
13
13
|
* - Table grids: the generator writes a second `<w:tblGrid>` between rows,
|
|
14
14
|
* which the schema doesn't allow; only the first is kept.
|
|
15
|
+
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
16
|
+
* size and margins) as its first child. The schema requires it last, and
|
|
17
|
+
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
15
18
|
*/
|
|
16
19
|
export async function patchStructure(wordDocument, structure) {
|
|
17
20
|
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
@@ -56,6 +59,12 @@ export function patchDocumentXml(documentXml, structure) {
|
|
|
56
59
|
changed = true;
|
|
57
60
|
}
|
|
58
61
|
}
|
|
62
|
+
const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];
|
|
63
|
+
const sectPr = body && children(body, 'sectPr')[0];
|
|
64
|
+
if (sectPr && body.lastElementChild !== sectPr) {
|
|
65
|
+
body.appendChild(sectPr);
|
|
66
|
+
changed = true;
|
|
67
|
+
}
|
|
59
68
|
if (!changed) {
|
|
60
69
|
return documentXml;
|
|
61
70
|
}
|
|
@@ -66,7 +75,7 @@ function isRulePlaceholder(paragraph) {
|
|
|
66
75
|
.map((t) => t.textContent ?? '')
|
|
67
76
|
.join('');
|
|
68
77
|
const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];
|
|
69
|
-
return text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center';
|
|
78
|
+
return (text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center');
|
|
70
79
|
}
|
|
71
80
|
/** Replaces the paragraph's content with nothing but a bottom border. */
|
|
72
81
|
function drawRule(paragraph) {
|