succulent
Version:
Powerful and easy runtime type checking
90 lines • 2.74 kB
JavaScript
import { messages, toDisplayString, trace } from "./base";
export class Schema {
static check(base, x) {
if (base instanceof Schema) {
return base.check(x);
}
return new Schema(base).check(x);
}
static is(base, x, ref) {
try {
Schema.check(base, x);
return true;
}
catch (error) {
if (ref && error instanceof Error)
ref.error = error;
return false;
}
}
static displayName(base) {
return Schema.from(base).displayName;
}
static every(base, predicate) {
return Array.from(Schema.from(base)).every(predicate);
}
static from(base) {
if (base instanceof Schema) {
return base;
}
return new Schema(base);
}
/**
* Used to iterate through all possible values accepted by the schema,
* for certain finite types
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function, class-methods-use-this
[Symbol.iterator] = function* () { };
_check;
displayName = "(unknown)";
constructor(base, options = {}) {
const { displayName, iter } = options;
// Constructing a Schema from a previous Schema, just copy
if (base instanceof Schema) {
this._check = base._check;
this.displayName = displayName || base.displayName;
this[Symbol.iterator] = iter ?? base[Symbol.iterator];
return;
}
// Constructing a Schema from a FunctionSchema
if (typeof base === "function") {
this._check = base;
if (displayName)
this.displayName = displayName;
if (iter)
this[Symbol.iterator] = iter;
return;
}
// Constructing a Schema from a LiteralSchema
this._check = (x) => Object.is(x, base);
this.displayName = displayName || toDisplayString(base);
this[Symbol.iterator] =
iter ??
function* () {
yield base;
};
}
/**
* A method used to check if a given value matches the schema
*/
check(x) {
let ok;
try {
ok = this._check(x);
}
catch (error) {
throw new TypeError(trace(messages.invalidValue(x, this), error));
}
if (!ok) {
throw new TypeError(messages.invalidValue(x, this));
}
return true;
}
that(...filters) {
return new Schema((x) => this.check(x) && filters.every((filter) => filter(x)));
}
toString() {
return this.displayName;
}
}
//# sourceMappingURL=schema.js.map