"use strict";
/*
 * @adonisjs/ace
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.templateFromFile = exports.template = void 0;
const vm_1 = require("vm");
const mustache_1 = __importDefault(require("mustache"));
const fs_1 = require("fs");
const STACK_REGEXP = /evalmachine\.<anonymous>:(\d+)(?::(\d+))?\n/;
const STACK_REGEXP_ALL = new RegExp(STACK_REGEXP.source, 'g');
/**
 * Process string as a template literal string and processes
 * data
 */
function template(tpl, data, filename = 'eval', isMustache = false) {
    if (isMustache) {
        return mustache_1.default.render(tpl, data);
    }
    try {
        return (0, vm_1.runInNewContext)('`' + tpl + '`', data);
    }
    catch (error) {
        const positions = error.stack.match(STACK_REGEXP_ALL);
        if (!positions) {
            throw error;
        }
        const position = [filename];
        const tokens = positions.pop().match(STACK_REGEXP);
        if (tokens[1]) {
            position.push(tokens[1]);
        }
        if (tokens[2]) {
            position.push(tokens[2]);
        }
        throw new Error(`Error in template ${position.join(':')}\n${error.message}`);
    }
}
exports.template = template;
/**
 * Loads template file from the disk and process it contents
 * using the [[template]] method
 */
function templateFromFile(file, data, isMustache) {
    const contents = (0, fs_1.readFileSync)(file, 'utf8');
    return template(contents, data, file, isMustache);
}
exports.templateFromFile = templateFromFile;
