"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchema = validateSchema; var _Either = require("fp-ts/lib/Either"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ /** * Validates the event according to the schema validator generated by {@link convertSchemaToIoTs}. * @throws Error when the event does not comply with the schema. * @param validator The io-ts validator for the event. * @param payload The payload to validate. */ function validateSchema(sourceName, validator, payload) { // Run io-ts validation to the event const result = validator.decode(payload); _Either.either.mapLeft(result, validationErrors => { const humanFriendlyErrors = validationErrors.map(err => { var _err$message; return `[${getFullPathKey(err.context)}]: ${(_err$message = err.message) !== null && _err$message !== void 0 ? _err$message : readableContext(err.context)}`; }).filter((errMsg, idx, listOfErrMsgs) => listOfErrMsgs.indexOf(errMsg, idx + 1) === -1); throw new Error(`Failed to validate payload coming from "${sourceName}":\n\t- ${humanFriendlyErrors.join('\n\t- ')}`); }); } /** * Picks the relevant fields of the validation error's context * @param context The {@link Context} coming from the validation error */ function readableContext(context) { // The information provided, the last context is good enough. // Otherwise, repeating the values for every nested key is too noisy. const last = context[context.length - 1]; return JSON.stringify({ expected: last.type.name, // Explicitly printing `undefined` to make it more obvious in the message actual: typeof last.actual, value: last.actual === undefined ? 'undefined' : last.actual }); } /** * Prints the full path to the key that raised the validation error. * @param context The {@link Context} coming from the validation error */ function getFullPathKey(context) { return context // Remove the context provided by InterfaceType and PartialType because their keys are simply numeric indices .filter(ctx => !['InterfaceType', 'PartialType'].includes(ctx.type._tag)).map(({ key }) => key).filter(Boolean).join('.'); }