Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/exportFormats.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Output formats of a project export that need no external program (contract §5.1):47 *48 * markdownToLatex a small Markdown → LaTeX converter (pandoc is not installed on the server). It covers what49 * the reports actually contain: headings, paragraphs, nested lists, pipe tables, block quotes,50 * code blocks, inline and display math, links, emphasis, and images as figure placeholders51 * with their captions. The document is meant to compile with XeLaTeX, LuaLaTeX or pdfLaTeX;52 * the server never compiles it.53 * zipArchive a ZIP writer (deflate, UTF-8 names) on top of node:zlib.54 */55import { deflateRawSync } from "node:zlib";5657// ─── LaTeX ───────────────────────────────────────────────────────────────────58/** Characters outside Latin text that the reports use, as LaTeX (so pdfLaTeX does not stop on them). */59const UNICODE_TEX: Record<string, string> = {60 "→": "$\\rightarrow$", "←": "$\\leftarrow$", "↑": "$\\uparrow$", "↓": "$\\downarrow$", "↔": "$\\leftrightarrow$", "⇒": "$\\Rightarrow$",61 "≥": "$\\geq$", "≤": "$\\leq$", "≠": "$\\neq$", "≈": "$\\approx$", "±": "$\\pm$", "×": "$\\times$", "÷": "$\\div$", "∞": "$\\infty$", "√": "$\\surd$",62 "∑": "$\\sum$", "∆": "$\\Delta$", "Δ": "$\\Delta$", "σ": "$\\sigma$", "μ": "$\\mu$", "µ": "$\\mu$", "β": "$\\beta$", "α": "$\\alpha$", "ρ": "$\\rho$", "λ": "$\\lambda$", "π": "$\\pi$", "θ": "$\\theta$", "γ": "$\\gamma$", "ε": "$\\varepsilon$", "ω": "$\\omega$", "φ": "$\\varphi$", "τ": "$\\tau$", "κ": "$\\kappa$", "ν": "$\\nu$", "χ": "$\\chi$",63 "−": "$-$", "•": "\\textbullet{}", "·": "\\textperiodcentered{}", "…": "\\ldots{}", "—": "---", "–": "--", "€": "\\texteuro{}", "£": "\\pounds{}", "°": "\\textdegree{}",64 "“": "``", "”": "''", "‘": "`", "’": "'", "«": "\\guillemotleft{}", "»": "\\guillemotright{}", " ": "~", " ": "\\,", " ": "\\,",65 "✓": "$\\checkmark$", "✔": "$\\checkmark$", "✗": "$\\times$", "²": "\\textsuperscript{2}", "³": "\\textsuperscript{3}", "½": "\\textonehalf{}", "‰": "\\textperthousand{}", "≡": "$\\equiv$", "∈": "$\\in$", "∂": "$\\partial$",66};67const UNICODE_RE = new RegExp(`[${Object.keys(UNICODE_TEX).join("")}]`, "gu");6869/** Escapes plain text for LaTeX. */70export function texEscape(s: string): string {71 return s72 .replace(/[\\&%$#_{}~^]/g, (c) => ({ "\\": "\\textbackslash{}", "&": "\\&", "%": "\\%", $: "\\$", "#": "\\#", _: "\\_", "{": "\\{", "}": "\\}", "~": "\\textasciitilde{}", "^": "\\textasciicircum{}" })[c]!)73 .replace(UNICODE_RE, (c) => UNICODE_TEX[c] ?? c)74 // Emoji and other pictographs have no glyph in a LaTeX text font: they are dropped rather than breaking the run.75 .replace(/[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{200D}]/gu, "");76}7778const texUrl = (u: string) => u.replace(/[\\{}^~\s]/g, (c) => encodeURIComponent(c)).replace(/[%#&_]/g, (c) => `\\${c}`);7980/** Inline Markdown → LaTeX: code spans, math, links, images, bold, italic. */81function inline(md: string): string {82 const kept: string[] = [];83 const keep = (tex: string) => `\u0000${kept.push(tex) - 1}\u0000`;84 let s = md;85 s = s.replace(/`([^`\n]+)`/g, (_m, code: string) => keep(`\\texttt{${texEscape(code)}}`));86 s = s.replace(/\\\((.+?)\\\)/g, (_m, expr: string) => keep(`$${expr}$`));87 // A dollar amount is not math ("$45 … $60"): inline math may not start or end on a space, and must look like88 // a formula (a command, an index, an exponent, an equality) or be a single symbol.89 s = s.replace(/(^|[^\\$\w])\$(?!\s)([^$\n]*?[^\s$\\])\$(?![\d\w])/g, (m, pre: string, expr: string) => (/[\\^_{}=<>]/.test(expr) || /^[A-Za-z]$/.test(expr) ? `${pre}${keep(`$${expr}$`)}` : m));90 s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, alt: string) => keep(`\\emph{[figure: ${texEscape(alt || "untitled")}]}`));91 s = s.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, label: string, url: string) => (/^(https?:|mailto:)/i.test(url) ? keep(`\\href{${texUrl(url)}}{${inline(label)}}`) : inline(label)));92 s = s.replace(/<(https?:\/\/[^>\s]+)>/g, (_m, url: string) => keep(`\\url{${texUrl(url)}}`));93 s = s.replace(/<br\s*\/?>/gi, " ").replace(/<\/?(sub|sup|span|div|b|i|em|strong|u)[^>]*>/gi, "");94 s = texEscape(s);95 s = s.replace(/\*\*(?!\s)(.+?)(?<!\s)\*\*/g, "\\textbf{$1}");96 s = s.replace(/(?<![*\w])\*(?![\s*])(.+?)(?<![\s*])\*(?![*\w])/g, "\\emph{$1}");97 // _emphasis_ only between word boundaries: the underscores of snake_case names (escaped just above) stay text.98 s = s.replace(/(?<![\w\\])\\_(?![\s\\])(.+?)(?<![\s\\])\\_(?!\w)/g, "\\emph{$1}");99 s = s.replace(/~~(.+?)~~/g, "$1");100 // eslint-disable-next-line no-control-regex101 return s.replace(/\u0000(\d+)\u0000/g, (_m, i: string) => kept[Number(i)]);102}103104const isTableRow = (line: string) => /^\s*\|.*\|\s*$/.test(line);105const isTableRule = (line: string) => /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line) && line.includes("-");106const cells = (line: string) => line.trim().replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/).map((c) => c.trim());107108function table(header: string[], rule: string[], rows: string[][]): string {109 const n = header.length;110 const align = Array.from({ length: n }, (_x, i) => {111 const r = rule[i] ?? "";112 return r.startsWith(":") && r.endsWith(":") ? "c" : r.endsWith(":") ? "r" : "l";113 });114 const row = (cs: string[]) => `${Array.from({ length: n }, (_x, i) => inline(cs[i] ?? "")).join(" & ")} \\\\`;115 return [116 "{\\small",117 `\\begin{longtable}{@{}${align.join("")}@{}}`,118 "\\toprule",119 `${Array.from({ length: n }, (_x, i) => `\\textbf{${inline(header[i] ?? "")}}`).join(" & ")} \\\\`,120 "\\midrule",121 "\\endhead",122 ...rows.map(row),123 "\\bottomrule",124 "\\end{longtable}",125 "}",126 ].join("\n");127}128129function figure(alt: string, src: string): string {130 const where = /^data:/i.test(src) ? "embedded image" : src;131 return [132 "\\begin{figure}[htbp]",133 "\\centering",134 // A placeholder frame: the image file is not part of the .tex export. Replace it with \includegraphics.135 `\\fbox{\\parbox{0.8\\linewidth}{\\centering\\vspace{2.5em}\\small\\texttt{${texEscape(where.length > 90 ? `${where.slice(0, 87)}...` : where)}}\\vspace{2.5em}}}`,136 `\\caption{${inline(alt || "Figure")}}`,137 "\\end{figure}",138 ].join("\n");139}140141/**142 * Body of a Markdown document as LaTeX (no preamble). `# ` becomes \section; `shift` raises every heading by143 * that many levels (a document whose top headings are `##` passes 1 so that they become sections).144 */145export function markdownBodyToLatex(markdown: string, shift = 0): string {146 const lines = markdown.replace(/\r\n?/g, "\n").split("\n");147 const out: string[] = [];148 let para: string[] = [];149 // Open lists, innermost last: the indentation that opened each and its environment.150 const lists: Array<{ indent: number; env: "itemize" | "enumerate" }> = [];151 const flushPara = () => {152 if (para.length > 0) out.push(inline(para.join(" ")), "");153 para = [];154 };155 const closeLists = (toIndent = -1) => {156 while (lists.length > 0 && lists[lists.length - 1].indent > toIndent) out.push(`\\end{${lists.pop()!.env}}`);157 if (lists.length === 0 && toIndent === -1) out.push("");158 };159 const endBlocks = () => {160 flushPara();161 if (lists.length > 0) closeLists();162 };163164 for (let i = 0; i < lines.length; i++) {165 const line = lines[i];166167 const fence = /^\s*(```|~~~)/.exec(line);168 if (fence) {169 endBlocks();170 const body: string[] = [];171 for (i++; i < lines.length && !lines[i].trimStart().startsWith(fence[1]); i++) body.push(lines[i]);172 // \end{verbatim} inside the listing would close it early.173 out.push("\\begin{verbatim}", ...body.map((l) => l.replace(/\\end\{verbatim\}/g, "\\end {verbatim}")), "\\end{verbatim}", "");174 continue;175 }176177 // Display math: $$ … $$ or \[ … \], on one line or several.178 const open = /^\s*(\$\$|\\\[)/.exec(line);179 if (open) {180 const close = open[1] === "$$" ? "$$" : "\\]";181 let body = line.trim().slice(open[1].length);182 let closed = false;183 if (body.includes(close)) {184 body = body.slice(0, body.indexOf(close));185 closed = true;186 }187 while (!closed && i + 1 < lines.length) {188 i++;189 if (lines[i].includes(close)) {190 body += `\n${lines[i].slice(0, lines[i].indexOf(close))}`;191 closed = true;192 } else body += `\n${lines[i]}`;193 }194 endBlocks();195 // A blank line inside display math is an error in LaTeX.196 out.push("\\[", body.split("\n").filter((l) => l.trim() !== "").join("\n"), "\\]", "");197 continue;198 }199200 if (line.trim() === "") {201 flushPara();202 // A blank line ends a list only when the next line is not another item or its continuation.203 const next = lines.slice(i + 1).find((l) => l.trim() !== "");204 if (lists.length > 0 && !(next !== undefined && (/^\s*([-*+]|\d+[.)])\s+/.test(next) || /^\s{2,}\S/.test(next)))) closeLists();205 continue;206 }207208 const heading = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);209 if (heading) {210 endBlocks();211 const level = Math.max(1, heading[1].length - shift);212 const cmd = level === 1 ? "section" : level === 2 ? "subsection" : level === 3 ? "subsubsection" : "paragraph";213 out.push(`\\${cmd}{${inline(heading[2])}}`, "");214 continue;215 }216217 if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {218 endBlocks();219 out.push("\\medskip\\hrule\\medskip", "");220 continue;221 }222223 if (isTableRow(line) && i + 1 < lines.length && isTableRule(lines[i + 1])) {224 endBlocks();225 const header = cells(line);226 const rule = cells(lines[i + 1]);227 const rows: string[][] = [];228 for (i += 2; i < lines.length && isTableRow(lines[i]); i++) rows.push(cells(lines[i]));229 i--;230 out.push(table(header, rule, rows), "");231 continue;232 }233234 const image = /^\s*!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)\s*$/.exec(line);235 if (image) {236 endBlocks();237 out.push(figure(image[1], image[2]), "");238 continue;239 }240241 const item = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);242 if (item) {243 flushPara();244 const indent = item[1].replace(/\t/g, " ").length;245 const env = /^\d/.test(item[2]) ? "enumerate" : "itemize";246 closeLists(indent);247 const top = lists[lists.length - 1];248 if (!top || top.indent < indent) {249 lists.push({ indent, env });250 out.push(`\\begin{${env}}`);251 } else if (top.env !== env) {252 out.push(`\\end{${lists.pop()!.env}}`);253 lists.push({ indent, env });254 out.push(`\\begin{${env}}`);255 }256 // "{}" after \\item: an item that starts with "[" (a task-list box) would otherwise be read as the item's label.257 out.push(`\\item{} ${inline(item[3])}`);258 continue;259 }260261 if (/^\s*>/.test(line)) {262 endBlocks();263 const body: string[] = [];264 for (; i < lines.length && /^\s*>/.test(lines[i]); i++) body.push(lines[i].replace(/^\s*>\s?/, ""));265 i--;266 out.push("\\begin{quote}", markdownBodyToLatex(body.join("\n"), shift).trim(), "\\end{quote}", "");267 continue;268 }269270 if (lists.length > 0 && /^\s{2,}\S/.test(line)) {271 // Continuation of the current list item.272 out.push(inline(line.trim()));273 continue;274 }275 if (lists.length > 0) closeLists();276 para.push(line.trim());277 }278 endBlocks();279 return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();280}281282/** A complete LaTeX document from Markdown. */283export function markdownToLatex(markdown: string, meta: { title: string; author?: string; date?: string }): string {284 // The top heading level actually used becomes \\section (fenced code is not looked at).285 const levels = markdown.replace(/^\s*(```|~~~)[\s\S]*?^\s*\1.*$/gm, "").match(/^#{1,6}(?=\s)/gm) ?? [];286 const shift = levels.length > 0 ? Math.min(...levels.map((h) => h.length)) - 1 : 0;287 return `% Generated by VQuant from the project's Markdown. Not compiled by the server.288% Compile with XeLaTeX or LuaLaTeX (preferred: full Unicode) or pdfLaTeX, twice (longtable settles its column289% widths on the second pass). Figures are placeholders: the image290% files are not part of this export; replace each framed box with \\includegraphics once the files are at hand.291\\documentclass[11pt,a4paper]{article}292\\usepackage{iftex}293\\ifPDFTeX294 \\usepackage[T1]{fontenc}295 \\usepackage[utf8]{inputenc}296 \\usepackage{textcomp}297\\else298 \\usepackage{fontspec}299\\fi300\\usepackage[margin=25mm]{geometry}301\\usepackage{amsmath,amssymb}302\\usepackage{booktabs,longtable}303\\usepackage{graphicx}304\\usepackage[hidelinks]{hyperref}305\\setlength{\\parindent}{0pt}306\\setlength{\\parskip}{0.6em}307\\setcounter{secnumdepth}{0}308309\\title{${inline(meta.title)}}310\\author{${texEscape(meta.author ?? "")}}311\\date{${texEscape(meta.date ?? "")}}312313\\begin{document}314\\maketitle315316${markdownBodyToLatex(markdown, shift)}317318\\end{document}319`;320}321322// ─── ZIP ─────────────────────────────────────────────────────────────────────323let crcTable: Uint32Array | null = null;324export function crc32(buf: Uint8Array): number {325 if (!crcTable) {326 crcTable = new Uint32Array(256);327 for (let n = 0; n < 256; n++) {328 let c = n;329 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;330 crcTable[n] = c >>> 0;331 }332 }333 let crc = 0xffffffff;334 for (let i = 0; i < buf.length; i++) crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);335 return (crc ^ 0xffffffff) >>> 0;336}337338/** A ZIP archive of the given files (names with forward slashes; no directory entries are needed). */339export function zipArchive(files: Array<{ name: string; data: Buffer | string }>, date = new Date()): Buffer {340 const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);341 const dosDate = ((Math.max(1980, date.getFullYear()) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();342 const local: Buffer[] = [];343 const central: Buffer[] = [];344 let offset = 0;345 for (const f of files) {346 const name = Buffer.from(f.name.replace(/^\/+/, ""), "utf8");347 const raw = typeof f.data === "string" ? Buffer.from(f.data, "utf8") : f.data;348 const deflated = deflateRawSync(raw);349 // Stored when deflate does not help (already compressed content).350 const method = deflated.length < raw.length ? 8 : 0;351 const body = method === 8 ? deflated : raw;352 const crc = crc32(raw);353354 const head = Buffer.alloc(30);355 head.writeUInt32LE(0x04034b50, 0);356 head.writeUInt16LE(20, 4); // version needed357 head.writeUInt16LE(0x0800, 6); // UTF-8 names358 head.writeUInt16LE(method, 8);359 head.writeUInt16LE(dosTime, 10);360 head.writeUInt16LE(dosDate, 12);361 head.writeUInt32LE(crc, 14);362 head.writeUInt32LE(body.length, 18);363 head.writeUInt32LE(raw.length, 22);364 head.writeUInt16LE(name.length, 26);365 head.writeUInt16LE(0, 28);366 local.push(head, name, body);367368 const entry = Buffer.alloc(46);369 entry.writeUInt32LE(0x02014b50, 0);370 entry.writeUInt16LE(20, 4); // version made by371 entry.writeUInt16LE(20, 6);372 entry.writeUInt16LE(0x0800, 8);373 entry.writeUInt16LE(method, 10);374 entry.writeUInt16LE(dosTime, 12);375 entry.writeUInt16LE(dosDate, 14);376 entry.writeUInt32LE(crc, 16);377 entry.writeUInt32LE(body.length, 20);378 entry.writeUInt32LE(raw.length, 24);379 entry.writeUInt16LE(name.length, 28);380 entry.writeUInt32LE(offset, 42);381 central.push(entry, name);382 offset += head.length + name.length + body.length;383 }384 const centralSize = central.reduce((n, b) => n + b.length, 0);385 const end = Buffer.alloc(22);386 end.writeUInt32LE(0x06054b50, 0);387 end.writeUInt16LE(files.length, 8);388 end.writeUInt16LE(files.length, 10);389 end.writeUInt32LE(centralSize, 12);390 end.writeUInt32LE(offset, 16);391 return Buffer.concat([...local, ...central, end]);392}393