UNPKG

shapeit

Version:

Object validation tools for Javascript and, specially, Typescript

1,176 lines (1,175 loc) 40.3 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); const config = { errorMessage: (typename) => `Invalid type provided. Expected: '${typename}'`, sizeErrorMessage: (size) => `Invalid size provided. Expected: ${size}`, showWarnings: true }; const defaults = __spreadValues({}, config); function set(key, value) { if (value === "default") { return config[key] = defaults[key]; } return config[key] = value; } function get(key) { return config[key]; } var index = /* @__PURE__ */ Object.freeze({ __proto__: null, [Symbol.toStringTag]: "Module", set, get }); const errorMessage = (typename) => get("errorMessage")(typename); const sizeErrorMessage = (size) => get("sizeErrorMessage")(size); function makeErrors(raw) { const all = Object.entries(raw).flatMap(([path, messages]) => { return (messages == null ? void 0 : messages.map((message) => ({ path, message }))) || []; }); const clone = __spreadValues({}, raw); Object.defineProperty(clone, "all", { value: all, configurable: false, enumerable: false, writable: false }); return clone; } function assert(cond, msg) { if (!cond) throw new AssertionError(msg); } class AssertionError extends Error { } async function validate(input, ...rules) { const errors = {}; if (!rules.length) { throw new Error("No rule specified"); } const rulesSet = rules.length > 1 ? rules : rules[0]; await applyRulesRecursively(input, rulesSet, "$", errors); return Object.keys(errors).length ? { valid: false, errors: makeErrors(errors) } : { valid: true, errors: null }; } async function applyRulesRecursively(input, rules, path, errors) { if (typeof rules === "function") { const isValid = rules; try { await isValid(input, assert); } catch (err) { if (!(err instanceof AssertionError)) throw err; (errors[path] || (errors[path] = [])).push(err.message); } } else { let promises = []; if (Array.isArray(rules)) { promises = rules.map((rule) => applyRulesRecursively(input, rule, path, errors)); } else if (Array.isArray(input) && "$each" in rules) { promises = input.map((v, i) => applyRulesRecursively(v, rules.$each, `${path}.${i}`, errors)); } else if (typeof input === "object" && input !== null) { const keys = Object.keys(rules); promises = keys.filter((key) => key in input).map((key) => applyRulesRecursively(input[key], rules[key], `${path}.${key}`, errors)); } await Promise.all(promises); } } function guard(name, validator) { let rawErrors = null; let errors = null; let overrideAllowed = false; let override = false; const isValid = Object.defineProperties((input) => { overrideAllowed = true; override = false; const result = validator(input); overrideAllowed = false; if (!override) { rawErrors = result ? null : { $: [errorMessage(name)] }; } if (get("showWarnings")) { if (override && result && rawErrors) { console.warn(`[Shapeit Warning] custom guard ${name} error was set when input was valid`); } else if (override && !result && !rawErrors) { console.warn(`[Shapeit Warning] custom guard ${name} error was set to null when input was not valid`); } } errors = rawErrors ? makeErrors(rawErrors) : null; return result; }, { errors: { get() { return errors; }, set(err) { if (!overrideAllowed) { if (get("showWarnings")) { console.warn("[Shapeit warning] guard errors override outside validator detected"); } return; } rawErrors = err; override = true; } }, typename: { value: name, configurable: false, enumerable: true, writable: false }, validate: { value: (...rules) => { return async (target) => { if (!isValid(target)) { return { typed: false, valid: false, errors: isValid.errors, target }; } const r = await validate(target, ...rules); return __spreadProps(__spreadValues({ typed: true }, r), { target }); }; }, configurable: false, enumerable: true, writable: false } }); return isValid; } const custom = guard; function isShapeGuard(guard2) { return typeof guard2 === "function" && "_shape" in guard2; } function isPlainRecord(input) { return typeof input === "object" && input !== null && !Array.isArray(input) && !Object.getOwnPropertySymbols(input).length; } function resolveGuard(guardOrPrimitive) { if (typeof guardOrPrimitive === "string") { return is(guardOrPrimitive); } return guardOrPrimitive; } function arrayOf(type, maxLength = Infinity) { const guard$1 = resolveGuard(type); if (maxLength <= 0) { throw new Error("maxLength should be greater than 0"); } const isValid = guard("array", (input) => { if (!Array.isArray(input)) { return false; } if (input.length > maxLength) { isValid.errors = { $: [sizeErrorMessage(`<= ${maxLength}`)] }; return false; } let result = true; const errors = {}; for (let i = 0; i < input.length; ++i) { const current = guard$1(input[i]); result = result && current; if (guard$1.errors) { for (const { path: subpath, message } of guard$1.errors.all) { const root = `$.${i}`; const path = subpath.replace("$", root); (errors[path] || (errors[path] = [])).push(message); } } } isValid.errors = result ? null : errors; return result; }); return isValid; } function oneOf(...types) { if (!types.length) { throw new Error("No guards provided"); } const guards = types.map(resolveGuard); const isValid = guard("one-of", (input) => { const result = guards.some((guard2) => guard2(input)); if (!result) { const errors = {}; for (const guard2 of guards) { for (const { path, message } of guard2.errors.all) { (errors[path] || (errors[path] = [])).push(message); } } isValid.errors = errors; } return result; }); return isValid; } function shape(schema, strict = true) { const guardsMap = Object.entries(schema).reduce((res, [key, val]) => { res[key] = resolveGuard(val); return res; }, {}); const keys = Object.keys(schema); const isValid = Object.assign(guard("object", (input) => { if (!isPlainRecord(input)) { return false; } let result = true; let errors = {}; if (strict) { const extraneousKeys = Object.keys(omit$1(input, keys)); if (extraneousKeys.length) { errors = extraneousKeys.reduce((res, key) => { res[`$.${key}`] = [errorMessage("undefined")]; return res; }, {}); result = false; } } const entries = keys.map((key) => { const root = `$.${key}`; return [root, guardsMap[key], input[key]]; }); for (const [root, guard2, value] of entries) { const current = guard2(value); result = result && current; if (guard2.errors) { for (const { path: subpath, message } of guard2.errors.all) { const path = subpath.replace("$", root); (errors[path] || (errors[path] = [])).push(message); } } } isValid.errors = result ? null : errors; return result; }), { _shape: { schema, strict } }); return isValid; } function omit$1(obj, keys) { const clone = __spreadValues({}, obj); for (const key of keys) delete clone[key]; return clone; } function deepPartial(guard2) { const { schema: baseSchema, strict } = guard2._shape; const schema = Object.entries(baseSchema).reduce((res, [key, val]) => { if (isShapeGuard(val)) { res[key] = oneOf(deepPartial(val), "undefined"); } else res[key] = oneOf(val, "undefined"); return res; }, {}); return shape(schema, strict); } function is(target) { const isValid = guard(target, (input) => { const type = input === null ? "null" : typeof input; return type === target; }); return isValid; } function maybe(guard2) { return oneOf(guard2, "undefined"); } function nullable(guard2) { return oneOf(guard2, "null"); } function partial(guard2) { const { schema: baseSchema, strict } = guard2._shape; const schema = Object.entries(baseSchema).reduce((res, [key, val]) => { res[key] = oneOf(val, "undefined"); return res; }, {}); return shape(schema, strict); } function tuple(...types) { const guards = types.map(resolveGuard); const isValid = guard("tuple", (input) => { if (!Array.isArray(input)) { return false; } if (input.length !== guards.length) { isValid.errors = { $: [sizeErrorMessage(guards.length)] }; return false; } const errors = {}; let result = true; for (let i = 0; i < input.length; ++i) { const guard2 = guards[i]; const current = guard2(input[i]); result = result && current; if (guard2.errors) { for (const { path: subpath, message } of guard2.errors.all) { const root = `$.${i}`; const path = subpath.replace("$", root); (errors[path] || (errors[path] = [])).push(message); } } } isValid.errors = result ? null : errors; return result; }); return isValid; } var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; var lodash_isequal = { exports: {} }; (function(module, exports) { var LARGE_ARRAY_SIZE = 200; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; var MAX_SAFE_INTEGER = 9007199254740991; var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]"; var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var reIsUint = /^(?:0|[1-9]\d*)$/; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); var freeExports = exports && !exports.nodeType && exports; var freeModule = freeExports && true && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var freeProcess = moduleExports && freeGlobal.process; var nodeUtil = function() { try { return freeProcess && freeProcess.binding && freeProcess.binding("util"); } catch (e) { } }(); var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; function arrayFilter(array, predicate) { var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index2 < length) { var value = array[index2]; if (predicate(value, index2, array)) { result[resIndex++] = value; } } return result; } function arrayPush(array, values) { var index2 = -1, length = values.length, offset = array.length; while (++index2 < length) { array[offset + index2] = values[index2]; } return array; } function arraySome(array, predicate) { var index2 = -1, length = array == null ? 0 : array.length; while (++index2 < length) { if (predicate(array[index2], index2, array)) { return true; } } return false; } function baseTimes(n, iteratee) { var index2 = -1, result = Array(n); while (++index2 < n) { result[index2] = iteratee(index2); } return result; } function baseUnary(func) { return function(value) { return func(value); }; } function cacheHas(cache, key) { return cache.has(key); } function getValue(object, key) { return object == null ? void 0 : object[key]; } function mapToArray(map) { var index2 = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index2] = [key, value]; }); return result; } function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } function setToArray(set2) { var index2 = -1, result = Array(set2.size); set2.forEach(function(value) { result[++index2] = value; }); return result; } var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; var coreJsData = root["__core-js_shared__"]; var funcToString = funcProto.toString; var hasOwnProperty = objectProto.hasOwnProperty; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); var nativeObjectToString = objectProto.toString; var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); var Buffer2 = moduleExports ? root.Buffer : void 0, Symbol2 = root.Symbol, Uint8Array2 = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, nativeKeys = overArg(Object.keys, Object); var DataView = getNative(root, "DataView"), Map = getNative(root, "Map"), Promise2 = getNative(root, "Promise"), Set2 = getNative(root, "Set"), WeakMap = getNative(root, "WeakMap"), nativeCreate = getNative(Object, "create"); var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap); var symbolProto = Symbol2 ? Symbol2.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; function Hash(entries) { var index2 = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? void 0 : result; } return hasOwnProperty.call(data, key) ? data[key] : void 0; } function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); } function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; return this; } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function ListCache(entries) { var index2 = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function listCacheClear() { this.__data__ = []; this.size = 0; } function listCacheDelete(key) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { return false; } var lastIndex = data.length - 1; if (index2 == lastIndex) { data.pop(); } else { splice.call(data, index2, 1); } --this.size; return true; } function listCacheGet(key) { var data = this.__data__, index2 = assocIndexOf(data, key); return index2 < 0 ? void 0 : data[index2][1]; } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } function listCacheSet(key, value) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { ++this.size; data.push([key, value]); } else { data[index2][1] = value; } return this; } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; function MapCache(entries) { var index2 = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } function mapCacheClear() { this.size = 0; this.__data__ = { "hash": new Hash(), "map": new (Map || ListCache)(), "string": new Hash() }; } function mapCacheDelete(key) { var result = getMapData(this, key)["delete"](key); this.size -= result ? 1 : 0; return result; } function mapCacheGet(key) { return getMapData(this, key).get(key); } function mapCacheHas(key) { return getMapData(this, key).has(key); } function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; function SetCache(values) { var index2 = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache(); while (++index2 < length) { this.add(values[index2]); } } function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } function setCacheHas(value) { return this.__data__.has(value); } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } function stackClear() { this.__data__ = new ListCache(); this.size = 0; } function stackDelete(key) { var data = this.__data__, result = data["delete"](key); this.size = data.size; return result; } function stackGet(key) { return this.__data__.get(key); } function stackHas(key) { return this.__data__.has(key); } function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } Stack.prototype.clear = stackClear; Stack.prototype["delete"] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { result.push(key); } } return result; } function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } function baseGetTag(value) { if (value == null) { return value === void 0 ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != "constructor") { result.push(key); } } return result; } function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index2 = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; stack.set(array, other); stack.set(other, array); while (++index2 < arrLength) { var arrValue = array[index2], othValue = other[index2]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack); } if (compared !== void 0) { if (compared) { continue; } result = false; break; } if (seen) { if (!arraySome(other, function(othValue2, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack["delete"](array); stack["delete"](other); return result; } function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: return object == other + ""; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack["delete"](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index2 = objLength; while (index2--) { var key = objProps[index2]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index2 < objLength) { key = objProps[index2]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key == "constructor"); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { result = false; } } stack["delete"](object); stack["delete"](other); return result; } function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : void 0; } function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = void 0; var unmasked = true; } catch (e) { } var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; var getTag = baseGetTag; if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; return value === proto; } function objectToString(value) { return nativeObjectToString.call(value); } function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) { } try { return func + ""; } catch (e) { } } return ""; } function eq(value, other) { return value === other || value !== value && other !== other; } var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); }; var isArray = Array.isArray; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } var isBuffer = nativeIsBuffer || stubFalse; function isEqual2(value, other) { return baseIsEqual(value, other); } function isFunction(value) { if (!isObject(value)) { return false; } var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } function isObjectLike(value) { return value != null && typeof value == "object"; } var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } function stubArray() { return []; } function stubFalse() { return false; } module.exports = isEqual2; })(lodash_isequal, lodash_isequal.exports); var isEqual = lodash_isequal.exports; function narrow(...targets) { targets = targets.filter((t) => typeof t !== "function"); if (!targets.length) { throw new Error("No valid narrowable objects provided"); } if (targets.length === 1) { const target = targets[0]; const typename = genType(target); const isValid = guard(typename, (input) => isEqual(input, target)); return isValid; } const narrows = targets.map((t) => narrow(t)); return oneOf(...narrows); } function genType(target) { var _a; const type = typeOf(target); if (type !== "object") { if (["null", "undefined"].includes(type)) return type; if (type === "symbol") return `Symbol(${target.description})`; if (type === "string") return `[string] ${JSON.stringify(target)}`; return `[${type}] ${target}`; } const constructor = ((_a = Object.getPrototypeOf(target)) == null ? void 0 : _a.constructor.name) || "Object: null prototype"; const content = Object.entries(target).map(([key, value]) => `${JSON.stringify(key)}: ${genType(value)}`).join(", "); return `[${constructor}] {${content}}`; } function typeOf(target) { var _a; const type = target === null ? "null" : typeof target; if (type === "object") { const constructor = (_a = Object.getPrototypeOf(target)) == null ? void 0 : _a.constructor; if (constructor === Number) { return "number"; } if (constructor === String) { return "string"; } } return type; } const regexMap = { string: ".*", number: "(?:\\d+\\.\\d*|\\d*\\.\\d+|\\d+)(?:[eE][+-]?\\d+)?", bigint: "\\d+", boolean: "true|false", null: "null", undefined: "undefined" }; function $(...values) { const descriptors = values.map((v) => { if (typeof v === "string") { return { regex: regexMap[v], typename: v }; } return v; }); const typename = descriptors.map((d) => d.typename).join("|").replace(/\$/g, "\\$"); const regex = "(" + descriptors.map((d) => `${d.regex}`).join("|") + ")"; return { typename, regex }; } function $$(...values) { const typename = values.map(valueToRegex).join("|"); return { regex: `(${typename})`, typename }; } function $$$(...template) { let regex = "("; let typename = "`"; for (const item of template) { if (typeof item === "string") { regex += valueToRegex(item); typename += item; } else if ("regex" in item) { regex += item.regex; typename += `\${${item.typename}}`; } } regex += ")"; typename += "`"; return { typename, regex }; } function valueToRegex(value) { if (typeof value !== "string") { value = String(value); } return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); } function literal(...template) { const descriptor = $$$(...template); const regexString = `^${descriptor.regex}$`; const { typename } = descriptor; const regex = new RegExp(regexString); const isValid = guard(typename, (input) => { return typeof input === "string" && regex.test(input); }); delete descriptor.typename; return Object.assign(isValid, descriptor); } function pick(guard2, keys) { const { schema: baseSchema, strict } = guard2._shape; const keysSet = new Set(keys); const schema = Object.entries(baseSchema).reduce((res, [key, val]) => { if (keysSet.has(key)) { res[key] = val; } return res; }, {}); return shape(schema, strict); } function omit(guard2, keys) { const { schema: baseSchema, strict } = guard2._shape; const keysSet = new Set(keys); const schema = Object.entries(baseSchema).reduce((res, [key, val]) => { if (!keysSet.has(key)) { res[key] = val; } return res; }, {}); return shape(schema, strict); } function instanceOf(constructor) { return guard(`${constructor.name} instance`, (input) => input instanceof constructor); } function any() { return guard("any", (_input) => true); } function unknown() { return guard("unknown", (_input) => true); } function never() { return guard("never", (_input) => false); } function allOf(...types) { if (!types.length) { throw new Error("No guards provided"); } const guards = types.map(resolveGuard); const isValid = guard("all-of", (input) => { var _a; let result = true; for (const guard2 of guards) { const current = guard2(input); result && (result = current); } if (!result) { const errors = {}; for (const guard2 of guards) { for (const { path, message } of ((_a = guard2.errors) == null ? void 0 : _a.all) || []) { (errors[path] || (errors[path] = [])).push(message); } } isValid.errors = errors; } return result; }); return isValid; } function looseShape(schema) { return shape(schema, false); } function strictShape(schema) { return shape(schema, true); } export { $, $$, $$$, AssertionError, allOf, any, arrayOf, assert, index as config, custom, deepPartial, guard, instanceOf, is, literal, looseShape, maybe, narrow, never, nullable, omit, oneOf, partial, pick, shape, strictShape, tuple, unknown, validate };