"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadPDFMethods = loadPDFMethods;
var fs = require("fs");
var os = require("os");
var path = require("path");
var axios_1 = require("axios");
var pdf_lib_1 = require("pdf-lib");
var puppeteer = require("puppeteer");
var simpl_schema_1 = require("simpl-schema");
var flag_collection_1 = require("../collections/flag.collection");
var common_1 = require("../util/common");
var PUPPETEER_ARGS = [
    '--disable-dev-shm-usage',
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-accelerated-2d-canvas',
    '--disable-gpu',
    '--allow-file-access-from-files',
    '--enable-local-file-accesses',
    '--font-render-hinting=none',
    '--disable-breakpad',
    '--no-zygote'
];
var LOW_RESOURCE_PUPPETEER_ARGS = [
    '--single-process',
    '--renderer-process-limit=1',
    '--disable-extensions',
    '--disable-features=AudioServiceOutOfProcess'
];
var cachedExecutablePath = null;
var cachedTmpExecutablePath = null;
function getBrowserConnectUrl() {
    var browserUrl = process.env.PUPPETEER_BROWSER_URL || process.env.PDF_PUPPETEER_BROWSER_URL || process.env.BROWSER_WS_URL;
    if (!browserUrl || typeof browserUrl !== 'string') {
        return null;
    }
    return browserUrl.trim() || null;
}
function envMs(name, fallback) {
    var raw = process.env[name];
    if (!raw) {
        return fallback;
    }
    var parsed = parseInt(raw, 10);
    if (!Number.isFinite(parsed) || parsed <= 0) {
        return fallback;
    }
    return parsed;
}
var PDF_LAUNCH_TIMEOUT_MS = envMs('PDF_LAUNCH_TIMEOUT_MS', 60000);
var PDF_CONTENT_TIMEOUT_MS = envMs('PDF_CONTENT_TIMEOUT_MS', 60000);
var PDF_FONTS_TIMEOUT_MS = envMs('PDF_FONTS_TIMEOUT_MS', 30000);
var PDF_IMAGES_TIMEOUT_MS = envMs('PDF_IMAGES_TIMEOUT_MS', 15000);
var PDF_RENDER_TIMEOUT_MS = envMs('PDF_RENDER_TIMEOUT_MS', 120000);
var PDF_PROTOCOL_TIMEOUT_MS = envMs('PDF_PROTOCOL_TIMEOUT_MS', 120000);
var PDF_OVERALL_TIMEOUT_MS = envMs('PDF_OVERALL_TIMEOUT_MS', 240000);
var PdfTimeoutError = /** @class */ (function (_super) {
    __extends(PdfTimeoutError, _super);
    function PdfTimeoutError(step, timeoutMs) {
        var _this = _super.call(this, "PDF step timed out after ".concat(timeoutMs, "ms: ").concat(step)) || this;
        _this.name = 'PdfTimeoutError';
        _this.step = step;
        _this.timeoutMs = timeoutMs;
        return _this;
    }
    return PdfTimeoutError;
}(Error));
function withTimeout(promise, timeoutMs, step) {
    if (!timeoutMs || timeoutMs <= 0) {
        return promise;
    }
    var timeoutHandle = null;
    // eslint-disable-next-line no-restricted-syntax
    return new Promise(function (resolve, reject) {
        timeoutHandle = setTimeout(function () {
            reject(new PdfTimeoutError(step, timeoutMs));
        }, timeoutMs);
        // eslint-disable-next-line no-restricted-syntax, promise/prefer-await-to-then
        promise.then(resolve, reject).finally(function () {
            if (timeoutHandle) {
                clearTimeout(timeoutHandle);
            }
        });
    });
}
function getEnvExecutablePath() {
    var envExecutablePath = process.env.PUPPETEER_EXECUTABLE_PATH || process.env.CHROME_EXECUTABLE_PATH || process.env.CHROME_PATH;
    if (envExecutablePath && fs.existsSync(envExecutablePath)) {
        return envExecutablePath;
    }
    return null;
}
function shouldRetryBrowserLaunch(err) {
    if (!err) {
        return false;
    }
    var message = err.message || '';
    var stderr = err.stderr ? err.stderr.toString() : '';
    return message.includes('chrome_crashpad_handler') || message.includes('Operation not permitted') || message.includes('Resource temporarily unavailable') || stderr.includes('pthread_create') || stderr.includes('Resource temporarily unavailable') || stderr.includes('Failed to connect to the bus');
}
function prepareExecutableFallback(executablePath) {
    try {
        var currentExecutablePath = executablePath || cachedExecutablePath || puppeteer.executablePath();
        if (!currentExecutablePath) {
            return null;
        }
        // Avoid copying if we're already running from a tmp dir.
        if (currentExecutablePath.startsWith(os.tmpdir())) {
            return null;
        }
        // Retry from a tmp location when the packaged Chromium cannot be executed (e.g. noexec home dirs).
        var chromiumDir = path.dirname(currentExecutablePath);
        var tmpRoot = path.join(os.tmpdir(), 'puppeteer-chromium');
        var tmpChromiumDir = path.join(tmpRoot, path.basename(chromiumDir));
        var tmpExecutablePath = path.join(tmpChromiumDir, path.basename(currentExecutablePath));
        if (!fs.existsSync(tmpExecutablePath)) {
            fs.mkdirSync(tmpChromiumDir, { recursive: true });
            fs.cpSync(chromiumDir, tmpChromiumDir, { recursive: true, force: true });
        }
        cachedTmpExecutablePath = tmpExecutablePath;
        return tmpExecutablePath;
    }
    catch (errCopy) {
        console.error(new Date(), 'Failed to prepare Chromium fallback', errCopy);
        return null;
    }
}
function sanitizeLaunchEnv(env) {
    var launchEnv = __assign(__assign({}, process.env), env);
    if (launchEnv.DBUS_SESSION_BUS_ADDRESS && !launchEnv.DBUS_SESSION_BUS_ADDRESS.startsWith('unix:') && !launchEnv.DBUS_SESSION_BUS_ADDRESS.startsWith('tcp:')) {
        delete launchEnv.DBUS_SESSION_BUS_ADDRESS;
    }
    return launchEnv;
}
function applyLowResourceLaunchTweaks(options) {
    var mergedArgs = __spreadArray([], __read((options.args || [])), false);
    LOW_RESOURCE_PUPPETEER_ARGS.forEach(function (arg) {
        if (!mergedArgs.includes(arg)) {
            mergedArgs.push(arg);
        }
    });
    return __assign(__assign({}, options), { args: mergedArgs, ignoreDefaultArgs: undefined, env: sanitizeLaunchEnv(options.env) });
}
function safeCloseBrowser(browser) {
    return __awaiter(this, void 0, void 0, function () {
        var proc, isConnectedBrowser, errClose_1, needsKill;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!browser) {
                        return [2 /*return*/];
                    }
                    proc = null;
                    isConnectedBrowser = false;
                    try {
                        proc = typeof browser.process === 'function' ? browser.process() : null;
                        isConnectedBrowser = !proc && browser.connected;
                    }
                    catch (_b) {
                        proc = null;
                        isConnectedBrowser = false;
                    }
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 6, 7, 8]);
                    if (!isConnectedBrowser) return [3 /*break*/, 3];
                    return [4 /*yield*/, Promise.resolve(browser.disconnect())];
                case 2:
                    _a.sent();
                    return [3 /*break*/, 5];
                case 3: return [4 /*yield*/, withTimeout(browser.close(), 5000, 'browser.close')];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5: return [3 /*break*/, 8];
                case 6:
                    errClose_1 = _a.sent();
                    console.error(new Date(), 'Puppeteer close failed, forcing kill', errClose_1 && errClose_1.message ? errClose_1.message : errClose_1);
                    return [3 /*break*/, 8];
                case 7:
                    needsKill = proc && proc.exitCode === null && proc.signalCode === null;
                    if (needsKill) {
                        try {
                            proc.kill('SIGKILL');
                        }
                        catch (errKill) {
                            if (!errKill || errKill.code !== 'ESRCH') {
                                console.error(new Date(), 'Failed to kill Puppeteer process', errKill);
                            }
                        }
                    }
                    return [7 /*endfinally*/];
                case 8: return [2 /*return*/];
            }
        });
    });
}
function launchPDFBrowser(headless, devtools) {
    return __awaiter(this, void 0, void 0, function () {
        var browserUrl, envExecutablePath, launchOptions, errLaunch_1, fallbackExecutablePath, retryOptions;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    browserUrl = getBrowserConnectUrl();
                    if (!browserUrl) return [3 /*break*/, 2];
                    return [4 /*yield*/, puppeteer.connect({
                            browserURL: browserUrl,
                            protocolTimeout: PDF_PROTOCOL_TIMEOUT_MS,
                            defaultViewport: null
                        })];
                case 1: return [2 /*return*/, _a.sent()];
                case 2:
                    envExecutablePath = getEnvExecutablePath();
                    if (!cachedExecutablePath) {
                        cachedExecutablePath = envExecutablePath || puppeteer.executablePath();
                    }
                    launchOptions = {
                        headless: headless,
                        devtools: devtools,
                        args: __spreadArray([], __read(PUPPETEER_ARGS), false),
                        ignoreDefaultArgs: ['--disable-extensions'],
                        env: sanitizeLaunchEnv(),
                        timeout: PDF_LAUNCH_TIMEOUT_MS,
                        protocolTimeout: PDF_PROTOCOL_TIMEOUT_MS
                    };
                    if (cachedExecutablePath) {
                        launchOptions.executablePath = cachedExecutablePath;
                    }
                    _a.label = 3;
                case 3:
                    _a.trys.push([3, 5, , 7]);
                    return [4 /*yield*/, puppeteer.launch(launchOptions)];
                case 4: return [2 /*return*/, _a.sent()];
                case 5:
                    errLaunch_1 = _a.sent();
                    if (!shouldRetryBrowserLaunch(errLaunch_1)) {
                        throw errLaunch_1;
                    }
                    fallbackExecutablePath = cachedTmpExecutablePath || prepareExecutableFallback(launchOptions.executablePath);
                    retryOptions = applyLowResourceLaunchTweaks(__assign(__assign({}, launchOptions), { executablePath: fallbackExecutablePath || launchOptions.executablePath }));
                    if (fallbackExecutablePath) {
                        cachedExecutablePath = fallbackExecutablePath;
                    }
                    console.warn(new Date(), 'Retrying Puppeteer launch with low-resource args');
                    return [4 /*yield*/, puppeteer.launch(retryOptions)];
                case 6: return [2 /*return*/, _a.sent()];
                case 7: return [2 /*return*/];
            }
        });
    });
}
function loadPDFMethods(methodManager) {
    methodManager.methods({
        generatePDF: {
            bypassSession: true,
            check: new simpl_schema_1.default({
                html: {
                    type: String
                },
                fileName: {
                    type: String
                },
                orientation: {
                    type: String,
                    optional: true
                },
                fontSize: {
                    type: String,
                    optional: true
                },
                upload: {
                    type: Boolean,
                    optional: true
                },
                uploadFileOrder: {
                    type: Number,
                    optional: true
                },
                uploadFileType: {
                    type: String,
                    optional: true
                }
            }),
            function: function (html_1, fileName_1) {
                return __awaiter(this, arguments, void 0, function (html, fileName, orientation, fontSize, upload, uploadFileOrder, uploadFileType) {
                    var enableDebugFlag, enableDebug, maxAttempts, lastError, _loop_1, this_1, attempt, state_1;
                    if (orientation === void 0) { orientation = 'portrait'; }
                    if (fontSize === void 0) { fontSize = '12px'; }
                    if (upload === void 0) { upload = false; }
                    if (uploadFileOrder === void 0) { uploadFileOrder = -1; }
                    if (uploadFileType === void 0) { uploadFileType = ''; }
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, flag_collection_1.Flags.findOne({ type: 'Enable Debug PDF' })];
                            case 1:
                                enableDebugFlag = _a.sent();
                                enableDebug = !!(enableDebugFlag && enableDebugFlag.value);
                                maxAttempts = 2;
                                lastError = null;
                                _loop_1 = function (attempt) {
                                    var browser, page, overallTimedOut, overallTimeoutHandle, pathToFont, dejavuserif_woff, dejavuserifBold_woff, dejavuserifItalic_woff, dejavuserifBoldItalic_woff, content, errImages_1, tmpFileName, data, fileData, err_1;
                                    return __generator(this, function (_b) {
                                        switch (_b.label) {
                                            case 0:
                                                browser = null;
                                                page = null;
                                                overallTimedOut = false;
                                                overallTimeoutHandle = null;
                                                _b.label = 1;
                                            case 1:
                                                _b.trys.push([1, 15, 18, 22]);
                                                return [4 /*yield*/, withTimeout(launchPDFBrowser(!enableDebug, enableDebug), PDF_LAUNCH_TIMEOUT_MS, 'launchPDFBrowser')];
                                            case 2:
                                                browser = _b.sent();
                                                overallTimeoutHandle = setTimeout(function () {
                                                    overallTimedOut = true;
                                                    console.error(new Date(), 'generatePDF overall timeout hit', { fileName: fileName, attempt: attempt });
                                                    // eslint-disable-next-line no-restricted-syntax, promise/prefer-await-to-then
                                                    safeCloseBrowser(browser).catch(function () { });
                                                }, PDF_OVERALL_TIMEOUT_MS);
                                                return [4 /*yield*/, browser.newPage()];
                                            case 3:
                                                page = _b.sent(); // create new tab
                                                page.setDefaultTimeout(PDF_CONTENT_TIMEOUT_MS);
                                                pathToFont = '';
                                                if (fs.existsSync(path.join(__dirname, ('../private/fonts/dejavuserif.woff')))) {
                                                    pathToFont = path.join(__dirname, ('../private/fonts/'));
                                                }
                                                else {
                                                    if (fs.existsSync(path.join(this_1.clientDir, ('./private/fonts/dejavuserif.woff')))) {
                                                        pathToFont = path.join(this_1.clientDir, ('./private/fonts/'));
                                                    }
                                                    else {
                                                        pathToFont = '/usr/share/fonts/dejavu/';
                                                    }
                                                }
                                                dejavuserif_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif.woff').buffer).toString('base64');
                                                dejavuserifBold_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-bold.woff').buffer).toString('base64');
                                                dejavuserifItalic_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-italic.woff').buffer).toString('base64');
                                                dejavuserifBoldItalic_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-bolditalic.woff').buffer).toString('base64');
                                                content = "\n\t\t\t\t\t\t\t<head>\n\t\t\t\t\t\t\t\t<style type=\"text/css\">\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: normal;\n\t\t\t\t\t\t\t\t\t\tfont-weight: normal;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserif_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: normal;\n\t\t\t\t\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifBold_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: italic;\n\t\t\t\t\t\t\t\t\t\tfont-weight: normal;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifItalic_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: italic;\n\t\t\t\t\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifBoldItalic_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tbody {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif', serif;\n\t\t\t\t\t\t\t\t\t\tfont-size:  " + (fontSize ? fontSize : '12px') + ";\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.row {\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\tdisplay: flex;\n\t\t\t\t\t\t\t\t\t\tflex-wrap: wrap;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex-wrap: wrap;\n\t\t\t\t\t\t\t\t\t\tpage-break-inside: avoid !important;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.page-break {\n\t\t\t\t\t\t\t\t\t\tpage-break-before: always !important;\n\t\t\t\t\t\t\t\t\t\tpadding-top: 1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.cell {\n\t\t\t\t\t\t\t\t\t\tbox-sizing: border-box;\n\t\t\t\t\t\t\t\t\t\tpadding : 2px;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex: 1;\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.cell-no-padding {\n\t\t\t\t\t\t\t\t\t\tbox-sizing: border-box;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex: 1;\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered {\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: center;\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\ttext-align: center;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered-left {\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: flex-start;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered-right {\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: flex-end;\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t.box {\n\t\t\t\t\t\t\t\t\t\tborder: 1px solid black;\n\t\t\t\t\t\t\t\t\t\tmargin: -1px 0px 0px -1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.boxNoBorder {\n\t\t\t\t\t\t\t\t\t\tmargin: -1px 0px 0px -1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tpre {\n\t\t\t\t\t\t\t\t\t\twhite-space: pre-wrap;       /* css-3 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -moz-pre-wrap;  /* Mozilla, since 1999 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -pre-wrap;      /* Opera 4-6 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -o-pre-wrap;    /* Opera 7 */\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;       /* Internet Explorer 5.5+ */\n\t\t\t\t\t\t\t\t\t\tfont-size: 12px;\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif'; \n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t\t<meta charset=\"UTF-8\">\n\t\t\t\t\t\t\t</head>\n\t\t\t\t\t\t\t\t<body>\n\t\t\t\t\t\t\t" + html.replace(new RegExp('flex-basis:', 'g'), '-webkit-flex-basis:').replace(new RegExp('flex:', 'g'), '-webkit-flex:') + '</body>';
                                                return [4 /*yield*/, withTimeout(page.setContent(content, { waitUntil: ['domcontentloaded'], timeout: PDF_CONTENT_TIMEOUT_MS }), PDF_CONTENT_TIMEOUT_MS, 'page.setContent')];
                                            case 4:
                                                _b.sent();
                                                return [4 /*yield*/, withTimeout(page.evaluateHandle('document.fonts.ready'), PDF_FONTS_TIMEOUT_MS, 'document.fonts.ready')];
                                            case 5:
                                                _b.sent();
                                                if (!(PDF_IMAGES_TIMEOUT_MS > 0)) return [3 /*break*/, 9];
                                                _b.label = 6;
                                            case 6:
                                                _b.trys.push([6, 8, , 9]);
                                                return [4 /*yield*/, withTimeout(page.waitForFunction(function () { return Array.from(document.images).every(function (img) { return img.complete; }); }, { timeout: 0 }), PDF_IMAGES_TIMEOUT_MS, 'waitForImages')];
                                            case 7:
                                                _b.sent();
                                                return [3 /*break*/, 9];
                                            case 8:
                                                errImages_1 = _b.sent();
                                                if (errImages_1 instanceof PdfTimeoutError) {
                                                    console.warn(new Date(), 'generatePDF timed out waiting for images', { fileName: fileName, attempt: attempt });
                                                }
                                                else {
                                                    throw errImages_1;
                                                }
                                                return [3 /*break*/, 9];
                                            case 9:
                                                tmpFileName = (0, common_1.objectIdHexString)() + '.pdf';
                                                return [4 /*yield*/, withTimeout(page.pdf({
                                                        scale: 1,
                                                        landscape: orientation === 'portrait' ? false : true,
                                                        format: 'letter',
                                                        margin: {
                                                            top: '1cm',
                                                            bottom: '1cm',
                                                            left: '1cm',
                                                            right: '1cm'
                                                        },
                                                        printBackground: true,
                                                        displayHeaderFooter: true,
                                                        headerTemplate: "\n\t\t\t\t\t\t\t\t\t<style>\n\t\t\t\t\t\t\t\t\t\t#header { \n\t\t\t\t\t\t\t\t\t\t\tpadding: 0 0 10px 10px !important; \n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t\t\t<span></span>\n\t\t\t\t\t\t\t\t",
                                                        footerTemplate: "\n\t\t\t\t\t\t\t\t\t<style>\n\t\t\t\t\t\t\t\t\t\t#footer { \n\t\t\t\t\t\t\t\t\t\t\tpadding: 0 0 10px 10px !important;\n\t\t\t\t\t\t\t\t\t\t\tfont-size: 10px;\n\t\t\t\t\t\t\t\t\t\t\tfont-family: san-serif;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t\t\t<div style=\"padding-bottom: 2px; padding-right: 15px; text-align: right; width: 100%;\">\n\t\t\t\t\t\t\t\t\t\tPage&nbsp;<span class=\"pageNumber\"></span>&nbsp;of&nbsp;<span class=\"totalPages\"></span>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t",
                                                        path: path.join(__dirname, (tmpFileName)),
                                                        timeout: PDF_RENDER_TIMEOUT_MS
                                                    }), PDF_RENDER_TIMEOUT_MS, 'page.pdf')];
                                            case 10:
                                                _b.sent();
                                                if (!(enableDebugFlag && enableDebugFlag.value)) return [3 /*break*/, 14];
                                                if (!(orientation === 'landscape')) return [3 /*break*/, 12];
                                                return [4 /*yield*/, page.setViewport({ width: 1100, height: 850 })];
                                            case 11:
                                                _b.sent();
                                                return [3 /*break*/, 14];
                                            case 12: return [4 /*yield*/, page.setViewport({ width: 850, height: 1100 })];
                                            case 13:
                                                _b.sent();
                                                _b.label = 14;
                                            case 14:
                                                if (fs.existsSync(path.join(__dirname, (tmpFileName)))) {
                                                    try {
                                                        data = fs.readFileSync(path.join(__dirname, (tmpFileName)));
                                                        fs.unlinkSync(path.join(__dirname, (tmpFileName)));
                                                        if (!upload) {
                                                            return [2 /*return*/, { value: 'data:application/pdf;base64,' + data.toString('base64') }];
                                                        }
                                                        else {
                                                            fileData = 'data:application/pdf;base64,' + data.toString('base64');
                                                            return [2 /*return*/, { value: this_1.callMethod('uploadFileAndSave', fileName, fileData, (4 * Math.ceil(fileData.length / 3)), uploadFileOrder !== null ? uploadFileOrder : -1, uploadFileType, false) }];
                                                        }
                                                    }
                                                    catch (errRead) {
                                                        errRead.message = 'Error in Generate PDF: No file - ' + errRead.message;
                                                        throw errRead;
                                                    }
                                                }
                                                else {
                                                    console.log('No tmp file ', tmpFileName);
                                                    throw new Error('Error in Generate PDF: No tmp file');
                                                }
                                                return [3 /*break*/, 22];
                                            case 15:
                                                err_1 = _b.sent();
                                                lastError = err_1;
                                                if (!browser) return [3 /*break*/, 17];
                                                return [4 /*yield*/, safeCloseBrowser(browser)];
                                            case 16:
                                                _b.sent();
                                                _b.label = 17;
                                            case 17:
                                                if (attempt < maxAttempts) {
                                                    console.warn(new Date(), 'Retry generatePDF after error', {
                                                        attempt: attempt,
                                                        message: err_1 && err_1.message ? err_1.message : err_1
                                                    });
                                                    return [2 /*return*/, "continue"];
                                                }
                                                console.error(new Date(), 'generatePDF failed', { fileName: fileName, attempt: attempt, message: err_1 && err_1.message ? err_1.message : err_1 });
                                                throw err_1;
                                            case 18:
                                                if (overallTimeoutHandle) {
                                                    clearTimeout(overallTimeoutHandle);
                                                }
                                                if (!page) return [3 /*break*/, 20];
                                                // eslint-disable-next-line no-restricted-syntax
                                                return [4 /*yield*/, page.close().catch(function () { })];
                                            case 19:
                                                // eslint-disable-next-line no-restricted-syntax
                                                _b.sent();
                                                page = null;
                                                _b.label = 20;
                                            case 20: return [4 /*yield*/, safeCloseBrowser(browser)];
                                            case 21:
                                                _b.sent();
                                                browser = null;
                                                if (overallTimedOut) {
                                                    throw new PdfTimeoutError('generatePDF overall', PDF_OVERALL_TIMEOUT_MS);
                                                }
                                                return [7 /*endfinally*/];
                                            case 22: return [2 /*return*/];
                                        }
                                    });
                                };
                                this_1 = this;
                                attempt = 1;
                                _a.label = 2;
                            case 2:
                                if (!(attempt <= maxAttempts)) return [3 /*break*/, 5];
                                return [5 /*yield**/, _loop_1(attempt)];
                            case 3:
                                state_1 = _a.sent();
                                if (typeof state_1 === "object")
                                    return [2 /*return*/, state_1.value];
                                _a.label = 4;
                            case 4:
                                attempt++;
                                return [3 /*break*/, 2];
                            case 5: throw lastError;
                        }
                    });
                });
            },
            workerTaskWeight: 2,
            maxConcurrency: 1,
            timeoutOverride: 300000
        },
        generatePDFNoPageNumber: {
            bypassSession: true,
            check: new simpl_schema_1.default({
                html: {
                    type: String
                },
                fileName: {
                    type: String
                },
                orientation: {
                    type: String,
                    optional: true
                },
                fontSize: {
                    type: String,
                    optional: true
                },
                upload: {
                    type: Boolean,
                    optional: true
                },
                uploadFileOrder: {
                    type: Number,
                    optional: true
                },
                uploadFileType: {
                    type: String,
                    optional: true
                }
            }),
            function: function (html_1, fileName_1) {
                return __awaiter(this, arguments, void 0, function (html, fileName, orientation, fontSize, upload, uploadFileOrder, uploadFileType) {
                    var maxAttempts, lastError, _loop_2, this_2, attempt, state_2;
                    if (orientation === void 0) { orientation = 'portrait'; }
                    if (fontSize === void 0) { fontSize = '12px'; }
                    if (upload === void 0) { upload = false; }
                    if (uploadFileOrder === void 0) { uploadFileOrder = -1; }
                    if (uploadFileType === void 0) { uploadFileType = ''; }
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                maxAttempts = 2;
                                lastError = null;
                                _loop_2 = function (attempt) {
                                    var browser, page, overallTimedOut, overallTimeoutHandle, pathToFont, dejavuserif_woff, dejavuserifBold_woff, dejavuserifItalic_woff, dejavuserifBoldItalic_woff, content, errImages_2, tmpFileName, data, fileData, err_2;
                                    return __generator(this, function (_b) {
                                        switch (_b.label) {
                                            case 0:
                                                browser = null;
                                                page = null;
                                                overallTimedOut = false;
                                                overallTimeoutHandle = null;
                                                _b.label = 1;
                                            case 1:
                                                _b.trys.push([1, 11, 14, 18]);
                                                return [4 /*yield*/, withTimeout(launchPDFBrowser(true, false), PDF_LAUNCH_TIMEOUT_MS, 'launchPDFBrowser')];
                                            case 2:
                                                browser = _b.sent();
                                                overallTimeoutHandle = setTimeout(function () {
                                                    overallTimedOut = true;
                                                    console.error(new Date(), 'generatePDFNoPageNumber overall timeout hit', { fileName: fileName, attempt: attempt });
                                                    // eslint-disable-next-line no-restricted-syntax, promise/prefer-await-to-then
                                                    safeCloseBrowser(browser).catch(function () { });
                                                }, PDF_OVERALL_TIMEOUT_MS);
                                                return [4 /*yield*/, browser.newPage()];
                                            case 3:
                                                page = _b.sent(); // create new tab
                                                page.setDefaultTimeout(PDF_CONTENT_TIMEOUT_MS);
                                                pathToFont = '';
                                                if (fs.existsSync(path.join(__dirname, ('../private/fonts/dejavuserif.woff')))) {
                                                    pathToFont = path.join(__dirname, ('../private/fonts/'));
                                                }
                                                else {
                                                    if (fs.existsSync(path.join(this_2.clientDir, ('./private/fonts/dejavuserif.woff')))) {
                                                        pathToFont = path.join(this_2.clientDir, ('./private/fonts/'));
                                                    }
                                                    else {
                                                        pathToFont = '/usr/share/fonts/dejavu/';
                                                    }
                                                }
                                                dejavuserif_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif.woff').buffer).toString('base64');
                                                dejavuserifBold_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-bold.woff').buffer).toString('base64');
                                                dejavuserifItalic_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-italic.woff').buffer).toString('base64');
                                                dejavuserifBoldItalic_woff = 'data:application/font-woff;base64,' + Buffer.from(fs.readFileSync(pathToFont + 'dejavuserif-bolditalic.woff').buffer).toString('base64');
                                                content = "\n\t\t\t\t\t\t\t<head>\n\t\t\t\t\t\t\t\t<style type=\"text/css\">\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: normal;\n\t\t\t\t\t\t\t\t\t\tfont-weight: normal;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserif_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: normal;\n\t\t\t\t\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifBold_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: italic;\n\t\t\t\t\t\t\t\t\t\tfont-weight: normal;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifItalic_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t@font-face {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif';\n\t\t\t\t\t\t\t\t\t\tfont-style: italic;\n\t\t\t\t\t\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\t\t\t\t\t\tsrc: url(\"" + dejavuserifBoldItalic_woff + "\") format('woff');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tbody {\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif', serif;\n\t\t\t\t\t\t\t\t\t\tfont-size:  " + (fontSize ? fontSize : '12px') + ";\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.row {\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\tdisplay: flex;\n\t\t\t\t\t\t\t\t\t\tflex-wrap: wrap;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex-wrap: wrap;\n\t\t\t\t\t\t\t\t\t\tpage-break-inside: avoid !important;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.page-break {\n\t\t\t\t\t\t\t\t\t\tpage-break-before: always !important;\n\t\t\t\t\t\t\t\t\t\tpadding-top: 1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.cell {\n\t\t\t\t\t\t\t\t\t\tbox-sizing: border-box;\n\t\t\t\t\t\t\t\t\t\tpadding : 2px;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex: 1;\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.cell-no-padding {\n\t\t\t\t\t\t\t\t\t\tbox-sizing: border-box;\n\t\t\t\t\t\t\t\t\t\t-webkit-flex: 1;\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered {\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: center;\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\ttext-align: center;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered-left {\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: flex-start;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.centered-right {\n\t\t\t\t\t\t\t\t\t\t-webkit-justify-content: flex-end;\n\t\t\t\t\t\t\t\t\t\t-webkit-align-items: center;\n\t\t\t\t\t\t\t\t\t\tdisplay: -webkit-flex;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t.box {\n\t\t\t\t\t\t\t\t\t\tborder: 1px solid black;\n\t\t\t\t\t\t\t\t\t\tmargin: -1px 0px 0px -1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t.boxNoBorder {\n\t\t\t\t\t\t\t\t\t\tmargin: -1px 0px 0px -1px;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tpre {\n\t\t\t\t\t\t\t\t\t\twhite-space: pre-wrap;       /* css-3 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -moz-pre-wrap;  /* Mozilla, since 1999 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -pre-wrap;      /* Opera 4-6 */\n\t\t\t\t\t\t\t\t\t\twhite-space: -o-pre-wrap;    /* Opera 7 */\n\t\t\t\t\t\t\t\t\t\tword-wrap: break-word;       /* Internet Explorer 5.5+ */\n\t\t\t\t\t\t\t\t\t\tfont-size: 12px;\n\t\t\t\t\t\t\t\t\t\tfont-family: 'Dejavu Serif'; \n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t<meta charset=\"UTF-8\">\n\t\t\t\t\t\t</head>\n\t\t\t\t\t\t\t<body>\n\t\t\t\t\t\t" + html.replace(new RegExp('flex-basis:', 'g'), '-webkit-flex-basis:').replace(new RegExp('flex:', 'g'), '-webkit-flex:') + "</body>";
                                                return [4 /*yield*/, withTimeout(page.setContent(content, { waitUntil: ['domcontentloaded'], timeout: PDF_CONTENT_TIMEOUT_MS }), PDF_CONTENT_TIMEOUT_MS, 'page.setContent')];
                                            case 4:
                                                _b.sent();
                                                return [4 /*yield*/, withTimeout(page.evaluateHandle('document.fonts.ready'), PDF_FONTS_TIMEOUT_MS, 'document.fonts.ready')];
                                            case 5:
                                                _b.sent();
                                                if (!(PDF_IMAGES_TIMEOUT_MS > 0)) return [3 /*break*/, 9];
                                                _b.label = 6;
                                            case 6:
                                                _b.trys.push([6, 8, , 9]);
                                                return [4 /*yield*/, withTimeout(page.waitForFunction(function () { return Array.from(document.images).every(function (img) { return img.complete; }); }, { timeout: 0 }), PDF_IMAGES_TIMEOUT_MS, 'waitForImages')];
                                            case 7:
                                                _b.sent();
                                                return [3 /*break*/, 9];
                                            case 8:
                                                errImages_2 = _b.sent();
                                                if (errImages_2 instanceof PdfTimeoutError) {
                                                    console.warn(new Date(), 'generatePDFNoPageNumber timed out waiting for images', { fileName: fileName, attempt: attempt });
                                                }
                                                else {
                                                    throw errImages_2;
                                                }
                                                return [3 /*break*/, 9];
                                            case 9:
                                                tmpFileName = (0, common_1.objectIdHexString)() + '.pdf';
                                                return [4 /*yield*/, withTimeout(page.pdf({
                                                        scale: 1,
                                                        landscape: orientation === 'portrait' ? false : true,
                                                        format: 'letter',
                                                        margin: {
                                                            top: '1cm',
                                                            bottom: '1cm',
                                                            left: '1cm',
                                                            right: '1cm'
                                                        },
                                                        printBackground: true,
                                                        displayHeaderFooter: true,
                                                        headerTemplate: "\n\t\t\t\t\t\t\t\t\t<style>\n\t\t\t\t\t\t\t\t\t\t#header { \n\t\t\t\t\t\t\t\t\t\t\tpadding: 0 0 10px 10px !important; \n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t\t\t<span></span>\n\t\t\t\t\t\t\t\t",
                                                        footerTemplate: "\n\t\t\t\t\t\t\t\t<style>\n\t\t\t\t\t\t\t\t\t#footer { \n\t\t\t\t\t\t\t\t\t\tpadding: 0 0 10px 10px !important;\n\t\t\t\t\t\t\t\t\t\tfont-size: 10px;\n\t\t\t\t\t\t\t\t\t\tfont-family: san-serif;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t</style>\n\t\t\t\t\t\t\t\t<div style=\"padding-bottom: 2px; padding-right: 15px; text-align: right; width: 100%;\">\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t",
                                                        path: path.join(__dirname, (tmpFileName)),
                                                        timeout: PDF_RENDER_TIMEOUT_MS
                                                    }), PDF_RENDER_TIMEOUT_MS, 'page.pdf')];
                                            case 10:
                                                _b.sent();
                                                if (fs.existsSync(path.join(__dirname, (tmpFileName)))) {
                                                    try {
                                                        data = fs.readFileSync(path.join(__dirname, (tmpFileName)));
                                                        fs.unlinkSync(path.join(__dirname, (tmpFileName)));
                                                        if (!upload) {
                                                            return [2 /*return*/, { value: 'data:application/pdf;base64,' + data.toString('base64') }];
                                                        }
                                                        else {
                                                            fileData = 'data:application/pdf;base64,' + data.toString('base64');
                                                            return [2 /*return*/, { value: this_2.callMethod('uploadFileAndSave', fileName, fileData, (4 * Math.ceil(fileData.length / 3)), uploadFileOrder !== null ? uploadFileOrder : -1, uploadFileType, false) }];
                                                        }
                                                    }
                                                    catch (errRead) {
                                                        errRead.message = 'Error in Generate PDF No Page Number: No file - ' + errRead.message;
                                                        throw errRead;
                                                    }
                                                }
                                                else {
                                                    console.log('No tmp file ', tmpFileName);
                                                    throw new Error('Error in Generate PDF No Page Number: No tmp file');
                                                }
                                                return [3 /*break*/, 18];
                                            case 11:
                                                err_2 = _b.sent();
                                                lastError = err_2;
                                                if (!browser) return [3 /*break*/, 13];
                                                return [4 /*yield*/, safeCloseBrowser(browser)];
                                            case 12:
                                                _b.sent();
                                                _b.label = 13;
                                            case 13:
                                                if (attempt < maxAttempts) {
                                                    console.warn(new Date(), 'Retry generatePDFNoPageNumber after error', {
                                                        attempt: attempt,
                                                        message: err_2 && err_2.message ? err_2.message : err_2
                                                    });
                                                    return [2 /*return*/, "continue"];
                                                }
                                                console.error(new Date(), 'generatePDFNoPageNumber failed', { fileName: fileName, attempt: attempt, message: err_2 && err_2.message ? err_2.message : err_2 });
                                                throw err_2;
                                            case 14:
                                                if (overallTimeoutHandle) {
                                                    clearTimeout(overallTimeoutHandle);
                                                }
                                                if (!page) return [3 /*break*/, 16];
                                                // eslint-disable-next-line no-restricted-syntax
                                                return [4 /*yield*/, page.close().catch(function () { })];
                                            case 15:
                                                // eslint-disable-next-line no-restricted-syntax
                                                _b.sent();
                                                page = null;
                                                _b.label = 16;
                                            case 16: return [4 /*yield*/, safeCloseBrowser(browser)];
                                            case 17:
                                                _b.sent();
                                                browser = null;
                                                if (overallTimedOut) {
                                                    throw new PdfTimeoutError('generatePDFNoPageNumber overall', PDF_OVERALL_TIMEOUT_MS);
                                                }
                                                return [7 /*endfinally*/];
                                            case 18: return [2 /*return*/];
                                        }
                                    });
                                };
                                this_2 = this;
                                attempt = 1;
                                _a.label = 1;
                            case 1:
                                if (!(attempt <= maxAttempts)) return [3 /*break*/, 4];
                                return [5 /*yield**/, _loop_2(attempt)];
                            case 2:
                                state_2 = _a.sent();
                                if (typeof state_2 === "object")
                                    return [2 /*return*/, state_2.value];
                                _a.label = 3;
                            case 3:
                                attempt++;
                                return [3 /*break*/, 1];
                            case 4: throw lastError;
                        }
                    });
                });
            },
            workerTaskWeight: 2,
            maxConcurrency: 1,
            timeoutOverride: 300000
        },
        mergePDFResolve: {
            bypassSession: true,
            check: new simpl_schema_1.default({
                fileKeys: {
                    type: Array
                },
                'fileKeys.$': {
                    type: String
                },
                fileName: {
                    type: String
                },
                fileType: {
                    type: String,
                    optional: true
                }
            }),
            function: function (fileKeys, fileName, fileType) {
                return __awaiter(this, void 0, void 0, function () {
                    var resSigneds, err_3, mergedPdf, i, signedUrl, fileKey, response, err_4, contentTypeHeader, contentType, responseData, fileDataBuffer, fileKeyLower, isPdf, isJpg, isPng, pdf, pageCount, pageIndex, copiedPages, img, page, imgDim, img, page, imgDim, err_5, mergedPDFUint8, mergedPDFBuffer;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                resSigneds = null;
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 4]);
                                return [4 /*yield*/, this.callMethod('getSignedUrls', fileKeys, 900)];
                            case 2:
                                resSigneds = _a.sent();
                                return [3 /*break*/, 4];
                            case 3:
                                err_3 = _a.sent();
                                err_3.message = 'Error in Merge PDF Resolve: PDF Merge - Get Signed URLs - ' + err_3.message;
                                throw err_3;
                            case 4:
                                if (!resSigneds || !resSigneds.length) {
                                    throw new Error('Error in Merge PDF Resolve: PDF Merge - No signed urls');
                                }
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 5:
                                mergedPdf = _a.sent();
                                i = 0;
                                _a.label = 6;
                            case 6:
                                if (!(i < resSigneds.length)) return [3 /*break*/, 27];
                                signedUrl = resSigneds[i];
                                fileKey = fileKeys && fileKeys[i] ? fileKeys[i] : '';
                                response = null;
                                _a.label = 7;
                            case 7:
                                _a.trys.push([7, 9, , 10]);
                                return [4 /*yield*/, axios_1.default.get(signedUrl, {
                                        responseType: 'arraybuffer'
                                    })];
                            case 8:
                                response = _a.sent();
                                return [3 /*break*/, 10];
                            case 9:
                                err_4 = _a.sent();
                                err_4.message = "Error in Merge PDF Resolve: PDF Merge - Download failed (".concat(fileKey || 'unknown key', ") - ").concat(err_4.message);
                                throw err_4;
                            case 10:
                                if (!response || response.status !== 200) {
                                    throw new Error("Error in Merge PDF Resolve: PDF Merge - Download failed (".concat(fileKey || 'unknown key', ") - status: ").concat(response ? response.status : 'unknown'));
                                }
                                contentTypeHeader = response.headers ? response.headers['content-type'] : '';
                                contentType = (contentTypeHeader ? String(contentTypeHeader) : '').toLowerCase().split(';')[0].trim();
                                responseData = response.data;
                                fileDataBuffer = Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData);
                                if (!fileDataBuffer) {
                                    throw new Error("Error in Merge PDF Resolve: PDF Merge - No file data returned (".concat(fileKey || 'unknown key', ")"));
                                }
                                fileKeyLower = fileKey ? fileKey.toLowerCase() : '';
                                isPdf = contentType === 'application/pdf' || contentType === 'application/x-pdf' || fileKeyLower.endsWith('.pdf');
                                isJpg = contentType === 'image/jpeg' || contentType === 'image/jpg' || fileKeyLower.endsWith('.jpg') || fileKeyLower.endsWith('.jpeg');
                                isPng = contentType === 'image/png' || fileKeyLower.endsWith('.png');
                                _a.label = 11;
                            case 11:
                                _a.trys.push([11, 24, 25, 26]);
                                if (!isPdf) return [3 /*break*/, 18];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.load(fileDataBuffer, { updateMetadata: false, parseSpeed: pdf_lib_1.ParseSpeeds.Fastest, ignoreEncryption: true })];
                            case 12:
                                pdf = _a.sent();
                                pageCount = pdf.getPageCount();
                                pageIndex = 0;
                                _a.label = 13;
                            case 13:
                                if (!(pageIndex < pageCount)) return [3 /*break*/, 17];
                                return [4 /*yield*/, mergedPdf.copyPages(pdf, [pageIndex])];
                            case 14:
                                copiedPages = _a.sent();
                                mergedPdf.addPage(copiedPages[0]);
                                if (!(pageIndex > 0 && pageIndex % 25 === 0)) return [3 /*break*/, 16];
                                // eslint-disable-next-line no-restricted-syntax
                                return [4 /*yield*/, new Promise(function (resolve) { return setImmediate(resolve); })];
                            case 15:
                                // eslint-disable-next-line no-restricted-syntax
                                _a.sent();
                                _a.label = 16;
                            case 16:
                                pageIndex++;
                                return [3 /*break*/, 13];
                            case 17: return [3 /*break*/, 23];
                            case 18:
                                if (!isJpg) return [3 /*break*/, 20];
                                return [4 /*yield*/, mergedPdf.embedJpg(fileDataBuffer)];
                            case 19:
                                img = _a.sent();
                                page = mergedPdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [3 /*break*/, 23];
                            case 20:
                                if (!isPng) return [3 /*break*/, 22];
                                return [4 /*yield*/, mergedPdf.embedPng(fileDataBuffer)];
                            case 21:
                                img = _a.sent();
                                page = mergedPdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [3 /*break*/, 23];
                            case 22:
                                console.log('Error - unsupported!!', { fileKey: fileKey, contentType: contentType });
                                throw new Error("Error in Merge PDF Resolve: Unsupported document type (".concat(contentType || 'unknown content-type', ")"));
                            case 23: return [3 /*break*/, 26];
                            case 24:
                                err_5 = _a.sent();
                                err_5.message = "Error in Merge PDF Resolve: PDF Merge - Error processing file (".concat(fileKey || 'unknown key', ") - ").concat(err_5.message);
                                throw err_5;
                            case 25:
                                response = null;
                                responseData = null;
                                fileDataBuffer = null;
                                return [7 /*endfinally*/];
                            case 26:
                                i++;
                                return [3 /*break*/, 6];
                            case 27: return [4 /*yield*/, mergedPdf.save()];
                            case 28:
                                mergedPDFUint8 = _a.sent();
                                mergedPDFBuffer = Buffer.from(mergedPDFUint8.buffer, mergedPDFUint8.byteOffset, mergedPDFUint8.byteLength);
                                return [2 /*return*/, this.callMethod('uploadPDFBufferAndSave', fileName, mergedPDFBuffer, mergedPDFBuffer.byteLength, -1, fileType || 'pdf')];
                        }
                    });
                });
            },
            workerTaskWeight: 2,
            maxConcurrency: 1,
            timeoutOverride: 300000
        },
        mergePDFResolveNoSave: {
            bypassSession: true,
            check: new simpl_schema_1.default({
                fileKeys: {
                    type: Array
                },
                'fileKeys.$': {
                    type: String
                }
            }),
            function: function (fileKeys) {
                return __awaiter(this, void 0, void 0, function () {
                    var resSigneds, promises_1, fileDatas, mergedPdf_1, i, fileData, pdf, copiedPages, pdf, img, page, imgDim, copiedPages, pdf, img, page, imgDim, copiedPages, error_1, mergedPDFUint8, b64PDF, err_6;
                    var _this = this;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 26, , 27]);
                                return [4 /*yield*/, this.callMethod('getSignedUrls', fileKeys, 900)];
                            case 1:
                                resSigneds = _a.sent();
                                if (!(resSigneds && resSigneds.length)) return [3 /*break*/, 24];
                                promises_1 = [];
                                resSigneds.forEach(function (signedUrl) {
                                    promises_1.push(_this.callMethod('getDataURIfromURL', signedUrl));
                                });
                                return [4 /*yield*/, Promise.all(promises_1)];
                            case 2:
                                fileDatas = _a.sent();
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 3:
                                mergedPdf_1 = _a.sent();
                                i = 0;
                                _a.label = 4;
                            case 4:
                                if (!(i < fileDatas.length)) return [3 /*break*/, 22];
                                fileData = fileDatas[i];
                                if (!fileData) return [3 /*break*/, 20];
                                _a.label = 5;
                            case 5:
                                _a.trys.push([5, 18, , 19]);
                                if (!fileData.startsWith('data:application/pdf;base64,')) return [3 /*break*/, 8];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.load(fileData, { updateMetadata: false, parseSpeed: pdf_lib_1.ParseSpeeds.Fastest, ignoreEncryption: true })];
                            case 6:
                                pdf = _a.sent();
                                return [4 /*yield*/, mergedPdf_1.copyPages(pdf, pdf.getPageIndices())];
                            case 7:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf_1.addPage(page);
                                });
                                return [3 /*break*/, 17];
                            case 8:
                                if (!(fileData.startsWith('data:image/jpeg;base64,/9j/') || fileData.startsWith('data:image/png;base64,/9j/'))) return [3 /*break*/, 12];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 9:
                                pdf = _a.sent();
                                return [4 /*yield*/, pdf.embedJpg(fileData)];
                            case 10:
                                img = _a.sent();
                                page = pdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [4 /*yield*/, mergedPdf_1.copyPages(pdf, pdf.getPageIndices())];
                            case 11:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf_1.addPage(page);
                                });
                                return [3 /*break*/, 17];
                            case 12:
                                if (!fileData.startsWith('data:image/png;base64,iVBOR')) return [3 /*break*/, 16];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 13:
                                pdf = _a.sent();
                                return [4 /*yield*/, pdf.embedPng(fileData)];
                            case 14:
                                img = _a.sent();
                                page = pdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [4 /*yield*/, mergedPdf_1.copyPages(pdf, pdf.getPageIndices())];
                            case 15:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf_1.addPage(page);
                                });
                                return [3 /*break*/, 17];
                            case 16:
                                console.log('Error - unsupported!!', fileData.slice(0, 60));
                                _a.label = 17;
                            case 17: return [3 /*break*/, 19];
                            case 18:
                                error_1 = _a.sent();
                                console.log('Error processing fileData:', fileData.slice(0, 60), error_1);
                                return [3 /*break*/, 19];
                            case 19: return [3 /*break*/, 21];
                            case 20:
                                console.log('Error - no filedata!!', fileData);
                                _a.label = 21;
                            case 21:
                                i++;
                                return [3 /*break*/, 4];
                            case 22: return [4 /*yield*/, mergedPdf_1.save()];
                            case 23:
                                mergedPDFUint8 = _a.sent();
                                b64PDF = 'data:application/pdf;base64,' + Buffer.from(mergedPDFUint8).toString('base64');
                                return [2 /*return*/, b64PDF];
                            case 24: throw new Error('Error in Merge PDF Resolve No Save: No signed urls');
                            case 25: return [3 /*break*/, 27];
                            case 26:
                                err_6 = _a.sent();
                                err_6.message = "Error in Merge PDF Resolve: ".concat(err_6.message);
                                throw err_6;
                            case 27: return [2 /*return*/];
                        }
                    });
                });
            },
            workerTaskWeight: 2,
            maxConcurrency: 1,
            timeoutOverride: 300000
        },
        mergePDFResolveHtml: {
            bypassSession: true,
            check: new simpl_schema_1.default({
                htmls: {
                    type: Array
                },
                'htmls.$': {
                    type: String
                },
                fileName: {
                    type: String
                },
                fileType: {
                    type: String,
                    optional: true
                },
                save: {
                    type: Boolean,
                    optional: true
                }
            }),
            function: function (htmls_1, fileName_1, fileType_1) {
                return __awaiter(this, arguments, void 0, function (htmls, fileName, fileType, save) {
                    var mergedPdf, i, fileData, pdf, copiedPages, pdf, img, page, imgDim, copiedPages, pdf, img, page, imgDim, copiedPages, error_2, mergedPDFUint8, b64PDF;
                    if (save === void 0) { save = true; }
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 1:
                                mergedPdf = _a.sent();
                                i = 0;
                                _a.label = 2;
                            case 2:
                                if (!(i < htmls.length)) return [3 /*break*/, 20];
                                fileData = htmls[i];
                                if (!fileData) return [3 /*break*/, 18];
                                _a.label = 3;
                            case 3:
                                _a.trys.push([3, 16, , 17]);
                                if (!fileData.startsWith('data:application/pdf;base64,')) return [3 /*break*/, 6];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.load(fileData, { updateMetadata: false, parseSpeed: pdf_lib_1.ParseSpeeds.Fastest, ignoreEncryption: true })];
                            case 4:
                                pdf = _a.sent();
                                return [4 /*yield*/, mergedPdf.copyPages(pdf, pdf.getPageIndices())];
                            case 5:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf.addPage(page);
                                });
                                return [3 /*break*/, 15];
                            case 6:
                                if (!(fileData.startsWith('data:image/jpeg;base64,/9j/') || fileData.startsWith('data:image/png;base64,/9j/'))) return [3 /*break*/, 10];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 7:
                                pdf = _a.sent();
                                return [4 /*yield*/, pdf.embedJpg(fileData)];
                            case 8:
                                img = _a.sent();
                                page = pdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [4 /*yield*/, mergedPdf.copyPages(pdf, pdf.getPageIndices())];
                            case 9:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf.addPage(page);
                                });
                                return [3 /*break*/, 15];
                            case 10:
                                if (!fileData.startsWith('data:image/png;base64,iVBOR')) return [3 /*break*/, 14];
                                return [4 /*yield*/, pdf_lib_1.PDFDocument.create()];
                            case 11:
                                pdf = _a.sent();
                                return [4 /*yield*/, pdf.embedPng(fileData)];
                            case 12:
                                img = _a.sent();
                                page = pdf.addPage();
                                imgDim = img.scaleToFit(page.getWidth() * 0.75, page.getHeight() * 0.75);
                                page.drawImage(img, {
                                    x: page.getWidth() / 2 - imgDim.width / 2,
                                    y: page.getHeight() / 2 - imgDim.height / 2,
                                    width: imgDim.width,
                                    height: imgDim.height,
                                });
                                return [4 /*yield*/, mergedPdf.copyPages(pdf, pdf.getPageIndices())];
                            case 13:
                                copiedPages = _a.sent();
                                copiedPages.forEach(function (page) {
                                    mergedPdf.addPage(page);
                                });
                                return [3 /*break*/, 15];
                            case 14:
                                console.log('Error - unsupported!!', fileData.slice(0, 60));
                                throw new Error('Error in Merge PDF Resolve HTML: Unsupported file - ' + fileData.slice(0, 60));
                            case 15: return [3 /*break*/, 17];
                            case 16:
                                error_2 = _a.sent();
                                console.log('Error processing fileData:', fileData.slice(0, 60), error_2);
                                error_2.message = "Error in Merge PDF Resolve HTML: Error processing filedata - ".concat(error_2.message);
                                throw error_2;
                            case 17: return [3 /*break*/, 19];
                            case 18:
                                console.log('Error - no filedata!!', fileData);
                                throw new Error('Error in Merge PDF Resolve HTML: No File data');
                            case 19:
                                i++;
                                return [3 /*break*/, 2];
                            case 20: return [4 /*yield*/, mergedPdf.save()];
                            case 21:
                                mergedPDFUint8 = _a.sent();
                                b64PDF = 'data:application/pdf;base64,' + Buffer.from(mergedPDFUint8).toString('base64');
                                if (save) {
                                    return [2 /*return*/, this.callMethod('uploadFileAndSave', fileName, b64PDF, (4 * Math.ceil(b64PDF.length / 3)), -1, fileType, false)];
                                }
                                else {
                                    return [2 /*return*/, b64PDF];
                                }
                                return [2 /*return*/];
                        }
                    });
                });
            },
            workerTaskWeight: 2,
            maxConcurrency: 1,
            timeoutOverride: 300000
        }
    });
}

//# sourceMappingURL=pdf.js.map
