import fs from "fs"; import path from "path"; import escape from "escape-html"; const TOKENS_EXT = /\.tokens\.json$/; // https://developer.mozilla.org/en-US/docs/Web/Media/Formats export const IMG_EXT = /\.(apng|avif|gif|jpg|jpeg|jfif|pjpeg|pjp|png|svg|webp)$/; export const AUDIO_EXT = /\.(mp3|wav|aac|aacp|mpeg|off|flac)$/; export const VIDEO_EXT = /\.(mp4|webm)$/; export const BASE_STYLE = ""; export const GMI_CSS = fs.readFileSync( path.resolve(path.dirname(new URL(import.meta.url).pathname), "./gmi.min.css"), "utf8" ); export default (options) => (file, cb) => { if (!TOKENS_EXT.test(file.path)) return cb(null); file.contents = Buffer.from(toHTML(file, options)); file.path = file.path.replace(TOKENS_EXT, ".html"); if (options.verbose) console.log(file.path); return cb(null, file); }; export function toHTML (file, options) { const tokens = JSON.parse(file.contents.toString("utf8")); const title = tokens[0].h1; return ` ${head(file.path, title, options)} ${gemtext(tokens, options)} `; }; export function head(file, title, options) { return ` ${ !options.css ? BASE_STYLE : `\n\n` }${ !options.canonical ? "" : `` } ${title} `; } export function gemtext(tokens, options) { let body = []; let cursor = tokens.shift(); while (tokens.length) { if (cursor.pre) { body.push(``); const closing = tokens.findIndex((token) => token.pre); body = body.concat(tokens.slice(0, closing).map(({ text }) => text)); body.push(""); tokens = tokens.slice(closing + 1); } else if (cursor.li) { body.push(`"); tokens = tokens.slice(closing); } else { body.push(line(cursor, options)); } cursor = tokens.shift(); } return body.join("\n"); } function line( { text, href, title, pre, alt, h1, h2, h3, li, quote }, { images, audio, video } = {} ) { if (text) return `

${escape(text)}

`; if (href) { const titleProp = title ? ` title="${title}"` : ""; if (images && IMG_EXT.test(href)) return ``; if (audio && AUDIO_EXT.test(href)) return ``; if (video && VIDEO_EXT.test(href)) return ``; return `${title ? escape(title) : href}`; } if (h1) return `

${escape(h1)}

`; if (h2) return `

${escape(h2)}

`; if (h3) return `

${escape(h3)}

`; if (li) return `
  • ${escape(li)}
  • `; if (quote) return `
    ${escape(quote)}
    `; return `


    `; }