a2r
Version:
A2R Framework
72 lines (71 loc) • 2.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const telemetry_1 = require("@a2r/telemetry");
const fs_1 = require("@a2r/fs");
/**
* Will handle files changes and validate them before
*/
class RuntimeValidator {
constructor(fileValidator, onValidation, sourcePath, targetPath) {
this.filesToProcess = new Array();
this.failingFiles = new Map();
this.validator = fileValidator;
this.onValidation = onValidation;
this.sourcePath = sourcePath;
this.targetPath = targetPath;
this.processing = true;
(0, fs_1.getFilesRecursively)(sourcePath, ['.ts']).then((files) => {
this.filesToProcess.push(...files);
this.processing = false;
this.processQueue();
});
}
/**
* Processes pending files (from `filesToProcess`)
*/
async processQueue() {
if (!this.processing) {
this.processing = true;
const filePath = this.filesToProcess.shift();
if (filePath) {
const validation = await this.validator(filePath);
if (validation) {
this.failingFiles.delete(filePath);
telemetry_1.out.verbose(`Validation OK for file ${filePath}`);
}
else {
this.failingFiles.set(filePath, true);
telemetry_1.out.warn(`Validation KO for file ${filePath}`);
}
this.processing = false;
await this.processQueue();
}
else {
if (!this.failingFiles.size) {
await this.onValidation(this.sourcePath, this.targetPath);
}
this.processing = false;
}
}
}
/**
* Add file to pending files queue
* @param processInfo Process info from watcher event
*/
async addFileToQueue(processInfo) {
const { type, targetPath } = processInfo;
let newFiles = this.filesToProcess.slice();
if (type === 'unlink') {
this.failingFiles.delete(targetPath);
}
if (type === 'add' || type === 'change') {
newFiles = newFiles.filter(p => p !== targetPath);
newFiles.push(targetPath);
this.filesToProcess = newFiles;
}
if (type !== 'addDir') {
await this.processQueue();
}
}
}
exports.default = RuntimeValidator;