"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFragment = useFragment;
const tslib_1 = require("tslib");
const equality_1 = tslib_1.__importDefault(require("@wry/equality"));
const React = tslib_1.__importStar(require("react"));
const index_js_1 = require("./internal/index.cjs");
const useApolloClient_js_1 = require("./useApolloClient.cjs");
const useSyncExternalStore_js_1 = require("./useSyncExternalStore.cjs");
function useFragment(options) {
    return (0, index_js_1.wrapHook)("useFragment", 
    // eslint-disable-next-line react-compiler/react-compiler
    useFragment_, (0, useApolloClient_js_1.useApolloClient)(options.client))(options);
}
function useFragment_(options) {
    const client = (0, useApolloClient_js_1.useApolloClient)(options.client);
    const { cache } = client;
    const { from, ...rest } = options;
    // We calculate the cache id seperately from `stableOptions` because we don't
    // want changes to non key fields in the `from` property to affect
    // `stableOptions` and retrigger our subscription. If the cache identifier
    // stays the same between renders, we want to reuse the existing subscription.
    const id = React.useMemo(() => typeof from === "string" ? from
        : from === null ? null
            : cache.identify(from), [cache, from]);
    const stableOptions = (0, index_js_1.useDeepMemo)(() => ({ ...rest, from: id }), [rest, id]);
    // Since .next is async, we need to make sure that we
    // get the correct diff on the next render given new diffOptions
    const diff = React.useMemo(() => {
        const { fragment, fragmentName, from, optimistic = true } = stableOptions;
        if (from === null) {
            return {
                result: diffToResult({
                    result: {},
                    complete: false,
                }),
            };
        }
        const { cache } = client;
        const diff = cache.diff({
            ...stableOptions,
            returnPartialData: true,
            id: from,
            query: cache["getFragmentDoc"](fragment, fragmentName),
            optimistic,
        });
        return {
            result: diffToResult({
                ...diff,
                result: client["queryManager"].maskFragment({
                    fragment,
                    fragmentName,
                    // TODO: Revert to `diff.result` once `useFragment` supports `null` as
                    // valid return value
                    data: diff.result === null ? {} : diff.result,
                }),
            } // TODO: Remove assertion
            ),
        };
    }, [client, stableOptions]);
    // Used for both getSnapshot and getServerSnapshot
    const getSnapshot = React.useCallback(() => diff.result, [diff]);
    return (0, useSyncExternalStore_js_1.useSyncExternalStore)(React.useCallback((forceUpdate) => {
        let lastTimeout = 0;
        const subscription = stableOptions.from === null ?
            null
            : client.watchFragment(stableOptions).subscribe({
                next: (result) => {
                    // Since `next` is called async by zen-observable, we want to avoid
                    // unnecessarily rerendering this hook for the initial result
                    // emitted from watchFragment which should be equal to
                    // `diff.result`.
                    if ((0, equality_1.default)(result, diff.result))
                        return;
                    diff.result = result;
                    // If we get another update before we've re-rendered, bail out of
                    // the update and try again. This ensures that the relative timing
                    // between useQuery and useFragment stays roughly the same as
                    // fixed in https://github.com/apollographql/apollo-client/pull/11083
                    clearTimeout(lastTimeout);
                    lastTimeout = setTimeout(forceUpdate);
                },
            });
        return () => {
            subscription?.unsubscribe();
            clearTimeout(lastTimeout);
        };
    }, [client, stableOptions, diff]), getSnapshot, getSnapshot);
}
function diffToResult(diff) {
    const result = {
        data: diff.result,
        complete: !!diff.complete,
    }; // TODO: Remove assertion once useFragment returns null
    if (diff.missing) {
        result.missing = diff.missing.missing;
    }
    return result;
}
//# sourceMappingURL=useFragment.cjs.map
