@creditkarma/dynamic-config
Version:
Dynamic Config for Node.js backed by Consul and Vault
67 lines • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsLoader = void 0;
const fs = require("fs");
const path = require("path");
const ts = require("typescript");
const vm = require("vm");
const logger_1 = require("../logger");
function locateFile(basePath, searchPath) {
const resolvedPath = path.resolve(path.dirname(basePath), searchPath);
if (fs.existsSync(`${resolvedPath}.ts`)) {
return `${resolvedPath}.ts`;
}
else {
return `${resolvedPath}.js`;
}
}
function loadTypeScript(filePath) {
try {
const contents = fs.readFileSync(filePath);
const source = contents.toString();
const result = ts.transpileModule(source, {});
const sandbox = Object.assign({}, global, {
exports: {},
require(pathToRequire) {
// User files will start with one of these characters
if (pathToRequire.startsWith('.') ||
pathToRequire.startsWith('/')) {
const resolvedFile = locateFile(filePath, pathToRequire);
// If the file to include ends in `ts` use our custom machinery to load file
if (path.extname(resolvedFile) === '.ts') {
return loadTypeScript(resolvedFile);
// Else use the default node system, resolving to absolute path to account for our
// shenanigans
}
else {
return require(resolvedFile);
}
}
else {
return require(pathToRequire);
}
},
});
vm.createContext(sandbox);
vm.runInContext(result.outputText, sandbox, {
displayErrors: true,
});
if (sandbox.exports.default) {
return sandbox.exports.default;
}
else {
return sandbox.exports;
}
}
catch (err) {
logger_1.defaultLogger.error(`Error parsing typescript config[${filePath}]: ${err instanceof Error ? err.message : 'Non Error Thrown'}`);
return {};
}
}
exports.tsLoader = {
type: 'ts',
async load(filePath) {
return loadTypeScript(filePath);
},
};
//# sourceMappingURL=typescript.js.map