UNPKG

@knennigtri/merge-markdown

Version:

Prepare input files to merge together and optionally output html/pdf/word presentation

286 lines (285 loc) • 19.9 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; var r = _regenerator(), e = r.m(_regeneratorRuntime), t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor; function n(r) { var e = "function" == typeof r && r.constructor; return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name)); } var o = { "throw": 1, "return": 2, "break": 3, "continue": 3 }; function a(r) { var e, t; return function (n) { e || (e = { stop: function stop() { return t(n.a, 2); }, "catch": function _catch() { return n.v; }, abrupt: function abrupt(r, e) { return t(n.a, o[r], e); }, delegateYield: function delegateYield(r, o, a) { return e.resultName = o, t(n.d, _regeneratorValues(r), a); }, finish: function finish(r) { return t(n.f, r); } }, t = function t(r, _t, o) { n.p = e.prev, n.n = e.next; try { return r(_t, o); } finally { e.next = n.n; } }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n; try { return r.call(this, e); } finally { n.p = e.prev, n.n = e.next; } }; } return (_regeneratorRuntime = function _regeneratorRuntime() { return { wrap: function wrap(e, t, n, o) { return r.w(a(e), t, n, o && o.reverse()); }, isGeneratorFunction: n, mark: r.m, awrap: function awrap(r, e) { return new _OverloadYield(r, e); }, AsyncIterator: _regeneratorAsyncIterator, async: function async(r, e, t, o, u) { return (n(e) ? _regeneratorAsyncGen : _regeneratorAsync)(a(r), e, t, o, u); }, keys: _regeneratorKeys, values: _regeneratorValues }; })(); } function _regeneratorValues(e) { if (null != e) { var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"], r = 0; if (t) return t.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) return { next: function next() { return e && r >= e.length && (e = void 0), { value: e && e[r++], done: !e }; } }; } throw new TypeError(_typeof(e) + " is not iterable"); } function _regeneratorKeys(e) { var n = Object(e), r = []; for (var t in n) r.unshift(t); return function e() { for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e; return e.done = !0, e; }; } function _regeneratorAsync(n, e, r, t, o) { var a = _regeneratorAsyncGen(n, e, r, t, o); return a.next().then(function (n) { return n.done ? n.value : a.next(); }); } function _regeneratorAsyncGen(r, e, t, o, n) { return new _regeneratorAsyncIterator(_regenerator().w(r, e, t, o), n || Promise); } function _regeneratorAsyncIterator(t, e) { function n(r, o, i, f) { try { var c = t[r](o), u = c.value; return u instanceof _OverloadYield ? e.resolve(u.v).then(function (t) { n("next", t, i, f); }, function (t) { n("throw", t, i, f); }) : e.resolve(u).then(function (t) { c.value = t, i(c); }, function (t) { return n("throw", t, i, f); }); } catch (t) { f(t); } } var r; this.next || (_regeneratorDefine2(_regeneratorAsyncIterator.prototype), _regeneratorDefine2(_regeneratorAsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () { return this; })), _regeneratorDefine2(this, "_invoke", function (t, o, i) { function f() { return new e(function (e, r) { n(t, i, e, r); }); } return r = r ? r.then(f, f) : f(); }, !0); } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); } function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine2(e, r, n, t); } function _OverloadYield(e, d) { this.v = e, this.k = d; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } var manifestUtil = require("./manifest.js"); var fs = require("fs"); var fsPromises = require("fs").promises; var path = require("path"); var _require = require("util"), promisify = _require.promisify; var _require2 = require("child_process"), execFile = _require2.execFile; var execFileAsync = promisify(execFile); var wkhtmltopdf = require("wkhtmltopdf"); var debug = require("debug")("presentation"); var debugPandoc = require("debug")("pandoc"); var debugPandocOptions = require("debug")("pandoc:options"); var debugPandocDefaults = require("debug")("pandoc:options:defaults"); var debugWkhtmltopdf = require("debug")("pdf"); var debugWkhtmltopdfOptions = require("debug")("pdf:options"); var debugPdfDefaults = require("debug")("pdf:options:defaults"); exports.debbugOptions = { "presentation": "", "html": "pandoc messages for html", "html:options": "pandoc options messages", "pdf": "wkhtmltopdf messages for pdf", "pdf:options": "wkhtmltopdf options messages" }; var EXTS = { pdf: ".pdf", html: ".html", docx: ".docx" }; exports.EXTS = EXTS; function build(_x, _x2, _x3) { return _build.apply(this, arguments); } // Input and Output files are expected to be ABS function _build() { _build = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputFile, outputFormat, manifestFileStr) { var manifest, manifestOutputName, manifestOutputPandoc, manifestOutputWkhtmltopdf, fileNames, generatedFiles, ext, fileName, pandocOutputExt, resultPandocFile, inputFileParsed, pdfFileName, outputNewName, outputPath, outputFile; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (outputFormat) { _context.next = 2; break; } return _context.abrupt("return", inputFile); case 2: console.log("\nšŸ“„ Converting to " + outputFormat + "..."); manifest = manifestUtil.getJSON_withABSPaths(manifestFileStr); manifestOutputName = manifest.output.name; manifestOutputPandoc = manifest.output.pandoc; manifestOutputWkhtmltopdf = manifest.output.wkhtmltopdf; fileNames = []; generatedFiles = path.parse(inputFile); for (ext in EXTS) { fileName = path.join(generatedFiles.dir, "".concat(generatedFiles.name).concat(ext)); fileNames.push(fileName); } debug("deleteGeneratedFiles: ".concat(JSON.stringify(fileNames))); deleteGeneratedFiles(fileNames); pandocOutputExt = outputFormat.includes(EXTS.docx) ? EXTS.docx : EXTS.html; _context.next = 15; return pandocWriteToFile(inputFile, manifestOutputPandoc, pandocOutputExt); case 15: resultPandocFile = _context.sent; if (!outputFormat.includes(EXTS.pdf)) { _context.next = 24; break; } inputFileParsed = path.parse(inputFile); pdfFileName = path.join(inputFileParsed.dir, "".concat(inputFileParsed.name).concat(EXTS.pdf)); _context.next = 21; return wkhtmltopdfWriteToFile(resultPandocFile, manifestOutputWkhtmltopdf, pdfFileName); case 21: return _context.abrupt("return", _context.sent); case 24: outputNewName = "".concat(path.parse(manifestOutputName).name).concat(pandocOutputExt); outputPath = path.parse(resultPandocFile).dir; outputFile = path.join(outputPath, outputNewName); debug("".concat(path.parse(resultPandocFile).base, " >> ").concat(outputNewName)); _context.prev = 28; _context.next = 31; return fsPromises.rename(resultPandocFile, outputFile); case 31: return _context.abrupt("return", outputFile); case 34: _context.prev = 34; _context.t0 = _context["catch"](28); console.error("\nāŒ Error renaming output file:"); console.error(" " + _context.t0.message); throw _context.t0; case 39: case "end": return _context.stop(); } }, _callee, null, [[28, 34]]); })); return _build.apply(this, arguments); } function pandocWriteToFile(_x4, _x5, _x6) { return _pandocWriteToFile.apply(this, arguments); } // Input and Output files are expected to be ABS function _pandocWriteToFile() { _pandocWriteToFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(inputFile, pandocParams, outputExt) { var outputFile, pandocArgs, _yield$execFileAsync, stderr, warningMsg, _warningMsg; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: debug("Creating ".concat(outputExt, " using Pandoc...")); outputFile = path.join(path.parse(inputFile).dir, "temp".concat(outputExt)); pandocArgs = buildPandocArgsArray(pandocParams, outputFile); debugPandoc("input: " + inputFile); debugPandoc("Args: " + JSON.stringify(pandocArgs)); _context2.prev = 5; _context2.next = 8; return execFileAsync("pandoc", [inputFile].concat(_toConsumableArray(pandocArgs))); case 8: _yield$execFileAsync = _context2.sent; stderr = _yield$execFileAsync.stderr; // Show any warnings even on success if (stderr && stderr.trim()) { warningMsg = stderr.trim(); console.log(" ⚠ " + warningMsg.split("\n")[0]); debugPandoc("Full output: " + warningMsg); } console.log(" āœ“ Generated " + path.parse(outputFile).base); return _context2.abrupt("return", outputFile); case 15: _context2.prev = 15; _context2.t0 = _context2["catch"](5); if (!fs.existsSync(outputFile)) { _context2.next = 23; break; } // File created successfully, stderr was just a warning if (_context2.t0.stderr) { _warningMsg = _context2.t0.stderr.trim(); if (_warningMsg) { console.log(" ⚠ Pandoc warning: " + _warningMsg.split("\n")[0]); debugPandoc("Full warning: " + _warningMsg); } } console.log(" āœ“ Generated " + path.parse(outputFile).base); return _context2.abrupt("return", outputFile); case 23: // Real error - file not created console.error("\nāŒ Pandoc error:"); if (_context2.t0.code === "ENOENT") { console.error(" Pandoc not found. Make sure it's installed and in your PATH"); console.error(" Install: https://pandoc.org/installing.html"); } else { console.error(" " + (_context2.t0.stderr ? _context2.t0.stderr.trim() : _context2.t0.message)); console.error(" Docs: https://pandoc.org/MANUAL.html"); } throw _context2.t0; case 26: case "end": return _context2.stop(); } }, _callee2, null, [[5, 15]]); })); return _pandocWriteToFile.apply(this, arguments); } function wkhtmltopdfWriteToFile(inputFile, wkhtmltopdfParams, outputFile) { debug("Creating PDF using wkhtmltopdf..."); var options = buildWkhtmltopdfOptions(wkhtmltopdfParams, outputFile); debugWkhtmltopdf("input: " + inputFile); debugWkhtmltopdf("Args: " + JSON.stringify(options, null, 2)); return new Promise(function (resolve, reject) { wkhtmltopdf(fs.createReadStream(inputFile), options, function (err) { if (err) { var errMsg = err.toString(); console.error("\nāŒ wkhtmltopdf error:"); if (errMsg.includes("spawn wkhtmltopdf ENOENT")) { console.error(" wkhtmltopdf not found. Make sure it's installed and in your PATH"); console.error(" Install: http://wkhtmltopdf.org/downloads.html"); } else if (errMsg.includes("EACCES")) { console.error(" Permission denied accessing file"); console.error(" " + errMsg); } else if (errMsg.includes("Exit with code")) { // wkhtmltopdf returned non-zero exit code var lines = errMsg.split("\n").filter(function (l) { return l.trim(); }); console.error(" " + lines[0]); if (lines.length > 1) { lines.slice(1, 4).forEach(function (line) { return console.error(" " + line); }); } console.error(" Docs: http://wkhtmltopdf.org/usage/wkhtmltopdf.txt"); } else { console.error(" " + errMsg.split("\n")[0]); console.error(" Docs: http://wkhtmltopdf.org/usage/wkhtmltopdf.txt"); } reject(err); } else { console.log(" āœ“ Generated " + path.parse(outputFile).base); resolve(outputFile); } }); }); } function buildPandocArgsArray(params, fileName) { // Build args as array for execFile // Don't use --quiet so we can see useful warnings var argsArray = ["-o", fileName]; debugPandocDefaults("Base args: " + JSON.stringify(argsArray)); if (params) { for (var key in params) { var paramValue = params[key].trim(); if (paramValue.includes("-o")) { debugPandocOptions("Arg [ -o ] cannot be changed. Ignoring."); } else { debugPandocOptions("Arg added: " + paramValue); // Split args that have spaces (e.g., "-c mystyle.css" becomes ["-c", "mystyle.css"]) var splitArgs = paramValue.match(/(?:[^\s"]+|"[^"]*")+/g) || []; argsArray.push.apply(argsArray, _toConsumableArray(splitArgs.map(function (arg) { return arg.replace(/^"(.*)"$/, "$1"); }))); } } } else { debugPandoc("No pandoc Args given in manifest. Using defaults."); } debugPandocOptions("Final Args: " + JSON.stringify(argsArray)); return argsArray; } function buildWkhtmltopdfOptions(params, fileName) { debugWkhtmltopdf("Adding wkhtmltopdf options from Manifest"); var defaultOptions = { output: fileName, enableLocalFileAccess: true, disableSmartShrinking: true, marginBottom: "1in", marginTop: "1in", marginLeft: ".7in", marginRight: ".7in", pageSize: "Letter", footerLine: true, footerCenter: "Page [page]" }; debugPdfDefaults(defaultOptions); var finalOptions = defaultOptions; if (params) { for (var key in params) { if (key == "enableLocalFileAccess" || key == "disableSmartShrinking" || key == "output") { debugWkhtmltopdfOptions("Option [ " + key + " ] cannot be changed for output. Ignoring."); } else { debugWkhtmltopdfOptions("Updating [" + key + "] to: " + params[key]); finalOptions[key] = params[key]; } } debugWkhtmltopdfOptions("Final Args: " + finalOptions); return finalOptions; } debugWkhtmltopdf("No options given in manifest. Using Default wkhtmltopdf options."); return finalOptions; } function deleteGeneratedFiles(fileArray) { fileArray.forEach(function (filePath) { if (fs.existsSync(filePath)) { debug("Deleting: " + filePath); fs.unlinkSync(filePath); } }); } exports.build = build;