"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Merge the `src` event pattern into the `dest` event pattern by adding all
 * values from `src` into the fields in `dest`.
 *
 * See `rule.addEventPattern` for details.
 */
function mergeEventPattern(dest, src) {
    dest = dest || {};
    mergeObject(dest, src);
    return dest;
    function mergeObject(destObj, srcObj) {
        if (typeof (srcObj) !== 'object') {
            throw new Error(`Invalid event pattern '${JSON.stringify(srcObj)}', expecting an object or an array`);
        }
        for (const field of Object.keys(srcObj)) {
            const srcValue = srcObj[field];
            const destValue = destObj[field];
            if (typeof (srcValue) !== 'object') {
                throw new Error(`Invalid event pattern field { ${field}: ${JSON.stringify(srcValue)} }. All fields must be arrays`);
            }
            // dest doesn't have this field
            if (!(field in destObj)) {
                destObj[field] = srcValue;
                continue;
            }
            if (Array.isArray(srcValue) !== Array.isArray(destValue)) {
                throw new Error(`Invalid event pattern field ${field}. ` +
                    `Type mismatch between existing pattern ${JSON.stringify(destValue)} and added pattern ${JSON.stringify(srcValue)}`);
            }
            // if this is an array, concat the values
            if (Array.isArray(srcValue)) {
                destObj[field] = destValue.concat(srcValue);
                continue;
            }
            // otherwise, it's an object, so recurse
            mergeObject(destObj[field], srcValue);
        }
    }
}
exports.mergeEventPattern = mergeEventPattern;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInV0aWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQTs7Ozs7R0FLRztBQUNILFNBQWdCLGlCQUFpQixDQUFDLElBQVMsRUFBRSxHQUFRO0lBQ2pELElBQUksR0FBRyxJQUFJLElBQUksRUFBRyxDQUFDO0lBRW5CLFdBQVcsQ0FBQyxJQUFJLEVBQUUsR0FBRyxDQUFDLENBQUM7SUFFdkIsT0FBTyxJQUFJLENBQUM7SUFFWixTQUFTLFdBQVcsQ0FBQyxPQUFZLEVBQUUsTUFBVzt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