@predictive-text-studio/lexical-model-compiler
Version:
Keyman Developer lexical model compiler
51 lines • 2.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
// TODO: this file is really only for lexical model compiler tests. Find a good name.
//
const fs = require("fs");
const path = require("path");
const ts = require("typescript");
const legacy_lexical_model_compiler_1 = require("../lexical-model-compiler/legacy-lexical-model-compiler");
/**
* Compiles a model.ts file, using paths relative to its location.
*
* @param filename path to model.ts source.
* @return model source code
*/
function compileModel(filename) {
let modelSource = loadFromFilename(filename);
let containingDirectory = path.dirname(filename);
return legacy_lexical_model_compiler_1.LegacyLexicalModelCompiler
.compileUsingLegacyInterface('<unknown>', modelSource, containingDirectory);
}
exports.compileModel = compileModel;
/**
* Loads a lexical model's source module from the given filename.
*
* @param filename path to the model source file.
*/
function loadFromFilename(filename) {
let sourceCode = fs.readFileSync(filename, 'utf8');
// Compile the module to JavaScript code.
// NOTE: transpile module does a very simple TS to JS compilation.
// It DOES NOT check for types!
let compilationOutput = ts.transpile(sourceCode, {
// Our runtime should support ES6 with Node/CommonJS modules.
target: ts.ScriptTarget.ES2015,
module: ts.ModuleKind.CommonJS,
});
// Turn the module into a function in which we can inject a global.
let moduleCode = '(function(exports){' + compilationOutput + '})';
// Run the module; its exports will be assigned to `moduleExports`.
let moduleExports = {};
let module = eval(moduleCode);
module(moduleExports);
if (!moduleExports['__esModule'] || !moduleExports['default']) {
console.error(`Model source '${filename}' does have a default export. Did you remember to write \`export default source;\`?`);
// TODO: throw an Error instead.
process.exit(65 /* EX_DATAERR */);
}
return moduleExports['default'];
}
exports.loadFromFilename = loadFromFilename;
//# sourceMappingURL=util.js.map