"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    ensureMongoDBConnectionStringSet: function() {
        return ensureMongoDBConnectionStringSet;
    },
    ensurePortSet: function() {
        return ensurePortSet;
    },
    fetchMongoDBConnectionString: function() {
        return fetchMongoDBConnectionString;
    },
    fetchServerPort: function() {
        return fetchServerPort;
    },
    isEnvProd: function() {
        return isEnvProd;
    },
    runMigrations: function() {
        return runMigrations;
    },
    setupEnvConfig: function() {
        return setupEnvConfig;
    },
    setupSentry: function() {
        return setupSentry;
    }
});
const _migratemongo = require("migrate-mongo");
const _path = require("path");
const _child_process = require("child_process");
const _node = /*#__PURE__*/ _interop_require_wildcard(require("@sentry/node"));
const _dotenv = require("dotenv");
const _serverconstants = require("./server.constants");
const _logger = require("./handlers/logger");
const _envutils = require("./utils/env.utils");
const _errorutils = require("./utils/error.utils");
const _fsutils = require("./utils/fs.utils");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const logger = new _logger.LoggerService("FDM-Environment", false);
const instructionsReferralURL = "https://docs.fdm-monster.net";
const packageJsonPath = (0, _path.join)((0, _fsutils.superRootPath)(), "./package.json");
const dotEnvPath = (0, _path.join)((0, _fsutils.superRootPath)(), "./.env");
function isEnvTest() {
    return process.env[_serverconstants.AppConstants.NODE_ENV_KEY] === _serverconstants.AppConstants.defaultTestEnv;
}
function isEnvProd() {
    return process.env[_serverconstants.AppConstants.NODE_ENV_KEY] === _serverconstants.AppConstants.defaultProductionEnv;
}
function ensureNodeEnvSet() {
    const environment = process.env[_serverconstants.AppConstants.NODE_ENV_KEY];
    if (!environment || !_serverconstants.AppConstants.knownEnvNames.includes(environment)) {
        const newEnvName = _serverconstants.AppConstants.defaultProductionEnv;
        process.env[_serverconstants.AppConstants.NODE_ENV_KEY] = newEnvName;
        logger.warn(`NODE_ENV=${environment} was not set, or not known. Defaulting to NODE_ENV=${newEnvName}`);
    } else {
        logger.log(`✓ NODE_ENV variable correctly set (${environment})!`);
    }
}
function ensureEnvNpmVersionSet() {
    const packageJsonVersion = require(packageJsonPath).version;
    if (!process.env[_serverconstants.AppConstants.VERSION_KEY]) {
        process.env[_serverconstants.AppConstants.VERSION_KEY] = packageJsonVersion;
        process.env[_serverconstants.AppConstants.NON_NPM_MODE_KEY] = "true";
        logger.log(`✓ Running server version ${process.env[_serverconstants.AppConstants.VERSION_KEY]} in non-NPM mode!`);
    } else {
        logger.debug(`✓ Running server version ${process.env[_serverconstants.AppConstants.VERSION_KEY]} in NPM mode!`);
    }
    if (process.env[_serverconstants.AppConstants.VERSION_KEY] !== packageJsonVersion) {
        process.env[_serverconstants.AppConstants.VERSION_KEY] = packageJsonVersion;
        logger.debug(`~ Had to synchronize FDM version to '${packageJsonVersion}' as it was outdated.`);
    }
}
function removePm2Service(reason) {
    logger.error(`Removing PM2 service as Server failed to start: ${reason}`);
    (0, _child_process.execSync)(`pm2 delete ${_serverconstants.AppConstants.pm2ServiceName}`);
}
function setupPackageJsonVersionOrThrow() {
    const result = (0, _envutils.verifyPackageJsonRequirements)((0, _fsutils.superRootPath)());
    if (!result) {
        if ((0, _envutils.isPm2)()) {
            removePm2Service("didnt pass startup validation (package.json)");
        }
        throw new Error("Aborting server.");
    }
}
function printInstructionsURL() {
    logger.log(`Please make sure to read ${instructionsReferralURL} for more information.`);
}
function fetchMongoDBConnectionString() {
    if (!process.env[_serverconstants.AppConstants.MONGO_KEY]) {
        logger.debug(`~ ${_serverconstants.AppConstants.MONGO_KEY} environment variable is not set. Assuming default`);
        printInstructionsURL();
        process.env[_serverconstants.AppConstants.MONGO_KEY] = _serverconstants.AppConstants.defaultMongoStringUnauthenticated;
    }
    return process.env[_serverconstants.AppConstants.MONGO_KEY];
}
function fetchServerPort() {
    let port = process.env[_serverconstants.AppConstants.SERVER_PORT_KEY];
    if (Number.isNaN(parseInt(port))) {
        process.env[_serverconstants.AppConstants.SERVER_PORT_KEY] = _serverconstants.AppConstants.defaultServerPort.toString();
        port = process.env[_serverconstants.AppConstants.SERVER_PORT_KEY];
    }
    return port;
}
function ensureMongoDBConnectionStringSet() {
    let dbConnectionString = process.env[_serverconstants.AppConstants.MONGO_KEY];
    if (!dbConnectionString) {
        fetchMongoDBConnectionString();
    } else {
        logger.log(`✓ ${_serverconstants.AppConstants.MONGO_KEY} environment variable set!`);
    }
}
function setupSentry() {
    const sentryDsnToken = (0, _envutils.getEnvOrDefault)(_serverconstants.AppConstants.sentryCustomDsnToken, _serverconstants.AppConstants.sentryCustomDsnDefault);
    _node.init({
        dsn: sentryDsnToken,
        environment: process.env.NODE_ENV,
        release: process.env.npm_package_version,
        enabled: !isEnvTest(),
        tracesSampleRate: (0, _envutils.isProductionEnvironment)() ? 0.25 : 1.0
    });
    process.on("unhandledRejection", (e)=>{
        const message = `Unhandled rejection error - ${(0, _errorutils.errorSummary)(e)}`;
        logger.error(message);
        _node.captureException(e);
    });
}
function ensurePortSet() {
    fetchServerPort();
    if (!process.env[_serverconstants.AppConstants.SERVER_PORT_KEY]) {
        logger.log(`~ ${_serverconstants.AppConstants.SERVER_PORT_KEY} environment variable is not set`);
        printInstructionsURL();
        process.env[_serverconstants.AppConstants.SERVER_PORT_KEY] = _serverconstants.AppConstants.defaultServerPort.toString();
    }
}
function setupEnvConfig(skipDotEnv = false) {
    if (!skipDotEnv) {
        (0, _dotenv.config)({
            path: dotEnvPath
        });
        logger.log("✓ Parsed environment and (optional) .env file");
    }
    ensureNodeEnvSet();
    setupPackageJsonVersionOrThrow();
    ensureEnvNpmVersionSet();
    setupSentry();
    ensureMongoDBConnectionStringSet();
    ensurePortSet();
}
async function runMigrations(db, client) {
    const migrationsStatus = await (0, _migratemongo.status)(db);
    const pendingMigrations = migrationsStatus.filter((m)=>m.appliedAt === "PENDING");
    if (pendingMigrations.length) {
        logger.log(`! MongoDB has ${pendingMigrations.length} migrations left to run (${migrationsStatus.length} migrations in total)`);
    } else {
        logger.log(`✓ Mongo Database is up to date [${migrationsStatus.length} migration applied]`);
    }
    const migrationResult = await (0, _migratemongo.up)(db, client);
    if (migrationResult?.length > 0) {
        logger.log(`Applied ${migrationResult.length} migrations successfully`, migrationResult);
    } else {
        logger.log("No migrations were run");
    }
}

//# sourceMappingURL=server.env.js.map