Mayank Chaudhari
Back to Blog
•

Building a Markdown-to-DOCX Compiler: ASTs over String Hacks

Building a Markdown-to-DOCX Compiler: ASTs over String Hacks
Engineering
#Compilers#AST#TypeScript#OpenXML#Architecture

Series Navigation: This is Part 3 in our 7-part engineering deep-dive on md2docx, our universal AST document compiler:


1. The Siren Song of the String Hack

Every engineering team tasked with exporting Markdown to Microsoft Word inevitably encounters the same seductive proposal:

"Word documents are just XML packaged inside a ZIP file. We can write a few regex passes, interpolate XML strings into a template, and zip it up."

On a whiteboard, this appears deceptively simple. A heading # Title maps to <w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Title</w:t></w:r></w:p>. An inline bold span **text** translates to <w:r><w:rPr><w:b/></w:rPr><w:t>text</w:t></w:r>. A quick prototype handles twenty words of sample text, Microsoft Word opens the file without protest, and the task is declared complete.

Production environments swiftly shatter this illusion.

The moment real-world Markdown enters the system—nested formatting such as **Caution: *Do not* restart the node.**, multi-line lists, GitHub Flavored Markdown (GFM) tables, or inline code containing XML-reserved characters—string replacement collapses. Regex engines lack the pushdown automata required to track nested scopes across arbitrary line breaks. String interpolation easily produces misnested tags or emits table cells lacking mandatory structural wrappers.

When an enterprise customer or executive attempts to open the resulting file, Microsoft Word halts with an explicit schema validation failure:

┌────────────────────────────────────────────────────────────────────────┐
│ Microsoft Word                                                         │
├────────────────────────────────────────────────────────────────────────┤
│ Word found unreadable content in "Q3-Infrastructure-Report.docx".       │
│ Do you want to recover the contents of this document? If you trust     │
│ the source of this document, click Yes.                                │
│                                                                        │
│ [ Yes ]                                                       [ No ]   │
│                                                                        │
│ Location: Part: /word/document.xml, Line: 2, Column: 14820             │
└────────────────────────────────────────────────────────────────────────┘

Document corruption in enterprise software directly damages product trust. In regulated banking, legal, and healthcare workflows, a corrupted audit report or executive summary halts operations.

To produce reliable, schema-conformant Word documents at scale, text-level substitution must give way to structured compilation. Document translation is not a string formatting exercise; it is a compiler problem.


2. Anatomy of the Target: ISO/IEC 29500 (OpenXML)

To understand why string manipulation fails, one must examine the target architecture: Office Open XML (OOXML), standardized under ISO/IEC 29500.

A .docx file is an Open Packaging Conventions (OPC) ZIP archive containing a multi-part graph of XML files, media blobs, and relationship manifests:

document.docx (ZIP Package)
├── [Content_Types].xml        <- MIME type registry for package parts
├── _rels/
│   └── .rels                  <- Root relationship graph
├── word/
│   ├── document.xml           <- Main document story (body content)
│   ├── styles.xml             <- Paragraph and run style definitions
│   ├── numbering.xml          <- Abstract list hierarchies and overrides
│   ├── footnotes.xml          <- Footnote body definitions
│   └── _rels/
│       └── document.xml.rels  <- Target URIs, images, and hyperlink IDs

Inside word/document.xml, Word enforces an uncompromising, deeply nested, strictly ordered schema:

┌───────────────────────────────────────────────────────────┐
│ <w:document>                                              │
│   └── <w:body>                                            │
│         ├── <w:p> (Paragraph)                             │
│         │     ├── <w:pPr> (Paragraph Properties)          │
│         │     │     ├── <w:pStyle w:val="Heading1"/>      │
│         │     │     └── <w:jc w:val="center"/>            │
│         │     └── <w:r> (Run)                             │
│         │           ├── <w:rPr> (Run Properties)          │
│         │           │     ├── <w:b/>                      │
│         │           │     └── <w:color w:val="003366"/>   │
│         │           └── <w:t>Text content</w:t>           │
│         └── <w:tbl> (Table)                               │
│               ├── <w:tblPr>                               │
│               └── <w:tr> (Table Row)                      │
│                     └── <w:tc> (Table Cell)               │
│                           ├── <w:tcPr/>                   │
│                           └── <w:p> (Mandatory Child)     │
└───────────────────────────────────────────────────────────┘

Why OpenXML Constraints Demand an Intermediate Tree

Three structural properties of OpenXML make ad-hoc text substitution uniquely error-prone:

1. Flat Run Fracturing vs. Nested Markup

In HTML and Markdown, formatting is tree-like and composable via nested tags:

<p>This is <strong>bold and <em>italicized</em></strong> text.</p>

In OpenXML, runs cannot nest. A run (<w:r>) is a flat, contiguous leaf node of text that shares an identical set of run properties (<w:rPr>). Any variation in bold, italic, strikethrough, font size, or color forces an immediate fracture into a new sibling run:

<w:p>
  <w:r>
    <w:t xml:space="preserve">This is </w:t>
  </w:r>
  <w:r>
    <w:rPr><w:b/></w:rPr>
    <w:t xml:space="preserve">bold and </w:t>
  </w:r>
  <w:r>
    <w:rPr><w:b/><w:i/></w:rPr>
    <w:t>italicized</w:t>
  </w:r>
  <w:r>
    <w:t xml:space="preserve"> text.</w:t>
  </w:r>
</w:p>

Resolving overlapping inline styles into a sequence of fractured sibling runs requires computing the exact set of active formatting flags across all token boundaries. Without a structured state stack, string operations routinely invert or miss closing markers.

2. Strict Child Ordering Requirements

OpenXML XML Schema Definition (XSD) rules enforce sequence ordering. Within <w:p>, <w:pPr> must precede all <w:r> runs. Inside <w:r>, <w:rPr> must precede <w:t>. Inside <w:tc>, at least one <w:p> is syntactically mandatory—an empty table cell (<w:tc/> or <w:tc><w:tcPr/></w:tc>) violates the schema and prompts Word's recovery dialog.

3. Dedicated Coordinate Physics

OpenXML operates entirely in specialized non-metric, non-pixel coordinate systems:

  • Twips (Twentieth of an Imperial Point): 1 pt=20 twips1\text{ pt} = 20\text{ twips}; 1 inch=72 pt=1,440 twips1\text{ inch} = 72\text{ pt} = 1,440\text{ twips}; 1 mm≈56.6929 twips1\text{ mm} \approx 56.6929\text{ twips}. Page margins, table cell paddings, and column widths must be calculated in integer twips.
  • Half-Points: Font sizes (<w:sz w:val="24"/>) are specified in half-points (24=12 pt24 = 12\text{ pt}).
  • EMUs (English Metric Units): Images and vector drawings must be positioned in EMUs (1 inch=914,400 EMUs1\text{ inch} = 914,400\text{ EMUs}; 1 cm=360,000 EMUs1\text{ cm} = 360,000\text{ EMUs}).

Managing twip conversions, relationship ID mappings (r:id="rId5"), and XML namespace bindings requires a compiler pipeline with structured intermediate models.


3. The Canonical Compiler Architecture: The MDAST-to-OpenXML Pipeline

In md2docx, document generation is organized as a classical multi-stage compiler pipeline. Rather than manipulating text, we parse Markdown into a Markdown Abstract Syntax Tree (MDAST), traverse the tree with dedicated visitor passes, project semantic nodes into validated in-memory OpenXML document primitives (docx.js), and serialize the package deterministically.

flowchart TD subgraph Frontend ["1. Frontend: Lexical Analysis & Grammar Parsing"] A["Raw Markdown Input"] --> B["unified() Pipeline"] B --> C["remark-parse<br/>(CommonMark Parser)"] B --> D["remark-gfm<br/>(Tables, Task Lists, Strikethrough)"] B --> E["remark-math<br/>(LaTeX Math Syntaxes)"] B --> F["remark-frontmatter<br/>(YAML / TOML Metadata)"] end subgraph IR ["2. Intermediate Representation (MDAST)"] C & D & E & F --> G["Unist MDAST Tree<br/>(Typed Node Graph)"] end subgraph MidEnd ["3. Middle-End: Visitor & Transformation Engine (@m2d/core)"] G --> H["Pass 1: Preprocessing & Hoisting<br/>(Link Defs, Footnotes, Frontmatter Metadata)"] H --> I["Pass 2: Hierarchical Traversal"] I --> J["processBlockNodeChildren<br/>(Headings, Paragraphs, Blockquotes, Lists)"] I --> K["processInlineNodeChildren<br/>(Run Property Accumulator Stack)"] I --> L["Plugin Interception Layer<br/>(@m2d/table, @m2d/code, custom hooks)"] end subgraph Backend ["4. Backend: OpenXML Model & Serialization (docx.js)"] J & K & L --> M["Typed OpenXML DOM Primitives<br/>(Document, Section, Paragraph, Table, Run)"] M --> N["Packer Serialization<br/>(Packer.toBlob / Packer.toBuffer)"] N --> O["Conformant .docx Package<br/>(ISO/IEC 29500 OPC ZIP)"] end

The Intermediate AST Representation

When the unified parser processes a Markdown snippet:

# Infrastructure

Deploy the **cluster** using [Terraform](#deploy).

It emits an unambiguous syntax tree conforming to the unist specification:

{
  "type": "root",
  "children": [
    {
      "type": "heading",
      "depth": 1,
      "children": [{ "type": "text", "value": "Infrastructure" }]
    },
    {
      "type": "paragraph",
      "children": [
        { "type": "text", "value": "Deploy the " },
        {
          "type": "strong",
          "children": [{ "type": "text", "value": "cluster" }]
        },
        { "type": "text", "value": " using " },
        {
          "type": "link",
          "url": "#deploy",
          "children": [{ "type": "text", "value": "Terraform" }]
        },
        { "type": "text", "value": "." }
      ]
    }
  ]
}

This structural representation delivers three foundational compiler properties:

  1. Syntax Tokens Discarded: Hashes, asterisks, brackets, and escapes are resolved into typed AST nodes (heading, strong, link).
  2. Explicit Nesting Hierarchy: The strong node encloses its children directly, making formatting inheritance a deterministic tree walk.
  3. Static Analysis & Extensibility: Plugins can inspect, mutate, reorder, or enrich nodes before emitting OpenXML primitives.

4. Architectural Implementation: Inside packages/core

To maintain clean separation of concerns, the compiler is partitioned across focused workspace packages:

PackageRole in Architecture
@m2d/coreThe visitor engine, section orchestrator, default inline/block walkers, and plugin hook dispatcher.
@m2d/remark-docxThe Unified.js plugin bridging remark processors to toDocx.
@m2d/md2docxThe client-side entry point pre-configured with GFM, math, and frontmatter.
@m2d/tableThe table visitor handling twip margins, alignments, zebra shading, and cell wrapping.

The Unified Pipeline Entry Point

In packages/md2docx/src/md2docx.ts, document generation is composed via standard Unified plugin chaining:

// packages/md2docx/src/md2docx.ts
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import remarkFrontmatter from "remark-frontmatter";
import { remarkDocx } from "@m2d/remark-docx";
import type { OutputType } from "docx";

export const md2docx = async (
  md: string,
  docxProps: IDocxProps = {},
  sectionProps?: ISectionProps,
  outputType: OutputType = "blob",
  pluginProps?: Mdast2DocxPluginProps,
) => {
  const processor = unified().use([
    remarkParse,
    remarkGfm,
    remarkMath,
    remarkFrontmatter,
    [remarkDocx, outputType, docxProps, sectionProps, pluginProps],
  ]);

  const res = await processor.process(md);
  return res.result;
};

When processor.process(md) executes:

  1. remarkParse tokenizes the Markdown string into a core MDAST.
  2. remarkGfm extends the grammar with tables, strikethrough, task lists, and autolinks.
  3. remarkMath captures LaTeX math blocks ($ and $$).
  4. remarkFrontmatter extracts YAML/TOML metadata headers.
  5. remarkDocx acts as the compiler terminal, invoking toDocx() on the completed tree.

5. Walking the Tree: The Two-Pass Visitor Pattern

Transforming an arbitrary AST into a valid OpenXML document requires two distinct phases: Definition Hoisting and Hierarchical Traversal.

flowchart TD subgraph Pass1 ["Pass 1: Definition Hoisting & Pre-Processing"] P1A["Scan Root Children"] --> P1B["Collect Link Definitions<br/>id -> target URI"] P1A --> P1C["Index Footnote Definitions<br/>identifier -> footnote body"] P1A --> P1D["Extract YAML/TOML Frontmatter<br/>Page setup, margins, headers"] P1B & P1C & P1D --> P1E["Execute Plugin preprocess() Hooks"] end subgraph Pass2 ["Pass 2: Recursive Block & Inline Visitors"] P2A["toSection()"] --> P2B["processBlockNodeChildren()"] P2B -->|Block: Heading| P2C["new Paragraph + Bookmark"] P2B -->|Block: Paragraph| P2D["new Paragraph"] P2B -->|Block: Table| P2E["tablePlugin.block -> new Table"] P2D --> P2F["processInlineNodeChildren()"] P2F -->|Inline: Text| P2G["new TextRun(value)"] P2F -->|Inline: Strong| P2H["runProps.bold = true -> recurse"] P2F -->|Inline: Link| P2I["new ExternalHyperlink / InternalHyperlink"] end Pass1 --> Pass2

Pass 1: Hoisting Definitions and Footnotes

In Markdown, reference definitions and footnotes can appear anywhere in the source document—often at the very end of the file:

Here is a reference to [Monorepo Architecture Documentation][arch-ref] and a footnote[^1].

[arch-ref]: /blog/from-fragmented-repositories-to-modern-monorepo
[^1]: Verified against ISO/IEC 29500-1:2016.

A single-pass streaming parser would encounter [arch-ref] before knowing its target URI.

In packages/core/src/index.ts, toDocx executes pre-flight definition indexing before visiting document body nodes:

// packages/core/src/index.ts (extract)
const processedAstInputs = await Promise.all(
  (Array.isArray(astInputs) ? astInputs : [{ ast: astInputs }]).map(
    async ({ ast, props }) => {
      // 1. Scan tree for link & footnote definitions
      const { definitions, footnoteDefinitions } = getDefinitions(
        ast.children as RootContent[],
      );

      // 2. Pre-compile footnotes into dedicated section models
      await Promise.all(
        Object.values(footnoteDefinitions).map(async (footnote, index) => {
          const footnoteId = index + 1;
          footnote.id = footnoteId;
          footnotes[footnoteId] = (await toSection(
            { type: "root", children: footnote.children },
            definitions,
            {},
            { footnoteProps },
          )) as { children: Paragraph[] };
        }),
      );

      return { ast, props: sectionProps, definitions, footnoteDefinitions };
    },
  ),
);

Pass 2: The Inline Node Processor & Property Stacking

Inline formatting in Markdown represents a state machine where properties inherit down the tree. When visiting strong, emphasis, or delete, formatting flags accumulate until a leaf text node is materialized.

Here is the exact implementation from packages/core/src/section.ts:

// packages/core/src/section.ts (extract)
const createInlineProcessor = (
  definitions: Definitions,
  footnoteDefinitions: FootnoteDefinitions,
  plugins: IPlugin[],
  trimInnerSpaces: boolean,
) => {
  const normalizeText = (text: string) =>
    trimInnerSpaces ? text.replace(/ +/g, " ") : text;

  const processInlineNodeChildren: InlineChildrenProcessor = (
    node,
    runProps = {},
  ) =>
    (
      node.children?.map((child) => {
        // Allow plugins to intercept inline rendering
        const docxNodes: InlineDocxNodes[] = plugins.flatMap(
          (plugin) =>
            plugin.inline?.(
              docx,
              child,
              runProps,
              definitions,
              footnoteDefinitions,
              processInlineNodeChildren,
            ) ?? [],
        );

        // Inherit styling properties from parent context
        const newRunProps = Object.assign({}, runProps, child.data);
        const url = child.url ?? definitions[child.identifier?.toUpperCase()];

        switch (child.type) {
          case "text":
            return [
              ...docxNodes,
              new TextRun({
                text: normalizeText(child.value),
                ...newRunProps,
              }),
            ];

          case "emphasis":
            newRunProps.italics = true;
            return [
              ...docxNodes,
              ...processInlineNodeChildren(child, newRunProps),
            ];

          case "strong":
            newRunProps.bold = true;
            return [
              ...docxNodes,
              ...processInlineNodeChildren(child, newRunProps),
            ];

          case "delete":
            newRunProps.strike = true;
            return [
              ...docxNodes,
              ...processInlineNodeChildren(child, newRunProps),
            ];

          case "inlineCode":
            return [
              ...docxNodes,
              new TextRun({
                text: normalizeText(child.value),
                ...newRunProps,
                style: "code",
                font: { name: "Consolas" },
              }),
            ];

          case "link":
          case "linkReference":
            newRunProps.underline = {};
            return [
              ...docxNodes,
              url.startsWith("#")
                ? new InternalHyperlink({
                    anchor: url.slice(1),
                    children: processInlineNodeChildren(child, newRunProps),
                  })
                : new ExternalHyperlink({
                    link: url,
                    children: processInlineNodeChildren(child, newRunProps),
                  }),
            ];

          case "footnoteReference":
            return [
              ...docxNodes,
              new FootnoteReferenceRun(
                footnoteDefinitions[child.identifier]?.id ?? 0,
              ),
            ];

          default:
            return [...docxNodes];
        }
      }) ?? []
    ).flat();

  return processInlineNodeChildren;
};

How State Accumulation Prevents Tag-Nesting Inversions

Consider how processInlineNodeChildren evaluates nested styles such as **bold *and italic***:

  1. The strong node receives an empty runProps object ({}). It assigns newRunProps.bold = true and recurses into its children.
  2. The first child is a text node ("bold "). It creates a TextRun({ text: "bold ", bold: true }).
  3. The second child is an emphasis node. It receives { bold: true }, assigns newRunProps.italics = true, and recurses.
  4. The leaf text node ("and italic") receives { bold: true, italics: true }. It creates a TextRun({ text: "and italic", bold: true, italics: true }).

The recursive walk flattens hierarchical styling into an array of concrete OpenXML <w:r> runs.

AST traversal enforces structural sequence invariants and tag nesting hierarchies required by the ISO/IEC 29500 specification (such as wrapping text in paragraphs and cells in tables), which significantly minimizes the risk of producing corrupted documents compared to string concatenation. However, AST traversal does not by itself ensure complete document validity: custom user plugins that inject malformed raw XML fragments or invalid font references can still trigger Word recovery prompts if not properly checked before serialization.


6. Transforming Complex Blocks: Tables and Margins

Tables in OpenXML require careful coordinate calculation. In Markdown, a table is simply lines of pipe-delimited text:

| Service | Latency (p99) | Status |
| :--- | :---: | ---: |
| Gateway | 1.2ms | Operational |
| Database | 4.8ms | Degraded |

In OpenXML, table generation involves several strict schema requirements:

  1. Calculating explicit twip margins for cell padding.
  2. Resolving column-level alignment rules (:---: vs ---:).
  3. Applying borders (<w:tblBorders>) and zebra shading (<w:shd>).
  4. Mandatory Block Wrapping: Every <w:tc> must contain at least one block element (<w:p>). Placing a raw run (<w:r>) directly inside a table cell produces an invalid schema and triggers a document repair dialog.

In @m2d/table, we handle this via wrapInBlockNodeIfNeeded and deterministic twip margin mapping:

// packages/table/src/index.ts (extract)
const border = { style: BorderStyle.SINGLE, color: "auto", size: 1 };

export const defaultTableOptions: IDefaultTablePluginProps = {
  tableProps: {
    width: { size: 100, type: WidthType.PERCENTAGE },
    margins: {
      top: convertMillimetersToTwip(2),
      right: convertMillimetersToTwip(4),
      bottom: convertMillimetersToTwip(2),
      left: convertMillimetersToTwip(4),
    },
    borders: {
      top: border,
      right: border,
      bottom: border,
      left: border,
      insideHorizontal: border,
      insideVertical: border,
    },
  },
  // ...
};

// Inside tablePlugin.block visitor:
const wrapInBlockNodeIfNeeded = (cell: { children: RootContent[] }) => {
  const children: RootContent[] = [];
  const tmp: PhrasingContent[] = [];
  for (const cellNode of cell.children) {
    if (blockNodeTypesThatCanComeInCell.includes(cellNode.type)) {
      if (tmp.length > 0) {
        children.push({ type: "paragraph", children: [...tmp] });
        tmp.length = 0;
      }
      children.push(cellNode);
    } else {
      tmp.push(cellNode as PhrasingContent);
    }
  }
  if (tmp.length > 0) {
    children.push({ type: "paragraph", children: tmp });
  }
  cell.children = children;
};

When building each row, the table plugin extracts alignment indicators from the MDAST node.align array and maps them directly to docx.AlignmentType:

const align = (node.align as (string | null)[] | null)?.map((a) => {
  switch (a) {
    case "left":
      return docx.AlignmentType.LEFT;
    case "right":
      return docx.AlignmentType.RIGHT;
    case "center":
      return docx.AlignmentType.CENTER;
    default:
      return undefined;
  }
});

Operating on the AST ensures that cells with complex contents (such as bold links or footnote references) inherit column alignment deterministically without breaking cell layout.


7. The Sentinel Pattern: Preventing Re-Processing

A subtle architectural challenge in AST-to-OpenXML compilation is avoiding double processing when plugins handle compound nodes.

When the tablePlugin encounters a table node, it consumes the node, constructs a complete docx.Table with all its rows and cells, and returns it. However, if the main tree walker continues traversing children naively, it might re-visit individual tableRow or tableCell nodes, causing duplicate or fragmented text runs.

To solve this cleanly, md2docx uses the EmptyNode Sentinel Pattern:

// packages/table/src/index.ts (extract)
const rows = node.children.map(createRow);

// Record original type for debugging/inspection
(node as unknown as EmptyNode)._type = node.type;

// Nullify type to signal to subsequent visitor passes that this subtree is resolved
// @ts-expect-error - Setting type to empty string prevents re-processing
node.type = "";

return [
  new Table({
    ...tableProps,
    rows,
  }),
];

By transitioning the node's type to an empty string (""), the outer visitor pass immediately skips the node on subsequent traversal cycles. This ensures that plugin transformations remain strictly idempotent.


8. Architectural Comparison: Regex vs. Headless Office vs. AST Compiler

When choosing a document generation architecture for enterprise-ready production systems, engineering teams must evaluate schema compliance, operational overhead, resource footprint, and portability:

Evaluation DimensionNaive Regex / String TemplatingHeadless Office / LibreOffice Clustersmd2docx AST Compiler Engine
Output ValidityFragile; frequently triggers schema validation errors on nested markup.High fidelity; uses native Office rendering engine.High structural determinism governed by typed AST schemas; conforms to ISO/IEC 29500.
Runtime DependenciesNone (pure JavaScript string operations).Heavy (LibreOffice binary, Java runtime, MS Core Fonts, OS packages).None (pure TypeScript; no native binary dependencies).
Cold Start Latency<5 ms< 5\text{ ms}1,200 ms−3,500 ms1,200\text{ ms} - 3,500\text{ ms} (container & process spawn overhead)15 ms−60 ms15\text{ ms} - 60\text{ ms} (in-process parse & serialize)
Memory Footprint<20 MB< 20\text{ MB}350 MB−800 MB+350\text{ MB} - 800\text{ MB}+ per worker container / process∼40 MB−80 MB\sim 40\text{ MB} - 80\text{ MB} peak heap for typical multi-page reports
Client-Side ExecutionYes (in-browser string operations).Unsupported (requires Linux server binaries and filesystem access).Full support (compiles in browser via Web Workers and Blobs).
Nested Structure SupportFails on nested lists, overlapping formatting, and multi-run tables.Full support.Full support via AST visitor property stacks.
Operational Attack SurfaceRisk of XML injection via unsanitized strings.High (CVEs in C++ document parsers, font renderers, macro handlers).In-process memory allocation; significantly reduces binary subprocess attack surface.

Benchmark Methodology:

  • Hardware: Modern 8-core CPU workstation (e.g. Apple M-series / Intel Core i7).
  • Runtime: Node.js 24 runtime, warm JIT execution.
  • Document: 15-page mixed report containing 8 tables, 12 equations, headings, and nested lists.
  • Measurement: Mean of 50 runs, measuring V8 heap delta and wall-clock execution time.

The Operational Trade-Off

The critical operational distinction lies in process boundaries.

Headless LibreOffice clusters require managing external OS-level subprocesses, mounting fonts into container images, and provisioning multi-gigabyte server instances. In serverless or containerized environments (AWS Lambda, Cloudflare Workers, Kubernetes pods), these heavy binaries introduce substantial cold-start penalties, high idle memory costs, and process management headaches under burst concurrency.

Conversely, string templating avoids binary overhead but cannot reliably produce valid OpenXML for non-trivial documents.

The AST compiler pattern provides the balanced path: the lightweight, in-process agility of pure TypeScript paired with the structural correctness of a formal compiler.


9. What’s Next in the Engineering Series

This is Part 3 of our 7-part deep dive into the engineering principles behind md2docx:


10. Key Takeaways for Systems Architects

  1. Treat Documents as Code Targets: A Word document is not a text file with formatting tags; it is an interconnected graph of XML structures governed by a strict schema. Treat document generators as compilers with formal frontends (lexers/parsers), intermediate representations, and backends (code generators).
  2. Avoid String Interpolation on XML: Direct string replacement cannot reliably track state transitions across overlapping formatting boundaries. Always represent intermediate state as an Abstract Syntax Tree.
  3. Isolate Visitor Passes: Decouple link/footnote hoisting, block layout, and inline property stacking into independent, testable passes. This allows plugins to hook into lifecycle events (preprocess, inline, block, postprocess) without destabilizing the core pipeline.
  4. Compile Everywhere: By avoiding binary dependencies (LibreOffice, Pandoc), your document generation pipeline runs identically inside a browser Web Worker, a Node.js microservice, a Bun CLI, or an edge function.

Explore the complete open-source codebase or integrate the engine into your own pipelines:

👉 View md2docx on GitHub
👉 Inspect @m2d/core on npm

Did you enjoy this post?

Give it a like to let me know!

Recommended Posts