@apollo/client
Version:
A fully-featured caching GraphQL client.
2,672 lines • 122 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var globals = require('../utilities/globals');
var core = require('../link/core');
var http = require('../link/http');
var equal = require('@wry/equality');
var utilities = require('../utilities');
var cache = require('../cache');
var errors = require('../errors');
var trie = require('@wry/trie');
var graphql = require('graphql');
var utils = require('../link/utils');
var tsInvariant = require('ts-invariant');
var graphqlTag = require('graphql-tag');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
var equal__default = /*#__PURE__*/_interopDefaultLegacy(equal);
var version = "3.11.8";
function isNonNullObject(obj) {
return obj !== null && typeof obj === "object";
}
function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
var defaultReconciler = function (target, source, property) {
return this.merge(target[property], source[property]);
};
var DeepMerger = (function () {
function DeepMerger(reconciler) {
if (reconciler === void 0) { reconciler = defaultReconciler; }
this.reconciler = reconciler;
this.isObject = isNonNullObject;
this.pastCopies = new Set();
}
DeepMerger.prototype.merge = function (target, source) {
var _this = this;
var context = [];
for (var _i = 2; _i < arguments.length; _i++) {
context[_i - 2] = arguments[_i];
}
if (isNonNullObject(source) && isNonNullObject(target)) {
Object.keys(source).forEach(function (sourceKey) {
if (hasOwnProperty$2.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (source[sourceKey] !== targetValue) {
var result = _this.reconciler.apply(_this, tslib.__spreadArray([target,
source,
sourceKey], context, false));
if (result !== targetValue) {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = result;
}
}
}
else {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = source[sourceKey];
}
});
return target;
}
return source;
};
DeepMerger.prototype.shallowCopyForMerge = function (value) {
if (isNonNullObject(value)) {
if (!this.pastCopies.has(value)) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
this.pastCopies.add(value);
}
}
return value;
};
return DeepMerger;
}());
function isExecutionPatchIncrementalResult(value) {
return "incremental" in value;
}
function mergeIncrementalData(prevResult, result) {
var mergedData = prevResult;
var merger = new DeepMerger();
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (_a) {
var data = _a.data, path = _a.path;
for (var i = path.length - 1; i >= 0; --i) {
var key = path[i];
var isNumericKey = !isNaN(+key);
var parent_1 = isNumericKey ? [] : {};
parent_1[key] = data;
data = parent_1;
}
mergedData = merger.merge(mergedData, data);
});
}
return mergedData;
}
exports.NetworkStatus = void 0;
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(exports.NetworkStatus || (exports.NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus ? networkStatus < 7 : false;
}
function isNetworkRequestSettled(networkStatus) {
return networkStatus === 7 || networkStatus === 8;
}
function equalByQuery(query, _a, _b, variables) {
var aData = _a.data, aRest = tslib.__rest(_a, ["data"]);
var bData = _b.data, bRest = tslib.__rest(_b, ["data"]);
return (equal__default(aRest, bRest) &&
equalBySelectionSet(utilities.getMainDefinition(query).selectionSet, aData, bData, {
fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
variables: variables,
}));
}
function equalBySelectionSet(selectionSet, aResult, bResult, context) {
if (aResult === bResult) {
return true;
}
var seenSelections = new Set();
return selectionSet.selections.every(function (selection) {
if (seenSelections.has(selection))
return true;
seenSelections.add(selection);
if (!utilities.shouldInclude(selection, context.variables))
return true;
if (selectionHasNonreactiveDirective(selection))
return true;
if (utilities.isField(selection)) {
var resultKey = utilities.resultKeyNameFromField(selection);
var aResultChild = aResult && aResult[resultKey];
var bResultChild = bResult && bResult[resultKey];
var childSelectionSet = selection.selectionSet;
if (!childSelectionSet) {
return equal__default(aResultChild, bResultChild);
}
var aChildIsArray = Array.isArray(aResultChild);
var bChildIsArray = Array.isArray(bResultChild);
if (aChildIsArray !== bChildIsArray)
return false;
if (aChildIsArray && bChildIsArray) {
var length_1 = aResultChild.length;
if (bResultChild.length !== length_1) {
return false;
}
for (var i = 0; i < length_1; ++i) {
if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {
return false;
}
}
return true;
}
return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);
}
else {
var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
if (fragment) {
if (selectionHasNonreactiveDirective(fragment))
return true;
return equalBySelectionSet(fragment.selectionSet,
aResult, bResult, context);
}
}
});
}
function selectionHasNonreactiveDirective(selection) {
return (!!selection.directives && selection.directives.some(directiveIsNonreactive));
}
function directiveIsNonreactive(dir) {
return dir.name.value === "nonreactive";
}
var assign = Object.assign, hasOwnProperty$1 = Object.hasOwnProperty;
var ObservableQuery = (function (_super) {
tslib.__extends(ObservableQuery, _super);
function ObservableQuery(_a) {
var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
var _this = _super.call(this, function (observer) {
try {
var subObserver = observer._subscription._observer;
if (subObserver && !subObserver.error) {
subObserver.error = defaultSubscriptionObserverErrorCallback;
}
}
catch (_a) { }
var first = !_this.observers.size;
_this.observers.add(observer);
var last = _this.last;
if (last && last.error) {
observer.error && observer.error(last.error);
}
else if (last && last.result) {
observer.next && observer.next(last.result);
}
if (first) {
_this.reobserve().catch(function () { });
}
return function () {
if (_this.observers.delete(observer) && !_this.observers.size) {
_this.tearDownQuery();
}
};
}) || this;
_this.observers = new Set();
_this.subscriptions = new Set();
_this.queryInfo = queryInfo;
_this.queryManager = queryManager;
_this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);
_this.isTornDown = false;
_this.subscribeToMore = _this.subscribeToMore.bind(_this);
var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e,
_f = options.initialFetchPolicy,
initialFetchPolicy = _f === void 0 ? fetchPolicy === "standby" ? defaultFetchPolicy : (fetchPolicy) : _f;
_this.options = tslib.__assign(tslib.__assign({}, options), {
initialFetchPolicy: initialFetchPolicy,
fetchPolicy: fetchPolicy });
_this.queryId = queryInfo.queryId || queryManager.generateQueryId();
var opDef = utilities.getOperationDefinition(_this.query);
_this.queryName = opDef && opDef.name && opDef.name.value;
return _this;
}
Object.defineProperty(ObservableQuery.prototype, "query", {
get: function () {
return this.lastQuery || this.options.query;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ObservableQuery.prototype, "variables", {
get: function () {
return this.options.variables;
},
enumerable: false,
configurable: true
});
ObservableQuery.prototype.result = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var observer = {
next: function (result) {
resolve(result);
_this.observers.delete(observer);
if (!_this.observers.size) {
_this.queryManager.removeQuery(_this.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: reject,
};
var subscription = _this.subscribe(observer);
});
};
ObservableQuery.prototype.resetDiff = function () {
this.queryInfo.resetDiff();
};
ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
if (saveAsLastResult === void 0) { saveAsLastResult = true; }
var lastResult = this.getLastResult(true);
var networkStatus = this.queryInfo.networkStatus ||
(lastResult && lastResult.networkStatus) ||
exports.NetworkStatus.ready;
var result = tslib.__assign(tslib.__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
if (
skipCacheDataFor(fetchPolicy) ||
this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) ;
else if (this.waitForOwnResult) {
this.queryInfo["updateWatch"]();
}
else {
var diff = this.queryInfo.getDiff();
if (diff.complete || this.options.returnPartialData) {
result.data = diff.result;
}
if (equal.equal(result.data, {})) {
result.data = void 0;
}
if (diff.complete) {
delete result.partial;
if (diff.complete &&
result.networkStatus === exports.NetworkStatus.loading &&
(fetchPolicy === "cache-first" || fetchPolicy === "cache-only")) {
result.networkStatus = exports.NetworkStatus.ready;
result.loading = false;
}
}
else {
result.partial = true;
}
if (globalThis.__DEV__ !== false &&
!diff.complete &&
!this.options.partialRefetch &&
!result.loading &&
!result.data &&
!result.error) {
logMissingFieldErrors(diff.missing);
}
}
if (saveAsLastResult) {
this.updateLastResult(result);
}
return result;
};
ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
if (!this.last) {
return true;
}
var resultIsDifferent = this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?
!equalByQuery(this.query, this.last.result, newResult, this.variables)
: !equal.equal(this.last.result, newResult);
return (resultIsDifferent || (variables && !equal.equal(this.last.variables, variables)));
};
ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
var last = this.last;
if (last &&
last[key] &&
(!variablesMustMatch || equal.equal(last.variables, this.variables))) {
return last[key];
}
};
ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
return this.getLast("result", variablesMustMatch);
};
ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
return this.getLast("error", variablesMustMatch);
};
ObservableQuery.prototype.resetLastResults = function () {
delete this.last;
this.isTornDown = false;
};
ObservableQuery.prototype.resetQueryStoreErrors = function () {
this.queryManager.resetErrors(this.queryId);
};
ObservableQuery.prototype.refetch = function (variables) {
var _a;
var reobserveOptions = {
pollInterval: 0,
};
var fetchPolicy = this.options.fetchPolicy;
if (fetchPolicy === "cache-and-network") {
reobserveOptions.fetchPolicy = fetchPolicy;
}
else if (fetchPolicy === "no-cache") {
reobserveOptions.fetchPolicy = "no-cache";
}
else {
reobserveOptions.fetchPolicy = "network-only";
}
if (globalThis.__DEV__ !== false && variables && hasOwnProperty$1.call(variables, "variables")) {
var queryDef = utilities.getQueryDefinition(this.query);
var vars = queryDef.variableDefinitions;
if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
globalThis.__DEV__ !== false && globals.invariant.warn(
20,
variables,
((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef
);
}
}
if (variables && !equal.equal(this.options.variables, variables)) {
reobserveOptions.variables = this.options.variables = tslib.__assign(tslib.__assign({}, this.options.variables), variables);
}
this.queryInfo.resetLastWrite();
return this.reobserve(reobserveOptions, exports.NetworkStatus.refetch);
};
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
var combinedOptions = tslib.__assign(tslib.__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: tslib.__assign(tslib.__assign({}, this.options.variables), fetchMoreOptions.variables) })))), {
fetchPolicy: "no-cache" });
combinedOptions.query = this.transformDocument(combinedOptions.query);
var qid = this.queryManager.generateQueryId();
this.lastQuery =
fetchMoreOptions.query ?
this.transformDocument(this.options.query)
: combinedOptions.query;
var queryInfo = this.queryInfo;
var originalNetworkStatus = queryInfo.networkStatus;
queryInfo.networkStatus = exports.NetworkStatus.fetchMore;
if (combinedOptions.notifyOnNetworkStatusChange) {
this.observe();
}
var updatedQuerySet = new Set();
var updateQuery = fetchMoreOptions === null || fetchMoreOptions === void 0 ? void 0 : fetchMoreOptions.updateQuery;
var isCached = this.options.fetchPolicy !== "no-cache";
if (!isCached) {
globals.invariant(updateQuery, 21);
}
return this.queryManager
.fetchQuery(qid, combinedOptions, exports.NetworkStatus.fetchMore)
.then(function (fetchMoreResult) {
_this.queryManager.removeQuery(qid);
if (queryInfo.networkStatus === exports.NetworkStatus.fetchMore) {
queryInfo.networkStatus = originalNetworkStatus;
}
if (isCached) {
_this.queryManager.cache.batch({
update: function (cache) {
var updateQuery = fetchMoreOptions.updateQuery;
if (updateQuery) {
cache.updateQuery({
query: _this.query,
variables: _this.variables,
returnPartialData: true,
optimistic: false,
}, function (previous) {
return updateQuery(previous, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
});
});
}
else {
cache.writeQuery({
query: combinedOptions.query,
variables: combinedOptions.variables,
data: fetchMoreResult.data,
});
}
},
onWatchUpdated: function (watch) {
updatedQuerySet.add(watch.query);
},
});
}
else {
var lastResult = _this.getLast("result");
var data = updateQuery(lastResult.data, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
});
_this.reportResult(tslib.__assign(tslib.__assign({}, lastResult), { data: data }), _this.variables);
}
return fetchMoreResult;
})
.finally(function () {
if (isCached && !updatedQuerySet.has(_this.query)) {
reobserveCacheFirst(_this);
}
});
};
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var subscription = this.queryManager
.startGraphQLSubscription({
query: options.document,
variables: options.variables,
context: options.context,
})
.subscribe({
next: function (subscriptionData) {
var updateQuery = options.updateQuery;
if (updateQuery) {
_this.updateQuery(function (previous, _a) {
var variables = _a.variables;
return updateQuery(previous, {
subscriptionData: subscriptionData,
variables: variables,
});
});
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
return;
}
globalThis.__DEV__ !== false && globals.invariant.error(22, err);
},
});
this.subscriptions.add(subscription);
return function () {
if (_this.subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (newOptions) {
return this.reobserve(newOptions);
};
ObservableQuery.prototype.silentSetOptions = function (newOptions) {
var mergedOptions = utilities.compact(this.options, newOptions || {});
assign(this.options, mergedOptions);
};
ObservableQuery.prototype.setVariables = function (variables) {
if (equal.equal(this.variables, variables)) {
return this.observers.size ? this.result() : Promise.resolve();
}
this.options.variables = variables;
if (!this.observers.size) {
return Promise.resolve();
}
return this.reobserve({
fetchPolicy: this.options.initialFetchPolicy,
variables: variables,
}, exports.NetworkStatus.setVariables);
};
ObservableQuery.prototype.updateQuery = function (mapFn) {
var queryManager = this.queryManager;
var result = queryManager.cache.diff({
query: this.options.query,
variables: this.variables,
returnPartialData: true,
optimistic: false,
}).result;
var newResult = mapFn(result, {
variables: this.variables,
});
if (newResult) {
queryManager.cache.writeQuery({
query: this.options.query,
data: newResult,
variables: this.variables,
});
queryManager.broadcastQueries();
}
};
ObservableQuery.prototype.startPolling = function (pollInterval) {
this.options.pollInterval = pollInterval;
this.updatePolling();
};
ObservableQuery.prototype.stopPolling = function () {
this.options.pollInterval = 0;
this.updatePolling();
};
ObservableQuery.prototype.applyNextFetchPolicy = function (reason,
options) {
if (options.nextFetchPolicy) {
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
if (fetchPolicy === "standby") ;
else if (typeof options.nextFetchPolicy === "function") {
options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
reason: reason,
options: options,
observable: this,
initialFetchPolicy: initialFetchPolicy,
});
}
else if (reason === "variables-changed") {
options.fetchPolicy = initialFetchPolicy;
}
else {
options.fetchPolicy = options.nextFetchPolicy;
}
}
return options.fetchPolicy;
};
ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {
this.queryManager.setObservableQuery(this);
return this.queryManager["fetchConcastWithInfo"](this.queryId, options, newNetworkStatus, query);
};
ObservableQuery.prototype.updatePolling = function () {
var _this = this;
if (this.queryManager.ssrMode) {
return;
}
var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
if (!pollInterval || !this.hasObservers()) {
if (pollingInfo) {
clearTimeout(pollingInfo.timeout);
delete this.pollingInfo;
}
return;
}
if (pollingInfo && pollingInfo.interval === pollInterval) {
return;
}
globals.invariant(pollInterval, 23);
var info = pollingInfo || (this.pollingInfo = {});
info.interval = pollInterval;
var maybeFetch = function () {
var _a, _b;
if (_this.pollingInfo) {
if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&
!((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {
_this.reobserve({
fetchPolicy: _this.options.initialFetchPolicy === "no-cache" ?
"no-cache"
: "network-only",
}, exports.NetworkStatus.poll).then(poll, poll);
}
else {
poll();
}
}
};
var poll = function () {
var info = _this.pollingInfo;
if (info) {
clearTimeout(info.timeout);
info.timeout = setTimeout(maybeFetch, info.interval);
}
};
poll();
};
ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
if (variables === void 0) { variables = this.variables; }
var error = this.getLastError();
if (error && this.last && !equal.equal(variables, this.last.variables)) {
error = void 0;
}
return (this.last = tslib.__assign({ result: this.queryManager.assumeImmutableResults ?
newResult
: utilities.cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));
};
ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
var _this = this;
this.isTornDown = false;
var useDisposableConcast =
newNetworkStatus === exports.NetworkStatus.refetch ||
newNetworkStatus === exports.NetworkStatus.fetchMore ||
newNetworkStatus === exports.NetworkStatus.poll;
var oldVariables = this.options.variables;
var oldFetchPolicy = this.options.fetchPolicy;
var mergedOptions = utilities.compact(this.options, newOptions || {});
var options = useDisposableConcast ?
mergedOptions
: assign(this.options, mergedOptions);
var query = this.transformDocument(options.query);
this.lastQuery = query;
if (!useDisposableConcast) {
this.updatePolling();
if (newOptions &&
newOptions.variables &&
!equal.equal(newOptions.variables, oldVariables) &&
options.fetchPolicy !== "standby" &&
(options.fetchPolicy === oldFetchPolicy ||
typeof options.nextFetchPolicy === "function")) {
this.applyNextFetchPolicy("variables-changed", options);
if (newNetworkStatus === void 0) {
newNetworkStatus = exports.NetworkStatus.setVariables;
}
}
}
this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));
var finishWaitingForOwnResult = function () {
if (_this.concast === concast) {
_this.waitForOwnResult = false;
}
};
var variables = options.variables && tslib.__assign({}, options.variables);
var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;
var observer = {
next: function (result) {
if (equal.equal(_this.variables, variables)) {
finishWaitingForOwnResult();
_this.reportResult(result, variables);
}
},
error: function (error) {
if (equal.equal(_this.variables, variables)) {
if (!errors.isApolloError(error)) {
error = new errors.ApolloError({ networkError: error });
}
finishWaitingForOwnResult();
_this.reportError(error, variables);
}
},
};
if (!useDisposableConcast && (fromLink || !this.concast)) {
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
}
this.concast = concast;
this.observer = observer;
}
concast.addObserver(observer);
return concast;
};
ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
return this.reobserveAsConcast(newOptions, newNetworkStatus)
.promise;
};
ObservableQuery.prototype.resubscribeAfterError = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var last = this.last;
this.resetLastResults();
var subscription = this.subscribe.apply(this, args);
this.last = last;
return subscription;
};
ObservableQuery.prototype.observe = function () {
this.reportResult(
this.getCurrentResult(false), this.variables);
};
ObservableQuery.prototype.reportResult = function (result, variables) {
var lastError = this.getLastError();
var isDifferent = this.isDifferentFromLastResult(result, variables);
if (lastError || !result.partial || this.options.returnPartialData) {
this.updateLastResult(result, variables);
}
if (lastError || isDifferent) {
utilities.iterateObserversSafely(this.observers, "next", result);
}
};
ObservableQuery.prototype.reportError = function (error, variables) {
var errorResult = tslib.__assign(tslib.__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: exports.NetworkStatus.error, loading: false });
this.updateLastResult(errorResult, variables);
utilities.iterateObserversSafely(this.observers, "error", (this.last.error = error));
};
ObservableQuery.prototype.hasObservers = function () {
return this.observers.size > 0;
};
ObservableQuery.prototype.tearDownQuery = function () {
if (this.isTornDown)
return;
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
delete this.concast;
delete this.observer;
}
this.stopPolling();
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptions.clear();
this.queryManager.stopQuery(this.queryId);
this.observers.clear();
this.isTornDown = true;
};
ObservableQuery.prototype.transformDocument = function (document) {
return this.queryManager.transform(document);
};
return ObservableQuery;
}(utilities.Observable));
utilities.fixObservableSubclass(ObservableQuery);
function reobserveCacheFirst(obsQuery) {
var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
return obsQuery.reobserve({
fetchPolicy: "cache-first",
nextFetchPolicy: function (currentFetchPolicy, context) {
this.nextFetchPolicy = nextFetchPolicy;
if (typeof this.nextFetchPolicy === "function") {
return this.nextFetchPolicy(currentFetchPolicy, context);
}
return fetchPolicy;
},
});
}
return obsQuery.reobserve();
}
function defaultSubscriptionObserverErrorCallback(error) {
globalThis.__DEV__ !== false && globals.invariant.error(24, error.message, error.stack);
}
function logMissingFieldErrors(missing) {
if (globalThis.__DEV__ !== false && missing) {
globalThis.__DEV__ !== false && globals.invariant.debug(25, missing);
}
}
function skipCacheDataFor(fetchPolicy ) {
return (fetchPolicy === "network-only" ||
fetchPolicy === "no-cache" ||
fetchPolicy === "standby");
}
var destructiveMethodCounts = new (utilities.canUseWeakMap ? WeakMap : Map)();
function wrapDestructiveCacheMethod(cache, methodName) {
var original = cache[methodName];
if (typeof original === "function") {
cache[methodName] = function () {
destructiveMethodCounts.set(cache,
(destructiveMethodCounts.get(cache) + 1) % 1e15);
return original.apply(this, arguments);
};
}
}
function cancelNotifyTimeout(info) {
if (info["notifyTimeout"]) {
clearTimeout(info["notifyTimeout"]);
info["notifyTimeout"] = void 0;
}
}
var QueryInfo = (function () {
function QueryInfo(queryManager, queryId) {
if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
this.queryId = queryId;
this.listeners = new Set();
this.document = null;
this.lastRequestId = 1;
this.stopped = false;
this.dirty = false;
this.observableQuery = null;
var cache = (this.cache = queryManager.cache);
if (!destructiveMethodCounts.has(cache)) {
destructiveMethodCounts.set(cache, 0);
wrapDestructiveCacheMethod(cache, "evict");
wrapDestructiveCacheMethod(cache, "modify");
wrapDestructiveCacheMethod(cache, "reset");
}
}
QueryInfo.prototype.init = function (query) {
var networkStatus = query.networkStatus || exports.NetworkStatus.loading;
if (this.variables &&
this.networkStatus !== exports.NetworkStatus.loading &&
!equal.equal(this.variables, query.variables)) {
networkStatus = exports.NetworkStatus.setVariables;
}
if (!equal.equal(query.variables, this.variables)) {
this.lastDiff = void 0;
}
Object.assign(this, {
document: query.document,
variables: query.variables,
networkError: null,
graphQLErrors: this.graphQLErrors || [],
networkStatus: networkStatus,
});
if (query.observableQuery) {
this.setObservableQuery(query.observableQuery);
}
if (query.lastRequestId) {
this.lastRequestId = query.lastRequestId;
}
return this;
};
QueryInfo.prototype.reset = function () {
cancelNotifyTimeout(this);
this.dirty = false;
};
QueryInfo.prototype.resetDiff = function () {
this.lastDiff = void 0;
};
QueryInfo.prototype.getDiff = function () {
var options = this.getDiffOptions();
if (this.lastDiff && equal.equal(options, this.lastDiff.options)) {
return this.lastDiff.diff;
}
this.updateWatch(this.variables);
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return { complete: false };
}
var diff = this.cache.diff(options);
this.updateLastDiff(diff, options);
return diff;
};
QueryInfo.prototype.updateLastDiff = function (diff, options) {
this.lastDiff =
diff ?
{
diff: diff,
options: options || this.getDiffOptions(),
}
: void 0;
};
QueryInfo.prototype.getDiffOptions = function (variables) {
var _a;
if (variables === void 0) { variables = this.variables; }
return {
query: this.document,
variables: variables,
returnPartialData: true,
optimistic: true,
canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
};
};
QueryInfo.prototype.setDiff = function (diff) {
var _this = this;
var _a;
var oldDiff = this.lastDiff && this.lastDiff.diff;
if (diff && !diff.complete && ((_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.getLastError())) {
return;
}
this.updateLastDiff(diff);
if (!this.dirty && !equal.equal(oldDiff && oldDiff.result, diff && diff.result)) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
}
}
};
QueryInfo.prototype.setObservableQuery = function (oq) {
var _this = this;
if (oq === this.observableQuery)
return;
if (this.oqListener) {
this.listeners.delete(this.oqListener);
}
this.observableQuery = oq;
if (oq) {
oq["queryInfo"] = this;
this.listeners.add((this.oqListener = function () {
var diff = _this.getDiff();
if (diff.fromOptimisticTransaction) {
oq["observe"]();
}
else {
reobserveCacheFirst(oq);
}
}));
}
else {
delete this.oqListener;
}
};
QueryInfo.prototype.notify = function () {
var _this = this;
cancelNotifyTimeout(this);
if (this.shouldNotify()) {
this.listeners.forEach(function (listener) { return listener(_this); });
}
this.dirty = false;
};
QueryInfo.prototype.shouldNotify = function () {
if (!this.dirty || !this.listeners.size) {
return false;
}
if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {
var fetchPolicy = this.observableQuery.options.fetchPolicy;
if (fetchPolicy !== "cache-only" && fetchPolicy !== "cache-and-network") {
return false;
}
}
return true;
};
QueryInfo.prototype.stop = function () {
if (!this.stopped) {
this.stopped = true;
this.reset();
this.cancel();
this.cancel = QueryInfo.prototype.cancel;
var oq = this.observableQuery;
if (oq)
oq.stopPolling();
}
};
QueryInfo.prototype.cancel = function () { };
QueryInfo.prototype.updateWatch = function (variables) {
var _this = this;
if (variables === void 0) { variables = this.variables; }
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return;
}
var watchOptions = tslib.__assign(tslib.__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
if (!this.lastWatch || !equal.equal(watchOptions, this.lastWatch)) {
this.cancel();
this.cancel = this.cache.watch((this.lastWatch = watchOptions));
}
};
QueryInfo.prototype.resetLastWrite = function () {
this.lastWrite = void 0;
};
QueryInfo.prototype.shouldWrite = function (result, variables) {
var lastWrite = this.lastWrite;
return !(lastWrite &&
lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
equal.equal(variables, lastWrite.variables) &&
equal.equal(result.data, lastWrite.result.data));
};
QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
var _this = this;
var merger = new utilities.DeepMerger();
var graphQLErrors = utilities.isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
this.reset();
if ("incremental" in result && utilities.isNonEmptyArray(result.incremental)) {
var mergedData = utilities.mergeIncrementalData(this.getDiff().result, result);
result.data = mergedData;
}
else if ("hasNext" in result && result.hasNext) {
var diff = this.getDiff();
result.data = merger.merge(diff.result, result.data);
}
this.graphQLErrors = graphQLErrors;
if (options.fetchPolicy === "no-cache") {
this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
}
else if (cacheWriteBehavior !== 0 ) {
if (shouldWriteResult(result, options.errorPolicy)) {
this.cache.performTransaction(function (cache) {
if (_this.shouldWrite(result, options.variables)) {
cache.writeQuery({
query: document,
data: result.data,
variables: options.variables,
overwrite: cacheWriteBehavior === 1 ,
});
_this.lastWrite = {
result: result,
variables: options.variables,
dmCount: destructiveMethodCounts.get(_this.cache),
};
}
else {
if (_this.lastDiff && _this.lastDiff.diff.complete) {
result.data = _this.lastDiff.diff.result;
return;
}
}
var diffOptions = _this.getDiffOptions(options.variables);
var diff = cache.diff(diffOptions);
if (!_this.stopped && equal.equal(_this.variables, options.variables)) {
_this.updateWatch(options.variables);
}
_this.updateLastDiff(diff, diffOptions);
if (diff.complete) {
result.data = diff.result;
}
});
}
else {
this.lastWrite = void 0;
}
}
};
QueryInfo.prototype.markReady = function () {
this.networkError = null;
return (this.networkStatus = exports.NetworkStatus.ready);
};
QueryInfo.prototype.markError = function (error) {
this.networkStatus = exports.NetworkStatus.error;
this.lastWrite = void 0;
this.reset();
if (error.graphQLErrors) {
this.graphQLErrors = error.graphQLErrors;
}
if (error.networkError) {
this.networkError = error.networkError;
}
return error;
};
return QueryInfo;
}());
function shouldWriteResult(result, errorPolicy) {
if (errorPolicy === void 0) { errorPolicy = "none"; }
var ignoreErrors = errorPolicy === "ignore" || errorPolicy === "all";
var writeWithErrors = !utilities.graphQLResultHasError(result);
if (!writeWithErrors && ignoreErrors && result.data) {
writeWithErrors = true;
}
return writeWithErrors;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var IGNORE = Object.create(null);
var QueryManager = (function () {
function QueryManager(options) {
var _this = this;
this.clientAwareness = {};
this.queries = new Map();
this.fetchCancelFns = new Map();
this.transformCache = new utilities.AutoCleanedWeakCache(utilities.cacheSizes["queryManager.getDocumentInfo"] ||
2000 );
this.queryIdCounter = 1;
this.requestIdCounter = 1;
this.mutationIdCounter = 1;
this.inFlightLinkObservables = new trie.Trie(false);
var defaultDocumentTransform = new utilities.DocumentTransform(function (document) { return _this.cache.transformDocument(document); },
{ cache: false });
this.cache = options.cache;
this.link = options.link;
this.defaultOptions = options.defaultOptions;
this.queryDeduplication = options.queryDeduplication;
this.clientAwareness = options.clientAwareness;
this.localState = options.localState;
this.ssrMode = options.ssrMode;
this.assumeImmutableResults = options.assumeImmutableResults;
var documentTransform = options.documentTransform;
this.documentTransform =
documentTransform ?
defaultDocumentTransform
.concat(documentTransform)
.concat(defaultDocumentTransform)
: defaultDocumentTransform;
this.defaultContext = options.defaultContext || Object.create(null);
if ((this.onBroadcast = options.onBroadcast)) {
this.mutationStore = Object.create(null);
}
}
QueryManager.prototype.stop = function () {
var _this = this;
this.queries.forEach(function (_info, queryId) {
_this.stopQueryNoBroadcast(queryId);
});
this.cancelPendingFetches(globals.newInvariantError(26));
};
QueryManager.prototype.cancelPendingFetches = function (error) {
this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
this.fetchCancelFns.clear();
};
QueryManager.prototype.mutate = function (_a) {
return tslib.__awaiter(this, arguments, void 0, function (_b) {
var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;
var _c, _d;
var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || "network-only" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || "none" : _h, keepRootFields = _b.keepRootFields, context = _b.context;
return tslib.__generator(this, function (_j) {
switch (_j.label) {
case 0:
globals.invariant(mutation, 27);
globals.invariant(fetchPolicy === "network-only" || fetchPolicy === "no-cache", 28);
mutationId = this.generateMutationId();
mutation = this.cache.transformForLink(this.transform(mutation));
hasClientExports = this.getDocumentInfo(mutation).hasClientExports;
variables = this.getVariables(mutation, variables);
if (!hasClientExports) return [3 , 2];
return [4 , this.localState.addExportedVariables(mutation, variables, context)];
case 1:
variables = (_j.sent());
_j.label = 2;
case 2:
mutationStoreValue = this.mutationStore &&
(this.mutationStore[mutationId] = {
mutation: mutation,
variables: variables,
loading: true,
error: null,
});
isOptimistic = optimisticResponse &&
this.markMutationOptimistic(optimisticResponse, {
mutationId: mutationId,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
updateQueries: updateQueries,
update: updateWithProxyFn,
keepRootFields: keepRootFields,
});
this.broadcastQueries();
self = this;
return [2 , new Promise(function (resolve, reject) {
return utilities.asyncMap(self.getObservableFromLink(mutation, tslib.__assign(tslib.__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, {}, false), function (result) {
if (utilities.graphQLResultHasError(result) && errorPolicy === "none") {
throw new errors.ApolloError({
graphQLErrors: utilities.getGraphQLErrorsFromResult(result),
});
}
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = null;
}
var storeResult = tslib.__assign({}, result);
if (typeof refetchQueries === "function") {
refetchQueries = refetchQueries(storeResult);
}
if (errorPolicy === "ignore" && utilities.graphQLResultHasError(storeResult)) {
delete storeResult.errors;
}
return self.markMutationResult({
mutationId: mutationId,
result: storeResult,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
update: updateWithProxyFn,
updateQueries: updateQueries,
awaitRefetchQueries: awaitRefetchQueries,
refetchQueries: refetchQueries,
removeOptimistic: isOptimistic ? mutationId : void 0,
onQueryUpdated: onQueryUpdated,
keepRootFields: keepRootFields,
});
}).subscribe({
next: function (storeResult) {
self.broadcastQueries();
if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
resolve(storeResult);
}
},
error: function (err) {
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = err;
}
if (isOptimistic) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(err instanceof errors.ApolloError ? err : (new errors.ApolloError({
networkError: err,
})));
},
});
})];
}
});
});
};
QueryManager.prototype.markMutationResult = function (mutation, cache) {
var _this = this;
if (cache === void 0) { cache = this.cache; }
var result = mutation.result;
var cacheWrites = [];
var skipCache = mutation.fetchPolicy === "no-cache";
if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
if (!utilities.isExecutionPatchIncrementalResult(result)) {
cacheWrites.push({
result: result.data,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
if (utilities.isExecutionPatchIncrementalResult(result) &&
utilities.isNonEmptyArray(result.incremental)) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
var mergedData = void 0;
if (diff.result) {
mergedData = mergeIncrementalData(diff.result, result);
}
if (typeof mergedData !== "undefined") {
result.data = mergedData;
cacheWrites.push({
result: mergedData,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
}
var updateQueries_1 = mutation.updateQueries;
if (updateQueries_1) {
this.queries.forEach(function (_a, queryId) {
var observableQuery = _a.observableQuery;
var queryName = observableQuery && observableQuery.queryName;
if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
return;
}
var updater = updateQueries_1[queryName];
var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
var _c = cache.diff({
query: document,
variables: variables,
returnPartialData: true,
optimistic: false,
}), currentQueryResult = _c.result, complete = _c.complete;
if (complete && currentQueryResult) {
var nextQueryResult = updater(currentQueryResult, {
mutationResult: result,
queryName: (document && utilities.getOperationName(document)) || void 0,
queryVariables: variables,
});
if (nextQueryResult) {
cacheWrites.push({
result: nextQueryResult,
dataId: "ROOT_QUERY",
query: document,
variables: variables,
});
}
}
});
}
}
if (cacheWrites.length > 0 ||
(mutation.refetchQueries || "").length > 0 ||
mutation.update ||
mutation.onQueryUpdated ||
mutation.removeOptimistic) {
var results_1 = [];
this.refetchQueries({
updateCache: function (cache) {
if (!skipCache) {
cacheWrites.forEach(function (write) { return cache.write(write); });
}
var update = mutation.update;
var isFinalResult = !utilities.isExecutionPatchResult(result) ||
(utilities.isExecutionPatchIncrementalResult(result) && !result.hasNext);
if (update) {
if (!skipCache) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: _this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
if (diff.complete) {
result = tslib.__assign(tslib.__assign({}, result), { data: diff.result });
if ("incremental" in result) {
delete result.incremental;
}
if ("hasNext" in result) {
delete result.hasNext;
}
}
}
if (isFinalResult) {
update(cache, result, {
context: mutation.context,
variables: mutation.variables,
});
}
}
if (!skipCache && !mutation.keepRootFields && isFinalResult) {
cache.modify({
id: "ROOT_MUTATION",
fields: function (value, _a) {
var fieldName = _a.fieldName, DELETE = _a.DELETE;
return fieldName === "__typename" ? value : DELETE;
},
});
}
},
include: mutation.refetchQueries,
optimistic: false,
removeOptimistic: mutation.removeOptimistic,
onQueryUpdated: mutation.onQueryUpdated || null,
}).forEach(function (result) { return results_1.push(result); });
if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
return Promise.all(results_1).then(function () { return result; });
}
}
return Promise.resolve(result);
};
QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
var _this = this;
var data = typeof optimisticResponse === "function" ?
optimisticResponse(mutation.variables, { IGNORE: IGNORE })
: optimisticResponse;
if (data === IGNORE) {
return false;
}
this.cache.recordOptimisticTransaction(function (cache) {
try {
_this.markMutationResult(tslib.__assign(tslib.__assign({}, mutation), { result: { data: data } }), cache);
}
catch (error) {
globalThis.__DEV__ !== false && globals.invariant.error(error);
}
}, mutation.mutationId);
return true;
};
QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
return this.fetchConcastWithInfo(queryId, options, networkStatus).concast
.promise;
};
QueryManager.prototype.getQueryStore = function () {
var store = Object.create(null);
this.queries.forEach(function (info, queryId) {
store[queryId] = {
variables: info.variables,
networkStatus: info.networkStatus,
networkError: info.networkError,
graphQLErrors: info.graphQLErrors,
};
});
return store;
};
QueryManager.prototype.resetErrors = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo) {
queryInfo.networkError = undefined;
queryInfo.graphQLErrors = [];
}
};
QueryManager.prototype.transform = function (document) {
return this.documentTransform.transformDocument(document);
};
QueryManager.prototype.getDocumentInfo = function (document) {
var transformCache = this.transformCache;
if (!transformCache.has(document)) {
var cacheEntry = {
hasClientExports: utilities.hasClientExports(document),
hasForcedResolvers: this.localState.shouldForceResolvers(document),
hasNonreactiveDirective: utilities.hasDirectives(["nonreactive"], document),
clientQuery: this.localState.clientQuery(document),
serverQuery: utilities.removeDirectivesFromDocument([
{ name: "client", remove: true },
{ name: "connection" },
{ name: "nonreactive" },
], document),
defaultVars: utilities.getDefaultValues(utilities.getOperationDefinition(document)),
asQuery: tslib.__assign(tslib.__assign({}, document), { definitions: document.definitions.map(function (def) {
if (def.kind === "OperationDefinition" &&
def.operation !== "query") {
return tslib.__assign(tslib.__assign({}, def), { operation: "query" });
}
return def;
}) }),
};
transformCache.set(document, cacheEntry);
}
return transformCache.get(document);
};
QueryManager.prototype.getVariables = function (document, variables) {
return tslib.__assign(tslib.__assign({}, this.getDocumentInfo(document).defaultVars), variables);
};
QueryManager.prototype.watchQuery = function (options) {
var query = this.transform(options.query);
options = tslib.__assign(tslib.__assign({}, options), { variables: this.getVariables(query, options.variables) });
if (typeof options.notifyOnNetworkStatusChange === "undefined") {
options.notifyOnNetworkStatusChange = false;
}
var queryInfo = new QueryInfo(this);
var observable = new ObservableQuery({
queryManager: this,
queryInfo: queryInfo,
options: options,
});
observable["lastQuery"] = query;
this.queries.set(observable.queryId, queryInfo);
queryInfo.init({
document: query,
observableQuery: observable,
variables: observable.variables,
});
return observable;
};
QueryManager.prototype.query = function (options, queryId) {
var _this = this;
if (queryId === void 0) { queryId = this.generateQueryId(); }
globals.invariant(options.query, 29);
globals.invariant(options.query.kind === "Document", 30);
globals.invariant(!options.returnPartialData, 31);
globals.invariant(!options.pollInterval, 32);
return this.fetchQuery(queryId, tslib.__assign(tslib.__assign({}, options), { query: this.transform(options.query) })).finally(function () { return _this.stopQuery(queryId); });
};
QueryManager.prototype.generateQueryId = function () {
return String(this.queryIdCounter++);
};
QueryManager.prototype.generateRequestId = function () {
return this.requestIdCounter++;
};
QueryManager.prototype.generateMutationId = function () {
return String(this.mutationIdCounter++);
};
QueryManager.prototype.stopQueryInStore = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo)
queryInfo.stop();
};
QueryManager.prototype.clearStore = function (options) {
if (options === void 0) { options = {
discardWatches: true,
}; }
this.cancelPendingFetches(globals.newInvariantError(33));
this.queries.forEach(function (queryInfo) {
if (queryInfo.observableQuery) {
queryInfo.networkStatus = exports.NetworkStatus.loading;
}
else {
queryInfo.stop();
}
});
if (this.mutationStore) {
this.mutationStore = Object.create(null);
}
return this.cache.reset(options);
};
QueryManager.prototype.getObservableQueries = function (include) {
var _this = this;
if (include === void 0) { include = "active"; }
var queries = new Map();
var queryNamesAndDocs = new Map();
var legacyQueryOptions = new Set();
if (Array.isArray(include)) {
include.forEach(function (desc) {
if (typeof desc === "string") {
queryNamesAndDocs.set(desc, false);
}
else if (utilities.isDocumentNode(desc)) {
queryNamesAndDocs.set(_this.transform(desc), false);
}
else if (utilities.isNonNullObject(desc) && desc.query) {
legacyQueryOptions.add(desc);
}
});
}
this.queries.forEach(function (_a, queryId) {
var oq = _a.observableQuery, document = _a.document;
if (oq) {
if (include === "all") {
queries.set(queryId, oq);
return;
}
var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
if (fetchPolicy === "standby" ||
(include === "active" && !oq.hasObservers())) {
return;
}
if (include === "active" ||
(queryName && queryNamesAndDocs.has(queryName)) ||
(document && queryNamesAndDocs.has(document))) {
queries.set(queryId, oq);
if (queryName)
queryNamesAndDocs.set(queryName, true);
if (document)
queryNamesAndDocs.set(document, true);
}
}
});
if (legacyQueryOptions.size) {
legacyQueryOptions.forEach(function (options) {
var queryId = utilities.makeUniqueId("legacyOneTimeQuery");
var queryInfo = _this.getQuery(queryId).init({
document: options.query,
variables: options.variables,
});
var oq = new ObservableQuery({
queryManager: _this,
queryInfo: queryInfo,
options: tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "network-only" }),
});
globals.invariant(oq.queryId === queryId);
queryInfo.setObservableQuery(oq);
queries.set(queryId, oq);
});
}
if (globalThis.__DEV__ !== false && queryNamesAndDocs.size) {
queryNamesAndDocs.forEach(function (included, nameOrDoc) {
if (!included) {
globalThis.__DEV__ !== false && globals.invariant.warn(typeof nameOrDoc === "string" ? 34 : 35, nameOrDoc);
}
});
}
return queries;
};
QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
var _this = this;
if (includeStandby === void 0) { includeStandby = false; }
var observableQueryPromises = [];
this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
var fetchPolicy = observableQuery.options.fetchPolicy;
observableQuery.resetLastResults();
if (includeStandby ||
(fetchPolicy !== "standby" && fetchPolicy !== "cache-only")) {
observableQueryPromises.push(observableQuery.refetch());
}
_this.getQuery(queryId).setDiff(null);
});
this.broadcastQueries();
return Promise.all(observableQueryPromises);
};
QueryManager.prototype.setObservableQuery = function (observableQuery) {
this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
};
QueryManager.prototype.startGraphQLSubscription = function (_a) {
var _this = this;
var query = _a.query, fetchPolicy = _a.fetchPolicy, _b = _a.errorPolicy, errorPolicy = _b === void 0 ? "none" : _b, variables = _a.variables, _c = _a.context, context = _c === void 0 ? {} : _c, _d = _a.extensions, extensions = _d === void 0 ? {} : _d;
query = this.transform(query);
variables = this.getVariables(query, variables);
var makeObservable = function (variables) {
return _this.getObservableFromLink(query, context, variables, extensions).map(function (result) {
if (fetchPolicy !== "no-cache") {
if (shouldWriteResult(result, errorPolicy)) {
_this.cache.write({
query: query,
result: result.data,
dataId: "ROOT_SUBSCRIPTION",
variables: variables,
});
}
_this.broadcastQueries();
}
var hasErrors = utilities.graphQLResultHasError(result);
var hasProtocolErrors = errors.graphQLResultHasProtocolErrors(result);
if (hasErrors || hasProtocolErrors) {
var errors$1 = {};
if (hasErrors) {
errors$1.graphQLErrors = result.errors;
}
if (hasProtocolErrors) {
errors$1.protocolErrors = result.extensions[errors.PROTOCOL_ERRORS_SYMBOL];
}
if (errorPolicy === "none" || hasProtocolErrors) {
throw new errors.ApolloError(errors$1);
}
}
if (errorPolicy === "ignore") {
delete result.errors;
}
return result;
});
};
if (this.getDocumentInfo(query).hasClientExports) {
var observablePromise_1 = this.localState
.addExportedVariables(query, variables, context)
.then(makeObservable);
return new utilities.Observable(function (observer) {
var sub = null;
observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);
return function () { return sub && sub.unsubscribe(); };
});
}
return makeObservable(variables);
};
QueryManager.prototype.stopQuery = function (queryId) {
this.stopQueryNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.removeQuery(queryId);
};
QueryManager.prototype.removeQuery = function (queryId) {
this.fetchCancelFns.delete(queryId);
if (this.queries.has(queryId)) {
this.getQuery(queryId).stop();
this.queries.delete(queryId);
}
};
QueryManager.prototype.broadcastQueries = function () {
if (this.onBroadcast)
this.onBroadcast();
this.queries.forEach(function (info) { return info.notify(); });
};
QueryManager.prototype.getLocalState = function () {
return this.localState;
};
QueryManager.prototype.getObservableFromLink = function (query, context, variables, extensions,
deduplication) {
var _this = this;
var _a;
if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
var observable;
var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;
if (serverQuery) {
var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;
var operation = {
query: serverQuery,
variables: variables,
operationName: utilities.getOperationName(serverQuery) || void 0,
context: this.prepareContext(tslib.__assign(tslib.__assign({}, context), { forceFetch: !deduplication })),
extensions: extensions,
};
context = operation.context;
if (deduplication) {
var printedServerQuery_1 = utilities.print(serverQuery);
var varJson_1 = cache.canonicalStringify(variables);
var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);
observable = entry.observable;
if (!observable) {
var concast = new utilities.Concast([
core.execute(link, operation),
]);
observable = entry.observable = concast;
concast.beforeNext(function () {
inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);
});
}
}
else {
observable = new utilities.Concast([
core.execute(link, operation),
]);
}
}
else {
observable = new utilities.Concast([utilities.Observable.of({ data: {} })]);
context = this.prepareContext(context);
}
if (clientQuery) {
observable = utilities.asyncMap(observable, function (result) {
return _this.localState.runResolvers({
document: clientQuery,
remoteResult: result,
context: context,
variables: variables,
});
});
}
return observable;
};
QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
var requestId = (queryInfo.lastRequestId = this.generateRequestId());
var linkDocument = this.cache.transformForLink(options.query);
return utilities.asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
var graphQLErrors = utilities.getGraphQLErrorsFromResult(result);
var hasErrors = graphQLErrors.length > 0;
var errorPolicy = options.errorPolicy;
if (requestId >= queryInfo.lastRequestId) {
if (hasErrors && errorPolicy === "none") {
throw queryInfo.markError(new errors.ApolloError({
graphQLErrors: graphQLErrors,
}));
}
queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
queryInfo.markReady();
}
var aqr = {
data: result.data,
loading: false,
networkStatus: exports.NetworkStatus.ready,
};
if (hasErrors && errorPolicy === "none") {
aqr.data = void 0;
}
if (hasErrors && errorPolicy !== "ignore") {
aqr.errors = graphQLErrors;
aqr.networkStatus = exports.NetworkStatus.error;
}
return aqr;
}, function (networkError) {
var error = errors.isApolloError(networkError) ? networkError : (new errors.ApolloError({ networkError: networkError }));
if (requestId >= queryInfo.lastRequestId) {
queryInfo.markError(error);
}
throw error;
});
};
QueryManager.prototype.fetchConcastWithInfo = function (queryId, options,
networkStatus, query) {
var _this = this;
if (networkStatus === void 0) { networkStatus = exports.NetworkStatus.loading; }
if (query === void 0) { query = options.query; }
var variables = this.getVariables(query, options.variables);
var queryInfo = this.getQuery(queryId);
var defaults = this.defaultOptions.watchQuery;
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
var normalized = Object.assign({}, options, {
query: query,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
returnPartialData: returnPartialData,
notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
context: context,
});
var fromVariables = function (variables) {
normalized.variables = variables;
var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
if (
normalized.fetchPolicy !== "standby" &&
sourcesWithInfo.sources.length > 0 &&
queryInfo.observableQuery) {
queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
}
return sourcesWithInfo;
};
var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
this.fetchCancelFns.set(queryId, function (reason) {
cleanupCancelFn();
setTimeout(function () { return concast.cancel(reason); });
});
var concast, containsDataFromLink;
if (this.getDocumentInfo(normalized.query).hasClientExports) {
concast = new utilities.Concast(this.localState
.addExportedVariables(normalized.query, normalized.variables, normalized.context)
.then(fromVariables)
.then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
containsDataFromLink = true;
}
else {
var sourcesWithInfo = fromVariables(normalized.variables);
containsDataFromLink = sourcesWithInfo.fromLink;
concast = new utilities.Concast(sourcesWithInfo.sources);
}
concast.promise.then(cleanupCancelFn, cleanupCancelFn);
return {
concast: concast,
fromLink: containsDataFromLink,
};
};
QueryManager.prototype.refetchQueries = function (_a) {
var _this = this;
var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? utilities.makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
var includedQueriesById = new Map();
if (include) {
this.getObservableQueries(include).forEach(function (oq, queryId) {
includedQueriesById.set(queryId, {
oq: oq,
lastDiff: _this.getQuery(queryId).getDiff(),
});
});
}
var results = new Map();
if (updateCache) {
this.cache.batch({
update: updateCache,
optimistic: (optimistic && removeOptimistic) || false,
removeOptimistic: removeOptimistic,
onWatchUpdated: function (watch, diff, lastDiff) {
var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;
if (oq) {
if (onQueryUpdated) {
includedQueriesById.delete(oq.queryId);
var result = onQueryUpdated(oq, diff, lastDiff);
if (result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
return result;
}
if (onQueryUpdated !== null) {
includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
}
}
},
});
}
if (includedQueriesById.size) {
includedQueriesById.forEach(function (_a, queryId) {
var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
var result;
if (onQueryUpdated) {
if (!diff) {
var info = oq["queryInfo"];
info.reset();
diff = info.getDiff();
}
result = onQueryUpdated(oq, diff, lastDiff);
}
if (!onQueryUpdated || result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
_this.stopQueryNoBroadcast(queryId);
}
});
}
if (removeOptimistic) {
this.cache.removeOptimistic(removeOptimistic);
}
return results;
};
QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a,
networkStatus) {
var _this = this;
var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
var oldNetworkStatus = queryInfo.networkStatus;
queryInfo.init({
document: query,
variables: variables,
networkStatus: networkStatus,
});
var readCache = function () { return queryInfo.getDiff(); };
var resultsFromCache = function (diff, networkStatus) {
if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || exports.NetworkStatus.loading; }
var data = diff.result;
if (globalThis.__DEV__ !== false && !returnPartialData && !equal.equal(data, {})) {
logMissingFieldErrors(diff.missing);
}
var fromData = function (data) {
return utilities.Observable.of(tslib.__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));
};
if (data && _this.getDocumentInfo(query).hasForcedResolvers) {
return _this.localState
.runResolvers({
document: query,
remoteResult: { data: data },
context: context,
variables: variables,
onlyRunForcedResolvers: true,
})
.then(function (resolved) { return fromData(resolved.data || void 0); });
}
if (errorPolicy === "none" &&
networkStatus === exports.NetworkStatus.refetch &&
Array.isArray(diff.missing)) {
return fromData(void 0);
}
return fromData(data);
};
var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0
: (networkStatus === exports.NetworkStatus.refetch &&
refetchWritePolicy !== "merge") ?
1
: 2 ;
var resultsFromLink = function () {
return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
query: query,
variables: variables,
context: context,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
});
};
var shouldNotify = notifyOnNetworkStatusChange &&
typeof oldNetworkStatus === "number" &&
oldNetworkStatus !== networkStatus &&
isNetworkRequestInFlight(networkStatus);
switch (fetchPolicy) {
default:
case "cache-first": {
var diff = readCache();
if (diff.complete) {
return {
fromLink: false,
sources: [resultsFromCache(diff, queryInfo.markReady())],
};
}
if (returnPartialData || shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(diff), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-and-network": {
var diff = readCache();
if (diff.complete || returnPartialData || shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(diff), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-only":
return {
fromLink: false,
sources: [resultsFromCache(readCache(), queryInfo.markReady())],
};
case "network-only":
if (shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(readCache()), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
case "no-cache":
if (shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
case "standby":
return { fromLink: false, sources: [] };
}
};
QueryManager.prototype.getQuery = function (queryId) {
if (queryId && !this.queries.has(queryId)) {
this.queries.set(queryId, new QueryInfo(this, queryId));
}
return this.queries.get(queryId);
};
QueryManager.prototype.prepareContext = function (context) {
if (context === void 0) { context = {}; }
var newContext = this.localState.prepareContext(context);
return tslib.__assign(tslib.__assign(tslib.__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });
};
return QueryManager;
}());
var LocalState = (function () {
function LocalState(_a) {
var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
this.selectionsToResolveCache = new WeakMap();
this.cache = cache;
if (client) {
this.client = client;
}
if (resolvers) {
this.addResolvers(resolvers);
}
if (fragmentMatcher) {
this.setFragmentMatcher(fragmentMatcher);
}
}
LocalState.prototype.addResolvers = function (resolvers) {
var _this = this;
this.resolvers = this.resolvers || {};
if (Array.isArray(resolvers)) {
resolvers.forEach(function (resolverGroup) {
_this.resolvers = utilities.mergeDeep(_this.resolvers, resolverGroup);
});
}
else {
this.resolvers = utilities.mergeDeep(this.resolvers, resolvers);
}
};
LocalState.prototype.setResolvers = function (resolvers) {
this.resolvers = {};
this.addResolvers(resolvers);
};
LocalState.prototype.getResolvers = function () {
return this.resolvers || {};
};
LocalState.prototype.runResolvers = function (_a) {
return tslib.__awaiter(this, arguments, void 0, function (_b) {
var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;
return tslib.__generator(this, function (_d) {
if (document) {
return [2 , this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (tslib.__assign(tslib.__assign({}, remoteResult), { data: localResult.result })); })];
}
return [2 , remoteResult];
});
});
};
LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
this.fragmentMatcher = fragmentMatcher;
};
LocalState.prototype.getFragmentMatcher = function () {
return this.fragmentMatcher;
};
LocalState.prototype.clientQuery = function (document) {
if (utilities.hasDirectives(["client"], document)) {
if (this.resolvers) {
return document;
}
}
return null;
};
LocalState.prototype.serverQuery = function (document) {
return utilities.removeClientSetsFromDocument(document);
};
LocalState.prototype.prepareContext = function (context) {
var cache = this.cache;
return tslib.__assign(tslib.__assign({}, context), { cache: cache,
getCacheKey: function (obj) {
return cache.identify(obj);
} });
};
LocalState.prototype.addExportedVariables = function (document_1) {
return tslib.__awaiter(this, arguments, void 0, function (document, variables, context) {
if (variables === void 0) { variables = {}; }
if (context === void 0) { context = {}; }
return tslib.__generator(this, function (_a) {
if (document) {
return [2 , this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (tslib.__assign(tslib.__assign({}, variables), data.exportedVariables)); })];
}
return [2 , tslib.__assign({}, variables)];
});
});
};
LocalState.prototype.shouldForceResolvers = function (document) {
var forceResolvers = false;
graphql.visit(document, {
Directive: {
enter: function (node) {
if (node.name.value === "client" && node.arguments) {
forceResolvers = node.arguments.some(function (arg) {
return arg.name.value === "always" &&
arg.value.kind === "BooleanValue" &&
arg.value.value === true;
});
if (forceResolvers) {
return graphql.BREAK;
}
}
},
},
});
return forceResolvers;
};
LocalState.prototype.buildRootValueFromCache = function (document, variables) {
return this.cache.diff({
query: utilities.buildQueryFromSelectionSet(document),
variables: variables,
returnPartialData: true,
optimistic: false,
}).result;
};
LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {
return tslib.__awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
if (context === void 0) { context = {}; }
if (variables === void 0) { variables = {}; }
if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
return tslib.__generator(this, function (_b) {
mainDefinition = utilities.getMainDefinition(document);
fragments = utilities.getFragmentDefinitions(document);
fragmentMap = utilities.createFragmentMap(fragments);
selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
definitionOperation = mainDefinition.operation;
defaultOperationType = definitionOperation ?
definitionOperation.charAt(0).toUpperCase() +
definitionOperation.slice(1)
: "Query";
_a = this, cache = _a.cache, client = _a.client;
execContext = {
fragmentMap: fragmentMap,
context: tslib.__assign(tslib.__assign({}, context), { cache: cache, client: client }),
variables: variables,
fragmentMatcher: fragmentMatcher,
defaultOperationType: defaultOperationType,
exportedVariables: {},
selectionsToResolve: selectionsToResolve,
onlyRunForcedResolvers: onlyRunForcedResolvers,
};
isClientFieldDescendant = false;
return [2 , this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
result: result,
exportedVariables: execContext.exportedVariables,
}); })];
});
});
};
LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
return tslib.__awaiter(this, void 0, void 0, function () {
var fragmentMap, context, variables, resultsToMerge, execute;
var _this = this;
return tslib.__generator(this, function (_a) {
fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
resultsToMerge = [rootValue];
execute = function (selection) { return tslib.__awaiter(_this, void 0, void 0, function () {
var fragment, typeCondition;
return tslib.__generator(this, function (_a) {
if (!isClientFieldDescendant &&
!execContext.selectionsToResolve.has(selection)) {
return [2 ];
}
if (!utilities.shouldInclude(selection, variables)) {
return [2 ];
}
if (utilities.isField(selection)) {
return [2 , this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
var _a;
if (typeof fieldResult !== "undefined") {
resultsToMerge.push((_a = {},
_a[utilities.resultKeyNameFromField(selection)] = fieldResult,
_a));
}
})];
}
if (utilities.isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
globals.invariant(fragment, 18, selection.name.value);
}
if (fragment && fragment.typeCondition) {
typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
return [2 , this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
resultsToMerge.push(fragmentResult);
})];
}
}
return [2 ];
});
}); };
return [2 , Promise.all(selectionSet.selections.map(execute)).then(function () {
return utilities.mergeDeepArray(resultsToMerge);
})];
});
});
};
LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
return tslib.__awaiter(this, void 0, void 0, function () {
var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
var _this = this;
return tslib.__generator(this, function (_a) {
if (!rootValue) {
return [2 , null];
}
variables = execContext.variables;
fieldName = field.name.value;
aliasedFieldName = utilities.resultKeyNameFromField(field);
aliasUsed = fieldName !== aliasedFieldName;
defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
resultPromise = Promise.resolve(defaultResult);
if (!execContext.onlyRunForcedResolvers ||
this.shouldForceResolvers(field)) {
resolverType = rootValue.__typename || execContext.defaultOperationType;
resolverMap = this.resolvers && this.resolvers[resolverType];
if (resolverMap) {
resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
if (resolve) {
resultPromise = Promise.resolve(
cache.cacheSlot.withValue(this.cache, resolve, [
rootValue,
utilities.argumentsObjectFromField(field, variables),
execContext.context,
{ field: field, fragmentMap: execContext.fragmentMap },
]));
}
}
}
return [2 , resultPromise.then(function (result) {
var _a, _b;
if (result === void 0) { result = defaultResult; }
if (field.directives) {
field.directives.forEach(function (directive) {
if (directive.name.value === "export" && directive.arguments) {
directive.arguments.forEach(function (arg) {
if (arg.name.value === "as" && arg.value.kind === "StringValue") {
execContext.exportedVariables[arg.value.value] = result;
}
});
}
});
}
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === "client"; })) !== null && _b !== void 0 ? _b : false;
if (Array.isArray(result)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
}
})];
});
});
};
LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
var _this = this;
return Promise.all(result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
}
}));
};
LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
var isSingleASTNode = function (node) { return !Array.isArray(node); };
var selectionsToResolveCache = this.selectionsToResolveCache;
function collectByDefinition(definitionNode) {
if (!selectionsToResolveCache.has(definitionNode)) {
var matches_1 = new Set();
selectionsToResolveCache.set(definitionNode, matches_1);
graphql.visit(definitionNode, {
Directive: function (node, _, __, ___, ancestors) {
if (node.name.value === "client") {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
matches_1.add(node);
}
});
}
},
FragmentSpread: function (spread, _, __, ___, ancestors) {
var fragment = fragmentMap[spread.name.value];
globals.invariant(fragment, 19, spread.name.value);
var fragmentSelections = collectByDefinition(fragment);
if (fragmentSelections.size > 0) {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && graphql.isSelectionNode(node)) {
matches_1.add(node);
}
});
matches_1.add(spread);
fragmentSelections.forEach(function (selection) {
matches_1.add(selection);
});
}
},
});
}
return selectionsToResolveCache.get(definitionNode);
}
return collectByDefinition(mainDefinition);
};
return LocalState;
}());
var cacheSizeSymbol = Symbol.for("apollo.cacheSize");
var cacheSizes = tslib.__assign({}, globals.global[cacheSizeSymbol]);
var globalCaches = {};
var getApolloClientMemoryInternals = globalThis.__DEV__ !== false ?
_getApolloClientMemoryInternals
: undefined;
function getCurrentCacheSizes() {
var defaults = {
parser: 1000 ,
canonicalStringify: 1000 ,
print: 2000 ,
"documentTransform.cache": 2000 ,
"queryManager.getDocumentInfo": 2000 ,
"PersistedQueryLink.persistedQueryHashes": 2000 ,
"fragmentRegistry.transform": 2000 ,
"fragmentRegistry.lookup": 1000 ,
"fragmentRegistry.findFragmentSpreads": 4000 ,
"cache.fragmentQueryDocuments": 1000 ,
"removeTypenameFromVariables.getVariableDefinitions": 2000 ,
"inMemoryCache.maybeBroadcastWatch": 5000 ,
"inMemoryCache.executeSelectionSet": 50000 ,
"inMemoryCache.executeSubSelectedArray": 10000 ,
};
return Object.fromEntries(Object.entries(defaults).map(function (_a) {
var k = _a[0], v = _a[1];
return [
k,
cacheSizes[k] || v,
];
}));
}
function _getApolloClientMemoryInternals() {
var _a, _b, _c, _d, _e;
if (!(globalThis.__DEV__ !== false))
throw new Error("only supported in development mode");
return {
limits: getCurrentCacheSizes(),
sizes: tslib.__assign({ print: (_a = globalCaches.print) === null || _a === void 0 ? void 0 : _a.call(globalCaches), parser: (_b = globalCaches.parser) === null || _b === void 0 ? void 0 : _b.call(globalCaches), canonicalStringify: (_c = globalCaches.canonicalStringify) === null || _c === void 0 ? void 0 : _c.call(globalCaches), links: linkInfo(this.link), queryManager: {
getDocumentInfo: this["queryManager"]["transformCache"].size,
documentTransforms: transformInfo(this["queryManager"].documentTransform),
} }, (_e = (_d = this.cache).getMemoryInternals) === null || _e === void 0 ? void 0 : _e.call(_d)),
};
}
function isWrapper(f) {
return !!f && "dirtyKey" in f;
}
function getWrapperInformation(f) {
return isWrapper(f) ? f.size : undefined;
}
function isDefined(value) {
return value != null;
}
function transformInfo(transform) {
return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
}
function recurseTransformInfo(transform) {
return transform ?
tslib.__spreadArray(tslib.__spreadArray([
getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
: [];
}
function linkInfo(link) {
var _a;
return link ?
tslib.__spreadArray(tslib.__spreadArray([
(_a = link === null || link === void 0 ? void 0 : link.getMemoryInternals) === null || _a === void 0 ? void 0 : _a.call(link)
], linkInfo(link === null || link === void 0 ? void 0 : link.left), true), linkInfo(link === null || link === void 0 ? void 0 : link.right), true).filter(isDefined)
: [];
}
var hasSuggestedDevtools = false;
var ApolloClient = (function () {
function ApolloClient(options) {
var _this = this;
this.resetStoreCallbacks = [];
this.clearStoreCallbacks = [];
if (!options.cache) {
throw globals.newInvariantError(15);
}
var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b,
connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _d = options.assumeImmutableResults, assumeImmutableResults = _d === void 0 ? cache.assumeImmutableResults : _d, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version, devtools = options.devtools;
var link = options.link;
if (!link) {
link =
uri ? new http.HttpLink({ uri: uri, credentials: credentials, headers: headers }) : core.ApolloLink.empty();
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
this.devtoolsConfig = tslib.__assign(tslib.__assign({}, devtools), { enabled: (devtools === null || devtools === void 0 ? void 0 : devtools.enabled) || connectToDevTools });
if (this.devtoolsConfig.enabled === undefined) {
this.devtoolsConfig.enabled = globalThis.__DEV__ !== false;
}
if (ssrForceFetchDelay) {
setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
}
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.watchFragment = this.watchFragment.bind(this);
this.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
this.version = version;
this.localState = new LocalState({
cache: cache,
client: this,
resolvers: resolvers,
fragmentMatcher: fragmentMatcher,
});
this.queryManager = new QueryManager({
cache: this.cache,
link: this.link,
defaultOptions: this.defaultOptions,
defaultContext: defaultContext,
documentTransform: documentTransform,
queryDeduplication: queryDeduplication,
ssrMode: ssrMode,
clientAwareness: {
name: clientAwarenessName,
version: clientAwarenessVersion,
},
localState: this.localState,
assumeImmutableResults: assumeImmutableResults,
onBroadcast: this.devtoolsConfig.enabled ?
function () {
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: {},
state: {
queries: _this.queryManager.getQueryStore(),
mutations: _this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: _this.cache.extract(true),
});
}
}
: void 0,
});
if (this.devtoolsConfig.enabled)
this.connectToDevTools();
}
ApolloClient.prototype.connectToDevTools = function () {
if (typeof window === "undefined") {
return;
}
var windowWithDevTools = window;
var devtoolsSymbol = Symbol.for("apollo.devtools");
(windowWithDevTools[devtoolsSymbol] =
windowWithDevTools[devtoolsSymbol] || []).push(this);
windowWithDevTools.__APOLLO_CLIENT__ = this;
if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {
hasSuggestedDevtools = true;
if (window.document &&
window.top === window.self &&
/^(https?|file):$/.test(window.location.protocol)) {
setTimeout(function () {
if (!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
var nav = window.navigator;
var ua = nav && nav.userAgent;
var url = void 0;
if (typeof ua === "string") {
if (ua.indexOf("Chrome/") > -1) {
url =
"https://chrome.google.com/webstore/detail/" +
"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
}
else if (ua.indexOf("Firefox/") > -1) {
url =
"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
}
}
if (url) {
globalThis.__DEV__ !== false && globals.invariant.log("Download the Apollo DevTools for a better development " +
"experience: %s", url);
}
}
}, 10000);
}
}
};
Object.defineProperty(ApolloClient.prototype, "documentTransform", {
get: function () {
return this.queryManager.documentTransform;
},
enumerable: false,
configurable: true
});
ApolloClient.prototype.stop = function () {
this.queryManager.stop();
};
ApolloClient.prototype.watchQuery = function (options) {
if (this.defaultOptions.watchQuery) {
options = utilities.mergeOptions(this.defaultOptions.watchQuery, options);
}
if (this.disableNetworkFetches &&
(options.fetchPolicy === "network-only" ||
options.fetchPolicy === "cache-and-network")) {
options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "cache-first" });
}
return this.queryManager.watchQuery(options);
};
ApolloClient.prototype.query = function (options) {
if (this.defaultOptions.query) {
options = utilities.mergeOptions(this.defaultOptions.query, options);
}
globals.invariant(options.fetchPolicy !== "cache-and-network", 16);
if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
options = tslib.__assign(tslib.__assign({}, options), { fetchPolicy: "cache-first" });
}
return this.queryManager.query(options);
};
ApolloClient.prototype.mutate = function (options) {
if (this.defaultOptions.mutate) {
options = utilities.mergeOptions(this.defaultOptions.mutate, options);
}
return this.queryManager.mutate(options);
};
ApolloClient.prototype.subscribe = function (options) {
return this.queryManager.startGraphQLSubscription(options);
};
ApolloClient.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readQuery(options, optimistic);
};
ApolloClient.prototype.watchFragment = function (options) {
return this.cache.watchFragment(options);
};
ApolloClient.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readFragment(options, optimistic);
};
ApolloClient.prototype.writeQuery = function (options) {
var ref = this.cache.writeQuery(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.writeFragment = function (options) {
var ref = this.cache.writeFragment(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.__actionHookForDevTools = function (cb) {
this.devToolsHookCb = cb;
};
ApolloClient.prototype.__requestRaw = function (payload) {
return core.execute(this.link, payload);
};
ApolloClient.prototype.resetStore = function () {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.queryManager.clearStore({
discardWatches: false,
});
})
.then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
.then(function () { return _this.reFetchObservableQueries(); });
};
ApolloClient.prototype.clearStore = function () {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.queryManager.clearStore({
discardWatches: true,
});
})
.then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
};
ApolloClient.prototype.onResetStore = function (cb) {
var _this = this;
this.resetStoreCallbacks.push(cb);
return function () {
_this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.onClearStore = function (cb) {
var _this = this;
this.clearStoreCallbacks.push(cb);
return function () {
_this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
return this.queryManager.reFetchObservableQueries(includeStandby);
};
ApolloClient.prototype.refetchQueries = function (options) {
var map = this.queryManager.refetchQueries(options);
var queries = [];
var results = [];
map.forEach(function (result, obsQuery) {
queries.push(obsQuery);
results.push(result);
});
var result = Promise.all(results);
result.queries = queries;
result.results = results;
result.catch(function (error) {
globalThis.__DEV__ !== false && globals.invariant.debug(17, error);
});
return result;
};
ApolloClient.prototype.getObservableQueries = function (include) {
if (include === void 0) { include = "active"; }
return this.queryManager.getObservableQueries(include);
};
ApolloClient.prototype.extract = function (optimistic) {
return this.cache.extract(optimistic);
};
ApolloClient.prototype.restore = function (serializedState) {
return this.cache.restore(serializedState);
};
ApolloClient.prototype.addResolvers = function (resolvers) {
this.localState.addResolvers(resolvers);
};
ApolloClient.prototype.setResolvers = function (resolvers) {
this.localState.setResolvers(resolvers);
};
ApolloClient.prototype.getResolvers = function () {
return this.localState.getResolvers();
};
ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
};
ApolloClient.prototype.setLink = function (newLink) {
this.link = this.queryManager.link = newLink;
};
Object.defineProperty(ApolloClient.prototype, "defaultContext", {
get: function () {
return this.queryManager.defaultContext;
},
enumerable: false,
configurable: true
});
return ApolloClient;
}());
if (globalThis.__DEV__ !== false) {
ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;
}
tsInvariant.setVerbosity(globalThis.__DEV__ !== false ? "log" : "silent");
exports.DocumentTransform = utilities.DocumentTransform;
exports.Observable = utilities.Observable;
exports.isReference = utilities.isReference;
exports.makeReference = utilities.makeReference;
exports.mergeOptions = utilities.mergeOptions;
exports.ApolloCache = cache.ApolloCache;
exports.Cache = cache.Cache;
exports.InMemoryCache = cache.InMemoryCache;
exports.MissingFieldError = cache.MissingFieldError;
exports.defaultDataIdFromObject = cache.defaultDataIdFromObject;
exports.makeVar = cache.makeVar;
exports.ApolloError = errors.ApolloError;
exports.isApolloError = errors.isApolloError;
exports.fromError = utils.fromError;
exports.fromPromise = utils.fromPromise;
exports.throwServerError = utils.throwServerError;
exports.toPromise = utils.toPromise;
exports.setLogVerbosity = tsInvariant.setVerbosity;
exports.disableExperimentalFragmentVariables = graphqlTag.disableExperimentalFragmentVariables;
exports.disableFragmentWarnings = graphqlTag.disableFragmentWarnings;
exports.enableExperimentalFragmentVariables = graphqlTag.enableExperimentalFragmentVariables;
exports.gql = graphqlTag.gql;
exports.resetCaches = graphqlTag.resetCaches;
exports.ApolloClient = ApolloClient;
exports.ObservableQuery = ObservableQuery;
exports.isNetworkRequestSettled = isNetworkRequestSettled;
for (var k in core) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = core[k];
}
for (var k in http) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = http[k];
}
//# sourceMappingURL=core.cjs.map