@apollo/client
Version:
A fully-featured caching GraphQL client.
1,162 lines (1,147 loc) • 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") {