guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
59 lines (58 loc) • 3.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateArray = void 0;
const stringify_1 = require("../stringify");
const createValidationResult_1 = require("./createValidationResult");
const createValidationError_1 = require("./createValidationError");
const createTreeNode_1 = require("./createTreeNode");
const combineResults_1 = require("./combineResults");
const validateObject_1 = require("./validateObject");
const getExpectedTypeName_1 = require("./getExpectedTypeName");
const typeGuardMeta_1 = require("./typeGuardMeta");
/**
* Validate an array and collect per-index validation errors.
*/
const validateArray = (value, itemGuard, context) => {
const propertyPath = context.path;
if (!Array.isArray(value)) {
const error = (0, createValidationError_1.createValidationError)(propertyPath, 'Array', value, `Expected ${propertyPath} (${JSON.stringify(value)}) to be "Array"`);
const treeNode = (0, createTreeNode_1.createTreeNode)(propertyPath, false, 'Array', value);
treeNode.errors = [error];
return (0, createValidationResult_1.createValidationResult)(false, [error], treeNode);
}
const itemSchema = (0, typeGuardMeta_1.getTypeGuardSchema)(itemGuard);
const results = value.map((item, index) => {
const itemPath = `${propertyPath}[${index}]`;
const itemContext = {
path: itemPath,
config: context.config || null,
};
if (itemSchema) {
return (0, validateObject_1.validateObject)(item, itemSchema, itemContext);
}
const isValid = itemGuard(item, null);
const expectedType = (0, getExpectedTypeName_1.getExpectedTypeName)(itemGuard);
const valueString = (0, stringify_1.stringify)(item);
if (isValid) {
return (0, createValidationResult_1.createValidationResult)(true, [], (0, createTreeNode_1.createTreeNode)(itemPath, true, expectedType, item));
}
const message = valueString.length > 200
? `Expected ${itemPath} to be "${expectedType}"`
: `Expected ${itemPath} (${valueString}) to be "${expectedType}"`;
const error = (0, createValidationError_1.createValidationError)(itemPath, expectedType, item, message);
const treeNode = (0, createTreeNode_1.createTreeNode)(itemPath, false, expectedType, item);
treeNode.errors = [error];
return (0, createValidationResult_1.createValidationResult)(false, [error], treeNode);
});
const combined = (0, combineResults_1.combineResults)(results, propertyPath);
const rootTree = (0, createTreeNode_1.createTreeNode)(propertyPath, combined.valid, 'Array', value);
rootTree.children = {};
results.forEach((result) => {
if (result.tree) {
const key = result.tree.path.match(/\[(\d+)\]$/)?.[1] ?? 'unknown';
rootTree.children[key] = result.tree;
}
});
return (0, createValidationResult_1.createValidationResult)(combined.valid, combined.errors, rootTree);
};
exports.validateArray = validateArray;