"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateWithError = exports.parseSchema = exports.URL_SCHEMA = void 0;
const yup_1 = require("yup");
const BadRequestHttpError_1 = require("../../util/errors/BadRequestHttpError");
const ErrorUtil_1 = require("../../util/errors/ErrorUtil");
const StringUtil_1 = require("../../util/StringUtil");
// The builtin `url` validator of `yup` does not support localhost URLs, so we create a custom one here.
// The reason for having a URL validator on the WebID is to prevent us from generating invalid ACL,
// which would break the pod creation causing us to have an incomplete pod.
exports.URL_SCHEMA = (0, yup_1.string)().trim().optional().test({
    name: 'url',
    message: (value) => `"${value.value}" is not a valid URL`,
    test(value) {
        if (!value) {
            return true;
        }
        return (0, StringUtil_1.isUrl)(value);
    },
});
function isObjectSchema(schema) {
    return schema.type === 'object';
}
/**
 * Recursive function used when generating yup schema representations.
 */
function parseSchemaDescription(schema) {
    const result = { required: !schema.spec.optional, type: schema.type };
    if (isObjectSchema(schema)) {
        result.fields = {};
        for (const [field, description] of Object.entries(schema.fields)) {
            // We never use references so this cast is fine
            result.fields[field] = parseSchemaDescription(description);
        }
    }
    return result;
}
/**
 * Generates a simplified representation of a yup schema.
 */
function parseSchema(schema) {
    const result = parseSchemaDescription(schema);
    return { fields: result.fields };
}
exports.parseSchema = parseSchema;
/**
 * Same functionality as the yup validate function, but throws a {@link BadRequestHttpError} if there is an error.
 */
async function validateWithError(schema, data, options) {
    try {
        // eslint-disable-next-line ts/no-unsafe-return
        return await schema.validate(data, options);
    }
    catch (error) {
        throw new BadRequestHttpError_1.BadRequestHttpError((0, ErrorUtil_1.createErrorMessage)(error));
    }
}
exports.validateWithError = validateWithError;
//# sourceMappingURL=YupUtil.js.map