import equal from "@wry/equality";
import { Kind } from "graphql";
import { createFragmentMap, getFragmentDefinitions, } from "@apollo/client/utilities";
import { __DEV__ } from "@apollo/client/utilities/environment";
import { invariant } from "@apollo/client/utilities/invariant";
import { maskDefinition } from "./maskDefinition.js";
import { warnOnImproperCacheImplementation } from "./utils.js";
/** @internal */
export function maskFragment(data, document, cache, fragmentName) {
    if (!cache.fragmentMatches) {
        if (__DEV__) {
            warnOnImproperCacheImplementation();
        }
        return data;
    }
    const fragments = document.definitions.filter((node) => node.kind === Kind.FRAGMENT_DEFINITION);
    if (typeof fragmentName === "undefined") {
        invariant(fragments.length === 1, 45, fragments.length);
        fragmentName = fragments[0].name.value;
    }
    const fragment = fragments.find((fragment) => fragment.name.value === fragmentName);
    invariant(!!fragment, 46, fragmentName);
    if (data == null) {
        // Maintain the original `null` or `undefined` value
        return data;
    }
    if (equal(data, {})) {
        // Return early and skip the masking algorithm if we don't have any data
        // yet. This can happen when cache.diff returns an empty object which is
        // used from watchFragment.
        return data;
    }
    return maskDefinition(data, fragment.selectionSet, {
        operationType: "fragment",
        operationName: fragment.name.value,
        fragmentMap: createFragmentMap(getFragmentDefinitions(document)),
        cache,
        mutableTargets: new WeakMap(),
        knownChanged: new WeakSet(),
    });
}
//# sourceMappingURL=maskFragment.js.map
