Loading .gitlab-ci.yml +2 Changes for .gitlab-ci.yml: 2 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -101,3 +101,5 @@ Build Pandoc docker image: - if: $CI_COMMIT_BRANCH && $CI_PROJECT_NAME == "tools" changes: - generateBaseline/dockerfile.pandoc - generateBaseline/mermaid-filter.js - generateBaseline/plantuml-filter.js generateBaseline/dockerfile.pandoc +62 −3 Changes for generateBaseline/dockerfile.pandoc: 62 added lines, 3 removed lines. Original line number Diff line number Diff line FROM node:18.20-bookworm-slim AS nodejs FROM ghcr.io/mermaid-js/mermaid-cli/mermaid-cli:11.17.0 AS mermaidcli FROM pandoc/latex:3.4.0-ubuntu RUN apt-get update -y && \ apt-get install -y npm &&\ npm install --global mermaid-filter # mermaid diagrams: copy a glibc Node binary, prebuilt mermaid-cli (mmdc), # and a local pandoc filter that shells out to it. Do not npm-install # mermaid-filter — that tree hangs for hours against registry.npmjs.org # from this runner. publish_spec.sh still uses -F mermaid-filter (PATH). ENV DEBIAN_FRONTEND=noninteractive \ DEBCONF_NOWARNINGS=yes \ HOME=/tmp \ PUPPETEER_SKIP_DOWNLOAD=true \ PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \ PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome-stable \ MERMAID_FILTER_PUPPETEER_CONFIG=/opt/mermaid/puppeteer.json \ MERMAID_FILTER_CMD_MMDC=/opt/mermaidcli/node_modules/@mermaid-js/mermaid-cli/src/cli.js \ PLANTUML_SERVER=https://tools.etsi.org/plant RUN echo 'man-db man-db/auto-update boolean false' | debconf-set-selections && \ rm -f /var/lib/man-db/auto-update && \ printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d && \ chmod +x /usr/sbin/policy-rc.d && \ printf '%s\n' \ 'path-exclude=/usr/share/doc/*' \ 'path-exclude=/usr/share/man/*' \ 'path-exclude=/usr/share/info/*' \ > /etc/dpkg/dpkg.cfg.d/01_nodoc && \ apt-get update -y && \ apt-get install -y --no-install-recommends \ wget \ ca-certificates \ fonts-liberation \ fonts-dejavu-core # Reuse the apt lists from the previous layer (do not apt-get update again). # Visible download, 30s network timeout so a blocked dl.google.com fails fast. RUN wget --timeout=30 --tries=2 --progress=dot:giga \ -O /tmp/google-chrome.deb \ https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install -y --no-install-recommends /tmp/google-chrome.deb && \ rm -f /tmp/google-chrome.deb && \ rm -rf /var/lib/apt/lists/* COPY --from=nodejs /usr/local/bin/node /usr/local/bin/node COPY --from=mermaidcli /home/mermaidcli/node_modules /opt/mermaidcli/node_modules COPY generateBaseline/mermaid-filter.js /usr/local/bin/mermaid-filter COPY generateBaseline/plantuml-filter.js /usr/local/bin/plantuml-filter RUN chmod +x /usr/local/bin/mermaid-filter /usr/local/bin/plantuml-filter && \ mkdir -p /opt/mermaid && \ printf '%s\n' \ '{' \ ' "executablePath": "/usr/bin/google-chrome-stable",' \ ' "headless": true,' \ ' "args": [' \ ' "--no-sandbox",' \ ' "--disable-setuid-sandbox",' \ ' "--disable-dev-shm-usage",' \ ' "--disable-gpu"' \ ' ]' \ '}' \ > /opt/mermaid/puppeteer.json CMD ["/bin/sh"] Loading generateBaseline/mermaid-filter.js +224 Changes for generateBaseline/mermaid-filter.js: 224 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env node 'use strict'; // Pandoc JSON filter (drop-in for mermaid-filter). No npm packages: // reads the AST from stdin, renders ```mermaid blocks with mmdc, writes AST to stdout. const fs = require('fs'); const os = require('os'); const path = require('path'); const { execFileSync } = require('child_process'); const MMDC = process.env.MERMAID_FILTER_CMD_MMDC || 'mmdc'; const PUPPETEER = process.env.MERMAID_FILTER_PUPPETEER_CONFIG || ''; const WIDTH = process.env.MERMAID_FILTER_WIDTH || '800'; const THEME = process.env.MERMAID_FILTER_THEME || 'default'; const BACKGROUND = process.env.MERMAID_FILTER_BACKGROUND || 'white'; function isMermaidBlock(el) { return el && el.t === 'CodeBlock' && Array.isArray(el.c) && Array.isArray(el.c[0]) && Array.isArray(el.c[0][1]) && el.c[0][1].indexOf('mermaid') >= 0; } function stringifyInlines(inlines) { if (!inlines) { return ''; } if (typeof inlines === 'string') { return inlines; } if (Array.isArray(inlines)) { return inlines.map(stringifyInlines).join(''); } if (inlines && typeof inlines === 'object') { if (inlines.t === 'Str') { return inlines.c || ''; } if (inlines.t === 'Space' || inlines.t === 'SoftBreak') { return ' '; } if (Object.prototype.hasOwnProperty.call(inlines, 'c')) { return stringifyInlines(inlines.c); } } return ''; } function isFigureCaptionPara(el) { if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) { return false; } if (el.c[0].t !== 'Strong') { return false; } return /^Figure\s/.test(stringifyInlines(el.c).trim()); } function figureCaptionInlines(el) { if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) { return el.c[0].c; } const out = []; for (let i = 0; i < el.c.length; i++) { const inline = el.c[i]; if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) { Array.prototype.push.apply(out, inline.c); } else { out.push(inline); } } return out; } function mermaidLibVersion() { try { const pkgPath = path.resolve(path.dirname(MMDC), '..', '..', '..', 'mermaid', 'package.json'); return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version; } catch (e) { return 'unknown'; } } // mermaid.live accepts `A --> B : IPE: send_goal<br/>...`. Quotes around that // label are not string syntax in stateDiagram-v2, so the inner ":" is still // token DESCR. Unwrap them; leave the rest of the diagram unchanged. function unwrapStateLabelQuotes(content) { return String(content).replace( /^(\s*(?:\[\*\]|[A-Za-z_][\w]*)\s*-->\s*(?:\[\*\]|[A-Za-z_][\w]*)\s*:\s*)"(.*)"\s*$/gm, function (_match, prefix, label) { return prefix + label; } ); } function renderMermaid(el, caption) { const attrs = el.c[0]; const content = el.c[1]; const id = attrs[0] || ''; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mermaid-')); const input = path.join(tmp, 'in.mmd'); const output = path.join(tmp, 'out.png'); fs.writeFileSync(input, unwrapStateLabelQuotes(content), 'utf8'); const args = [ '-i', input, '-o', output, '-w', String(WIDTH), '-s', '1', '-t', THEME, '-b', BACKGROUND ]; if (PUPPETEER && fs.existsSync(PUPPETEER)) { args.unshift('-p', PUPPETEER); } // Non-root CI users have no HOME; Chrome/Puppeteer need a writable one. const env = Object.assign({}, process.env, { HOME: process.env.HOME || os.tmpdir(), PUPPETEER_CACHE_DIR: process.env.PUPPETEER_CACHE_DIR || path.join(os.tmpdir(), 'puppeteer') }); try { // Run via node so ESM cli.js works even if the .bin shim is not +x. execFileSync(process.execPath, [MMDC].concat(args), { stdio: ['ignore', 'pipe', 'pipe'], env: env }); } catch (err) { const stderr = err.stderr ? err.stderr.toString() : String(err); fs.writeSync(2, 'mermaid ' + mermaidLibVersion() + '\n'); fs.writeSync(2, 'mmdc failed:\n' + stderr + '\n'); process.exit(1); } const data = fs.readFileSync(output); const src = 'data:image/png;base64,' + data.toString('base64'); try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (e) { /* ignore */ } const captionInlines = Array.isArray(caption) ? caption : []; const image = { t: 'Image', c: [[id, [], []], captionInlines, [src, 'fig:']] }; // Always a Figure so docx postprocessing can style mermaid like other figures. return { t: 'Figure', c: [ [id, [], []], [null, captionInlines.length ? [{ t: 'Plain', c: captionInlines }] : []], [{ t: 'Plain', c: [image] }] ] }; } function captionFromAttrs(el) { const kvs = el && el.c && el.c[0] && el.c[0][2]; if (!Array.isArray(kvs)) { return []; } for (let i = 0; i < kvs.length; i++) { if (kvs[i] && kvs[i][0] === 'caption' && kvs[i][1]) { return [{ t: 'Str', c: String(kvs[i][1]) }]; } } return []; } function warnMermaidBlock() { fs.writeSync(2, '⚠ WARNING: Mermaid block found. Please, substitute it with a regular image.\n'); } function walkBlocks(blocks) { const out = []; for (let i = 0; i < blocks.length; i++) { const el = blocks[i]; if (isMermaidBlock(el)) { warnMermaidBlock(); let caption = captionFromAttrs(el); if (isFigureCaptionPara(blocks[i + 1])) { caption = figureCaptionInlines(blocks[i + 1]); i += 1; } out.push(renderMermaid(el, caption)); } else { out.push(walk(el)); } } return out; } function walk(node) { if (Array.isArray(node)) { if (node.some(isMermaidBlock)) { return walkBlocks(node); } return node.map(walk); } if (node && typeof node === 'object') { if (isMermaidBlock(node)) { warnMermaidBlock(); return renderMermaid(node, []); } // Pandoc 3 JSON is {pandoc-api-version, meta, blocks}. Older filters // only walked `c`, so top-level mermaid CodeBlocks were left unchanged. if (Object.prototype.hasOwnProperty.call(node, 'c')) { node.c = walk(node.c); } if (Object.prototype.hasOwnProperty.call(node, 'blocks')) { node.blocks = walk(node.blocks); } return node; } return node; } let raw = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { raw += chunk; }); process.stdin.on('end', function () { const doc = JSON.parse(raw); process.stdout.write(JSON.stringify(walk(doc))); }); generateBaseline/pandocFilter.py +7 −3 Changes for generateBaseline/pandocFilter.py: 7 added lines, 3 removed lines. Original line number Diff line number Diff line Loading @@ -290,12 +290,16 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: _lines.append(line) continue if matches: # Replace the previous figure markdown name with the captions # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].count('![') == 0: while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx > 0: if _idx >= 0 and _lines[_idx].count('![') > 0: _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) else: _lines.append(line) print(f'Corresponding figure not found for caption: {matches[0]}, figure caption is not removed') elif re.findall(nocaptionfigureregex, line): _lines.append(re.sub(r'^.*?]', f'![]', line)) else: Loading generateBaseline/plantuml-filter.js +248 Changes for generateBaseline/plantuml-filter.js: 248 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env node 'use strict'; // Pandoc JSON filter: render ```plantuml blocks via the PlantUML server, write AST to stdout. const fs = require('fs'); const os = require('os'); const path = require('path'); const zlib = require('zlib'); const { execFileSync } = require('child_process'); const SERVER = (process.env.PLANTUML_SERVER || 'https://tools.etsi.org/plant').replace(/\/+$/, ''); const WGET = process.env.PLANTUML_FILTER_WGET || 'wget'; function isPlantumlBlock(el) { if (!el || el.t !== 'CodeBlock' || !Array.isArray(el.c) || !Array.isArray(el.c[0]) || !Array.isArray(el.c[0][1])) { return false; } const classes = el.c[0][1]; return classes.indexOf('plantuml') >= 0 || classes.indexOf('puml') >= 0; } function stringifyInlines(inlines) { if (!inlines) { return ''; } if (typeof inlines === 'string') { return inlines; } if (Array.isArray(inlines)) { return inlines.map(stringifyInlines).join(''); } if (inlines && typeof inlines === 'object') { if (inlines.t === 'Str') { return inlines.c || ''; } if (inlines.t === 'Space' || inlines.t === 'SoftBreak') { return ' '; } if (Object.prototype.hasOwnProperty.call(inlines, 'c')) { return stringifyInlines(inlines.c); } } return ''; } function isFigureCaptionPara(el) { if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) { return false; } if (el.c[0].t !== 'Strong') { return false; } return /^Figure\s/.test(stringifyInlines(el.c).trim()); } function figureCaptionInlines(el) { if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) { return el.c[0].c; } const out = []; for (let i = 0; i < el.c.length; i++) { const inline = el.c[i]; if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) { Array.prototype.push.apply(out, inline.c); } else { out.push(inline); } } return out; } function encode6bit(b) { if (b < 10) { return String.fromCharCode(48 + b); } b -= 10; if (b < 26) { return String.fromCharCode(65 + b); } b -= 26; if (b < 26) { return String.fromCharCode(97 + b); } b -= 26; if (b === 0) { return '-'; } if (b === 1) { return '_'; } return '?'; } function append3bytes(b1, b2, b3) { const c1 = b1 >> 2; const c2 = ((b1 & 0x3) << 4) | (b2 >> 4); const c3 = ((b2 & 0xF) << 2) | (b3 >> 6); const c4 = b3 & 0x3F; return encode6bit(c1 & 0x3F) + encode6bit(c2 & 0x3F) + encode6bit(c3 & 0x3F) + encode6bit(c4 & 0x3F); } function encode64(data) { let r = ''; for (let i = 0; i < data.length; i += 3) { if (i + 2 === data.length) { r += append3bytes(data[i], data[i + 1], 0); } else if (i + 1 === data.length) { r += append3bytes(data[i], 0, 0); } else { r += append3bytes(data[i], data[i + 1], data[i + 2]); } } return r; } function encodePlantuml(text) { return encode64(zlib.deflateRawSync(Buffer.from(text, 'utf8'))); } function ensureStartUml(content) { const text = String(content).trim(); if (/@startuml/i.test(text)) { return text + '\n'; } return '@startuml\n' + text + '\n@enduml\n'; } function figureFromPng(id, png, caption) { const captionInlines = Array.isArray(caption) ? caption : []; const src = 'data:image/png;base64,' + png.toString('base64'); const image = { t: 'Image', c: [[id, [], []], captionInlines, [src, 'fig:']] }; return { t: 'Figure', c: [ [id, [], []], [null, captionInlines.length ? [{ t: 'Plain', c: captionInlines }] : []], [{ t: 'Plain', c: [image] }] ] }; } function renderPlantuml(el, caption) { const attrs = el.c[0]; const id = attrs[0] || ''; const source = ensureStartUml(el.c[1]); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'plantuml-')); const output = path.join(tmp, 'out.png'); const url = SERVER + '/png/' + encodePlantuml(source); try { execFileSync(WGET, [ '--timeout=30', '--tries=2', '-q', '-O', output, url ], { stdio: ['ignore', 'pipe', 'pipe'] }); } catch (err) { const stderr = err.stderr ? err.stderr.toString() : String(err); fs.writeSync(2, 'plantuml server failed (' + SERVER + '):\n' + stderr + '\n'); process.exit(1); } const data = fs.readFileSync(output); if (data.length < 8 || data[0] !== 0x89 || data[1] !== 0x50) { fs.writeSync(2, 'plantuml server did not return a PNG from ' + SERVER + '\n'); process.exit(1); } try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (e) { /* ignore */ } return figureFromPng(id, data, caption); } function captionFromAttrs(el) { const kvs = el && el.c && el.c[0] && el.c[0][2]; if (!Array.isArray(kvs)) { return []; } for (let i = 0; i < kvs.length; i++) { if (kvs[i] && kvs[i][0] === 'caption' && kvs[i][1]) { return [{ t: 'Str', c: String(kvs[i][1]) }]; } } return []; } function warnPlantumlBlock() { fs.writeSync(2, '⚠ WARNING: PlantUML block found. Please, substitute it with a regular image.\n'); } function walkBlocks(blocks) { const out = []; for (let i = 0; i < blocks.length; i++) { const el = blocks[i]; if (isPlantumlBlock(el)) { warnPlantumlBlock(); let caption = captionFromAttrs(el); if (isFigureCaptionPara(blocks[i + 1])) { caption = figureCaptionInlines(blocks[i + 1]); i += 1; } out.push(renderPlantuml(el, caption)); } else { out.push(walk(el)); } } return out; } function walk(node) { if (Array.isArray(node)) { if (node.some(isPlantumlBlock)) { return walkBlocks(node); } return node.map(walk); } if (node && typeof node === 'object') { if (isPlantumlBlock(node)) { warnPlantumlBlock(); return renderPlantuml(node, []); } if (Object.prototype.hasOwnProperty.call(node, 'c')) { node.c = walk(node.c); } if (Object.prototype.hasOwnProperty.call(node, 'blocks')) { node.blocks = walk(node.blocks); } return node; } return node; } let raw = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { raw += chunk; }); process.stdin.on('end', function () { const doc = JSON.parse(raw); process.stdout.write(JSON.stringify(walk(doc))); }); Loading
.gitlab-ci.yml +2 Changes for .gitlab-ci.yml: 2 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -101,3 +101,5 @@ Build Pandoc docker image: - if: $CI_COMMIT_BRANCH && $CI_PROJECT_NAME == "tools" changes: - generateBaseline/dockerfile.pandoc - generateBaseline/mermaid-filter.js - generateBaseline/plantuml-filter.js
generateBaseline/dockerfile.pandoc +62 −3 Changes for generateBaseline/dockerfile.pandoc: 62 added lines, 3 removed lines. Original line number Diff line number Diff line FROM node:18.20-bookworm-slim AS nodejs FROM ghcr.io/mermaid-js/mermaid-cli/mermaid-cli:11.17.0 AS mermaidcli FROM pandoc/latex:3.4.0-ubuntu RUN apt-get update -y && \ apt-get install -y npm &&\ npm install --global mermaid-filter # mermaid diagrams: copy a glibc Node binary, prebuilt mermaid-cli (mmdc), # and a local pandoc filter that shells out to it. Do not npm-install # mermaid-filter — that tree hangs for hours against registry.npmjs.org # from this runner. publish_spec.sh still uses -F mermaid-filter (PATH). ENV DEBIAN_FRONTEND=noninteractive \ DEBCONF_NOWARNINGS=yes \ HOME=/tmp \ PUPPETEER_SKIP_DOWNLOAD=true \ PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \ PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome-stable \ MERMAID_FILTER_PUPPETEER_CONFIG=/opt/mermaid/puppeteer.json \ MERMAID_FILTER_CMD_MMDC=/opt/mermaidcli/node_modules/@mermaid-js/mermaid-cli/src/cli.js \ PLANTUML_SERVER=https://tools.etsi.org/plant RUN echo 'man-db man-db/auto-update boolean false' | debconf-set-selections && \ rm -f /var/lib/man-db/auto-update && \ printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d && \ chmod +x /usr/sbin/policy-rc.d && \ printf '%s\n' \ 'path-exclude=/usr/share/doc/*' \ 'path-exclude=/usr/share/man/*' \ 'path-exclude=/usr/share/info/*' \ > /etc/dpkg/dpkg.cfg.d/01_nodoc && \ apt-get update -y && \ apt-get install -y --no-install-recommends \ wget \ ca-certificates \ fonts-liberation \ fonts-dejavu-core # Reuse the apt lists from the previous layer (do not apt-get update again). # Visible download, 30s network timeout so a blocked dl.google.com fails fast. RUN wget --timeout=30 --tries=2 --progress=dot:giga \ -O /tmp/google-chrome.deb \ https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install -y --no-install-recommends /tmp/google-chrome.deb && \ rm -f /tmp/google-chrome.deb && \ rm -rf /var/lib/apt/lists/* COPY --from=nodejs /usr/local/bin/node /usr/local/bin/node COPY --from=mermaidcli /home/mermaidcli/node_modules /opt/mermaidcli/node_modules COPY generateBaseline/mermaid-filter.js /usr/local/bin/mermaid-filter COPY generateBaseline/plantuml-filter.js /usr/local/bin/plantuml-filter RUN chmod +x /usr/local/bin/mermaid-filter /usr/local/bin/plantuml-filter && \ mkdir -p /opt/mermaid && \ printf '%s\n' \ '{' \ ' "executablePath": "/usr/bin/google-chrome-stable",' \ ' "headless": true,' \ ' "args": [' \ ' "--no-sandbox",' \ ' "--disable-setuid-sandbox",' \ ' "--disable-dev-shm-usage",' \ ' "--disable-gpu"' \ ' ]' \ '}' \ > /opt/mermaid/puppeteer.json CMD ["/bin/sh"] Loading
generateBaseline/mermaid-filter.js +224 Changes for generateBaseline/mermaid-filter.js: 224 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env node 'use strict'; // Pandoc JSON filter (drop-in for mermaid-filter). No npm packages: // reads the AST from stdin, renders ```mermaid blocks with mmdc, writes AST to stdout. const fs = require('fs'); const os = require('os'); const path = require('path'); const { execFileSync } = require('child_process'); const MMDC = process.env.MERMAID_FILTER_CMD_MMDC || 'mmdc'; const PUPPETEER = process.env.MERMAID_FILTER_PUPPETEER_CONFIG || ''; const WIDTH = process.env.MERMAID_FILTER_WIDTH || '800'; const THEME = process.env.MERMAID_FILTER_THEME || 'default'; const BACKGROUND = process.env.MERMAID_FILTER_BACKGROUND || 'white'; function isMermaidBlock(el) { return el && el.t === 'CodeBlock' && Array.isArray(el.c) && Array.isArray(el.c[0]) && Array.isArray(el.c[0][1]) && el.c[0][1].indexOf('mermaid') >= 0; } function stringifyInlines(inlines) { if (!inlines) { return ''; } if (typeof inlines === 'string') { return inlines; } if (Array.isArray(inlines)) { return inlines.map(stringifyInlines).join(''); } if (inlines && typeof inlines === 'object') { if (inlines.t === 'Str') { return inlines.c || ''; } if (inlines.t === 'Space' || inlines.t === 'SoftBreak') { return ' '; } if (Object.prototype.hasOwnProperty.call(inlines, 'c')) { return stringifyInlines(inlines.c); } } return ''; } function isFigureCaptionPara(el) { if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) { return false; } if (el.c[0].t !== 'Strong') { return false; } return /^Figure\s/.test(stringifyInlines(el.c).trim()); } function figureCaptionInlines(el) { if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) { return el.c[0].c; } const out = []; for (let i = 0; i < el.c.length; i++) { const inline = el.c[i]; if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) { Array.prototype.push.apply(out, inline.c); } else { out.push(inline); } } return out; } function mermaidLibVersion() { try { const pkgPath = path.resolve(path.dirname(MMDC), '..', '..', '..', 'mermaid', 'package.json'); return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version; } catch (e) { return 'unknown'; } } // mermaid.live accepts `A --> B : IPE: send_goal<br/>...`. Quotes around that // label are not string syntax in stateDiagram-v2, so the inner ":" is still // token DESCR. Unwrap them; leave the rest of the diagram unchanged. function unwrapStateLabelQuotes(content) { return String(content).replace( /^(\s*(?:\[\*\]|[A-Za-z_][\w]*)\s*-->\s*(?:\[\*\]|[A-Za-z_][\w]*)\s*:\s*)"(.*)"\s*$/gm, function (_match, prefix, label) { return prefix + label; } ); } function renderMermaid(el, caption) { const attrs = el.c[0]; const content = el.c[1]; const id = attrs[0] || ''; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mermaid-')); const input = path.join(tmp, 'in.mmd'); const output = path.join(tmp, 'out.png'); fs.writeFileSync(input, unwrapStateLabelQuotes(content), 'utf8'); const args = [ '-i', input, '-o', output, '-w', String(WIDTH), '-s', '1', '-t', THEME, '-b', BACKGROUND ]; if (PUPPETEER && fs.existsSync(PUPPETEER)) { args.unshift('-p', PUPPETEER); } // Non-root CI users have no HOME; Chrome/Puppeteer need a writable one. const env = Object.assign({}, process.env, { HOME: process.env.HOME || os.tmpdir(), PUPPETEER_CACHE_DIR: process.env.PUPPETEER_CACHE_DIR || path.join(os.tmpdir(), 'puppeteer') }); try { // Run via node so ESM cli.js works even if the .bin shim is not +x. execFileSync(process.execPath, [MMDC].concat(args), { stdio: ['ignore', 'pipe', 'pipe'], env: env }); } catch (err) { const stderr = err.stderr ? err.stderr.toString() : String(err); fs.writeSync(2, 'mermaid ' + mermaidLibVersion() + '\n'); fs.writeSync(2, 'mmdc failed:\n' + stderr + '\n'); process.exit(1); } const data = fs.readFileSync(output); const src = 'data:image/png;base64,' + data.toString('base64'); try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (e) { /* ignore */ } const captionInlines = Array.isArray(caption) ? caption : []; const image = { t: 'Image', c: [[id, [], []], captionInlines, [src, 'fig:']] }; // Always a Figure so docx postprocessing can style mermaid like other figures. return { t: 'Figure', c: [ [id, [], []], [null, captionInlines.length ? [{ t: 'Plain', c: captionInlines }] : []], [{ t: 'Plain', c: [image] }] ] }; } function captionFromAttrs(el) { const kvs = el && el.c && el.c[0] && el.c[0][2]; if (!Array.isArray(kvs)) { return []; } for (let i = 0; i < kvs.length; i++) { if (kvs[i] && kvs[i][0] === 'caption' && kvs[i][1]) { return [{ t: 'Str', c: String(kvs[i][1]) }]; } } return []; } function warnMermaidBlock() { fs.writeSync(2, '⚠ WARNING: Mermaid block found. Please, substitute it with a regular image.\n'); } function walkBlocks(blocks) { const out = []; for (let i = 0; i < blocks.length; i++) { const el = blocks[i]; if (isMermaidBlock(el)) { warnMermaidBlock(); let caption = captionFromAttrs(el); if (isFigureCaptionPara(blocks[i + 1])) { caption = figureCaptionInlines(blocks[i + 1]); i += 1; } out.push(renderMermaid(el, caption)); } else { out.push(walk(el)); } } return out; } function walk(node) { if (Array.isArray(node)) { if (node.some(isMermaidBlock)) { return walkBlocks(node); } return node.map(walk); } if (node && typeof node === 'object') { if (isMermaidBlock(node)) { warnMermaidBlock(); return renderMermaid(node, []); } // Pandoc 3 JSON is {pandoc-api-version, meta, blocks}. Older filters // only walked `c`, so top-level mermaid CodeBlocks were left unchanged. if (Object.prototype.hasOwnProperty.call(node, 'c')) { node.c = walk(node.c); } if (Object.prototype.hasOwnProperty.call(node, 'blocks')) { node.blocks = walk(node.blocks); } return node; } return node; } let raw = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { raw += chunk; }); process.stdin.on('end', function () { const doc = JSON.parse(raw); process.stdout.write(JSON.stringify(walk(doc))); });
generateBaseline/pandocFilter.py +7 −3 Changes for generateBaseline/pandocFilter.py: 7 added lines, 3 removed lines. Original line number Diff line number Diff line Loading @@ -290,12 +290,16 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: _lines.append(line) continue if matches: # Replace the previous figure markdown name with the captions # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].count('![') == 0: while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx > 0: if _idx >= 0 and _lines[_idx].count('![') > 0: _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) else: _lines.append(line) print(f'Corresponding figure not found for caption: {matches[0]}, figure caption is not removed') elif re.findall(nocaptionfigureregex, line): _lines.append(re.sub(r'^.*?]', f'![]', line)) else: Loading
generateBaseline/plantuml-filter.js +248 Changes for generateBaseline/plantuml-filter.js: 248 added lines, 0 removed lines. Original line number Diff line number Diff line #!/usr/bin/env node 'use strict'; // Pandoc JSON filter: render ```plantuml blocks via the PlantUML server, write AST to stdout. const fs = require('fs'); const os = require('os'); const path = require('path'); const zlib = require('zlib'); const { execFileSync } = require('child_process'); const SERVER = (process.env.PLANTUML_SERVER || 'https://tools.etsi.org/plant').replace(/\/+$/, ''); const WGET = process.env.PLANTUML_FILTER_WGET || 'wget'; function isPlantumlBlock(el) { if (!el || el.t !== 'CodeBlock' || !Array.isArray(el.c) || !Array.isArray(el.c[0]) || !Array.isArray(el.c[0][1])) { return false; } const classes = el.c[0][1]; return classes.indexOf('plantuml') >= 0 || classes.indexOf('puml') >= 0; } function stringifyInlines(inlines) { if (!inlines) { return ''; } if (typeof inlines === 'string') { return inlines; } if (Array.isArray(inlines)) { return inlines.map(stringifyInlines).join(''); } if (inlines && typeof inlines === 'object') { if (inlines.t === 'Str') { return inlines.c || ''; } if (inlines.t === 'Space' || inlines.t === 'SoftBreak') { return ' '; } if (Object.prototype.hasOwnProperty.call(inlines, 'c')) { return stringifyInlines(inlines.c); } } return ''; } function isFigureCaptionPara(el) { if (!el || el.t !== 'Para' || !Array.isArray(el.c) || el.c.length === 0) { return false; } if (el.c[0].t !== 'Strong') { return false; } return /^Figure\s/.test(stringifyInlines(el.c).trim()); } function figureCaptionInlines(el) { if (el.c.length === 1 && el.c[0].t === 'Strong' && Array.isArray(el.c[0].c)) { return el.c[0].c; } const out = []; for (let i = 0; i < el.c.length; i++) { const inline = el.c[i]; if (inline && inline.t === 'Strong' && Array.isArray(inline.c)) { Array.prototype.push.apply(out, inline.c); } else { out.push(inline); } } return out; } function encode6bit(b) { if (b < 10) { return String.fromCharCode(48 + b); } b -= 10; if (b < 26) { return String.fromCharCode(65 + b); } b -= 26; if (b < 26) { return String.fromCharCode(97 + b); } b -= 26; if (b === 0) { return '-'; } if (b === 1) { return '_'; } return '?'; } function append3bytes(b1, b2, b3) { const c1 = b1 >> 2; const c2 = ((b1 & 0x3) << 4) | (b2 >> 4); const c3 = ((b2 & 0xF) << 2) | (b3 >> 6); const c4 = b3 & 0x3F; return encode6bit(c1 & 0x3F) + encode6bit(c2 & 0x3F) + encode6bit(c3 & 0x3F) + encode6bit(c4 & 0x3F); } function encode64(data) { let r = ''; for (let i = 0; i < data.length; i += 3) { if (i + 2 === data.length) { r += append3bytes(data[i], data[i + 1], 0); } else if (i + 1 === data.length) { r += append3bytes(data[i], 0, 0); } else { r += append3bytes(data[i], data[i + 1], data[i + 2]); } } return r; } function encodePlantuml(text) { return encode64(zlib.deflateRawSync(Buffer.from(text, 'utf8'))); } function ensureStartUml(content) { const text = String(content).trim(); if (/@startuml/i.test(text)) { return text + '\n'; } return '@startuml\n' + text + '\n@enduml\n'; } function figureFromPng(id, png, caption) { const captionInlines = Array.isArray(caption) ? caption : []; const src = 'data:image/png;base64,' + png.toString('base64'); const image = { t: 'Image', c: [[id, [], []], captionInlines, [src, 'fig:']] }; return { t: 'Figure', c: [ [id, [], []], [null, captionInlines.length ? [{ t: 'Plain', c: captionInlines }] : []], [{ t: 'Plain', c: [image] }] ] }; } function renderPlantuml(el, caption) { const attrs = el.c[0]; const id = attrs[0] || ''; const source = ensureStartUml(el.c[1]); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'plantuml-')); const output = path.join(tmp, 'out.png'); const url = SERVER + '/png/' + encodePlantuml(source); try { execFileSync(WGET, [ '--timeout=30', '--tries=2', '-q', '-O', output, url ], { stdio: ['ignore', 'pipe', 'pipe'] }); } catch (err) { const stderr = err.stderr ? err.stderr.toString() : String(err); fs.writeSync(2, 'plantuml server failed (' + SERVER + '):\n' + stderr + '\n'); process.exit(1); } const data = fs.readFileSync(output); if (data.length < 8 || data[0] !== 0x89 || data[1] !== 0x50) { fs.writeSync(2, 'plantuml server did not return a PNG from ' + SERVER + '\n'); process.exit(1); } try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (e) { /* ignore */ } return figureFromPng(id, data, caption); } function captionFromAttrs(el) { const kvs = el && el.c && el.c[0] && el.c[0][2]; if (!Array.isArray(kvs)) { return []; } for (let i = 0; i < kvs.length; i++) { if (kvs[i] && kvs[i][0] === 'caption' && kvs[i][1]) { return [{ t: 'Str', c: String(kvs[i][1]) }]; } } return []; } function warnPlantumlBlock() { fs.writeSync(2, '⚠ WARNING: PlantUML block found. Please, substitute it with a regular image.\n'); } function walkBlocks(blocks) { const out = []; for (let i = 0; i < blocks.length; i++) { const el = blocks[i]; if (isPlantumlBlock(el)) { warnPlantumlBlock(); let caption = captionFromAttrs(el); if (isFigureCaptionPara(blocks[i + 1])) { caption = figureCaptionInlines(blocks[i + 1]); i += 1; } out.push(renderPlantuml(el, caption)); } else { out.push(walk(el)); } } return out; } function walk(node) { if (Array.isArray(node)) { if (node.some(isPlantumlBlock)) { return walkBlocks(node); } return node.map(walk); } if (node && typeof node === 'object') { if (isPlantumlBlock(node)) { warnPlantumlBlock(); return renderPlantuml(node, []); } if (Object.prototype.hasOwnProperty.call(node, 'c')) { node.c = walk(node.c); } if (Object.prototype.hasOwnProperty.call(node, 'blocks')) { node.blocks = walk(node.blocks); } return node; } return node; } let raw = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { raw += chunk; }); process.stdin.on('end', function () { const doc = JSON.parse(raw); process.stdout.write(JSON.stringify(walk(doc))); });