High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
// Different content conversions for campaign bodies, eg: html -> plaintext
// Trim multilines and optionally remove empty lines.
function trimLines(str, removeEmptyLines) {
const out = str.split('\n');
for (let i = 0; i < out.length; i += 1) {
const line = out[i].trim();
if (removeEmptyLines) {
out[i] = line;
} else if (line === '') {
out[i] = '';
}
}
// 3+ lines, compress to 2.
return out.join('\n').replace(/\n\s*\n\s*\n/g, '\n\n');
}
// Pretty-print an HTML string with 4-space indentation.
class HTMLBeautifier {
// Tags whose content flows inline and so must not force line breaks.
static INLINE_TAGS = new Set(['a', 'span', 'b', 'strong', 'em', 'i', 'code',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
// Void elements never have a closing tag / children.
static VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img',
'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
// Raw-text elements whose contents must be preserved verbatim (they can hold
// stray '<' that isn't markup).
static RAW_TAGS = new Set(['script', 'style', 'pre', 'textarea']);
static INDENT = ' ';
// Pretty-print HTML.
beautify(html) {
const lines = [];
let depth = 0;
let buf = '';
const pad = () => HTMLBeautifier.INDENT.repeat(Math.max(0, depth));
const flush = () => {
const t = buf.replace(/\s+/g, ' ').trim();
if (t) {
lines.push(pad() + t);
}
buf = '';
};
this._tokenize(html).forEach((tk) => {
if (tk.type === 'text') {
buf += tk.raw;
} else if (tk.type === 'raw') {
flush();
lines.push(tk.raw.replace(/^\n+|\s+$/g, ''));
} else if (tk.type === 'other') {
flush();
lines.push(pad() + tk.raw.trim());
} else if (HTMLBeautifier.INLINE_TAGS.has(tk.name)) {
buf += tk.raw;
} else if (tk.closing) {
flush();
depth -= 1;
lines.push(pad() + tk.raw.trim());
} else if (tk.selfClose) {
flush();
lines.push(pad() + tk.raw.trim());
} else {
flush();
lines.push(pad() + tk.raw.trim());
depth += 1;
}
});
flush();
return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
// Find the index just past the '>' that closes a tag opened at `start`,
// skipping any '>' inside quoted attribute values.
_findTagEnd(html, start) {
let quote = null;
for (let j = start + 1; j < html.length; j += 1) {
const ch = html[j];
if (quote) {
if (ch === quote) quote = null;
} else if (ch === '"' || ch === '\'') {
quote = ch;
} else if (ch === '>') {
return j + 1;
}
}
return html.length;
}
// Split HTML into a list of tokens. Won't error-out on malformed tags.
_tokenize(html) {
const tokens = [];
const n = html.length;
let i = 0;
while (i < n) {
if (html[i] !== '<') {
const next = html.indexOf('<', i);
const stop = next === -1 ? n : next;
tokens.push({ type: 'text', raw: html.slice(i, stop) });
i = stop;
} else if (html.startsWith('<!--', i)) {
const end = html.indexOf('-->', i + 4);
const stop = end === -1 ? n : end + 3;
tokens.push({ type: 'other', raw: html.slice(i, stop) });
i = stop;
} else if (html[i + 1] === '!' || html[i + 1] === '?') {
const stop = this._findTagEnd(html, i);
tokens.push({ type: 'other', raw: html.slice(i, stop) });
i = stop;
} else {
const m = /^<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)/.exec(html.slice(i));
if (!m) {
// A stray '<' that isn't a tag is considered text.
tokens.push({ type: 'text', raw: '<' });
i += 1;
} else {
const stop = this._findTagEnd(html, i);
const raw = html.slice(i, stop);
const name = m[2].toLowerCase();
const closing = m[1] === '/';
const selfClose = /\/>\s*$/.test(raw) || HTMLBeautifier.VOID_TAGS.has(name);
tokens.push({
type: 'tag', raw, name, closing, selfClose,
});
i = stop;
// Capture raw text element contents verbatim up to its close tag.
if (!closing && !selfClose && HTMLBeautifier.RAW_TAGS.has(name)) {
const close = new RegExp(`</${name}\\s*>`, 'i').exec(html.slice(i));
const contentEnd = close ? i + close.index : n;
if (contentEnd > i) {
tokens.push({ type: 'raw', raw: html.slice(i, contentEnd) });
}
i = contentEnd;
}
}
}
}
return tokens;
}
}
// Simple HTML to Markdown (lossy!) converter.
class HTMLToMarkdown {
static BLOCK_TAGS = new Set(['div', 'section', 'article', 'main', 'header', 'footer',
'aside', 'figure', 'fieldset', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th',
'ul', 'ol', 'li', 'p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
convert(html) {
const div = document.createElement('div');
div.innerHTML = html || '';
// Drop trailing spaces before paragraph breaks (keeps Markdown's " \n" hard
// breaks intact) and compress blank lines.
return this._block(div)
.replace(/[^\S\n]+\n\n/g, '\n\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
_isBlock(n) {
return HTMLToMarkdown.BLOCK_TAGS.has(n.tagName.toLowerCase())
|| [...n.children].some((c) => HTMLToMarkdown.BLOCK_TAGS.has(c.tagName.toLowerCase()));
}
// Render inline elements (bold, italics, links, code, images).
_inline(node) {
let out = '';
node.childNodes.forEach((n) => {
if (n.nodeType === Node.TEXT_NODE) {
out += n.textContent.replace(/\s+/g, ' ');
return;
}
if (n.nodeType !== Node.ELEMENT_NODE) {
return;
}
const t = n.tagName.toLowerCase();
if (t === 'strong' || t === 'b') {
out += `**${this._inline(n).trim()}**`;
} else if (t === 'em' || t === 'i') {
out += `*${this._inline(n).trim()}*`;
} else if (t === 'code') {
out += `\`${n.textContent}\``;
} else if (t === 'br') {
out += ' \n';
} else if (t === 'a') {
out += `[${this._inline(n).trim()}](${n.getAttribute('href') || ''})`;
} else if (t === 'img') {
out += ` || ''})`;
} else {
out += this._inline(n);
}
});
return out;
}
// Render block-level content.
_block(node) {
let out = '';
node.childNodes.forEach((n) => {
if (n.nodeType === Node.TEXT_NODE) {
out += n.textContent.replace(/\s+/g, ' ').replace(/^\s+$/, '');
return;
}
if (n.nodeType !== Node.ELEMENT_NODE) {
return;
}
const t = n.tagName.toLowerCase();
if (/^h[1-6]$/.test(t)) {
out += `\n${'#'.repeat(Number(t[1]))} ${this._inline(n).trim()}\n\n`;
} else if (t === 'p') {
out += `${this._inline(n).trim()}\n\n`;
} else if (t === 'hr') {
out += '\n---\n\n';
} else if (t === 'blockquote') {
out += `${this._block(n).trim().split('\n').map((l) => `> ${l}`).join('\n')}\n\n`;
} else if (t === 'pre') {
out += `\`\`\`\n${n.textContent.trim()}\n\`\`\`\n\n`;
} else if (t === 'ul' || t === 'ol') {
[...n.children].forEach((li, i) => {
out += `${t === 'ol' ? `${i + 1}.` : '-'} ${this._inline(li).trim()}\n`;
});
out += '\n';
} else if (t === 'br') {
out += '\n\n';
} else if (t === 'img') {
out += ` || ''})\n\n`;
} else if (this._isBlock(n)) {
// Structural container (div, table, etc.)
out += `${this._block(n).trim()}\n\n`;
} else {
out += this._inline(n);
}
});
return out;
}
}
// Simple Markdown to HTML (lossy!) converter.
class MarkdownToHTML {
convert(md) {
// Normalise newlines and drop NULs (used internally as placeholders).
const src = String(md ?? '').replace(/\r\n?/g, '\n').replace(/