import { IConfig, IHash, Component, Config } from "merapi"; import { ICompile, IHelper } from "interfaces/main"; import * as path from "path"; import * as fs from "fs"; import * as yaml from "js-yaml"; export default class Compile extends Component implements ICompile { private directives : any = { include(file : string, basepath : string, helper : IHelper) { const ext = path.extname(file); if (ext === ".yml" || ext === ".yaml") { return helper.loadYaml(path.resolve(basepath, file)); } else if (ext === ".json") { return require(path.resolve(basepath, file)); } else { return fs.readFileSync(path.resolve(basepath, file)).toString(); } } }; constructor(private helper : IHelper) { super(); } public execDirective(name : string, directive : any, dict : IHash, basepath : string) { for (const i in dict) { if (typeof dict[i] !== "string") { continue; } const val = dict[i].trim(); if (val.indexOf("$" + name + "(") === 0 && val.charAt(val.length - 1) === ")") { dict[i] = directive(dict[i].substring(2 + name.length, dict[i].length - 1), basepath, this.helper); } } } public execDirectives(config : IConfig, basepath : string) : IConfig { const flattened = config.flatten(); for (const i in this.directives) { if (i) { this.execDirective(i, this.directives[i], flattened, basepath); } } return config.create(flattened); } }