esbuild-plugin-kaitai
Version:
An esbuild plugin for importing Kaitai Struct files.
54 lines (53 loc) • 2.43 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileKaitaiApi = void 0;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const yaml_1 = __importDefault(require("yaml"));
class DefaultFileLoader {
constructor(root) {
this.root = root;
}
importYaml(filePath, mode) {
return __awaiter(this, void 0, void 0, function* () {
const resolvedPath = mode == 'abs' ? filePath : path_1.default.resolve(this.root, filePath);
const fileContent = yield fs_1.promises.readFile(resolvedPath, { encoding: 'utf-8' });
return yaml_1.default.parse(fileContent);
});
}
}
/**
* Compiles a ksy file with the given API compiler.
* @param filePath The path to the file to compile.
* @param options The compilation options.
* @returns The results of the compilation.
*/
function compileKaitaiApi(filePath, options) {
return __awaiter(this, void 0, void 0, function* () {
const root = path_1.default.dirname(filePath);
const fileLoader = options.fileLoader || new DefaultFileLoader(root);
const compiler = options.compiler;
const fileData = yield fileLoader.importYaml(filePath, 'abs');
const results = yield compiler.compile('javascript', fileData, fileLoader, false);
// Assume the first output file is the only one
const output = Object.values(results)[0];
return {
contents: output,
loader: 'js',
resolveDir: root
};
});
}
exports.compileKaitaiApi = compileKaitaiApi;