@jsvfs/extras
Version:
Shared classes and helpers for JSVFS adapters.
110 lines (109 loc) • 3.65 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Matcher = exports.Journal = void 0;
/**
* [[include:packages/extras/README.md]]
* @packageDocumentation
* @module @jsvfs/extras
*/
const types_1 = require("@jsvfs/types");
const ajv_1 = require("ajv");
const picomatch = require("picomatch");
const ajv = new ajv_1.default({ allErrors: true, allowUnionTypes: true });
const validate = ajv.compile(types_1.JSON_SCHEMA.JournalEntry);
/** Journal class for error handling, extending built-in Array class. */
class Journal extends Array {
constructor(...inputs) {
if (inputs.length === 1 && typeof inputs[0] === 'number') {
super(inputs[0]);
}
else {
super();
}
if (inputs.length > 0 && typeof inputs[0] === 'object') {
this.push(...inputs);
}
}
validate(data) {
return validate(data);
}
/** Get all journal entries matching an operation and optionally a certain level. */
getEntries(op, ...level) {
return this.filter(entry => {
if (Array.isArray(level) && level.length > 0) {
return (op === 'all' || entry.op === op) && level.includes(entry.level);
}
return op === 'all' || entry.op === op;
});
}
/** Does the journal have one or more errors. */
get hasError() {
return this.errors.length > 0;
}
/** Get the highest level of journal entry in this journal. */
get maxLevel() {
switch (true) {
case this.critical.length > 0:
return 'crit';
case this.errors.length > 0:
return 'error';
case this.warnings.length > 0:
return 'warn';
default:
return 'info';
}
}
/** List all critical errors. */
get critical() {
return this.getEntries('all', 'crit');
}
/** List all errors including critical. */
get errors() {
return this.getEntries('all', 'error', 'crit');
}
/** List all information entries. */
get info() {
return this.getEntries('all', 'info');
}
/** List all warning entries. */
get warnings() {
return this.getEntries('all', 'warn');
}
/** Get critical errors by operation name. */
getCritical(op) {
return this.getEntries(op, 'crit');
}
/** Get errors, including critical, by operation name. */
getErrors(op) {
return this.getEntries(op, 'error', 'crit');
}
/** Get information by operation name. */
getInfo(op) {
return this.getEntries(op, 'info');
}
/** Get warnings by operation name. */
getWarnings(op) {
return this.getEntries(op, 'warn');
}
/** Only valid journal entries will be added to the array; invalid entries will be dropped. If no entry `id` is provided, it will be added. */
push(...entries) {
for (const entry of entries) {
const result = this.validate(entry);
if (result) {
if (typeof entry.id === 'undefined') {
entry.id = this.length;
}
super.push(entry);
}
}
return this.length;
}
}
exports.Journal = Journal;
class Matcher {
constructor(include = []) {
this.include = Array.isArray(include) && include.length > 0 ? Array.from(include) : ['**'];
this.match = picomatch(this.include);
}
}
exports.Matcher = Matcher;