- Table content blocks (migration 044): a grid of text, a row per line, cells split by |, the first row the header; cells take the same formatting as a paragraph; wide tables scroll on a phone - Blog posts -> Import from Word: the server reads the .docx (zip and XML read without a library, sizes capped) and creates an unpublished post through the CRUD engine: title, date, headings, paragraphs, lists, tables, bold, italic and links; the editor opens with a note of what came over and what didn't (images) - docs/importing.md, and an nginx block for the upload Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
10 KiB
JavaScript
249 lines
10 KiB
JavaScript
/* ═══════════════════════════════════════════════════════════════
|
|
DOCX → CONTENT BLOCKS
|
|
|
|
Reads a Word document and turns it into a blog post's content
|
|
blocks (routes/import.js; Blog posts → Import from Word):
|
|
|
|
the Title, or the first Heading 1 the post's title
|
|
a date line right under it the post's date
|
|
Heading 1 and 2 heading blocks
|
|
Heading 3 and below subheading blocks
|
|
paragraphs paragraph blocks
|
|
runs of list paragraphs one list block, one item each
|
|
tables table blocks (a row per line,
|
|
cells split by |)
|
|
bold, italic, links **bold**, *italic*, [text](url)
|
|
|
|
Images, text boxes, footnotes and comments aren't carried over;
|
|
the result counts what was skipped so the editor can say so.
|
|
|
|
A .docx is a zip of XML. Both are read here with no library: the
|
|
zip through Node's own zlib, the XML with a small tokenizer. The
|
|
file is someone's upload, so every size is capped and the XML is
|
|
walked once, with no pattern that rescans it.
|
|
═══════════════════════════════════════════════════════════════ */
|
|
|
|
import { inflateRawSync } from "node:zlib";
|
|
|
|
export class DocxError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.status = 400;
|
|
}
|
|
}
|
|
|
|
const MAX_PART_BYTES = 20 * 1024 * 1024; // any one XML part, unpacked
|
|
const PARTS = ["word/document.xml", "word/styles.xml", "word/_rels/document.xml.rels"];
|
|
|
|
/* ── Zip ───────────────────────────────────────────────────────── */
|
|
|
|
/* The named entries of a zip, unpacked. Reads the central directory
|
|
(the index at the end), so it never walks the whole file. */
|
|
function unzip(buf, wanted) {
|
|
const out = {};
|
|
// End of central directory: the last 0x06054b50 in the final 64 KB.
|
|
let eocd = -1;
|
|
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
|
|
if (buf.readUInt32LE(i) === 0x06054b50) {
|
|
eocd = i;
|
|
break;
|
|
}
|
|
}
|
|
if (eocd === -1) throw new DocxError("That file isn't a Word document (.docx).");
|
|
const count = buf.readUInt16LE(eocd + 10);
|
|
let at = buf.readUInt32LE(eocd + 16);
|
|
for (let n = 0; n < count && at + 46 <= buf.length; n++) {
|
|
if (buf.readUInt32LE(at) !== 0x02014b50) break;
|
|
const method = buf.readUInt16LE(at + 10);
|
|
const packed = buf.readUInt32LE(at + 20);
|
|
const size = buf.readUInt32LE(at + 24);
|
|
const nameLen = buf.readUInt16LE(at + 28);
|
|
const extraLen = buf.readUInt16LE(at + 30);
|
|
const commentLen = buf.readUInt16LE(at + 32);
|
|
const local = buf.readUInt32LE(at + 42);
|
|
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
|
|
at += 46 + nameLen + extraLen + commentLen;
|
|
if (!wanted.includes(name)) continue;
|
|
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
|
|
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
|
const data = buf.subarray(dataAt, dataAt + packed);
|
|
if (method === 0) out[name] = data.toString("utf8");
|
|
else if (method === 8) out[name] = inflateRawSync(data, { maxOutputLength: MAX_PART_BYTES }).toString("utf8");
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/* ── XML ───────────────────────────────────────────────────────── */
|
|
|
|
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
const decode = (s) =>
|
|
s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos);/gi, (_, e) => {
|
|
if (e[0] !== "#") return ENTITY[e.toLowerCase()];
|
|
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));
|
|
return String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
|
|
});
|
|
|
|
/* A tree of { name, attrs, children, text }. One pass of one global
|
|
regex over the tags, so its cost is the file's length. */
|
|
function parseXml(xml) {
|
|
const root = { name: "#root", attrs: {}, children: [] };
|
|
const stack = [root];
|
|
const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([^\s>/]+)([^>]*?)(\/?)>|([^<]+)/g;
|
|
let m;
|
|
while ((m = token.exec(xml))) {
|
|
const top = stack[stack.length - 1];
|
|
if (m[1] !== undefined) top.children.push({ name: "#text", text: m[1] });
|
|
else if (m[6] !== undefined) top.children.push({ name: "#text", text: decode(m[6]) });
|
|
else if (m[3]) {
|
|
if (m[2]) {
|
|
if (stack.length > 1) stack.pop();
|
|
} else {
|
|
const attrs = {};
|
|
for (const a of m[4].matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) attrs[a[1]] = decode(a[2]);
|
|
const node = { name: m[3], attrs, children: [] };
|
|
top.children.push(node);
|
|
if (!m[5]) stack.push(node);
|
|
}
|
|
}
|
|
}
|
|
return root;
|
|
}
|
|
|
|
const kids = (node, name) => (node?.children ?? []).filter((c) => c.name === name);
|
|
const kid = (node, name) => (node?.children ?? []).find((c) => c.name === name);
|
|
function* all(node, name) {
|
|
for (const c of node?.children ?? []) {
|
|
if (c.name === name) yield c;
|
|
yield* all(c, name);
|
|
}
|
|
}
|
|
const on = (el) => el && !["0", "false"].includes(el.attrs["w:val"]);
|
|
|
|
/* ── Text ──────────────────────────────────────────────────────── */
|
|
|
|
function runText(r) {
|
|
let t = "";
|
|
for (const c of r.children) {
|
|
if (c.name === "w:t") t += c.children.map((x) => x.text ?? "").join("");
|
|
else if (c.name === "w:tab") t += " ";
|
|
else if (c.name === "w:br" || c.name === "w:cr") t += " ";
|
|
}
|
|
if (!t.trim()) return t;
|
|
const rpr = kid(r, "w:rPr");
|
|
const b = on(kid(rpr, "w:b"));
|
|
const i = on(kid(rpr, "w:i"));
|
|
const lead = t.match(/^\s*/)[0];
|
|
const trail = t.match(/\s*$/)[0];
|
|
const core = t.trim();
|
|
const marked = b && i ? `***${core}***` : b ? `**${core}**` : i ? `*${core}*` : core;
|
|
return lead + marked + trail;
|
|
}
|
|
|
|
const SAFE_LINK = /^(https?:|mailto:)/i;
|
|
|
|
function paragraphText(p, rels, counts) {
|
|
let out = "";
|
|
for (const c of p.children) {
|
|
if (c.name === "w:r") {
|
|
if (kid(c, "w:drawing") || kid(c, "w:pict")) counts.images++;
|
|
out += runText(c);
|
|
} else if (c.name === "w:hyperlink") {
|
|
const label = [...all(c, "w:r")].map(runText).join("").trim();
|
|
const href = rels[c.attrs["r:id"]];
|
|
out += href && SAFE_LINK.test(href) && label ? `[${label.replace(/[[\]]/g, "")}](${href})` : label;
|
|
} else if (c.name === "w:ins" || c.name === "w:smartTag" || c.name === "w:sdt") {
|
|
out += [...all(c, "w:r")].map(runText).join("");
|
|
}
|
|
}
|
|
// Word splits a phrase into runs; adjacent bold runs meet as "** **".
|
|
return out.replace(/\*\*(\s*)\*\*/g, "$1").replace(/\s+/g, " ").trim();
|
|
}
|
|
|
|
/* ── Document ──────────────────────────────────────────────────── */
|
|
|
|
const DATE_LINE = /^([A-Z][a-z]{2,8}\.? \d{1,2},? \d{4}|\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8} \d{4})\b/;
|
|
|
|
export function readDocx(buf) {
|
|
const parts = unzip(buf, PARTS);
|
|
if (!parts["word/document.xml"]) throw new DocxError("That file isn't a Word document (.docx).");
|
|
|
|
const rels = {};
|
|
for (const r of all(parseXml(parts["word/_rels/document.xml.rels"] ?? ""), "Relationship")) {
|
|
if (r.attrs.TargetMode === "External" || /^https?:|^mailto:/i.test(r.attrs.Target ?? "")) rels[r.attrs.Id] = r.attrs.Target;
|
|
}
|
|
const styleName = {};
|
|
for (const s of all(parseXml(parts["word/styles.xml"] ?? ""), "w:style")) {
|
|
styleName[s.attrs["w:styleId"]] = (kid(s, "w:name")?.attrs["w:val"] ?? s.attrs["w:styleId"]).toLowerCase();
|
|
}
|
|
|
|
const body = kid(kid(parseXml(parts["word/document.xml"]), "w:document"), "w:body");
|
|
if (!body) throw new DocxError("That document has no body to import.");
|
|
|
|
const counts = { images: 0 };
|
|
const blocks = [];
|
|
let title = null;
|
|
let date = null;
|
|
let list = null; // the list block being filled
|
|
|
|
const close = () => {
|
|
if (list) blocks.push(list);
|
|
list = null;
|
|
};
|
|
|
|
for (const el of body.children) {
|
|
if (el.name === "w:tbl") {
|
|
close();
|
|
const rows = kids(el, "w:tr").map((tr) =>
|
|
kids(tr, "w:tc")
|
|
.map((tc) =>
|
|
kids(tc, "w:p")
|
|
.map((p) => paragraphText(p, rels, counts))
|
|
.filter(Boolean)
|
|
.join(" / ")
|
|
.replace(/\|/g, "\\|"),
|
|
)
|
|
.join(" | "),
|
|
);
|
|
if (rows.some((r) => r.replace(/[|\s]/g, ""))) blocks.push({ type: "table", text: rows.join("\n") });
|
|
continue;
|
|
}
|
|
if (el.name !== "w:p") continue;
|
|
|
|
const ppr = kid(el, "w:pPr");
|
|
const style = styleName[kid(ppr, "w:pStyle")?.attrs["w:val"]] ?? "";
|
|
const text = paragraphText(el, rels, counts);
|
|
if (!text) continue;
|
|
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
|
|
|
|
if (!title && (level === 0 || level === 1)) {
|
|
close();
|
|
title = text.replace(/\*/g, "");
|
|
continue;
|
|
}
|
|
// The line under the title, when it starts with a date ("Sep 28,
|
|
// 2026 · @Aidan"), is the post's date, not part of the body.
|
|
if (title && !date && blocks.length === 0 && !list) {
|
|
const d = DATE_LINE.exec(text.replace(/\*/g, ""));
|
|
const parsed = d && new Date(d[1]);
|
|
if (parsed && !Number.isNaN(parsed.getTime())) {
|
|
date = parsed.toISOString().slice(0, 10);
|
|
continue;
|
|
}
|
|
}
|
|
if (level >= 1) {
|
|
close();
|
|
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
|
|
continue;
|
|
}
|
|
if (kid(ppr, "w:numPr") || /list/.test(style)) {
|
|
if (!list) list = { type: "list", items: [] };
|
|
list.items.push({ text });
|
|
continue;
|
|
}
|
|
close();
|
|
blocks.push({ type: "paragraph", text });
|
|
}
|
|
close();
|
|
|
|
return { title, date, blocks, skipped: counts };
|
|
}
|