"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getArkiverSubgraph = exports.createClient = void 0;
var cross_fetch_1 = __importDefault(require("cross-fetch"));
var client_1 = require("@apollo/client");
var ws_1 = require("@apollo/client/link/ws");
var utilities_1 = require("@apollo/client/utilities");
var retry_1 = require("@apollo/client/link/retry");
var urlForProtocol_1 = require("./urlForProtocol");
function createClient(options) {
    if (options === void 0) { options = {}; }
    var cache = options.cache || new client_1.InMemoryCache({});
    if (typeof window !== 'undefined') {
        // @ts-ignore
        cache.restore(window.__APOLLO_STATE__);
    }
    var link = getLinks();
    return new client_1.ApolloClient({
        connectToDevTools: true,
        cache: cache,
        link: link,
    });
}
exports.createClient = createClient;
// set default here for deployment to prod
var _a = process.env, _b = _a.PUBLIC_API, PUBLIC_API = _b === void 0 ? '' : _b, _c = _a.PUBLIC_SUBGRAPH_SUFFIX, PUBLIC_SUBGRAPH_SUFFIX = _c === void 0 ? '' : _c, PUBLIC_SUBGRAPH = _a.PUBLIC_SUBGRAPH, _d = _a.PUBLIC_FORK_CHAIN, PUBLIC_FORK_CHAIN = _d === void 0 ? 'mainnet' : _d, _e = _a.PUBLIC_ARKIVER_API_KEY, PUBLIC_ARKIVER_API_KEY = _e === void 0 ? '' : _e;
var getSectorSubgraphUrl = function (chain) {
    var subgraphName = chain;
    switch (subgraphName) {
        case 'localhost':
            if (PUBLIC_SUBGRAPH === 'localhost') {
                return "http://localhost:8000/subgraphs/name/sector-fi/sector-".concat(PUBLIC_SUBGRAPH);
            }
            else {
                return "https://api.thegraph.com/subgraphs/name/sector-fi/sector-".concat(PUBLIC_FORK_CHAIN).concat(PUBLIC_SUBGRAPH_SUFFIX);
            }
        default:
            return "https://api.thegraph.com/subgraphs/name/sector-fi/sector-".concat(subgraphName).concat(PUBLIC_SUBGRAPH_SUFFIX);
    }
};
var getScionRewardsSubgraphUrl = function (chain) {
    return "https://api.thegraph.com/subgraphs/name/sector-fi/scion-rewards-".concat(chain);
};
var getSubgraphHealthUrl = function () {
    return "https://api.thegraph.com/index-node/graphql";
};
var getServerUrl = function () {
    return PUBLIC_API + '/graphql';
};
var getArrakisSubgraph = function (chain) {
    var prefix = "https://api.thegraph.com/subgraphs/name/arrakisfinance/arrakis-vault-v2";
    if (chain === 'mainnet')
        return prefix;
    return "".concat(prefix, "-").concat(chain);
};
var getArkiverSubgraph = function (vaultType) {
    switch (vaultType) {
        case 'arrakis':
            return "https://data.staging.arkiver.net/robolabs/arrakis-vaults-stga/graphql?apiKey=".concat(PUBLIC_ARKIVER_API_KEY);
        case 'defiedge':
            return "https://data.staging.arkiver.net/robolabs/defiedge-vaults/graphql?apiKey=".concat(PUBLIC_ARKIVER_API_KEY);
        default:
            return "https://data.staging.arkiver.net/robolabs/arrakis-vaults-stga/graphql?apiKey=".concat(PUBLIC_ARKIVER_API_KEY);
    }
};
exports.getArkiverSubgraph = getArkiverSubgraph;
function getLinks() {
    var uri = '';
    var setUri = new client_1.ApolloLink(function (op, forward) {
        var _a = op.getContext(), chain = _a.chain, health = _a.health, server = _a.server, scionRewards = _a.scionRewards, uniV2Dex = _a.uniV2Dex, uniV3Dex = _a.uniV3Dex, arrakis = _a.arrakis, arkiver = _a.arkiver;
        var uri = uniV3Dex
            ? (0, urlForProtocol_1.urlForProtocol)(uniV3Dex)
            : uniV2Dex
                ? (0, urlForProtocol_1.urlForUniv2)(uniV2Dex)
                : health // This means subgraph health, not server health.
                    ? getSubgraphHealthUrl()
                    : server
                        ? getServerUrl()
                        : scionRewards
                            ? getScionRewardsSubgraphUrl(chain)
                            : arrakis
                                ? getArrakisSubgraph(chain)
                                : arkiver
                                    ? (0, exports.getArkiverSubgraph)(arkiver)
                                    : getSectorSubgraphUrl(chain);
        op.setContext({ uri: uri });
        return forward(op);
    });
    var httpLink = new client_1.HttpLink({ uri: "".concat(uri), fetch: cross_fetch_1.default });
    var wsLink = getWsLink(uri);
    if (!wsLink)
        return (0, client_1.from)([setUri, httpLink]);
    return new retry_1.RetryLink({
        delay: {
            // Starting with initialDelay, the delay of each subsequent retry is increased exponentially,
            // meaning it's multiplied by 2 each time. For example, if initialDelay is 100, additional
            // retries will occur after delays of 200, 400, 800, etc.
            initial: 500,
            max: Infinity,
            jitter: true,
        },
        attempts: {
            max: 3,
        },
    }).split(
    // split based on operation type
    function (_a) {
        var query = _a.query;
        var definition = (0, utilities_1.getMainDefinition)(query);
        return (definition.kind === 'OperationDefinition' &&
            definition.operation === 'subscription');
    }, (0, client_1.from)([setUri, wsLink]), (0, client_1.from)([setUri, httpLink]));
}
function getWsLink(uri) {
    try {
        var wsUri = uri.replace('http', 'ws');
        var wsLink = new ws_1.WebSocketLink({
            uri: "".concat(wsUri),
            options: {
                reconnect: true,
                reconnectionAttempts: 50,
                lazy: true,
                timeout: 20000,
            },
        });
        return wsLink;
    }
    catch (err) {
        return null;
    }
}
//# sourceMappingURL=apolloClient.js.map