"use strict"; const isArguments = require("is-arguments"); const flat = require("array.prototype.flat"); const ValidationError = require("@validatem/error"); const annotateErrors = require("@validatem/annotate-errors"); const applyValidators = require("../apply-validators"); const createValidationMethod = require("./validation-method"); // TODO: Simplify below by treating it like an array or object? Or would that introduce too much complexity through specialcasing? // TODO: Find a way to produce validatem-style errors for the below invocation errors, without introducing recursion module.exports = createValidationMethod((args, argumentDefinitions) => { if (!isArguments(args)) { throw new Error(`First argument is not an 'arguments' object; maybe you forgot to put it before the validation rules?`); } else if (argumentDefinitions == null) { throw new Error(`Validation rules (second argument) are missing; maybe you forgot to specify them?`); } else if (args.length > argumentDefinitions.length) { return { errors: [ new ValidationError(`Got ${args.length} arguments, but only expected ${argumentDefinitions.length}`) ], // Cast the below to an array, for consistency with *success* output, in case we ever want to expose the new values to the user in an error case too. newValue: Array.from(args) }; } else { let results = argumentDefinitions.map((definition, i) => { let argument = args[i]; let [ argumentName, ...argumentRules ] = definition; if (typeof argumentName !== "string") { throw new Error("First item in the argument rules list must be the argument name"); } else { let validatorResult = applyValidators(argument, argumentRules); return { errors: annotateErrors({ pathSegments: [ argumentName ], errors: validatorResult.errors }), newValue: (validatorResult.newValue !== undefined) ? validatorResult.newValue : argument }; } }); let combinedErrors = results.map((result) => result.errors); let flattenedErrors = flat(combinedErrors); let newValues = results.map((result) => result.newValue); return { errors: flattenedErrors, newValue: newValues }; } });