"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isExecutionPatchIncrementalResult = isExecutionPatchIncrementalResult;
exports.isExecutionPatchInitialResult = isExecutionPatchInitialResult;
exports.isExecutionPatchResult = isExecutionPatchResult;
exports.isApolloPayloadResult = isApolloPayloadResult;
exports.mergeIncrementalData = mergeIncrementalData;
const arrays_js_1 = require("./arrays.cjs");
const mergeDeep_js_1 = require("./mergeDeep.cjs");
const objects_js_1 = require("./objects.cjs");
function isExecutionPatchIncrementalResult(value) {
    return "incremental" in value;
}
function isExecutionPatchInitialResult(value) {
    return "hasNext" in value && "data" in value;
}
function isExecutionPatchResult(value) {
    return (isExecutionPatchIncrementalResult(value) ||
        isExecutionPatchInitialResult(value));
}
// This function detects an Apollo payload result before it is transformed
// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult
// once it leaves the link chain.
function isApolloPayloadResult(value) {
    return (0, objects_js_1.isNonNullObject)(value) && "payload" in value;
}
function mergeIncrementalData(prevResult, result) {
    let mergedData = prevResult;
    const merger = new mergeDeep_js_1.DeepMerger();
    if (isExecutionPatchIncrementalResult(result) &&
        (0, arrays_js_1.isNonEmptyArray)(result.incremental)) {
        result.incremental.forEach(({ data, path }) => {
            for (let i = path.length - 1; i >= 0; --i) {
                const key = path[i];
                const isNumericKey = !isNaN(+key);
                const parent = isNumericKey ? [] : {};
                parent[key] = data;
                data = parent;
            }
            mergedData = merger.merge(mergedData, data);
        });
    }
    return mergedData;
}
//# sourceMappingURL=incrementalResult.cjs.map
