added all files
This commit is contained in:
+12
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
const shim = new Proxy((() => {}), {
|
||||
get: () => shim,
|
||||
apply: () => shim
|
||||
});
|
||||
|
||||
module.exports = shim;
|
||||
} else {
|
||||
module.exports = require('./dist');
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare class ArgumentError extends Error {
|
||||
readonly validationErrors: ReadonlyMap<string, Set<string>>;
|
||||
constructor(message: string, context: Function, errors?: Map<string, Set<string>>);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ArgumentError = void 0;
|
||||
const generate_stack_1 = require("./utils/generate-stack");
|
||||
const wrapStackTrace = (error, stack) => `${error.name}: ${error.message}\n${stack}`;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
class ArgumentError extends Error {
|
||||
constructor(message, context, errors = new Map()) {
|
||||
super(message);
|
||||
Object.defineProperty(this, "validationErrors", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
this.name = 'ArgumentError';
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, context);
|
||||
}
|
||||
else {
|
||||
this.stack = wrapStackTrace(this, generate_stack_1.generateStackTrace());
|
||||
}
|
||||
this.validationErrors = errors;
|
||||
}
|
||||
}
|
||||
exports.ArgumentError = ArgumentError;
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { Predicate } from './predicates/predicate';
|
||||
import { BasePredicate } from './predicates/base-predicate';
|
||||
import { Modifiers } from './modifiers';
|
||||
import { Predicates } from './predicates';
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare type Main = <T>(value: T, label: string | Function, predicate: BasePredicate<T>, idLabel?: boolean) => void;
|
||||
export interface Ow extends Modifiers, Predicates {
|
||||
/**
|
||||
Test if the value matches the predicate. Throws an `ArgumentError` if the test fails.
|
||||
|
||||
@param value - Value to test.
|
||||
@param predicate - Predicate to test against.
|
||||
*/
|
||||
<T>(value: unknown, predicate: BasePredicate<T>): asserts value is T;
|
||||
/**
|
||||
Test if `value` matches the provided `predicate`. Throws an `ArgumentError` with the specified `label` if the test fails.
|
||||
|
||||
@param value - Value to test.
|
||||
@param label - Label which should be used in error messages.
|
||||
@param predicate - Predicate to test against.
|
||||
*/
|
||||
<T>(value: unknown, label: string, predicate: BasePredicate<T>): asserts value is T;
|
||||
/**
|
||||
Returns `true` if the value matches the predicate, otherwise returns `false`.
|
||||
|
||||
@param value - Value to test.
|
||||
@param predicate - Predicate to test against.
|
||||
*/
|
||||
isValid: <T>(value: T, predicate: BasePredicate<T>) => value is T;
|
||||
/**
|
||||
Create a reusable validator.
|
||||
|
||||
@param predicate - Predicate used in the validator function.
|
||||
*/
|
||||
create: (<T>(predicate: BasePredicate<T>) => ReusableValidator<T>) & (<T>(label: string, predicate: BasePredicate<T>) => ReusableValidator<T>);
|
||||
}
|
||||
/**
|
||||
A reusable validator.
|
||||
*/
|
||||
export interface ReusableValidator<T> {
|
||||
/**
|
||||
Test if the value matches the predicate. Throws an `ArgumentError` if the test fails.
|
||||
|
||||
@param value - Value to test.
|
||||
@param label - Override the label which should be used in error messages.
|
||||
*/
|
||||
(value: T, label?: string): void;
|
||||
}
|
||||
declare const _ow: Ow;
|
||||
export default _ow;
|
||||
export { BasePredicate, Predicate };
|
||||
export * from './predicates';
|
||||
export { ArgumentError } from './argument-error';
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ArgumentError = exports.Predicate = void 0;
|
||||
const callsites_1 = require("callsites");
|
||||
const infer_label_1 = require("./utils/infer-label");
|
||||
const predicate_1 = require("./predicates/predicate");
|
||||
Object.defineProperty(exports, "Predicate", { enumerable: true, get: function () { return predicate_1.Predicate; } });
|
||||
const base_predicate_1 = require("./predicates/base-predicate");
|
||||
const modifiers_1 = require("./modifiers");
|
||||
const predicates_1 = require("./predicates");
|
||||
const test_1 = require("./test");
|
||||
const ow = (value, labelOrPredicate, predicate) => {
|
||||
if (!base_predicate_1.isPredicate(labelOrPredicate) && typeof labelOrPredicate !== 'string') {
|
||||
throw new TypeError(`Expected second argument to be a predicate or a string, got \`${typeof labelOrPredicate}\``);
|
||||
}
|
||||
if (base_predicate_1.isPredicate(labelOrPredicate)) {
|
||||
// If the second argument is a predicate, infer the label
|
||||
const stackFrames = callsites_1.default();
|
||||
test_1.default(value, () => infer_label_1.inferLabel(stackFrames), labelOrPredicate);
|
||||
return;
|
||||
}
|
||||
test_1.default(value, labelOrPredicate, predicate);
|
||||
};
|
||||
Object.defineProperties(ow, {
|
||||
isValid: {
|
||||
value: (value, predicate) => {
|
||||
try {
|
||||
test_1.default(value, '', predicate);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
},
|
||||
create: {
|
||||
value: (labelOrPredicate, predicate) => (value, label) => {
|
||||
if (base_predicate_1.isPredicate(labelOrPredicate)) {
|
||||
const stackFrames = callsites_1.default();
|
||||
test_1.default(value, label !== null && label !== void 0 ? label : (() => infer_label_1.inferLabel(stackFrames)), labelOrPredicate);
|
||||
return;
|
||||
}
|
||||
test_1.default(value, label !== null && label !== void 0 ? label : (labelOrPredicate), predicate);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Can't use `export default predicates(modifiers(ow)) as Ow` because the variable needs a type annotation to avoid a compiler error when used:
|
||||
// Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)
|
||||
// See https://github.com/microsoft/TypeScript/issues/36931 for more details.
|
||||
const _ow = predicates_1.default(modifiers_1.default(ow));
|
||||
exports.default = _ow;
|
||||
__exportStar(require("./predicates"), exports);
|
||||
var argument_error_1 = require("./argument-error");
|
||||
Object.defineProperty(exports, "ArgumentError", { enumerable: true, get: function () { return argument_error_1.ArgumentError; } });
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { BasePredicate } from '.';
|
||||
import { Predicates } from './predicates';
|
||||
declare type Optionalify<P> = P extends BasePredicate<infer X> ? P & BasePredicate<X | undefined> : P;
|
||||
export interface Modifiers {
|
||||
/**
|
||||
Make the following predicate optional so it doesn't fail when the value is `undefined`.
|
||||
*/
|
||||
readonly optional: {
|
||||
[K in keyof Predicates]: Optionalify<Predicates[K]>;
|
||||
};
|
||||
}
|
||||
declare const _default: <T>(object: T) => T & Modifiers;
|
||||
export default _default;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const predicates_1 = require("./predicates");
|
||||
exports.default = (object) => {
|
||||
Object.defineProperties(object, {
|
||||
optional: {
|
||||
get: () => predicates_1.default({}, { optional: true })
|
||||
}
|
||||
});
|
||||
return object;
|
||||
};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { Predicate } from '../predicates/predicate';
|
||||
/**
|
||||
Operator which inverts the following validation.
|
||||
|
||||
@hidden
|
||||
|
||||
@param predictate - Predicate to wrap inside the operator.
|
||||
*/
|
||||
export declare const not: (predicate: Predicate) => Predicate;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.not = void 0;
|
||||
const random_id_1 = require("../utils/random-id");
|
||||
const predicate_1 = require("../predicates/predicate");
|
||||
/**
|
||||
Operator which inverts the following validation.
|
||||
|
||||
@hidden
|
||||
|
||||
@param predictate - Predicate to wrap inside the operator.
|
||||
*/
|
||||
const not = (predicate) => {
|
||||
const originalAddValidator = predicate.addValidator;
|
||||
predicate.addValidator = (validator) => {
|
||||
const { validator: fn, message, negatedMessage } = validator;
|
||||
const placeholder = random_id_1.default();
|
||||
validator.message = (value, label) => (negatedMessage ?
|
||||
negatedMessage(value, label) :
|
||||
message(value, placeholder).replace(/ to /, '$¬ ').replace(placeholder, label));
|
||||
validator.validator = (value) => !fn(value);
|
||||
predicate[predicate_1.validatorSymbol].push(validator);
|
||||
predicate.addValidator = originalAddValidator;
|
||||
return predicate;
|
||||
};
|
||||
return predicate;
|
||||
};
|
||||
exports.not = not;
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
/// <reference types="node" />
|
||||
import { TypedArray } from 'type-fest';
|
||||
import { StringPredicate } from './predicates/string';
|
||||
import { NumberPredicate } from './predicates/number';
|
||||
import { BigIntPredicate } from './predicates/bigint';
|
||||
import { BooleanPredicate } from './predicates/boolean';
|
||||
import { Predicate, PredicateOptions } from './predicates/predicate';
|
||||
import { ArrayPredicate } from './predicates/array';
|
||||
import { ObjectPredicate, Shape } from './predicates/object';
|
||||
import { DatePredicate } from './predicates/date';
|
||||
import { ErrorPredicate } from './predicates/error';
|
||||
import { MapPredicate } from './predicates/map';
|
||||
import { WeakMapPredicate } from './predicates/weak-map';
|
||||
import { SetPredicate } from './predicates/set';
|
||||
import { WeakSetPredicate } from './predicates/weak-set';
|
||||
import { TypedArrayPredicate } from './predicates/typed-array';
|
||||
import { ArrayBufferPredicate } from './predicates/array-buffer';
|
||||
import { DataViewPredicate } from './predicates/data-view';
|
||||
import { BasePredicate } from './predicates/base-predicate';
|
||||
import { AnyPredicate } from './predicates/any';
|
||||
export interface Predicates {
|
||||
/**
|
||||
Test the value to be a string.
|
||||
*/
|
||||
readonly string: StringPredicate;
|
||||
/**
|
||||
Test the value to be a number.
|
||||
*/
|
||||
readonly number: NumberPredicate;
|
||||
/**
|
||||
Test the value to be an bigint.
|
||||
*/
|
||||
readonly bigint: BigIntPredicate;
|
||||
/**
|
||||
Test the value to be a boolean.
|
||||
*/
|
||||
readonly boolean: BooleanPredicate;
|
||||
/**
|
||||
Test the value to be undefined.
|
||||
*/
|
||||
readonly undefined: Predicate<undefined>;
|
||||
/**
|
||||
Test the value to be null.
|
||||
*/
|
||||
readonly null: Predicate<null>;
|
||||
/**
|
||||
Test the value to be null or undefined.
|
||||
*/
|
||||
readonly nullOrUndefined: Predicate<null | undefined>;
|
||||
/**
|
||||
Test the value to be not a number.
|
||||
*/
|
||||
readonly nan: Predicate<number>;
|
||||
/**
|
||||
Test the value to be a Symbol.
|
||||
*/
|
||||
readonly symbol: Predicate<symbol>;
|
||||
/**
|
||||
Test the value to be an array.
|
||||
*/
|
||||
readonly array: ArrayPredicate;
|
||||
/**
|
||||
Test the value to be an object.
|
||||
*/
|
||||
readonly object: ObjectPredicate;
|
||||
/**
|
||||
Test the value to be a Date.
|
||||
*/
|
||||
readonly date: DatePredicate;
|
||||
/**
|
||||
Test the value to be an Error.
|
||||
*/
|
||||
readonly error: ErrorPredicate;
|
||||
/**
|
||||
Test the value to be a Map.
|
||||
*/
|
||||
readonly map: MapPredicate;
|
||||
/**
|
||||
Test the value to be a WeakMap.
|
||||
*/
|
||||
readonly weakMap: WeakMapPredicate;
|
||||
/**
|
||||
Test the value to be a Set.
|
||||
*/
|
||||
readonly set: SetPredicate;
|
||||
/**
|
||||
Test the value to be a WeakSet.
|
||||
*/
|
||||
readonly weakSet: WeakSetPredicate;
|
||||
/**
|
||||
Test the value to be a Function.
|
||||
*/
|
||||
readonly function: Predicate<Function>;
|
||||
/**
|
||||
Test the value to be a Buffer.
|
||||
*/
|
||||
readonly buffer: Predicate<Buffer>;
|
||||
/**
|
||||
Test the value to be a RegExp.
|
||||
*/
|
||||
readonly regExp: Predicate<RegExp>;
|
||||
/**
|
||||
Test the value to be a Promise.
|
||||
*/
|
||||
readonly promise: Predicate<Promise<unknown>>;
|
||||
/**
|
||||
Test the value to be a typed array.
|
||||
*/
|
||||
readonly typedArray: TypedArrayPredicate<TypedArray>;
|
||||
/**
|
||||
Test the value to be a Int8Array.
|
||||
*/
|
||||
readonly int8Array: TypedArrayPredicate<Int8Array>;
|
||||
/**
|
||||
Test the value to be a Uint8Array.
|
||||
*/
|
||||
readonly uint8Array: TypedArrayPredicate<Uint8Array>;
|
||||
/**
|
||||
Test the value to be a Uint8ClampedArray.
|
||||
*/
|
||||
readonly uint8ClampedArray: TypedArrayPredicate<Uint8ClampedArray>;
|
||||
/**
|
||||
Test the value to be a Int16Array.
|
||||
*/
|
||||
readonly int16Array: TypedArrayPredicate<Int16Array>;
|
||||
/**
|
||||
Test the value to be a Uint16Array.
|
||||
*/
|
||||
readonly uint16Array: TypedArrayPredicate<Uint16Array>;
|
||||
/**
|
||||
Test the value to be a Int32Array.
|
||||
*/
|
||||
readonly int32Array: TypedArrayPredicate<Int32Array>;
|
||||
/**
|
||||
Test the value to be a Uint32Array.
|
||||
*/
|
||||
readonly uint32Array: TypedArrayPredicate<Uint32Array>;
|
||||
/**
|
||||
Test the value to be a Float32Array.
|
||||
*/
|
||||
readonly float32Array: TypedArrayPredicate<Float32Array>;
|
||||
/**
|
||||
Test the value to be a Float64Array.
|
||||
*/
|
||||
readonly float64Array: TypedArrayPredicate<Float64Array>;
|
||||
/**
|
||||
Test the value to be a ArrayBuffer.
|
||||
*/
|
||||
readonly arrayBuffer: ArrayBufferPredicate<ArrayBuffer>;
|
||||
/**
|
||||
Test the value to be a SharedArrayBuffer.
|
||||
*/
|
||||
readonly sharedArrayBuffer: ArrayBufferPredicate<SharedArrayBuffer>;
|
||||
/**
|
||||
Test the value to be a DataView.
|
||||
*/
|
||||
readonly dataView: DataViewPredicate;
|
||||
/**
|
||||
Test the value to be Iterable.
|
||||
*/
|
||||
readonly iterable: Predicate<Iterable<unknown>>;
|
||||
/**
|
||||
Test that the value matches at least one of the given predicates.
|
||||
*/
|
||||
any: (<T1>(p1: BasePredicate<T1>) => AnyPredicate<T1>) & (<T1, T2>(p1: BasePredicate<T1>, p2: BasePredicate<T2>) => AnyPredicate<T1 | T2>) & (<T1, T2, T3>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>) => AnyPredicate<T1 | T2 | T3>) & (<T1, T2, T3, T4>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>) => AnyPredicate<T1 | T2 | T3 | T4>) & (<T1, T2, T3, T4, T5>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>) => AnyPredicate<T1 | T2 | T3 | T4 | T5>) & (<T1, T2, T3, T4, T5, T6>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>, p6: BasePredicate<T6>) => AnyPredicate<T1 | T2 | T3 | T4 | T5 | T6>) & (<T1, T2, T3, T4, T5, T6, T7>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>, p6: BasePredicate<T6>, p7: BasePredicate<T7>) => AnyPredicate<T1 | T2 | T3 | T4 | T5 | T6 | T7>) & (<T1, T2, T3, T4, T5, T6, T7, T8>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>, p6: BasePredicate<T6>, p7: BasePredicate<T7>, p8: BasePredicate<T8>) => AnyPredicate<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>) & (<T1, T2, T3, T4, T5, T6, T7, T8, T9>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>, p6: BasePredicate<T6>, p7: BasePredicate<T7>, p8: BasePredicate<T8>, p9: BasePredicate<T9>) => AnyPredicate<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>) & (<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(p1: BasePredicate<T1>, p2: BasePredicate<T2>, p3: BasePredicate<T3>, p4: BasePredicate<T4>, p5: BasePredicate<T5>, p6: BasePredicate<T6>, p7: BasePredicate<T7>, p8: BasePredicate<T8>, p9: BasePredicate<T9>, p10: BasePredicate<T10>) => AnyPredicate<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>) & ((...predicate: BasePredicate[]) => AnyPredicate);
|
||||
}
|
||||
declare const _default: <T>(object: T, options?: PredicateOptions | undefined) => T & Predicates;
|
||||
export default _default;
|
||||
export { StringPredicate, NumberPredicate, BigIntPredicate, BooleanPredicate, ArrayPredicate, ObjectPredicate, DatePredicate, ErrorPredicate, MapPredicate, WeakMapPredicate, SetPredicate, WeakSetPredicate, TypedArrayPredicate, ArrayBufferPredicate, DataViewPredicate, AnyPredicate, Shape };
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AnyPredicate = exports.DataViewPredicate = exports.ArrayBufferPredicate = exports.TypedArrayPredicate = exports.WeakSetPredicate = exports.SetPredicate = exports.WeakMapPredicate = exports.MapPredicate = exports.ErrorPredicate = exports.DatePredicate = exports.ObjectPredicate = exports.ArrayPredicate = exports.BooleanPredicate = exports.BigIntPredicate = exports.NumberPredicate = exports.StringPredicate = void 0;
|
||||
const string_1 = require("./predicates/string");
|
||||
Object.defineProperty(exports, "StringPredicate", { enumerable: true, get: function () { return string_1.StringPredicate; } });
|
||||
const number_1 = require("./predicates/number");
|
||||
Object.defineProperty(exports, "NumberPredicate", { enumerable: true, get: function () { return number_1.NumberPredicate; } });
|
||||
const bigint_1 = require("./predicates/bigint");
|
||||
Object.defineProperty(exports, "BigIntPredicate", { enumerable: true, get: function () { return bigint_1.BigIntPredicate; } });
|
||||
const boolean_1 = require("./predicates/boolean");
|
||||
Object.defineProperty(exports, "BooleanPredicate", { enumerable: true, get: function () { return boolean_1.BooleanPredicate; } });
|
||||
const predicate_1 = require("./predicates/predicate");
|
||||
const array_1 = require("./predicates/array");
|
||||
Object.defineProperty(exports, "ArrayPredicate", { enumerable: true, get: function () { return array_1.ArrayPredicate; } });
|
||||
const object_1 = require("./predicates/object");
|
||||
Object.defineProperty(exports, "ObjectPredicate", { enumerable: true, get: function () { return object_1.ObjectPredicate; } });
|
||||
const date_1 = require("./predicates/date");
|
||||
Object.defineProperty(exports, "DatePredicate", { enumerable: true, get: function () { return date_1.DatePredicate; } });
|
||||
const error_1 = require("./predicates/error");
|
||||
Object.defineProperty(exports, "ErrorPredicate", { enumerable: true, get: function () { return error_1.ErrorPredicate; } });
|
||||
const map_1 = require("./predicates/map");
|
||||
Object.defineProperty(exports, "MapPredicate", { enumerable: true, get: function () { return map_1.MapPredicate; } });
|
||||
const weak_map_1 = require("./predicates/weak-map");
|
||||
Object.defineProperty(exports, "WeakMapPredicate", { enumerable: true, get: function () { return weak_map_1.WeakMapPredicate; } });
|
||||
const set_1 = require("./predicates/set");
|
||||
Object.defineProperty(exports, "SetPredicate", { enumerable: true, get: function () { return set_1.SetPredicate; } });
|
||||
const weak_set_1 = require("./predicates/weak-set");
|
||||
Object.defineProperty(exports, "WeakSetPredicate", { enumerable: true, get: function () { return weak_set_1.WeakSetPredicate; } });
|
||||
const typed_array_1 = require("./predicates/typed-array");
|
||||
Object.defineProperty(exports, "TypedArrayPredicate", { enumerable: true, get: function () { return typed_array_1.TypedArrayPredicate; } });
|
||||
const array_buffer_1 = require("./predicates/array-buffer");
|
||||
Object.defineProperty(exports, "ArrayBufferPredicate", { enumerable: true, get: function () { return array_buffer_1.ArrayBufferPredicate; } });
|
||||
const data_view_1 = require("./predicates/data-view");
|
||||
Object.defineProperty(exports, "DataViewPredicate", { enumerable: true, get: function () { return data_view_1.DataViewPredicate; } });
|
||||
const any_1 = require("./predicates/any");
|
||||
Object.defineProperty(exports, "AnyPredicate", { enumerable: true, get: function () { return any_1.AnyPredicate; } });
|
||||
exports.default = (object, options) => {
|
||||
Object.defineProperties(object, {
|
||||
string: {
|
||||
get: () => new string_1.StringPredicate(options)
|
||||
},
|
||||
number: {
|
||||
get: () => new number_1.NumberPredicate(options)
|
||||
},
|
||||
bigint: {
|
||||
get: () => new bigint_1.BigIntPredicate(options)
|
||||
},
|
||||
boolean: {
|
||||
get: () => new boolean_1.BooleanPredicate(options)
|
||||
},
|
||||
undefined: {
|
||||
get: () => new predicate_1.Predicate('undefined', options)
|
||||
},
|
||||
null: {
|
||||
get: () => new predicate_1.Predicate('null', options)
|
||||
},
|
||||
nullOrUndefined: {
|
||||
get: () => new predicate_1.Predicate('nullOrUndefined', options)
|
||||
},
|
||||
nan: {
|
||||
get: () => new predicate_1.Predicate('nan', options)
|
||||
},
|
||||
symbol: {
|
||||
get: () => new predicate_1.Predicate('symbol', options)
|
||||
},
|
||||
array: {
|
||||
get: () => new array_1.ArrayPredicate(options)
|
||||
},
|
||||
object: {
|
||||
get: () => new object_1.ObjectPredicate(options)
|
||||
},
|
||||
date: {
|
||||
get: () => new date_1.DatePredicate(options)
|
||||
},
|
||||
error: {
|
||||
get: () => new error_1.ErrorPredicate(options)
|
||||
},
|
||||
map: {
|
||||
get: () => new map_1.MapPredicate(options)
|
||||
},
|
||||
weakMap: {
|
||||
get: () => new weak_map_1.WeakMapPredicate(options)
|
||||
},
|
||||
set: {
|
||||
get: () => new set_1.SetPredicate(options)
|
||||
},
|
||||
weakSet: {
|
||||
get: () => new weak_set_1.WeakSetPredicate(options)
|
||||
},
|
||||
function: {
|
||||
get: () => new predicate_1.Predicate('Function', options)
|
||||
},
|
||||
buffer: {
|
||||
get: () => new predicate_1.Predicate('Buffer', options)
|
||||
},
|
||||
regExp: {
|
||||
get: () => new predicate_1.Predicate('RegExp', options)
|
||||
},
|
||||
promise: {
|
||||
get: () => new predicate_1.Predicate('Promise', options)
|
||||
},
|
||||
typedArray: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('TypedArray', options)
|
||||
},
|
||||
int8Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Int8Array', options)
|
||||
},
|
||||
uint8Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Uint8Array', options)
|
||||
},
|
||||
uint8ClampedArray: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Uint8ClampedArray', options)
|
||||
},
|
||||
int16Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Int16Array', options)
|
||||
},
|
||||
uint16Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Uint16Array', options)
|
||||
},
|
||||
int32Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Int32Array', options)
|
||||
},
|
||||
uint32Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Uint32Array', options)
|
||||
},
|
||||
float32Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Float32Array', options)
|
||||
},
|
||||
float64Array: {
|
||||
get: () => new typed_array_1.TypedArrayPredicate('Float64Array', options)
|
||||
},
|
||||
arrayBuffer: {
|
||||
get: () => new array_buffer_1.ArrayBufferPredicate('ArrayBuffer', options)
|
||||
},
|
||||
sharedArrayBuffer: {
|
||||
get: () => new array_buffer_1.ArrayBufferPredicate('SharedArrayBuffer', options)
|
||||
},
|
||||
dataView: {
|
||||
get: () => new data_view_1.DataViewPredicate(options)
|
||||
},
|
||||
iterable: {
|
||||
get: () => new predicate_1.Predicate('Iterable', options)
|
||||
},
|
||||
any: {
|
||||
value: (...predicates) => new any_1.AnyPredicate(predicates, options)
|
||||
}
|
||||
});
|
||||
return object;
|
||||
};
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { BasePredicate, testSymbol } from './base-predicate';
|
||||
import { PredicateOptions } from './predicate';
|
||||
import { Main } from '..';
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare class AnyPredicate<T = unknown> implements BasePredicate<T> {
|
||||
private readonly predicates;
|
||||
private readonly options;
|
||||
constructor(predicates: BasePredicate[], options?: PredicateOptions);
|
||||
[testSymbol](value: T, main: Main, label: string | Function, idLabel: boolean): asserts value;
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AnyPredicate = void 0;
|
||||
const argument_error_1 = require("../argument-error");
|
||||
const base_predicate_1 = require("./base-predicate");
|
||||
const generate_argument_error_message_1 = require("../utils/generate-argument-error-message");
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
class AnyPredicate {
|
||||
constructor(predicates, options = {}) {
|
||||
Object.defineProperty(this, "predicates", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: predicates
|
||||
});
|
||||
Object.defineProperty(this, "options", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: options
|
||||
});
|
||||
}
|
||||
[base_predicate_1.testSymbol](value, main, label, idLabel) {
|
||||
const errors = new Map();
|
||||
for (const predicate of this.predicates) {
|
||||
try {
|
||||
main(value, label, predicate, idLabel);
|
||||
return;
|
||||
}
|
||||
catch (error) {
|
||||
if (value === undefined && this.options.optional === true) {
|
||||
return;
|
||||
}
|
||||
// If we received an ArgumentError, then..
|
||||
if (error instanceof argument_error_1.ArgumentError) {
|
||||
// Iterate through every error reported.
|
||||
for (const [key, value] of error.validationErrors.entries()) {
|
||||
// Get the current errors set, if any.
|
||||
const alreadyPresent = errors.get(key);
|
||||
// Add all errors under the same key
|
||||
errors.set(key, new Set([...alreadyPresent !== null && alreadyPresent !== void 0 ? alreadyPresent : [], ...value]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (errors.size > 0) {
|
||||
// Generate the `error.message` property.
|
||||
const message = generate_argument_error_message_1.generateArgumentErrorMessage(errors, true);
|
||||
throw new argument_error_1.ArgumentError(`Any predicate failed with the following errors:\n${message}`, main, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.AnyPredicate = AnyPredicate;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { Predicate } from './predicate';
|
||||
export declare class ArrayBufferPredicate<T extends ArrayBufferLike> extends Predicate<T> {
|
||||
/**
|
||||
Test an array buffer to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the array buffer.
|
||||
*/
|
||||
byteLength(byteLength: number): this;
|
||||
/**
|
||||
Test an array buffer to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the array buffer.
|
||||
*/
|
||||
minByteLength(byteLength: number): this;
|
||||
/**
|
||||
Test an array buffer to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the array buffer.
|
||||
*/
|
||||
maxByteLength(byteLength: number): this;
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ArrayBufferPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class ArrayBufferPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
Test an array buffer to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the array buffer.
|
||||
*/
|
||||
byteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength === byteLength
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array buffer to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the array buffer.
|
||||
*/
|
||||
minByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength >= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength - 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array buffer to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the array buffer.
|
||||
*/
|
||||
maxByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength <= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength + 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.ArrayBufferPredicate = ArrayBufferPredicate;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { BasePredicate } from './base-predicate';
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class ArrayPredicate<T = unknown> extends Predicate<T[]> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test an array to have a specific length.
|
||||
|
||||
@param length - The length of the array.
|
||||
*/
|
||||
length(length: number): this;
|
||||
/**
|
||||
Test an array to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the array.
|
||||
*/
|
||||
minLength(length: number): this;
|
||||
/**
|
||||
Test an array to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the array.
|
||||
*/
|
||||
maxLength(length: number): this;
|
||||
/**
|
||||
Test an array to start with a specific value. The value is tested by identity, not structure.
|
||||
|
||||
@param searchElement - The value that should be the start of the array.
|
||||
*/
|
||||
startsWith(searchElement: T): this;
|
||||
/**
|
||||
Test an array to end with a specific value. The value is tested by identity, not structure.
|
||||
|
||||
@param searchElement - The value that should be the end of the array.
|
||||
*/
|
||||
endsWith(searchElement: T): this;
|
||||
/**
|
||||
Test an array to include all the provided elements. The values are tested by identity, not structure.
|
||||
|
||||
@param searchElements - The values that should be included in the array.
|
||||
*/
|
||||
includes(...searchElements: readonly T[]): this;
|
||||
/**
|
||||
Test an array to include any of the provided elements. The values are tested by identity, not structure.
|
||||
|
||||
@param searchElements - The values that should be included in the array.
|
||||
*/
|
||||
includesAny(...searchElements: readonly T[]): this;
|
||||
/**
|
||||
Test an array to be empty.
|
||||
*/
|
||||
get empty(): this;
|
||||
/**
|
||||
Test an array to be not empty.
|
||||
*/
|
||||
get nonEmpty(): this;
|
||||
/**
|
||||
Test an array to be deeply equal to the provided array.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
deepEqual(expected: readonly T[]): this;
|
||||
/**
|
||||
Test all elements in the array to match to provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every individual item.
|
||||
|
||||
@example
|
||||
```
|
||||
ow(['a', 1], ow.array.ofType(ow.any(ow.string, ow.number)));
|
||||
```
|
||||
*/
|
||||
ofType<U extends T>(predicate: BasePredicate<U>): ArrayPredicate<U>;
|
||||
/**
|
||||
Test if the elements in the array exactly matches the elements placed at the same indices in the predicates array.
|
||||
|
||||
@param predicates - Predicates to test the array against. Describes what the tested array should look like.
|
||||
|
||||
@example
|
||||
```
|
||||
ow(['1', 2], ow.array.exactShape([ow.string, ow.number]));
|
||||
```
|
||||
*/
|
||||
exactShape(predicates: Predicate[]): this;
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ArrayPredicate = void 0;
|
||||
const isEqual = require("lodash.isequal");
|
||||
const predicate_1 = require("./predicate");
|
||||
const match_shape_1 = require("../utils/match-shape");
|
||||
const of_type_1 = require("../utils/of-type");
|
||||
class ArrayPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('array', options);
|
||||
}
|
||||
/**
|
||||
Test an array to have a specific length.
|
||||
|
||||
@param length - The length of the array.
|
||||
*/
|
||||
length(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have length \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length === length
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the array.
|
||||
*/
|
||||
minLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum length of \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length >= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum length of \`${length - 1}\`, got \`${value.length}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the array.
|
||||
*/
|
||||
maxLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum length of \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length <= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum length of \`${length + 1}\`, got \`${value.length}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to start with a specific value. The value is tested by identity, not structure.
|
||||
|
||||
@param searchElement - The value that should be the start of the array.
|
||||
*/
|
||||
startsWith(searchElement) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to start with \`${searchElement}\`, got \`${value[0]}\``,
|
||||
validator: value => value[0] === searchElement
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to end with a specific value. The value is tested by identity, not structure.
|
||||
|
||||
@param searchElement - The value that should be the end of the array.
|
||||
*/
|
||||
endsWith(searchElement) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to end with \`${searchElement}\`, got \`${value[value.length - 1]}\``,
|
||||
validator: value => value[value.length - 1] === searchElement
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to include all the provided elements. The values are tested by identity, not structure.
|
||||
|
||||
@param searchElements - The values that should be included in the array.
|
||||
*/
|
||||
includes(...searchElements) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to include all elements of \`${JSON.stringify(searchElements)}\`, got \`${JSON.stringify(value)}\``,
|
||||
validator: value => searchElements.every(element => value.includes(element))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to include any of the provided elements. The values are tested by identity, not structure.
|
||||
|
||||
@param searchElements - The values that should be included in the array.
|
||||
*/
|
||||
includesAny(...searchElements) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to include any element of \`${JSON.stringify(searchElements)}\`, got \`${JSON.stringify(value)}\``,
|
||||
validator: value => searchElements.some(element => value.includes(element))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to be empty.
|
||||
*/
|
||||
get empty() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be empty, got \`${JSON.stringify(value)}\``,
|
||||
validator: value => value.length === 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to be not empty.
|
||||
*/
|
||||
get nonEmpty() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to not be empty`,
|
||||
validator: value => value.length > 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an array to be deeply equal to the provided array.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
deepEqual(expected) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be deeply equal to \`${JSON.stringify(expected)}\`, got \`${JSON.stringify(value)}\``,
|
||||
validator: value => isEqual(value, expected)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all elements in the array to match to provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every individual item.
|
||||
|
||||
@example
|
||||
```
|
||||
ow(['a', 1], ow.array.ofType(ow.any(ow.string, ow.number)));
|
||||
```
|
||||
*/
|
||||
ofType(predicate) {
|
||||
// TODO [typescript@>=5] If higher-kinded types are supported natively by typescript, refactor `addValidator` to use them to avoid the usage of `any`. Otherwise, bump or remove this TODO.
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: value => of_type_1.default(value, 'values', predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test if the elements in the array exactly matches the elements placed at the same indices in the predicates array.
|
||||
|
||||
@param predicates - Predicates to test the array against. Describes what the tested array should look like.
|
||||
|
||||
@example
|
||||
```
|
||||
ow(['1', 2], ow.array.exactShape([ow.string, ow.number]));
|
||||
```
|
||||
*/
|
||||
exactShape(predicates) {
|
||||
const shape = predicates;
|
||||
return this.addValidator({
|
||||
message: (_, label, message) => `${message.replace('Expected', 'Expected element')} in ${label}`,
|
||||
validator: object => match_shape_1.exact(object, shape, undefined, true)
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.ArrayPredicate = ArrayPredicate;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { Main } from '..';
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare const testSymbol: unique symbol;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare const isPredicate: (value: unknown) => value is BasePredicate<unknown>;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export interface BasePredicate<T = unknown> {
|
||||
[testSymbol](value: T, main: Main, label: string | Function, idLabel?: boolean): void;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isPredicate = exports.testSymbol = void 0;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
exports.testSymbol = Symbol('test');
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
const isPredicate = (value) => Boolean(value[exports.testSymbol]);
|
||||
exports.isPredicate = isPredicate;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class BigIntPredicate extends Predicate<bigint> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BigIntPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class BigIntPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('bigint', options);
|
||||
}
|
||||
}
|
||||
exports.BigIntPredicate = BigIntPredicate;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class BooleanPredicate extends Predicate<boolean> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a boolean to be true.
|
||||
*/
|
||||
get true(): this;
|
||||
/**
|
||||
Test a boolean to be false.
|
||||
*/
|
||||
get false(): this;
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BooleanPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class BooleanPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('boolean', options);
|
||||
}
|
||||
/**
|
||||
Test a boolean to be true.
|
||||
*/
|
||||
get true() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be true, got ${value}`,
|
||||
validator: value => value
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a boolean to be false.
|
||||
*/
|
||||
get false() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be false, got ${value}`,
|
||||
validator: value => !value
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.BooleanPredicate = BooleanPredicate;
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class DataViewPredicate extends Predicate<DataView> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a DataView to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the DataView.
|
||||
*/
|
||||
byteLength(byteLength: number): this;
|
||||
/**
|
||||
Test a DataView to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the DataView.
|
||||
*/
|
||||
minByteLength(byteLength: number): this;
|
||||
/**
|
||||
Test a DataView to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the DataView.
|
||||
*/
|
||||
maxByteLength(byteLength: number): this;
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DataViewPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class DataViewPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('DataView', options);
|
||||
}
|
||||
/**
|
||||
Test a DataView to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the DataView.
|
||||
*/
|
||||
byteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength === byteLength
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a DataView to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the DataView.
|
||||
*/
|
||||
minByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength >= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength - 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a DataView to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the DataView.
|
||||
*/
|
||||
maxByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength <= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength + 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.DataViewPredicate = DataViewPredicate;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class DatePredicate extends Predicate<Date> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a date to be before another date.
|
||||
|
||||
@param date - Maximum value.
|
||||
*/
|
||||
before(date: Date): this;
|
||||
/**
|
||||
Test a date to be before another date.
|
||||
|
||||
@param date - Minimum value.
|
||||
*/
|
||||
after(date: Date): this;
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DatePredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class DatePredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('date', options);
|
||||
}
|
||||
/**
|
||||
Test a date to be before another date.
|
||||
|
||||
@param date - Maximum value.
|
||||
*/
|
||||
before(date) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} ${value.toISOString()} to be before ${date.toISOString()}`,
|
||||
validator: value => value.getTime() < date.getTime()
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a date to be before another date.
|
||||
|
||||
@param date - Minimum value.
|
||||
*/
|
||||
after(date) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} ${value.toISOString()} to be after ${date.toISOString()}`,
|
||||
validator: value => value.getTime() > date.getTime()
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.DatePredicate = DatePredicate;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class ErrorPredicate extends Predicate<Error> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test an error to have a specific name.
|
||||
|
||||
@param expected - Expected name of the Error.
|
||||
*/
|
||||
name(expected: string): this;
|
||||
/**
|
||||
Test an error to have a specific message.
|
||||
|
||||
@param expected - Expected message of the Error.
|
||||
*/
|
||||
message(expected: string): this;
|
||||
/**
|
||||
Test the error message to include a specific message.
|
||||
|
||||
@param message - Message that should be included in the error.
|
||||
*/
|
||||
messageIncludes(message: string): this;
|
||||
/**
|
||||
Test the error object to have specific keys.
|
||||
|
||||
@param keys - One or more keys which should be part of the error object.
|
||||
*/
|
||||
hasKeys(...keys: readonly string[]): this;
|
||||
/**
|
||||
Test an error to be of a specific instance type.
|
||||
|
||||
@param instance - The expected instance type of the error.
|
||||
*/
|
||||
instanceOf(instance: Function): this;
|
||||
/**
|
||||
Test an Error to be a TypeError.
|
||||
*/
|
||||
get typeError(): this;
|
||||
/**
|
||||
Test an Error to be an EvalError.
|
||||
*/
|
||||
get evalError(): this;
|
||||
/**
|
||||
Test an Error to be a RangeError.
|
||||
*/
|
||||
get rangeError(): this;
|
||||
/**
|
||||
Test an Error to be a ReferenceError.
|
||||
*/
|
||||
get referenceError(): this;
|
||||
/**
|
||||
Test an Error to be a SyntaxError.
|
||||
*/
|
||||
get syntaxError(): this;
|
||||
/**
|
||||
Test an Error to be a URIError.
|
||||
*/
|
||||
get uriError(): this;
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ErrorPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class ErrorPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('error', options);
|
||||
}
|
||||
/**
|
||||
Test an error to have a specific name.
|
||||
|
||||
@param expected - Expected name of the Error.
|
||||
*/
|
||||
name(expected) {
|
||||
return this.addValidator({
|
||||
message: (error, label) => `Expected ${label} to have name \`${expected}\`, got \`${error.name}\``,
|
||||
validator: error => error.name === expected
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an error to have a specific message.
|
||||
|
||||
@param expected - Expected message of the Error.
|
||||
*/
|
||||
message(expected) {
|
||||
return this.addValidator({
|
||||
message: (error, label) => `Expected ${label} message to be \`${expected}\`, got \`${error.message}\``,
|
||||
validator: error => error.message === expected
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test the error message to include a specific message.
|
||||
|
||||
@param message - Message that should be included in the error.
|
||||
*/
|
||||
messageIncludes(message) {
|
||||
return this.addValidator({
|
||||
message: (error, label) => `Expected ${label} message to include \`${message}\`, got \`${error.message}\``,
|
||||
validator: error => error.message.includes(message)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test the error object to have specific keys.
|
||||
|
||||
@param keys - One or more keys which should be part of the error object.
|
||||
*/
|
||||
hasKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} message to have keys \`${keys.join('`, `')}\``,
|
||||
validator: error => keys.every(key => Object.prototype.hasOwnProperty.call(error, key))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an error to be of a specific instance type.
|
||||
|
||||
@param instance - The expected instance type of the error.
|
||||
*/
|
||||
instanceOf(instance) {
|
||||
return this.addValidator({
|
||||
message: (error, label) => `Expected ${label} \`${error.name}\` to be of type \`${instance.name}\``,
|
||||
validator: error => error instanceof instance
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an Error to be a TypeError.
|
||||
*/
|
||||
get typeError() {
|
||||
return this.instanceOf(TypeError);
|
||||
}
|
||||
/**
|
||||
Test an Error to be an EvalError.
|
||||
*/
|
||||
get evalError() {
|
||||
return this.instanceOf(EvalError);
|
||||
}
|
||||
/**
|
||||
Test an Error to be a RangeError.
|
||||
*/
|
||||
get rangeError() {
|
||||
return this.instanceOf(RangeError);
|
||||
}
|
||||
/**
|
||||
Test an Error to be a ReferenceError.
|
||||
*/
|
||||
get referenceError() {
|
||||
return this.instanceOf(ReferenceError);
|
||||
}
|
||||
/**
|
||||
Test an Error to be a SyntaxError.
|
||||
*/
|
||||
get syntaxError() {
|
||||
return this.instanceOf(SyntaxError);
|
||||
}
|
||||
/**
|
||||
Test an Error to be a URIError.
|
||||
*/
|
||||
get uriError() {
|
||||
return this.instanceOf(URIError);
|
||||
}
|
||||
}
|
||||
exports.ErrorPredicate = ErrorPredicate;
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class MapPredicate<T1 = unknown, T2 = unknown> extends Predicate<Map<T1, T2>> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a Map to have a specific size.
|
||||
|
||||
@param size - The size of the Map.
|
||||
*/
|
||||
size(size: number): this;
|
||||
/**
|
||||
Test an Map to have a minimum size.
|
||||
|
||||
@param size - The minimum size of the Map.
|
||||
*/
|
||||
minSize(size: number): this;
|
||||
/**
|
||||
Test an Map to have a maximum size.
|
||||
|
||||
@param size - The maximum size of the Map.
|
||||
*/
|
||||
maxSize(size: number): this;
|
||||
/**
|
||||
Test a Map to include all the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that should be a key in the Map.
|
||||
*/
|
||||
hasKeys(...keys: readonly T1[]): this;
|
||||
/**
|
||||
Test a Map to include any of the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that could be a key in the Map.
|
||||
*/
|
||||
hasAnyKeys(...keys: readonly T1[]): this;
|
||||
/**
|
||||
Test a Map to include all the provided values. The values are tested by identity, not structure.
|
||||
|
||||
@param values - The values that should be a value in the Map.
|
||||
*/
|
||||
hasValues(...values: readonly T2[]): this;
|
||||
/**
|
||||
Test a Map to include any of the provided values. The values are tested by identity, not structure.
|
||||
|
||||
@param values - The values that could be a value in the Map.
|
||||
*/
|
||||
hasAnyValues(...values: readonly T2[]): this;
|
||||
/**
|
||||
Test all the keys in the Map to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every key in the Map.
|
||||
*/
|
||||
keysOfType(predicate: Predicate<T1>): this;
|
||||
/**
|
||||
Test all the values in the Map to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the Map.
|
||||
*/
|
||||
valuesOfType(predicate: Predicate<T2>): this;
|
||||
/**
|
||||
Test a Map to be empty.
|
||||
*/
|
||||
get empty(): this;
|
||||
/**
|
||||
Test a Map to be not empty.
|
||||
*/
|
||||
get nonEmpty(): this;
|
||||
/**
|
||||
Test a Map to be deeply equal to the provided Map.
|
||||
|
||||
@param expected - Expected Map to match.
|
||||
*/
|
||||
deepEqual(expected: Map<T1, T2>): this;
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MapPredicate = void 0;
|
||||
const isEqual = require("lodash.isequal");
|
||||
const has_items_1 = require("../utils/has-items");
|
||||
const of_type_1 = require("../utils/of-type");
|
||||
const predicate_1 = require("./predicate");
|
||||
class MapPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('Map', options);
|
||||
}
|
||||
/**
|
||||
Test a Map to have a specific size.
|
||||
|
||||
@param size - The size of the Map.
|
||||
*/
|
||||
size(size) {
|
||||
return this.addValidator({
|
||||
message: (map, label) => `Expected ${label} to have size \`${size}\`, got \`${map.size}\``,
|
||||
validator: map => map.size === size
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an Map to have a minimum size.
|
||||
|
||||
@param size - The minimum size of the Map.
|
||||
*/
|
||||
minSize(size) {
|
||||
return this.addValidator({
|
||||
message: (map, label) => `Expected ${label} to have a minimum size of \`${size}\`, got \`${map.size}\``,
|
||||
validator: map => map.size >= size,
|
||||
negatedMessage: (map, label) => `Expected ${label} to have a maximum size of \`${size - 1}\`, got \`${map.size}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an Map to have a maximum size.
|
||||
|
||||
@param size - The maximum size of the Map.
|
||||
*/
|
||||
maxSize(size) {
|
||||
return this.addValidator({
|
||||
message: (map, label) => `Expected ${label} to have a maximum size of \`${size}\`, got \`${map.size}\``,
|
||||
validator: map => map.size <= size,
|
||||
negatedMessage: (map, label) => `Expected ${label} to have a minimum size of \`${size + 1}\`, got \`${map.size}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to include all the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that should be a key in the Map.
|
||||
*/
|
||||
hasKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingKeys) => `Expected ${label} to have keys \`${JSON.stringify(missingKeys)}\``,
|
||||
validator: map => has_items_1.default(map, keys)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to include any of the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that could be a key in the Map.
|
||||
*/
|
||||
hasAnyKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any key of \`${JSON.stringify(keys)}\``,
|
||||
validator: map => keys.some(key => map.has(key))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to include all the provided values. The values are tested by identity, not structure.
|
||||
|
||||
@param values - The values that should be a value in the Map.
|
||||
*/
|
||||
hasValues(...values) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingValues) => `Expected ${label} to have values \`${JSON.stringify(missingValues)}\``,
|
||||
validator: map => has_items_1.default(new Set(map.values()), values)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to include any of the provided values. The values are tested by identity, not structure.
|
||||
|
||||
@param values - The values that could be a value in the Map.
|
||||
*/
|
||||
hasAnyValues(...values) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any value of \`${JSON.stringify(values)}\``,
|
||||
validator: map => {
|
||||
const valueSet = new Set(map.values());
|
||||
return values.some(key => valueSet.has(key));
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all the keys in the Map to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every key in the Map.
|
||||
*/
|
||||
keysOfType(predicate) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: map => of_type_1.default(map.keys(), 'keys', predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all the values in the Map to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the Map.
|
||||
*/
|
||||
valuesOfType(predicate) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: map => of_type_1.default(map.values(), 'values', predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to be empty.
|
||||
*/
|
||||
get empty() {
|
||||
return this.addValidator({
|
||||
message: (map, label) => `Expected ${label} to be empty, got \`${JSON.stringify([...map])}\``,
|
||||
validator: map => map.size === 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to be not empty.
|
||||
*/
|
||||
get nonEmpty() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to not be empty`,
|
||||
validator: map => map.size > 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Map to be deeply equal to the provided Map.
|
||||
|
||||
@param expected - Expected Map to match.
|
||||
*/
|
||||
deepEqual(expected) {
|
||||
return this.addValidator({
|
||||
message: (map, label) => `Expected ${label} to be deeply equal to \`${JSON.stringify([...expected])}\`, got \`${JSON.stringify([...map])}\``,
|
||||
validator: map => isEqual(map, expected)
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.MapPredicate = MapPredicate;
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class NumberPredicate extends Predicate<number> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a number to be in a specified range.
|
||||
|
||||
@param start - Start of the range.
|
||||
@param end - End of the range.
|
||||
*/
|
||||
inRange(start: number, end: number): this;
|
||||
/**
|
||||
Test a number to be greater than the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
greaterThan(number: number): this;
|
||||
/**
|
||||
Test a number to be greater than or equal to the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
greaterThanOrEqual(number: number): this;
|
||||
/**
|
||||
Test a number to be less than the provided value.
|
||||
|
||||
@param number - Maximum value.
|
||||
*/
|
||||
lessThan(number: number): this;
|
||||
/**
|
||||
Test a number to be less than or equal to the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
lessThanOrEqual(number: number): this;
|
||||
/**
|
||||
Test a number to be equal to a specified number.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
equal(expected: number): this;
|
||||
/**
|
||||
Test if a number is an element of the provided list.
|
||||
|
||||
@param list - List of possible values.
|
||||
*/
|
||||
oneOf(list: readonly number[]): this;
|
||||
/**
|
||||
Test a number to be an integer.
|
||||
*/
|
||||
get integer(): this;
|
||||
/**
|
||||
Test a number to be finite.
|
||||
*/
|
||||
get finite(): this;
|
||||
/**
|
||||
Test a number to be infinite.
|
||||
*/
|
||||
get infinite(): this;
|
||||
/**
|
||||
Test a number to be positive.
|
||||
*/
|
||||
get positive(): this;
|
||||
/**
|
||||
Test a number to be negative.
|
||||
*/
|
||||
get negative(): this;
|
||||
/**
|
||||
Test a number to be an integer or infinite.
|
||||
*/
|
||||
get integerOrInfinite(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 8-bit unsigned integer.
|
||||
*/
|
||||
get uint8(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 16-bit unsigned integer.
|
||||
*/
|
||||
get uint16(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 32-bit unsigned integer.
|
||||
*/
|
||||
get uint32(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 8-bit signed integer.
|
||||
*/
|
||||
get int8(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 16-bit signed integer.
|
||||
*/
|
||||
get int16(): this;
|
||||
/**
|
||||
Test a number to be in a valid range for a 32-bit signed integer.
|
||||
*/
|
||||
get int32(): this;
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.NumberPredicate = void 0;
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const predicate_1 = require("./predicate");
|
||||
class NumberPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('number', options);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a specified range.
|
||||
|
||||
@param start - Start of the range.
|
||||
@param end - End of the range.
|
||||
*/
|
||||
inRange(start, end) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be in range [${start}..${end}], got ${value}`,
|
||||
validator: value => is_1.default.inRange(value, [start, end])
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be greater than the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
greaterThan(number) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be greater than ${number}, got ${value}`,
|
||||
validator: value => value > number
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be greater than or equal to the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
greaterThanOrEqual(number) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be greater than or equal to ${number}, got ${value}`,
|
||||
validator: value => value >= number
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be less than the provided value.
|
||||
|
||||
@param number - Maximum value.
|
||||
*/
|
||||
lessThan(number) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be less than ${number}, got ${value}`,
|
||||
validator: value => value < number
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be less than or equal to the provided value.
|
||||
|
||||
@param number - Minimum value.
|
||||
*/
|
||||
lessThanOrEqual(number) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be less than or equal to ${number}, got ${value}`,
|
||||
validator: value => value <= number
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be equal to a specified number.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
equal(expected) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be equal to ${expected}, got ${value}`,
|
||||
validator: value => value === expected
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test if a number is an element of the provided list.
|
||||
|
||||
@param list - List of possible values.
|
||||
*/
|
||||
oneOf(list) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => {
|
||||
let printedList = JSON.stringify(list);
|
||||
if (list.length > 10) {
|
||||
const overflow = list.length - 10;
|
||||
printedList = JSON.stringify(list.slice(0, 10)).replace(/]$/, `,…+${overflow} more]`);
|
||||
}
|
||||
return `Expected ${label} to be one of \`${printedList}\`, got ${value}`;
|
||||
},
|
||||
validator: value => list.includes(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be an integer.
|
||||
*/
|
||||
get integer() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be an integer, got ${value}`,
|
||||
validator: value => is_1.default.integer(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be finite.
|
||||
*/
|
||||
get finite() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be finite, got ${value}`,
|
||||
validator: value => !is_1.default.infinite(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be infinite.
|
||||
*/
|
||||
get infinite() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be infinite, got ${value}`,
|
||||
validator: value => is_1.default.infinite(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be positive.
|
||||
*/
|
||||
get positive() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be positive, got ${value}`,
|
||||
validator: value => value > 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be negative.
|
||||
*/
|
||||
get negative() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be negative, got ${value}`,
|
||||
validator: value => value < 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be an integer or infinite.
|
||||
*/
|
||||
get integerOrInfinite() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be an integer or infinite, got ${value}`,
|
||||
validator: value => is_1.default.integer(value) || is_1.default.infinite(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 8-bit unsigned integer.
|
||||
*/
|
||||
get uint8() {
|
||||
return this.integer.inRange(0, 255);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 16-bit unsigned integer.
|
||||
*/
|
||||
get uint16() {
|
||||
return this.integer.inRange(0, 65535);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 32-bit unsigned integer.
|
||||
*/
|
||||
get uint32() {
|
||||
return this.integer.inRange(0, 4294967295);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 8-bit signed integer.
|
||||
*/
|
||||
get int8() {
|
||||
return this.integer.inRange(-128, 127);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 16-bit signed integer.
|
||||
*/
|
||||
get int16() {
|
||||
return this.integer.inRange(-32768, 32767);
|
||||
}
|
||||
/**
|
||||
Test a number to be in a valid range for a 32-bit signed integer.
|
||||
*/
|
||||
get int32() {
|
||||
return this.integer.inRange(-2147483648, 2147483647);
|
||||
}
|
||||
}
|
||||
exports.NumberPredicate = NumberPredicate;
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { Shape, TypeOfShape } from '../utils/match-shape';
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
import { BasePredicate } from './base-predicate';
|
||||
export { Shape };
|
||||
export declare class ObjectPredicate<T extends object = object> extends Predicate<T> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test if an Object is a plain object.
|
||||
*/
|
||||
get plain(): this;
|
||||
/**
|
||||
Test an object to be empty.
|
||||
*/
|
||||
get empty(): this;
|
||||
/**
|
||||
Test an object to be not empty.
|
||||
*/
|
||||
get nonEmpty(): this;
|
||||
/**
|
||||
Test all the values in the object to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the object.
|
||||
*/
|
||||
valuesOfType<T>(predicate: BasePredicate<T>): this;
|
||||
/**
|
||||
Test all the values in the object deeply to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the object.
|
||||
*/
|
||||
deepValuesOfType<T>(predicate: Predicate<T>): this;
|
||||
/**
|
||||
Test an object to be deeply equal to the provided object.
|
||||
|
||||
@param expected - Expected object to match.
|
||||
*/
|
||||
deepEqual(expected: object): this;
|
||||
/**
|
||||
Test an object to be of a specific instance type.
|
||||
|
||||
@param instance - The expected instance type of the object.
|
||||
*/
|
||||
instanceOf(instance: Function): this;
|
||||
/**
|
||||
Test an object to include all the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.
|
||||
|
||||
@param keys - The keys that should be present in the object.
|
||||
*/
|
||||
hasKeys(...keys: readonly string[]): this;
|
||||
/**
|
||||
Test an object to include any of the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.
|
||||
|
||||
@param keys - The keys that could be a key in the object.
|
||||
*/
|
||||
hasAnyKeys(...keys: readonly string[]): this;
|
||||
/**
|
||||
Test an object to match the `shape` partially. This means that it ignores unexpected properties. The shape comparison is deep.
|
||||
|
||||
The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.
|
||||
|
||||
@param shape - Shape to test the object against.
|
||||
|
||||
@example
|
||||
```
|
||||
import ow from 'ow';
|
||||
|
||||
const object = {
|
||||
unicorn: '🦄',
|
||||
rainbow: '🌈'
|
||||
};
|
||||
|
||||
ow(object, ow.object.partialShape({
|
||||
unicorn: ow.string
|
||||
}));
|
||||
```
|
||||
*/
|
||||
partialShape<S extends Shape = Shape>(shape: S): ObjectPredicate<TypeOfShape<S>>;
|
||||
/**
|
||||
Test an object to match the `shape` exactly. This means that will fail if it comes across unexpected properties. The shape comparison is deep.
|
||||
|
||||
The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.
|
||||
|
||||
@param shape - Shape to test the object against.
|
||||
|
||||
@example
|
||||
```
|
||||
import ow from 'ow';
|
||||
|
||||
ow({unicorn: '🦄'}, ow.object.exactShape({
|
||||
unicorn: ow.string
|
||||
}));
|
||||
```
|
||||
*/
|
||||
exactShape<S extends Shape = Shape>(shape: S): ObjectPredicate<TypeOfShape<S>>;
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ObjectPredicate = void 0;
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const dotProp = require("dot-prop");
|
||||
const isEqual = require("lodash.isequal");
|
||||
const has_items_1 = require("../utils/has-items");
|
||||
const of_type_1 = require("../utils/of-type");
|
||||
const of_type_deep_1 = require("../utils/of-type-deep");
|
||||
const match_shape_1 = require("../utils/match-shape");
|
||||
const predicate_1 = require("./predicate");
|
||||
class ObjectPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('object', options);
|
||||
}
|
||||
/**
|
||||
Test if an Object is a plain object.
|
||||
*/
|
||||
get plain() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to be a plain object`,
|
||||
validator: object => is_1.default.plainObject(object)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to be empty.
|
||||
*/
|
||||
get empty() {
|
||||
return this.addValidator({
|
||||
message: (object, label) => `Expected ${label} to be empty, got \`${JSON.stringify(object)}\``,
|
||||
validator: object => Object.keys(object).length === 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to be not empty.
|
||||
*/
|
||||
get nonEmpty() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to not be empty`,
|
||||
validator: object => Object.keys(object).length > 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all the values in the object to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the object.
|
||||
*/
|
||||
valuesOfType(predicate) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: object => of_type_1.default(Object.values(object), 'values', predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all the values in the object deeply to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every value in the object.
|
||||
*/
|
||||
deepValuesOfType(predicate) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: object => of_type_deep_1.default(object, predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to be deeply equal to the provided object.
|
||||
|
||||
@param expected - Expected object to match.
|
||||
*/
|
||||
deepEqual(expected) {
|
||||
return this.addValidator({
|
||||
message: (object, label) => `Expected ${label} to be deeply equal to \`${JSON.stringify(expected)}\`, got \`${JSON.stringify(object)}\``,
|
||||
validator: object => isEqual(object, expected)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to be of a specific instance type.
|
||||
|
||||
@param instance - The expected instance type of the object.
|
||||
*/
|
||||
instanceOf(instance) {
|
||||
return this.addValidator({
|
||||
message: (object, label) => {
|
||||
var _a;
|
||||
let { name } = (_a = object === null || object === void 0 ? void 0 : object.constructor) !== null && _a !== void 0 ? _a : {};
|
||||
if (!name || name === 'Object') {
|
||||
name = JSON.stringify(object);
|
||||
}
|
||||
return `Expected ${label} \`${name}\` to be of type \`${instance.name}\``;
|
||||
},
|
||||
validator: object => object instanceof instance
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to include all the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.
|
||||
|
||||
@param keys - The keys that should be present in the object.
|
||||
*/
|
||||
hasKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingKeys) => `Expected ${label} to have keys \`${JSON.stringify(missingKeys)}\``,
|
||||
validator: object => has_items_1.default({
|
||||
has: item => dotProp.has(object, item)
|
||||
}, keys)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to include any of the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.
|
||||
|
||||
@param keys - The keys that could be a key in the object.
|
||||
*/
|
||||
hasAnyKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any key of \`${JSON.stringify(keys)}\``,
|
||||
validator: object => keys.some(key => dotProp.has(object, key))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to match the `shape` partially. This means that it ignores unexpected properties. The shape comparison is deep.
|
||||
|
||||
The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.
|
||||
|
||||
@param shape - Shape to test the object against.
|
||||
|
||||
@example
|
||||
```
|
||||
import ow from 'ow';
|
||||
|
||||
const object = {
|
||||
unicorn: '🦄',
|
||||
rainbow: '🌈'
|
||||
};
|
||||
|
||||
ow(object, ow.object.partialShape({
|
||||
unicorn: ow.string
|
||||
}));
|
||||
```
|
||||
*/
|
||||
partialShape(shape) {
|
||||
return this.addValidator({
|
||||
// TODO: Improve this when message handling becomes smarter
|
||||
message: (_, label, message) => `${message.replace('Expected', 'Expected property')} in ${label}`,
|
||||
validator: object => match_shape_1.partial(object, shape)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test an object to match the `shape` exactly. This means that will fail if it comes across unexpected properties. The shape comparison is deep.
|
||||
|
||||
The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.
|
||||
|
||||
@param shape - Shape to test the object against.
|
||||
|
||||
@example
|
||||
```
|
||||
import ow from 'ow';
|
||||
|
||||
ow({unicorn: '🦄'}, ow.object.exactShape({
|
||||
unicorn: ow.string
|
||||
}));
|
||||
```
|
||||
*/
|
||||
exactShape(shape) {
|
||||
// TODO [typescript@>=5] If higher-kinded types are supported natively by typescript, refactor `addValidator` to use them to avoid the usage of `any`. Otherwise, bump or remove this TODO.
|
||||
return this.addValidator({
|
||||
// TODO: Improve this when message handling becomes smarter
|
||||
message: (_, label, message) => `${message.replace('Expected', 'Expected property')} in ${label}`,
|
||||
validator: object => match_shape_1.exact(object, shape)
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.ObjectPredicate = ObjectPredicate;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { BasePredicate, testSymbol } from './base-predicate';
|
||||
import { Main } from '..';
|
||||
/**
|
||||
Function executed when the provided validation fails.
|
||||
|
||||
@param value - The tested value.
|
||||
@param label - Label of the tested value.
|
||||
|
||||
@returns {string} - The actual error message.
|
||||
*/
|
||||
export declare type ValidatorMessageBuilder<T> = (value: T, label?: string) => string;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export interface Validator<T> {
|
||||
message(value: T, label?: string, result?: any): string;
|
||||
validator(value: T): unknown;
|
||||
/**
|
||||
Provide custom message used by `not` operator.
|
||||
|
||||
When absent, the return value of `message()` is used and 'not' is inserted after the first 'to', e.g. `Expected 'smth' to be empty` -> `Expected 'smth' to not be empty`.
|
||||
*/
|
||||
negatedMessage?(value: T, label: string): string;
|
||||
}
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export interface PredicateOptions {
|
||||
optional?: boolean;
|
||||
}
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export interface Context<T = unknown> extends PredicateOptions {
|
||||
validators: Array<Validator<T>>;
|
||||
}
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare const validatorSymbol: unique symbol;
|
||||
export declare type CustomValidator<T> = (value: T) => {
|
||||
/**
|
||||
Should be `true` if the validation is correct.
|
||||
*/
|
||||
validator: boolean;
|
||||
/**
|
||||
The error message which should be shown if the `validator` is `false`. Or a error function which returns the error message and accepts the label as first argument.
|
||||
*/
|
||||
message: string | ((label: string) => string);
|
||||
};
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export declare class Predicate<T = unknown> implements BasePredicate<T> {
|
||||
private readonly type;
|
||||
private readonly options;
|
||||
private readonly context;
|
||||
constructor(type: string, options?: PredicateOptions);
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
[testSymbol](value: T, main: Main, label: string | Function, idLabel: boolean): asserts value is T;
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
get [validatorSymbol](): Array<Validator<T>>;
|
||||
/**
|
||||
Invert the following validators.
|
||||
*/
|
||||
get not(): this;
|
||||
/**
|
||||
Test if the value matches a custom validation function. The validation function should return an object containing a `validator` and `message`. If the `validator` is `false`, the validation fails and the `message` will be used as error message. If the `message` is a function, the function is invoked with the `label` as argument to let you further customize the error message.
|
||||
|
||||
@param customValidator - Custom validation function.
|
||||
*/
|
||||
validate(customValidator: CustomValidator<T>): this;
|
||||
/**
|
||||
Test if the value matches a custom validation function. The validation function should return `true` if the value passes the function. If the function either returns `false` or a string, the function fails and the string will be used as error message.
|
||||
|
||||
@param validator - Validation function.
|
||||
*/
|
||||
is(validator: (value: T) => boolean | string): this;
|
||||
/**
|
||||
Provide a new error message to be thrown when the validation fails.
|
||||
|
||||
@param newMessage - Either a string containing the new message or a function returning the new message.
|
||||
|
||||
@example
|
||||
```
|
||||
ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
|
||||
//=> ArgumentError: Expected unicorn, got rainbow
|
||||
```
|
||||
|
||||
@example
|
||||
```
|
||||
ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
|
||||
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`
|
||||
```
|
||||
*/
|
||||
message(newMessage: string | ValidatorMessageBuilder<T>): this;
|
||||
/**
|
||||
Register a new validator.
|
||||
|
||||
@param validator - Validator to register.
|
||||
*/
|
||||
addValidator(validator: Validator<T>): this;
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Predicate = exports.validatorSymbol = void 0;
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const argument_error_1 = require("../argument-error");
|
||||
const not_1 = require("../operators/not");
|
||||
const base_predicate_1 = require("./base-predicate");
|
||||
const generate_argument_error_message_1 = require("../utils/generate-argument-error-message");
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
exports.validatorSymbol = Symbol('validators');
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
class Predicate {
|
||||
constructor(type, options = {}) {
|
||||
Object.defineProperty(this, "type", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: type
|
||||
});
|
||||
Object.defineProperty(this, "options", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: options
|
||||
});
|
||||
Object.defineProperty(this, "context", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
validators: []
|
||||
}
|
||||
});
|
||||
this.context = {
|
||||
...this.context,
|
||||
...this.options
|
||||
};
|
||||
const typeString = this.type.charAt(0).toLowerCase() + this.type.slice(1);
|
||||
this.addValidator({
|
||||
message: (value, label) => {
|
||||
// We do not include type in this label as we do for other messages, because it would be redundant.
|
||||
const label_ = label === null || label === void 0 ? void 0 : label.slice(this.type.length + 1);
|
||||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
||||
return `Expected ${label_ || 'argument'} to be of type \`${this.type}\` but received type \`${is_1.default(value)}\``;
|
||||
},
|
||||
validator: value => is_1.default[typeString](value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
[base_predicate_1.testSymbol](value, main, label, idLabel) {
|
||||
// Create a map of labels -> received errors.
|
||||
const errors = new Map();
|
||||
for (const { validator, message } of this.context.validators) {
|
||||
if (this.options.optional === true && value === undefined) {
|
||||
continue;
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = validator(value);
|
||||
}
|
||||
catch (error) {
|
||||
// Any errors caught means validators couldn't process the input.
|
||||
result = error;
|
||||
}
|
||||
if (result === true) {
|
||||
continue;
|
||||
}
|
||||
const label2 = is_1.default.function_(label) ? label() : label;
|
||||
const labelWithTick = (label2 && idLabel) ? `\`${label2}\`` : label2;
|
||||
const label_ = labelWithTick ?
|
||||
`${this.type} ${labelWithTick}` :
|
||||
this.type;
|
||||
const mapKey = label2 || this.type;
|
||||
// Get the current errors encountered for this label.
|
||||
const currentErrors = errors.get(mapKey);
|
||||
// Pre-generate the error message that will be reported to the user.
|
||||
const errorMessage = message(value, label_, result);
|
||||
// If we already have any errors for this label.
|
||||
if (currentErrors) {
|
||||
// If we don't already have this error logged, add it.
|
||||
currentErrors.add(errorMessage);
|
||||
}
|
||||
else {
|
||||
// Set this label and error in the full map.
|
||||
errors.set(mapKey, new Set([errorMessage]));
|
||||
}
|
||||
}
|
||||
// If we have any errors to report, throw.
|
||||
if (errors.size > 0) {
|
||||
// Generate the `error.message` property.
|
||||
const message = generate_argument_error_message_1.generateArgumentErrorMessage(errors);
|
||||
throw new argument_error_1.ArgumentError(message, main, errors);
|
||||
}
|
||||
}
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
get [exports.validatorSymbol]() {
|
||||
return this.context.validators;
|
||||
}
|
||||
/**
|
||||
Invert the following validators.
|
||||
*/
|
||||
get not() {
|
||||
return not_1.not(this);
|
||||
}
|
||||
/**
|
||||
Test if the value matches a custom validation function. The validation function should return an object containing a `validator` and `message`. If the `validator` is `false`, the validation fails and the `message` will be used as error message. If the `message` is a function, the function is invoked with the `label` as argument to let you further customize the error message.
|
||||
|
||||
@param customValidator - Custom validation function.
|
||||
*/
|
||||
validate(customValidator) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => typeof error === 'string' ?
|
||||
`(${label}) ${error}` :
|
||||
error(label),
|
||||
validator: value => {
|
||||
const { message, validator } = customValidator(value);
|
||||
if (validator) {
|
||||
return true;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test if the value matches a custom validation function. The validation function should return `true` if the value passes the function. If the function either returns `false` or a string, the function fails and the string will be used as error message.
|
||||
|
||||
@param validator - Validation function.
|
||||
*/
|
||||
is(validator) {
|
||||
return this.addValidator({
|
||||
message: (value, label, error) => (error ?
|
||||
`(${label}) ${error}` :
|
||||
`Expected ${label} \`${value}\` to pass custom validation function`),
|
||||
validator
|
||||
});
|
||||
}
|
||||
/**
|
||||
Provide a new error message to be thrown when the validation fails.
|
||||
|
||||
@param newMessage - Either a string containing the new message or a function returning the new message.
|
||||
|
||||
@example
|
||||
```
|
||||
ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
|
||||
//=> ArgumentError: Expected unicorn, got rainbow
|
||||
```
|
||||
|
||||
@example
|
||||
```
|
||||
ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
|
||||
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`
|
||||
```
|
||||
*/
|
||||
message(newMessage) {
|
||||
const { validators } = this.context;
|
||||
validators[validators.length - 1].message = (value, label) => {
|
||||
if (typeof newMessage === 'function') {
|
||||
return newMessage(value, label);
|
||||
}
|
||||
return newMessage;
|
||||
};
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
Register a new validator.
|
||||
|
||||
@param validator - Validator to register.
|
||||
*/
|
||||
addValidator(validator) {
|
||||
this.context.validators.push(validator);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
exports.Predicate = Predicate;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class SetPredicate<T = any> extends Predicate<Set<T>> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a Set to have a specific size.
|
||||
|
||||
@param size - The size of the Set.
|
||||
*/
|
||||
size(size: number): this;
|
||||
/**
|
||||
Test a Set to have a minimum size.
|
||||
|
||||
@param size - The minimum size of the Set.
|
||||
*/
|
||||
minSize(size: number): this;
|
||||
/**
|
||||
Test a Set to have a maximum size.
|
||||
|
||||
@param size - The maximum size of the Set.
|
||||
*/
|
||||
maxSize(size: number): this;
|
||||
/**
|
||||
Test a Set to include all the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that should be a item in the Set.
|
||||
*/
|
||||
has(...items: readonly T[]): this;
|
||||
/**
|
||||
Test a Set to include any of the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that could be a item in the Set.
|
||||
*/
|
||||
hasAny(...items: readonly T[]): this;
|
||||
/**
|
||||
Test all the items in the Set to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every item in the Set.
|
||||
*/
|
||||
ofType(predicate: Predicate<T>): this;
|
||||
/**
|
||||
Test a Set to be empty.
|
||||
*/
|
||||
get empty(): this;
|
||||
/**
|
||||
Test a Set to be not empty.
|
||||
*/
|
||||
get nonEmpty(): this;
|
||||
/**
|
||||
Test a Set to be deeply equal to the provided Set.
|
||||
|
||||
@param expected - Expected Set to match.
|
||||
*/
|
||||
deepEqual(expected: Set<T>): this;
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SetPredicate = void 0;
|
||||
const isEqual = require("lodash.isequal");
|
||||
const has_items_1 = require("../utils/has-items");
|
||||
const of_type_1 = require("../utils/of-type");
|
||||
const predicate_1 = require("./predicate");
|
||||
class SetPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('Set', options);
|
||||
}
|
||||
/**
|
||||
Test a Set to have a specific size.
|
||||
|
||||
@param size - The size of the Set.
|
||||
*/
|
||||
size(size) {
|
||||
return this.addValidator({
|
||||
message: (set, label) => `Expected ${label} to have size \`${size}\`, got \`${set.size}\``,
|
||||
validator: set => set.size === size
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to have a minimum size.
|
||||
|
||||
@param size - The minimum size of the Set.
|
||||
*/
|
||||
minSize(size) {
|
||||
return this.addValidator({
|
||||
message: (set, label) => `Expected ${label} to have a minimum size of \`${size}\`, got \`${set.size}\``,
|
||||
validator: set => set.size >= size,
|
||||
negatedMessage: (set, label) => `Expected ${label} to have a maximum size of \`${size - 1}\`, got \`${set.size}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to have a maximum size.
|
||||
|
||||
@param size - The maximum size of the Set.
|
||||
*/
|
||||
maxSize(size) {
|
||||
return this.addValidator({
|
||||
message: (set, label) => `Expected ${label} to have a maximum size of \`${size}\`, got \`${set.size}\``,
|
||||
validator: set => set.size <= size,
|
||||
negatedMessage: (set, label) => `Expected ${label} to have a minimum size of \`${size + 1}\`, got \`${set.size}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to include all the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that should be a item in the Set.
|
||||
*/
|
||||
has(...items) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingItems) => `Expected ${label} to have items \`${JSON.stringify(missingItems)}\``,
|
||||
validator: set => has_items_1.default(set, items)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to include any of the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that could be a item in the Set.
|
||||
*/
|
||||
hasAny(...items) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any item of \`${JSON.stringify(items)}\``,
|
||||
validator: set => items.some(item => set.has(item))
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test all the items in the Set to match the provided predicate.
|
||||
|
||||
@param predicate - The predicate that should be applied against every item in the Set.
|
||||
*/
|
||||
ofType(predicate) {
|
||||
return this.addValidator({
|
||||
message: (_, label, error) => `(${label}) ${error}`,
|
||||
validator: set => of_type_1.default(set, 'values', predicate)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to be empty.
|
||||
*/
|
||||
get empty() {
|
||||
return this.addValidator({
|
||||
message: (set, label) => `Expected ${label} to be empty, got \`${JSON.stringify([...set])}\``,
|
||||
validator: set => set.size === 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to be not empty.
|
||||
*/
|
||||
get nonEmpty() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to not be empty`,
|
||||
validator: set => set.size > 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a Set to be deeply equal to the provided Set.
|
||||
|
||||
@param expected - Expected Set to match.
|
||||
*/
|
||||
deepEqual(expected) {
|
||||
return this.addValidator({
|
||||
message: (set, label) => `Expected ${label} to be deeply equal to \`${JSON.stringify([...expected])}\`, got \`${JSON.stringify([...set])}\``,
|
||||
validator: set => isEqual(set, expected)
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.SetPredicate = SetPredicate;
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class StringPredicate extends Predicate<string> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a string to have a specific length.
|
||||
|
||||
@param length - The length of the string.
|
||||
*/
|
||||
length(length: number): this;
|
||||
/**
|
||||
Test a string to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the string.
|
||||
*/
|
||||
minLength(length: number): this;
|
||||
/**
|
||||
Test a string to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the string.
|
||||
*/
|
||||
maxLength(length: number): this;
|
||||
/**
|
||||
Test a string against a regular expression.
|
||||
|
||||
@param regex - The regular expression to match the value with.
|
||||
*/
|
||||
matches(regex: RegExp): this;
|
||||
/**
|
||||
Test a string to start with a specific value.
|
||||
|
||||
@param searchString - The value that should be the start of the string.
|
||||
*/
|
||||
startsWith(searchString: string): this;
|
||||
/**
|
||||
Test a string to end with a specific value.
|
||||
|
||||
@param searchString - The value that should be the end of the string.
|
||||
*/
|
||||
endsWith(searchString: string): this;
|
||||
/**
|
||||
Test a string to include a specific value.
|
||||
|
||||
@param searchString - The value that should be included in the string.
|
||||
*/
|
||||
includes(searchString: string): this;
|
||||
/**
|
||||
Test if the string is an element of the provided list.
|
||||
|
||||
@param list - List of possible values.
|
||||
*/
|
||||
oneOf(list: readonly string[]): this;
|
||||
/**
|
||||
Test a string to be empty.
|
||||
*/
|
||||
get empty(): this;
|
||||
/**
|
||||
Test a string to be not empty.
|
||||
*/
|
||||
get nonEmpty(): this;
|
||||
/**
|
||||
Test a string to be equal to a specified string.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
equals(expected: string): this;
|
||||
/**
|
||||
Test a string to be alphanumeric.
|
||||
*/
|
||||
get alphanumeric(): this;
|
||||
/**
|
||||
Test a string to be alphabetical.
|
||||
*/
|
||||
get alphabetical(): this;
|
||||
/**
|
||||
Test a string to be numeric.
|
||||
*/
|
||||
get numeric(): this;
|
||||
/**
|
||||
Test a string to be a valid date.
|
||||
*/
|
||||
get date(): this;
|
||||
/**
|
||||
Test a non-empty string to be lowercase. Matching both alphabetical & numbers.
|
||||
*/
|
||||
get lowercase(): this;
|
||||
/**
|
||||
Test a non-empty string to be uppercase. Matching both alphabetical & numbers.
|
||||
*/
|
||||
get uppercase(): this;
|
||||
/**
|
||||
Test a string to be a valid URL.
|
||||
*/
|
||||
get url(): this;
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StringPredicate = void 0;
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const valiDate = require("vali-date");
|
||||
const predicate_1 = require("./predicate");
|
||||
class StringPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('string', options);
|
||||
}
|
||||
/**
|
||||
Test a string to have a specific length.
|
||||
|
||||
@param length - The length of the string.
|
||||
*/
|
||||
length(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have length \`${length}\`, got \`${value}\``,
|
||||
validator: value => value.length === length
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the string.
|
||||
*/
|
||||
minLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum length of \`${length}\`, got \`${value}\``,
|
||||
validator: value => value.length >= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum length of \`${length - 1}\`, got \`${value}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the string.
|
||||
*/
|
||||
maxLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum length of \`${length}\`, got \`${value}\``,
|
||||
validator: value => value.length <= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum length of \`${length + 1}\`, got \`${value}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string against a regular expression.
|
||||
|
||||
@param regex - The regular expression to match the value with.
|
||||
*/
|
||||
matches(regex) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to match \`${regex}\`, got \`${value}\``,
|
||||
validator: value => regex.test(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to start with a specific value.
|
||||
|
||||
@param searchString - The value that should be the start of the string.
|
||||
*/
|
||||
startsWith(searchString) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to start with \`${searchString}\`, got \`${value}\``,
|
||||
validator: value => value.startsWith(searchString)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to end with a specific value.
|
||||
|
||||
@param searchString - The value that should be the end of the string.
|
||||
*/
|
||||
endsWith(searchString) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to end with \`${searchString}\`, got \`${value}\``,
|
||||
validator: value => value.endsWith(searchString)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to include a specific value.
|
||||
|
||||
@param searchString - The value that should be included in the string.
|
||||
*/
|
||||
includes(searchString) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to include \`${searchString}\`, got \`${value}\``,
|
||||
validator: value => value.includes(searchString)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test if the string is an element of the provided list.
|
||||
|
||||
@param list - List of possible values.
|
||||
*/
|
||||
oneOf(list) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => {
|
||||
let printedList = JSON.stringify(list);
|
||||
if (list.length > 10) {
|
||||
const overflow = list.length - 10;
|
||||
printedList = JSON.stringify(list.slice(0, 10)).replace(/]$/, `,…+${overflow} more]`);
|
||||
}
|
||||
return `Expected ${label} to be one of \`${printedList}\`, got \`${value}\``;
|
||||
},
|
||||
validator: value => list.includes(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be empty.
|
||||
*/
|
||||
get empty() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be empty, got \`${value}\``,
|
||||
validator: value => value === ''
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be not empty.
|
||||
*/
|
||||
get nonEmpty() {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to not be empty`,
|
||||
validator: value => value !== ''
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be equal to a specified string.
|
||||
|
||||
@param expected - Expected value to match.
|
||||
*/
|
||||
equals(expected) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be equal to \`${expected}\`, got \`${value}\``,
|
||||
validator: value => value === expected
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be alphanumeric.
|
||||
*/
|
||||
get alphanumeric() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be alphanumeric, got \`${value}\``,
|
||||
validator: value => /^[a-z\d]+$/i.test(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be alphabetical.
|
||||
*/
|
||||
get alphabetical() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be alphabetical, got \`${value}\``,
|
||||
validator: value => /^[a-z]+$/gi.test(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be numeric.
|
||||
*/
|
||||
get numeric() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be numeric, got \`${value}\``,
|
||||
validator: value => /^[+-]?\d+$/i.test(value)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be a valid date.
|
||||
*/
|
||||
get date() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be a date, got \`${value}\``,
|
||||
validator: valiDate
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a non-empty string to be lowercase. Matching both alphabetical & numbers.
|
||||
*/
|
||||
get lowercase() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be lowercase, got \`${value}\``,
|
||||
validator: value => value.trim() !== '' && value === value.toLowerCase()
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a non-empty string to be uppercase. Matching both alphabetical & numbers.
|
||||
*/
|
||||
get uppercase() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be uppercase, got \`${value}\``,
|
||||
validator: value => value.trim() !== '' && value === value.toUpperCase()
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a string to be a valid URL.
|
||||
*/
|
||||
get url() {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to be a URL, got \`${value}\``,
|
||||
validator: is_1.default.urlString
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.StringPredicate = StringPredicate;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { TypedArray } from 'type-fest';
|
||||
import { Predicate } from './predicate';
|
||||
export declare class TypedArrayPredicate<T extends TypedArray> extends Predicate<T> {
|
||||
/**
|
||||
Test a typed array to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the typed array.
|
||||
*/
|
||||
byteLength(byteLength: number): this;
|
||||
/**
|
||||
Test a typed array to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the typed array.
|
||||
*/
|
||||
minByteLength(byteLength: number): this;
|
||||
/**
|
||||
Test a typed array to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the typed array.
|
||||
*/
|
||||
maxByteLength(byteLength: number): this;
|
||||
/**
|
||||
Test a typed array to have a specific length.
|
||||
|
||||
@param length - The length of the typed array.
|
||||
*/
|
||||
length(length: number): this;
|
||||
/**
|
||||
Test a typed array to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the typed array.
|
||||
*/
|
||||
minLength(length: number): this;
|
||||
/**
|
||||
Test a typed array to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the typed array.
|
||||
*/
|
||||
maxLength(length: number): this;
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TypedArrayPredicate = void 0;
|
||||
const predicate_1 = require("./predicate");
|
||||
class TypedArrayPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
Test a typed array to have a specific byte length.
|
||||
|
||||
@param byteLength - The byte length of the typed array.
|
||||
*/
|
||||
byteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength === byteLength
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a typed array to have a minimum byte length.
|
||||
|
||||
@param byteLength - The minimum byte length of the typed array.
|
||||
*/
|
||||
minByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength >= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength - 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a typed array to have a minimum byte length.
|
||||
|
||||
@param length - The minimum byte length of the typed array.
|
||||
*/
|
||||
maxByteLength(byteLength) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum byte length of \`${byteLength}\`, got \`${value.byteLength}\``,
|
||||
validator: value => value.byteLength <= byteLength,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum byte length of \`${byteLength + 1}\`, got \`${value.byteLength}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a typed array to have a specific length.
|
||||
|
||||
@param length - The length of the typed array.
|
||||
*/
|
||||
length(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have length \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length === length
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a typed array to have a minimum length.
|
||||
|
||||
@param length - The minimum length of the typed array.
|
||||
*/
|
||||
minLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a minimum length of \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length >= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a maximum length of \`${length - 1}\`, got \`${value.length}\``
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a typed array to have a maximum length.
|
||||
|
||||
@param length - The maximum length of the typed array.
|
||||
*/
|
||||
maxLength(length) {
|
||||
return this.addValidator({
|
||||
message: (value, label) => `Expected ${label} to have a maximum length of \`${length}\`, got \`${value.length}\``,
|
||||
validator: value => value.length <= length,
|
||||
negatedMessage: (value, label) => `Expected ${label} to have a minimum length of \`${length + 1}\`, got \`${value.length}\``
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.TypedArrayPredicate = TypedArrayPredicate;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class WeakMapPredicate<KeyType extends object = object> extends Predicate<WeakMap<KeyType, unknown>> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a WeakMap to include all the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that should be a key in the WeakMap.
|
||||
*/
|
||||
hasKeys(...keys: readonly KeyType[]): this;
|
||||
/**
|
||||
Test a WeakMap to include any of the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that could be a key in the WeakMap.
|
||||
*/
|
||||
hasAnyKeys(...keys: readonly KeyType[]): this;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WeakMapPredicate = void 0;
|
||||
const has_items_1 = require("../utils/has-items");
|
||||
const predicate_1 = require("./predicate");
|
||||
class WeakMapPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('WeakMap', options);
|
||||
}
|
||||
/**
|
||||
Test a WeakMap to include all the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that should be a key in the WeakMap.
|
||||
*/
|
||||
hasKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingKeys) => `Expected ${label} to have keys \`${JSON.stringify(missingKeys)}\``,
|
||||
validator: map => has_items_1.default(map, keys)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a WeakMap to include any of the provided keys. The keys are tested by identity, not structure.
|
||||
|
||||
@param keys - The keys that could be a key in the WeakMap.
|
||||
*/
|
||||
hasAnyKeys(...keys) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any key of \`${JSON.stringify(keys)}\``,
|
||||
validator: map => keys.some(key => map.has(key))
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.WeakMapPredicate = WeakMapPredicate;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { Predicate, PredicateOptions } from './predicate';
|
||||
export declare class WeakSetPredicate<T extends object = object> extends Predicate<WeakSet<T>> {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options?: PredicateOptions);
|
||||
/**
|
||||
Test a WeakSet to include all the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that should be a item in the WeakSet.
|
||||
*/
|
||||
has(...items: readonly T[]): this;
|
||||
/**
|
||||
Test a WeakSet to include any of the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that could be a item in the WeakSet.
|
||||
*/
|
||||
hasAny(...items: readonly T[]): this;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WeakSetPredicate = void 0;
|
||||
const has_items_1 = require("../utils/has-items");
|
||||
const predicate_1 = require("./predicate");
|
||||
class WeakSetPredicate extends predicate_1.Predicate {
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
constructor(options) {
|
||||
super('WeakSet', options);
|
||||
}
|
||||
/**
|
||||
Test a WeakSet to include all the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that should be a item in the WeakSet.
|
||||
*/
|
||||
has(...items) {
|
||||
return this.addValidator({
|
||||
message: (_, label, missingItems) => `Expected ${label} to have items \`${JSON.stringify(missingItems)}\``,
|
||||
validator: set => has_items_1.default(set, items)
|
||||
});
|
||||
}
|
||||
/**
|
||||
Test a WeakSet to include any of the provided items. The items are tested by identity, not structure.
|
||||
|
||||
@param items - The items that could be a item in the WeakSet.
|
||||
*/
|
||||
hasAny(...items) {
|
||||
return this.addValidator({
|
||||
message: (_, label) => `Expected ${label} to have any item of \`${JSON.stringify(items)}\``,
|
||||
validator: set => items.some(item => set.has(item))
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.WeakSetPredicate = WeakSetPredicate;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { BasePredicate } from './predicates/base-predicate';
|
||||
/**
|
||||
Validate the value against the provided predicate.
|
||||
|
||||
@hidden
|
||||
|
||||
@param value - Value to test.
|
||||
@param label - Label which should be used in error messages.
|
||||
@param predicate - Predicate to test to value against.
|
||||
@param idLabel - If true, the label is a variable or type. Default: true.
|
||||
*/
|
||||
export default function test<T>(value: T, label: string | Function, predicate: BasePredicate<T>, idLabel?: boolean): void;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const base_predicate_1 = require("./predicates/base-predicate");
|
||||
/**
|
||||
Validate the value against the provided predicate.
|
||||
|
||||
@hidden
|
||||
|
||||
@param value - Value to test.
|
||||
@param label - Label which should be used in error messages.
|
||||
@param predicate - Predicate to test to value against.
|
||||
@param idLabel - If true, the label is a variable or type. Default: true.
|
||||
*/
|
||||
function test(value, label, predicate, idLabel = true) {
|
||||
predicate[base_predicate_1.testSymbol](value, test, label, idLabel);
|
||||
}
|
||||
exports.default = test;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
Generates a complete message from all errors generated by predicates.
|
||||
|
||||
@param errors - The errors generated by the predicates.
|
||||
@param isAny - If this function is called from the any argument.
|
||||
@hidden
|
||||
*/
|
||||
export declare const generateArgumentErrorMessage: (errors: Map<string, Set<string>>, isAny?: boolean) => string;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generateArgumentErrorMessage = void 0;
|
||||
/**
|
||||
Generates a complete message from all errors generated by predicates.
|
||||
|
||||
@param errors - The errors generated by the predicates.
|
||||
@param isAny - If this function is called from the any argument.
|
||||
@hidden
|
||||
*/
|
||||
const generateArgumentErrorMessage = (errors, isAny = false) => {
|
||||
const message = [];
|
||||
const errorArray = [...errors.entries()];
|
||||
const anyErrorWithoutOneItemOnly = errorArray.some(([, array]) => array.size !== 1);
|
||||
// If only one error "key" is present, enumerate all of those errors only.
|
||||
if (errorArray.length === 1) {
|
||||
const [, returnedErrors] = errorArray[0];
|
||||
if (!isAny && returnedErrors.size === 1) {
|
||||
const [errorMessage] = returnedErrors;
|
||||
return errorMessage;
|
||||
}
|
||||
for (const entry of returnedErrors) {
|
||||
message.push(`${isAny ? ' - ' : ''}${entry}`);
|
||||
}
|
||||
return message.join('\n');
|
||||
}
|
||||
// If every predicate returns just one error, enumerate them as is.
|
||||
if (!anyErrorWithoutOneItemOnly) {
|
||||
return errorArray.map(([, [item]]) => ` - ${item}`).join('\n');
|
||||
}
|
||||
// Else, iterate through all the errors and enumerate them.
|
||||
for (const [key, value] of errorArray) {
|
||||
message.push(`Errors from the "${key}" predicate:`);
|
||||
for (const entry of value) {
|
||||
message.push(` - ${entry}`);
|
||||
}
|
||||
}
|
||||
return message.join('\n');
|
||||
};
|
||||
exports.generateArgumentErrorMessage = generateArgumentErrorMessage;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
Generates a useful stacktrace that points to the user's code where the error happened on platforms without the `Error.captureStackTrace()` method.
|
||||
|
||||
@hidden
|
||||
*/
|
||||
export declare const generateStackTrace: () => string;
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generateStackTrace = void 0;
|
||||
/**
|
||||
Generates a useful stacktrace that points to the user's code where the error happened on platforms without the `Error.captureStackTrace()` method.
|
||||
|
||||
@hidden
|
||||
*/
|
||||
const generateStackTrace = () => {
|
||||
const stack = new RangeError('INTERNAL_OW_ERROR').stack;
|
||||
return stack;
|
||||
};
|
||||
exports.generateStackTrace = generateStackTrace;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
@hidden
|
||||
*/
|
||||
export interface CollectionLike<T> {
|
||||
has: (item: T) => boolean;
|
||||
}
|
||||
declare const _default: <T>(source: CollectionLike<T>, items: readonly T[], maxValues?: number) => true | T[];
|
||||
/**
|
||||
Retrieve the missing values in a collection based on an array of items.
|
||||
|
||||
@hidden
|
||||
|
||||
@param source - Source collection to search through.
|
||||
@param items - Items to search for.
|
||||
@param maxValues - Maximum number of values after the search process is stopped. Default: 5.
|
||||
*/
|
||||
export default _default;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
Retrieve the missing values in a collection based on an array of items.
|
||||
|
||||
@hidden
|
||||
|
||||
@param source - Source collection to search through.
|
||||
@param items - Items to search for.
|
||||
@param maxValues - Maximum number of values after the search process is stopped. Default: 5.
|
||||
*/
|
||||
exports.default = (source, items, maxValues = 5) => {
|
||||
const missingValues = [];
|
||||
for (const value of items) {
|
||||
if (source.has(value)) {
|
||||
continue;
|
||||
}
|
||||
missingValues.push(value);
|
||||
if (missingValues.length === maxValues) {
|
||||
return missingValues;
|
||||
}
|
||||
}
|
||||
return missingValues.length === 0 ? true : missingValues;
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare const inferLabel: () => void;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.inferLabel = void 0;
|
||||
const inferLabel = () => { };
|
||||
exports.inferLabel = inferLabel;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { CallSite } from 'callsites';
|
||||
/**
|
||||
Infer the label of the caller.
|
||||
|
||||
@hidden
|
||||
|
||||
@param callsites - List of stack frames.
|
||||
*/
|
||||
export declare const inferLabel: (callsites: readonly CallSite[]) => void | string;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.inferLabel = void 0;
|
||||
const fs = require("fs");
|
||||
const is_valid_identifier_1 = require("./is-valid-identifier");
|
||||
const is_node_1 = require("./node/is-node");
|
||||
// Regex to extract the label out of the `ow` function call
|
||||
const labelRegex = /^.*?\((?<label>.*?)[,)]/;
|
||||
/**
|
||||
Infer the label of the caller.
|
||||
|
||||
@hidden
|
||||
|
||||
@param callsites - List of stack frames.
|
||||
*/
|
||||
const inferLabel = (callsites) => {
|
||||
var _a;
|
||||
if (!is_node_1.default) {
|
||||
// Exit if we are not running in a Node.js environment
|
||||
return;
|
||||
}
|
||||
// Grab the stackframe with the `ow` function call
|
||||
const functionCallStackFrame = callsites[1];
|
||||
if (!functionCallStackFrame) {
|
||||
return;
|
||||
}
|
||||
const fileName = functionCallStackFrame.getFileName();
|
||||
const lineNumber = functionCallStackFrame.getLineNumber();
|
||||
const columnNumber = functionCallStackFrame.getColumnNumber();
|
||||
if (fileName === null || lineNumber === null || columnNumber === null) {
|
||||
return;
|
||||
}
|
||||
let content = [];
|
||||
try {
|
||||
content = fs.readFileSync(fileName, 'utf8').split('\n');
|
||||
}
|
||||
catch {
|
||||
return;
|
||||
}
|
||||
let line = content[lineNumber - 1];
|
||||
if (!line) {
|
||||
// Exit if the line number couldn't be found
|
||||
return;
|
||||
}
|
||||
line = line.slice(columnNumber - 1);
|
||||
const match = labelRegex.exec(line);
|
||||
if (!((_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.label)) {
|
||||
// Exit if we didn't find a label
|
||||
return;
|
||||
}
|
||||
const token = match.groups.label;
|
||||
if (is_valid_identifier_1.default(token) || is_valid_identifier_1.default(token.split('.').pop())) {
|
||||
return token;
|
||||
}
|
||||
return;
|
||||
};
|
||||
exports.inferLabel = inferLabel;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
declare const _default: (string: string | undefined) => string | boolean | undefined;
|
||||
/**
|
||||
Test if the string is a valid JavaScript identifier.
|
||||
|
||||
@param string - String to test.
|
||||
*/
|
||||
export default _default;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const identifierRegex = /^[a-z$_][$\w]*$/i;
|
||||
const reservedSet = new Set([
|
||||
'undefined',
|
||||
'null',
|
||||
'true',
|
||||
'false',
|
||||
'super',
|
||||
'this',
|
||||
'Infinity',
|
||||
'NaN'
|
||||
]);
|
||||
/**
|
||||
Test if the string is a valid JavaScript identifier.
|
||||
|
||||
@param string - String to test.
|
||||
*/
|
||||
exports.default = (string) => string && !reservedSet.has(string) && identifierRegex.test(string);
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { BasePredicate } from '..';
|
||||
export interface Shape {
|
||||
[key: string]: BasePredicate | Shape;
|
||||
}
|
||||
/**
|
||||
Extracts a regular type from a shape definition.
|
||||
|
||||
@example
|
||||
```
|
||||
const myShape = {
|
||||
foo: ow.string,
|
||||
bar: {
|
||||
baz: ow.boolean
|
||||
}
|
||||
}
|
||||
|
||||
type X = TypeOfShape<typeof myShape> // {foo: string; bar: {baz: boolean}}
|
||||
```
|
||||
|
||||
This is used in the `ow.object.partialShape(…)` and `ow.object.exactShape(…)` functions.
|
||||
*/
|
||||
export declare type TypeOfShape<S extends BasePredicate | Shape> = S extends BasePredicate<infer X> ? X : S extends Shape ? {
|
||||
[K in keyof S]: TypeOfShape<S[K]>;
|
||||
} : never;
|
||||
/**
|
||||
Test if the `object` matches the `shape` partially.
|
||||
|
||||
@hidden
|
||||
|
||||
@param object - Object to test against the provided shape.
|
||||
@param shape - Shape to test the object against.
|
||||
@param parent - Name of the parent property.
|
||||
*/
|
||||
export declare function partial(object: Record<string, any>, shape: Shape, parent?: string): boolean | string;
|
||||
/**
|
||||
Test if the `object` matches the `shape` exactly.
|
||||
|
||||
@hidden
|
||||
|
||||
@param object - Object to test against the provided shape.
|
||||
@param shape - Shape to test the object against.
|
||||
@param parent - Name of the parent property.
|
||||
*/
|
||||
export declare function exact(object: Record<string, any>, shape: Shape, parent?: string, isArray?: boolean): boolean | string;
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.exact = exports.partial = void 0;
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const test_1 = require("../test");
|
||||
const base_predicate_1 = require("../predicates/base-predicate");
|
||||
/**
|
||||
Test if the `object` matches the `shape` partially.
|
||||
|
||||
@hidden
|
||||
|
||||
@param object - Object to test against the provided shape.
|
||||
@param shape - Shape to test the object against.
|
||||
@param parent - Name of the parent property.
|
||||
*/
|
||||
function partial(object, shape, parent) {
|
||||
try {
|
||||
for (const key of Object.keys(shape)) {
|
||||
const label = parent ? `${parent}.${key}` : key;
|
||||
if (base_predicate_1.isPredicate(shape[key])) {
|
||||
test_1.default(object[key], label, shape[key]);
|
||||
}
|
||||
else if (is_1.default.plainObject(shape[key])) {
|
||||
const result = partial(object[key], shape[key], label);
|
||||
if (result !== true) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
exports.partial = partial;
|
||||
/**
|
||||
Test if the `object` matches the `shape` exactly.
|
||||
|
||||
@hidden
|
||||
|
||||
@param object - Object to test against the provided shape.
|
||||
@param shape - Shape to test the object against.
|
||||
@param parent - Name of the parent property.
|
||||
*/
|
||||
function exact(object, shape, parent, isArray) {
|
||||
try {
|
||||
const objectKeys = new Set(Object.keys(object));
|
||||
for (const key of Object.keys(shape)) {
|
||||
objectKeys.delete(key);
|
||||
const label = parent ? `${parent}.${key}` : key;
|
||||
if (base_predicate_1.isPredicate(shape[key])) {
|
||||
test_1.default(object[key], label, shape[key]);
|
||||
}
|
||||
else if (is_1.default.plainObject(shape[key])) {
|
||||
if (!Object.prototype.hasOwnProperty.call(object, key)) {
|
||||
return `Expected \`${label}\` to exist`;
|
||||
}
|
||||
const result = exact(object[key], shape[key], label);
|
||||
if (result !== true) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (objectKeys.size > 0) {
|
||||
const firstKey = [...objectKeys.keys()][0];
|
||||
const label = parent ? `${parent}.${firstKey}` : firstKey;
|
||||
return `Did not expect ${isArray ? 'element' : 'property'} \`${label}\` to exist, got \`${object[firstKey]}\``;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
exports.exact = exact;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
declare const _default: boolean;
|
||||
export default _default;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
"use strict";
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = Boolean((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node);
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { Predicate } from '../predicates/predicate';
|
||||
declare const _default: (object: unknown, predicate: Predicate) => boolean | string;
|
||||
/**
|
||||
Test all the values in the object against a provided predicate.
|
||||
|
||||
@hidden
|
||||
|
||||
@param predicate - Predicate to test every value in the given object against.
|
||||
*/
|
||||
export default _default;
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const is_1 = require("@sindresorhus/is");
|
||||
const test_1 = require("../test");
|
||||
const ofTypeDeep = (object, predicate) => {
|
||||
if (!is_1.default.plainObject(object)) {
|
||||
test_1.default(object, 'deep values', predicate, false);
|
||||
return true;
|
||||
}
|
||||
return Object.values(object).every(value => ofTypeDeep(value, predicate));
|
||||
};
|
||||
/**
|
||||
Test all the values in the object against a provided predicate.
|
||||
|
||||
@hidden
|
||||
|
||||
@param predicate - Predicate to test every value in the given object against.
|
||||
*/
|
||||
exports.default = (object, predicate) => {
|
||||
try {
|
||||
return ofTypeDeep(object, predicate);
|
||||
}
|
||||
catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { BasePredicate } from '../predicates/base-predicate';
|
||||
declare const _default: <T>(source: IterableIterator<T> | Set<T> | T[], name: string, predicate: BasePredicate<T>) => boolean | string;
|
||||
/**
|
||||
Test all the values in the collection against a provided predicate.
|
||||
|
||||
@hidden
|
||||
@param source Source collection to test.
|
||||
@param name The name to call the collection of values, such as `values` or `keys`.
|
||||
@param predicate Predicate to test every item in the source collection against.
|
||||
*/
|
||||
export default _default;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const test_1 = require("../test");
|
||||
/**
|
||||
Test all the values in the collection against a provided predicate.
|
||||
|
||||
@hidden
|
||||
@param source Source collection to test.
|
||||
@param name The name to call the collection of values, such as `values` or `keys`.
|
||||
@param predicate Predicate to test every item in the source collection against.
|
||||
*/
|
||||
exports.default = (source, name, predicate) => {
|
||||
try {
|
||||
for (const item of source) {
|
||||
test_1.default(item, name, predicate, false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
declare const _default: () => string;
|
||||
export default _default;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = () => Math.random().toString(16).slice(2);
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"name": "ow",
|
||||
"version": "0.27.0",
|
||||
"description": "Function argument validation for humans",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/ow",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
},
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && nyc ava",
|
||||
"docs": "typedoc source/index.ts",
|
||||
"build": "del-cli dist && tsc",
|
||||
"prepare": "npm run build",
|
||||
"postpublish": "npm run docs && gh-pages --dist docs --no-history --message \"Deploy documentation\"",
|
||||
"example": "npm run build && node example.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"dev-only.js"
|
||||
],
|
||||
"keywords": [
|
||||
"type",
|
||||
"types",
|
||||
"check",
|
||||
"checking",
|
||||
"guard",
|
||||
"guards",
|
||||
"assert",
|
||||
"assertion",
|
||||
"predicate",
|
||||
"predicates",
|
||||
"is",
|
||||
"validate",
|
||||
"validation",
|
||||
"utility",
|
||||
"util",
|
||||
"typeof",
|
||||
"instanceof",
|
||||
"object"
|
||||
],
|
||||
"dependencies": {
|
||||
"@sindresorhus/is": "^4.0.1",
|
||||
"callsites": "^3.1.0",
|
||||
"dot-prop": "^6.0.1",
|
||||
"lodash.isequal": "^4.5.0",
|
||||
"type-fest": "^1.2.1",
|
||||
"vali-date": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sindresorhus/tsconfig": "^0.8.0",
|
||||
"@types/lodash.isequal": "^4.5.5",
|
||||
"@types/node": "^15.12.4",
|
||||
"@types/vali-date": "^1.0.0",
|
||||
"ava": "^2.4.0",
|
||||
"del-cli": "^4.0.0",
|
||||
"expect-type": "^0.11.0",
|
||||
"gh-pages": "^3.2.3",
|
||||
"nyc": "^15.1.0",
|
||||
"ts-node": "^10.0.0",
|
||||
"typedoc": "^0.21.1",
|
||||
"typescript": "^4.3.4",
|
||||
"xo": "^0.38.2"
|
||||
},
|
||||
"browser": {
|
||||
"./dist/utils/infer-label.js": "./dist/utils/infer-label.browser.js"
|
||||
},
|
||||
"types": "dist",
|
||||
"sideEffects": false,
|
||||
"xo": {
|
||||
"parserOptions": {
|
||||
"project": "./tsconfig.xo.json"
|
||||
},
|
||||
"ignores": [
|
||||
"example.js",
|
||||
"dev-only.js",
|
||||
"source/utils/infer-label.browser.ts"
|
||||
],
|
||||
"rules": {
|
||||
"no-useless-return": "off",
|
||||
"ava/no-ignored-test-files": "off",
|
||||
"@typescript-eslint/explicit-function-return-type": "error",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-empty-function": "off",
|
||||
"@typescript-eslint/restrict-template-expressions": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"import/no-anonymous-default-export": "off"
|
||||
}
|
||||
},
|
||||
"ava": {
|
||||
"babel": false,
|
||||
"compileEnhancements": false,
|
||||
"files": [
|
||||
"test/**",
|
||||
"!test/fixtures/**"
|
||||
],
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register"
|
||||
]
|
||||
},
|
||||
"nyc": {
|
||||
"reporter": [
|
||||
"text",
|
||||
"lcov"
|
||||
]
|
||||
}
|
||||
}
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
<p align="center">
|
||||
<img src="media/logo.png" width="300">
|
||||
<br>
|
||||
<br>
|
||||
</p>
|
||||
|
||||
[](https://codecov.io/gh/sindresorhus/ow)
|
||||
[](https://bundlephobia.com/result?p=ow)
|
||||
[](https://packagephobia.now.sh/result?p=ow)
|
||||
|
||||
> Function argument validation for humans
|
||||
|
||||
## Highlights
|
||||
|
||||
- Expressive chainable API
|
||||
- Lots of built-in validations
|
||||
- Supports custom validations
|
||||
- Automatic label inference in Node.js
|
||||
- Written in TypeScript
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install ow
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
*If you use CommonJS, you need to import is as `const {default: ow} = require('ow')`.*
|
||||
|
||||
```ts
|
||||
import ow from 'ow';
|
||||
|
||||
const unicorn = input => {
|
||||
ow(input, ow.string.minLength(5));
|
||||
|
||||
// …
|
||||
};
|
||||
|
||||
unicorn(3);
|
||||
//=> ArgumentError: Expected `input` to be of type `string` but received type `number`
|
||||
|
||||
unicorn('yo');
|
||||
//=> ArgumentError: Expected string `input` to have a minimum length of `5`, got `yo`
|
||||
```
|
||||
|
||||
We can also match the shape of an object.
|
||||
|
||||
```ts
|
||||
import ow from 'ow';
|
||||
|
||||
const unicorn = {
|
||||
rainbow: '🌈',
|
||||
stars: {
|
||||
value: '🌟'
|
||||
}
|
||||
};
|
||||
|
||||
ow(unicorn, ow.object.exactShape({
|
||||
rainbow: ow.string,
|
||||
stars: {
|
||||
value: ow.number
|
||||
}
|
||||
}));
|
||||
//=> ArgumentError: Expected property `stars.value` to be of type `number` but received type `string` in object `unicorn`
|
||||
```
|
||||
|
||||
***Note:*** If you intend on using `ow` for development purposes only, use `require('ow/dev-only')` instead of the usual `import 'ow'`, and run the bundler with `NODE_ENV` set to `production` (e.g. `$ NODE_ENV="production" parcel build index.js`). This will make `ow` automatically export a shim when running in production, which should result in a significantly lower bundle size.
|
||||
|
||||
## API
|
||||
|
||||
[Complete API documentation](https://sindresorhus.com/ow/interfaces/ow.html)
|
||||
|
||||
Ow includes TypeScript type guards, so using it will narrow the type of previously-unknown values.
|
||||
|
||||
```ts
|
||||
function (input: unknown) {
|
||||
input.slice(0, 3) // Error, Property 'slice' does not exist on type 'unknown'
|
||||
|
||||
ow(input, ow.string)
|
||||
|
||||
input.slice(0, 3) // OK
|
||||
}
|
||||
```
|
||||
|
||||
### ow(value, predicate)
|
||||
|
||||
Test if `value` matches the provided `predicate`. Throws an `ArgumentError` if the test fails.
|
||||
|
||||
### ow(value, label, predicate)
|
||||
|
||||
Test if `value` matches the provided `predicate`. Throws an `ArgumentError` with the specified `label` if the test fails.
|
||||
|
||||
The `label` is automatically inferred in Node.js but you can override it by passing in a value for `label`. The automatic label inference doesn't work in the browser.
|
||||
|
||||
### ow.isValid(value, predicate)
|
||||
|
||||
Returns `true` if the value matches the predicate, otherwise returns `false`.
|
||||
|
||||
### ow.create(predicate)
|
||||
|
||||
Create a reusable validator.
|
||||
|
||||
```ts
|
||||
const checkPassword = ow.create(ow.string.minLength(6));
|
||||
|
||||
const password = 'foo';
|
||||
|
||||
checkPassword(password);
|
||||
//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`
|
||||
```
|
||||
|
||||
### ow.create(label, predicate)
|
||||
|
||||
Create a reusable validator with a specific `label`.
|
||||
|
||||
```ts
|
||||
const checkPassword = ow.create('password', ow.string.minLength(6));
|
||||
|
||||
checkPassword('foo');
|
||||
//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`
|
||||
```
|
||||
|
||||
### ow.any(...predicate[])
|
||||
|
||||
Returns a predicate that verifies if the value matches at least one of the given predicates.
|
||||
|
||||
```ts
|
||||
ow('foo', ow.any(ow.string.maxLength(3), ow.number));
|
||||
```
|
||||
|
||||
### ow.optional.{type}
|
||||
|
||||
Makes the predicate optional. An optional predicate means that it doesn't fail if the value is `undefined`.
|
||||
|
||||
```ts
|
||||
ow(1, ow.optional.number);
|
||||
|
||||
ow(undefined, ow.optional.number);
|
||||
```
|
||||
|
||||
### ow.{type}
|
||||
|
||||
All the below types return a predicate. Every predicate has some extra operators that you can use to test the value even more fine-grained.
|
||||
|
||||
#### Primitives
|
||||
|
||||
- [`undefined`](https://sindresorhus.com/ow/interfaces/ow.html#undefined-1)
|
||||
- [`null`](https://sindresorhus.com/ow/interfaces/ow.html#null)
|
||||
- [`string`](https://sindresorhus.com/ow/classes/stringpredicate.html)
|
||||
- [`number`](https://sindresorhus.com/ow/classes/numberpredicate.html)
|
||||
- [`boolean`](https://sindresorhus.com/ow/classes/booleanpredicate.html)
|
||||
- [`symbol`](https://sindresorhus.com/ow/interfaces/ow.html#symbol-1)
|
||||
|
||||
#### Built-in types
|
||||
|
||||
- [`array`](https://sindresorhus.com/ow/classes/arraypredicate.html)
|
||||
- [`function`](https://sindresorhus.com/ow/interfaces/ow.html#function)
|
||||
- [`buffer`](https://sindresorhus.com/ow/interfaces/ow.html#buffer)
|
||||
- [`object`](https://sindresorhus.com/ow/classes/objectpredicate.html)
|
||||
- [`regExp`](https://sindresorhus.com/ow/interfaces/ow.html#regexp-1)
|
||||
- [`date`](https://sindresorhus.com/ow/classes/datepredicate.html)
|
||||
- [`error`](https://sindresorhus.com/ow/classes/errorpredicate.html)
|
||||
- [`promise`](https://sindresorhus.com/ow/interfaces/ow.html#promise-1)
|
||||
- [`map`](https://sindresorhus.com/ow/classes/mappredicate.html)
|
||||
- [`set`](https://sindresorhus.com/ow/classes/setpredicate.html)
|
||||
- [`weakMap`](https://sindresorhus.com/ow/classes/weakmappredicate.html)
|
||||
- [`weakSet`](https://sindresorhus.com/ow/classes/weaksetpredicate.html)
|
||||
|
||||
#### Typed arrays
|
||||
|
||||
- [`int8Array`](https://sindresorhus.com/ow/interfaces/ow.html#int8Array)
|
||||
- [`uint8Array`](https://sindresorhus.com/ow/interfaces/ow.html#uint8Array-1)
|
||||
- [`uint8ClampedArray`](https://sindresorhus.com/ow/interfaces/ow.html#uint8ClampedArray-1)
|
||||
- [`int16Array`](https://sindresorhus.com/ow/interfaces/ow.html#int16Array)
|
||||
- [`uint16Array`](https://sindresorhus.com/ow/interfaces/ow.html#uint16Array-1)
|
||||
- [`int32Array`](https://sindresorhus.com/ow/interfaces/ow.html#in32Array)
|
||||
- [`uint32Array`](https://sindresorhus.com/ow/interfaces/ow.html#uin32Array-1)
|
||||
- [`float32Array`](https://sindresorhus.com/ow/interfaces/ow.html#float32Array)
|
||||
- [`float64Array`](https://sindresorhus.com/ow/interfaces/ow.html#float64Array)
|
||||
|
||||
#### Structured data
|
||||
|
||||
- [`arrayBuffer`](https://sindresorhus.com/ow/interfaces/ow.html#arraybuffer)
|
||||
- [`dataView`](https://sindresorhus.com/ow/interfaces/ow.html#dataview)
|
||||
- [`sharedArrayBuffer`](https://sindresorhus.com/ow/interfaces/ow.html#sharedarraybuffer-1)
|
||||
|
||||
#### Miscellaneous
|
||||
|
||||
- [`nan`](https://sindresorhus.com/ow/interfaces/ow.html#nan)
|
||||
- [`nullOrUndefined`](https://sindresorhus.com/ow/interfaces/ow.html#nullorundefined)
|
||||
- [`iterable`](https://sindresorhus.com/ow/interfaces/ow.html#iterable)
|
||||
- [`typedArray`](https://sindresorhus.com/ow/interfaces/ow.html#typedarray-1)
|
||||
|
||||
### Predicates
|
||||
|
||||
The following predicates are available on every type.
|
||||
|
||||
#### not
|
||||
|
||||
Inverts the following predicate.
|
||||
|
||||
```ts
|
||||
ow(1, ow.number.not.infinite);
|
||||
|
||||
ow('', ow.string.not.empty);
|
||||
//=> ArgumentError: Expected string to not be empty, got ``
|
||||
```
|
||||
|
||||
#### is(fn)
|
||||
|
||||
Use a custom validation function. Return `true` if the value matches the validation, return `false` if it doesn't.
|
||||
|
||||
```ts
|
||||
ow(1, ow.number.is(x => x < 10));
|
||||
|
||||
ow(1, ow.number.is(x => x > 10));
|
||||
//=> ArgumentError: Expected `1` to pass custom validation function
|
||||
```
|
||||
|
||||
Instead of returning `false`, you can also return a custom error message which results in a failure.
|
||||
|
||||
```ts
|
||||
const greaterThan = (max: number, x: number) => {
|
||||
return x > max || `Expected \`${x}\` to be greater than \`${max}\``;
|
||||
};
|
||||
|
||||
ow(5, ow.number.is(x => greaterThan(10, x)));
|
||||
//=> ArgumentError: Expected `5` to be greater than `10`
|
||||
```
|
||||
|
||||
#### validate(fn)
|
||||
|
||||
Use a custom validation object. The difference with `is` is that the function should return a validation object, which allows more flexibility.
|
||||
|
||||
```ts
|
||||
ow(1, ow.number.validate(value => ({
|
||||
validator: value > 10,
|
||||
message: `Expected value to be greater than 10, got ${value}`
|
||||
})));
|
||||
//=> ArgumentError: (number) Expected value to be greater than 10, got 1
|
||||
```
|
||||
|
||||
You can also pass in a function as `message` value which accepts the label as argument.
|
||||
|
||||
```ts
|
||||
ow(1, 'input', ow.number.validate(value => ({
|
||||
validator: value > 10,
|
||||
message: label => `Expected ${label} to be greater than 10, got ${value}`
|
||||
})));
|
||||
//=> ArgumentError: Expected number `input` to be greater than 10, got 1
|
||||
```
|
||||
|
||||
#### message(string | fn)
|
||||
|
||||
Provide a custom message:
|
||||
|
||||
```ts
|
||||
ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
|
||||
//=> ArgumentError: Expected unicorn, got rainbow
|
||||
```
|
||||
|
||||
You can also pass in a function which receives the value as the first parameter and the label as the second parameter and is expected to return the message.
|
||||
|
||||
```ts
|
||||
ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
|
||||
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`
|
||||
```
|
||||
|
||||
It's also possible to add a separate message per validation:
|
||||
|
||||
```ts
|
||||
ow(
|
||||
'1234',
|
||||
ow.string
|
||||
.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
|
||||
.url.message('This is no url')
|
||||
);
|
||||
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `1234`
|
||||
|
||||
ow(
|
||||
'12345',
|
||||
ow.string
|
||||
.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
|
||||
.url.message('This is no url')
|
||||
);
|
||||
//=> ArgumentError: This is no url
|
||||
```
|
||||
|
||||
This can be useful for creating your own reusable validators which can be extracted to a separate npm package.
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Sam Verschueren](https://github.com/SamVerschueren)
|
||||
|
||||
## Related
|
||||
|
||||
- [@sindresorhus/is](https://github.com/sindresorhus/is) - Type check values
|
||||
- [ngx-ow](https://github.com/SamVerschueren/ngx-ow) - Angular form validation on steroids
|
||||
Reference in New Issue
Block a user