@apollo/client 4.3.0-alpha.5 → 4.3.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/__cjs/cache/core/cache.cjs +1 -1
  3. package/__cjs/cache/inmemory/entityStore.cjs +3 -3
  4. package/__cjs/cache/inmemory/key-extractor.cjs +1 -1
  5. package/__cjs/cache/inmemory/policies.cjs +28 -6
  6. package/__cjs/cache/inmemory/policies.cjs.map +1 -1
  7. package/__cjs/cache/inmemory/readFromStore.cjs +3 -3
  8. package/__cjs/cache/inmemory/readFromStore.cjs.map +1 -1
  9. package/__cjs/cache/inmemory/writeToStore.cjs +4 -4
  10. package/__cjs/core/ObservableQuery.cjs +175 -62
  11. package/__cjs/core/ObservableQuery.cjs.map +1 -1
  12. package/__cjs/core/ObservableQuery.d.cts +4 -7
  13. package/__cjs/core/QueryInfo.cjs +13 -136
  14. package/__cjs/core/QueryInfo.cjs.map +1 -1
  15. package/__cjs/core/QueryInfo.d.cts +2 -26
  16. package/__cjs/core/QueryManager.cjs +26 -25
  17. package/__cjs/core/QueryManager.cjs.map +1 -1
  18. package/__cjs/core/RefetchEventManager.cjs +3 -3
  19. package/__cjs/invariantErrorCodes.cjs +57 -32
  20. package/__cjs/utilities/internal/index.cjs +3 -1
  21. package/__cjs/utilities/internal/index.cjs.map +1 -1
  22. package/__cjs/utilities/internal/index.d.cts +1 -0
  23. package/__cjs/utilities/internal/toDiffWithDataState.cjs +20 -0
  24. package/__cjs/utilities/internal/toDiffWithDataState.cjs.map +1 -0
  25. package/__cjs/utilities/internal/toDiffWithDataState.d.cts +8 -0
  26. package/__cjs/version.cjs +1 -1
  27. package/cache/core/cache.js +1 -1
  28. package/cache/inmemory/entityStore.js +3 -3
  29. package/cache/inmemory/key-extractor.js +1 -1
  30. package/cache/inmemory/policies.js +28 -6
  31. package/cache/inmemory/policies.js.map +1 -1
  32. package/cache/inmemory/readFromStore.js +3 -3
  33. package/cache/inmemory/readFromStore.js.map +1 -1
  34. package/cache/inmemory/writeToStore.js +4 -4
  35. package/core/ObservableQuery.d.ts +4 -7
  36. package/core/ObservableQuery.js +172 -63
  37. package/core/ObservableQuery.js.map +1 -1
  38. package/core/QueryInfo.d.ts +3 -27
  39. package/core/QueryInfo.js +14 -137
  40. package/core/QueryInfo.js.map +1 -1
  41. package/core/QueryManager.js +26 -25
  42. package/core/QueryManager.js.map +1 -1
  43. package/core/RefetchEventManager.js +3 -3
  44. package/invariantErrorCodes.js +57 -32
  45. package/package.json +1 -1
  46. package/utilities/internal/index.d.ts +1 -0
  47. package/utilities/internal/index.js +1 -0
  48. package/utilities/internal/index.js.map +1 -1
  49. package/utilities/internal/toDiffWithDataState.d.ts +8 -0
  50. package/utilities/internal/toDiffWithDataState.js +17 -0
  51. package/utilities/internal/toDiffWithDataState.js.map +1 -0
  52. package/version.js +1 -1
@@ -75,7 +75,7 @@ class StoreWriter {
75
75
  path: [],
76
76
  });
77
77
  if (!(0, utilities_1.isReference)(ref)) {
78
- throw (0, invariant_1.newInvariantError)(116, result);
78
+ throw (0, invariant_1.newInvariantError)(118, result);
79
79
  }
80
80
  // So far, the store has not been modified, so now it's time to process
81
81
  // context.incomingById and merge those incoming fields into context.store.
@@ -237,7 +237,7 @@ class StoreWriter {
237
237
  // provide a default value, so its absence from the written data should
238
238
  // not be cause for alarm.
239
239
  !policies.getReadFunction(typename, field.name.value)) {
240
- invariant_1.invariant.error(117, (0, internal_1.resultKeyNameFromField)(field), result);
240
+ invariant_1.invariant.error(119, (0, internal_1.resultKeyNameFromField)(field), result);
241
241
  }
242
242
  });
243
243
  // Identify the result object, even if dataId was already provided,
@@ -385,7 +385,7 @@ class StoreWriter {
385
385
  else {
386
386
  const fragment = (0, internal_1.getFragmentFromSelection)(selection, context.lookupFragment);
387
387
  if (!fragment && selection.kind === graphql_1.Kind.FRAGMENT_SPREAD) {
388
- throw (0, invariant_1.newInvariantError)(118, selection.name.value);
388
+ throw (0, invariant_1.newInvariantError)(120, selection.name.value);
389
389
  }
390
390
  if (fragment &&
391
391
  policies.fragmentMatches(fragment, typename, result, context.variables)) {
@@ -558,7 +558,7 @@ function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
558
558
  }
559
559
  });
560
560
  }
561
- __DEV__ && invariant_1.invariant.warn(119, fieldName, parentType, childTypenames.length ?
561
+ __DEV__ && invariant_1.invariant.warn(121, fieldName, parentType, childTypenames.length ?
562
562
  "either ensure all objects of type " +
563
563
  childTypenames.join(" and ") +
564
564
  " have an ID or a custom merge function, or "
@@ -29,16 +29,29 @@ const empty = {
29
29
  dataState: "empty",
30
30
  partial: true,
31
31
  };
32
+ const destructiveMethodCounts = new WeakMap();
33
+ function wrapDestructiveCacheMethod(cache, methodName) {
34
+ const original = cache[methodName];
35
+ if (typeof original === "function") {
36
+ // @ts-expect-error this is just too generic to be typed correctly
37
+ cache[methodName] = function () {
38
+ destructiveMethodCounts.set(cache,
39
+ // The %1e15 allows the count to wrap around to 0 safely every
40
+ // quadrillion evictions, so there's no risk of overflow. To be
41
+ // clear, this is more of a pedantic principle than something
42
+ // that matters in any conceivable practical scenario.
43
+ (destructiveMethodCounts.get(cache) + 1) % 1e15);
44
+ // @ts-expect-error this is just too generic to be typed correctly
45
+ return original.apply(this, arguments);
46
+ };
47
+ }
48
+ }
32
49
  class ObservableQuery {
33
50
  options;
34
51
  queryName;
35
52
  variablesUnknown = false;
36
- /**
37
- * @internal will be read and written from `QueryInfo`
38
- *
39
- * @deprecated This is an internal API and should not be used directly. This can be removed or changed at any time.
40
- */
41
- _lastWrite;
53
+ didWarnOnFeud = false;
54
+ lastMissing;
42
55
  // The `query` computed property will always reflect the document transformed
43
56
  // by the last run query. `this.options.query` will always reflect the raw
44
57
  // untransformed query to ensure document transforms with runtime conditionals
@@ -75,6 +88,18 @@ class ObservableQuery {
75
88
  }
76
89
  constructor({ queryManager, options, transformedQuery = queryManager.transform(options.query), }) {
77
90
  this.queryManager = queryManager;
91
+ // Track how often destructive cache methods are called, since we want
92
+ // eviction to override the feud-stopping logic in `shouldAutoRefetch`,
93
+ // by causing it to return true. Wrapping these cache methods is a bit of a
94
+ // hack, but it saves us from having to make eviction counting an official
95
+ // part of the ApolloCache API.
96
+ const { cache } = queryManager;
97
+ if (!destructiveMethodCounts.has(cache)) {
98
+ destructiveMethodCounts.set(cache, 0);
99
+ wrapDestructiveCacheMethod(cache, "evict");
100
+ wrapDestructiveCacheMethod(cache, "modify");
101
+ wrapDestructiveCacheMethod(cache, "reset");
102
+ }
78
103
  // active state
79
104
  this.waitForNetworkResult = options.fetchPolicy === "network-only";
80
105
  this.isTornDown = false;
@@ -214,12 +239,13 @@ class ObservableQuery {
214
239
  * @deprecated This is an internal API and should not be used directly. This can be removed or changed at any time.
215
240
  */
216
241
  getCacheDiff({ optimistic = true } = {}) {
217
- return this.cache.diff({
242
+ return (0, internal_1.toDiffWithDataState)(this.cache.diff({
218
243
  query: this.query,
219
244
  variables: this.variables,
220
245
  returnPartialData: true,
221
246
  optimistic,
222
- });
247
+ [internal_1.handleIncrementalSymbol]: undefined,
248
+ }));
223
249
  }
224
250
  getInitialResult(initialFetchPolicy) {
225
251
  let fetchPolicy = initialFetchPolicy || this.options.fetchPolicy;
@@ -229,16 +255,18 @@ class ObservableQuery {
229
255
  }
230
256
  const cacheResult = () => {
231
257
  const diff = this.getCacheDiff();
258
+ let { dataState } = diff;
232
259
  // TODO: queryInfo.getDiff should handle this since cache.diff returns a
233
260
  // null when returnPartialData is false
234
261
  const data = this.options.returnPartialData || diff.complete ?
235
262
  diff.result ?? undefined
236
263
  : undefined;
264
+ if (data === undefined) {
265
+ dataState = "empty";
266
+ }
237
267
  return this.maskResult({
238
268
  data,
239
- dataState: diff.complete ? "complete"
240
- : data === undefined ? "empty"
241
- : "partial",
269
+ dataState,
242
270
  loading: !diff.complete,
243
271
  networkStatus: diff.complete ? networkStatus_js_1.NetworkStatus.ready : networkStatus_js_1.NetworkStatus.loading,
244
272
  partial: !diff.complete,
@@ -399,7 +427,6 @@ class ObservableQuery {
399
427
  reobserveOptions.variables = this.options.variables =
400
428
  this.getVariablesWithDefaults({ ...this.variables, ...variables });
401
429
  }
402
- this._lastWrite = undefined;
403
430
  return this._reobserve(reobserveOptions, {
404
431
  newNetworkStatus: networkStatus_js_1.NetworkStatus.refetch,
405
432
  });
@@ -887,7 +914,6 @@ class ObservableQuery {
887
914
  if (this.pollingInfo) {
888
915
  if (!(0, utilities_1.isNetworkRequestInFlight)(this.networkStatus) &&
889
916
  !this.options.skipPollAttempt?.()) {
890
- this._lastWrite = undefined;
891
917
  this._reobserve({
892
918
  // Most fetchPolicy options don't make sense to use in a polling context, as
893
919
  // users wouldn't want to be polling the cache directly. However, network-only and
@@ -933,7 +959,10 @@ class ObservableQuery {
933
959
  }
934
960
  _reobserve(newOptions, internalOptions) {
935
961
  this.isTornDown = false;
936
- let { newNetworkStatus } = internalOptions || {};
962
+ let { newNetworkStatus, keepLastMissing } = internalOptions || {};
963
+ if (!keepLastMissing) {
964
+ this.lastMissing = undefined;
965
+ }
937
966
  this.queryManager.obsQueries.add(this);
938
967
  const useDisposableObservable =
939
968
  // Refetching uses a disposable Observable to allow refetches using different
@@ -1074,7 +1103,7 @@ class ObservableQuery {
1074
1103
  this.queryManager.obsQueries.delete(this);
1075
1104
  this.isTornDown = true;
1076
1105
  this.abortActiveOperations();
1077
- this._lastWrite = undefined;
1106
+ this.lastMissing = undefined;
1078
1107
  }
1079
1108
  transformDocument(document) {
1080
1109
  return this.queryManager.transform(document);
@@ -1132,53 +1161,126 @@ class ObservableQuery {
1132
1161
  return;
1133
1162
  }
1134
1163
  }
1135
- const { dirty } = this;
1164
+ const { dirty, lastMissing } = this;
1165
+ const { fetchPolicy } = this.options;
1136
1166
  this.resetNotifications();
1137
- if (dirty &&
1138
- (this.options.fetchPolicy === "cache-only" ||
1139
- this.options.fetchPolicy === "cache-and-network" ||
1140
- !this.activeOperations.size)) {
1141
- const diff = this.getCacheDiff();
1142
- if (
1143
- // `fromOptimisticTransaction` is not available through the `cache.diff`
1144
- // code path, so we need to check it this way
1145
- (0, equality_1.equal)(diff.result, this.getCacheDiff({ optimistic: false }).result)) {
1146
- //If this diff did not come from an optimistic transaction
1147
- // make the ObservableQuery "reobserve" the latest data
1148
- // using a temporary fetch policy of "cache-first", so complete cache
1149
- // results have a chance to be delivered without triggering additional
1150
- // network requests, even when options.fetchPolicy is "network-only"
1151
- // or "cache-and-network". All other fetch policies are preserved by
1152
- // this method, and are handled by calling oq.reobserve(). If this
1153
- // reobservation is spurious, distinctUntilChanged still has a
1154
- // chance to catch it before delivery to ObservableQuery subscribers.
1155
- this.reobserveCacheFirst();
1167
+ if (!dirty ||
1168
+ (fetchPolicy !== "cache-only" &&
1169
+ fetchPolicy !== "cache-and-network" &&
1170
+ this.activeOperations.size)) {
1171
+ return;
1172
+ }
1173
+ const diff = this.getCacheDiff();
1174
+ const current = this.getCurrentResult();
1175
+ // `fromOptimisticTransaction` is not available through the `cache.diff`
1176
+ // code path, so we need to check whether the cache result is an optimistic
1177
+ // result this way.
1178
+ const isOptimistic = !(0, equality_1.equal)(diff.result, this.getCacheDiff({ optimistic: false }).result);
1179
+ if (
1180
+ // When this diff came from an optimistic transaction, deliver the
1181
+ // current cache data to the ObservableQuery, but don't perform a
1182
+ // reobservation, since oq.reobserveCacheFirst might make a network
1183
+ // request, and we never want to trigger network requests in the
1184
+ // middle of optimistic updates.
1185
+ isOptimistic ||
1186
+ // If we get a cache update in the middle of streaming (possible with
1187
+ // cache-and-network fetch policy), just deliver the cache value without
1188
+ // going through the full reobserve which would otherwise trigger another
1189
+ // request (deduplication should kick in, but doing so replays any
1190
+ // previous emits from the link chain, which get rewritten into the cache
1191
+ // and might clobber this cache update)
1192
+ (!diff.complete && current.networkStatus === networkStatus_js_1.NetworkStatus.streaming)) {
1193
+ this.deliverCacheDiff(diff);
1194
+ return;
1195
+ }
1196
+ if (diff.complete) {
1197
+ this.lastMissing = undefined;
1198
+ }
1199
+ else if (!lastMissing ||
1200
+ // If a destructive cache method has been called since the last recorded
1201
+ // incomplete result, there's a chance fetching this data again will
1202
+ // restore what was evicted, even though the cache result looks the same
1203
+ // as before.
1204
+ lastMissing.dmCount !== destructiveMethodCounts.get(this.cache) ||
1205
+ !(0, equality_1.equal)(lastMissing.variables, this.variables) ||
1206
+ !(0, equality_1.equal)(lastMissing.missing, diff.missing?.missing)) {
1207
+ this.didWarnOnFeud = false;
1208
+ this.lastMissing = {
1209
+ variables: this.variables,
1210
+ missing: diff.missing?.missing,
1211
+ dmCount: destructiveMethodCounts.get(this.cache),
1212
+ };
1213
+ }
1214
+ else if (
1215
+ // reobserveCacheFirst with cache-only fetch policy only calls
1216
+ // reobserve which never fetches from the network so we are ok
1217
+ // allowing cache-only queries to fallthrough to reobserveCacheFirst.
1218
+ // This also prevents the feud warning which would be confusing for a
1219
+ // cache-only query anyways.
1220
+ fetchPolicy !== "cache-only") {
1221
+ // If we've fallen through to this case, a cache emit has returned the
1222
+ // same missing fields which means at least one value on the fields we've
1223
+ // already delivered have changed. We are ok delivering the updated
1224
+ // partial result in this case to keep the result as fresh as possible. We
1225
+ // NEVER want to downgrade this query from a complete query to a partial
1226
+ // query though, so we also make sure we only deliver if the previous
1227
+ // result was also partial.
1228
+ if (current.dataState === "partial") {
1229
+ this.deliverCacheDiff(diff);
1156
1230
  }
1157
- else {
1158
- // If this diff came from an optimistic transaction, deliver the
1159
- // current cache data to the ObservableQuery, but don't perform a
1160
- // reobservation, since oq.reobserveCacheFirst might make a network
1161
- // request, and we never want to trigger network requests in the
1162
- // middle of optimistic updates.
1163
- this.input.next({
1164
- kind: "N",
1165
- value: {
1166
- data: diff.result,
1167
- dataState: diff.complete ? "complete"
1168
- : diff.result ? "partial"
1169
- : "empty",
1170
- networkStatus: networkStatus_js_1.NetworkStatus.ready,
1171
- loading: false,
1172
- error: undefined,
1173
- partial: !diff.complete,
1174
- },
1175
- source: "cache",
1176
- query: this.query,
1177
- variables: this.variables,
1178
- meta: {},
1179
- });
1231
+ // If the (partial) result is the same as the last partial result
1232
+ // we recorded from a previous broadcast (and the variables match
1233
+ // too), avoid calling reobserveCacheFirst to refetch this query
1234
+ // again. If we allow refetching anytime this result becomes partial,
1235
+ // we risk feuds between queries competing to update the same data in
1236
+ // incompatible ways, which can lead to an endless cycle of cache
1237
+ // broadcasts and useless network requests. As with any
1238
+ // feud, eventually one side must step back from the brink,
1239
+ // letting the other side(s) have the last word(s). There may
1240
+ // be other points where we could break this cycle, such as
1241
+ // silencing the broadcast for cache.writeQuery (not a good
1242
+ // idea, since it just delays the feud a bit) or somehow
1243
+ // avoiding the network request that just happened (also bad,
1244
+ // because the server could return useful new data). All
1245
+ // options considered, returning early and stopping the
1246
+ // reobserveCacheFirst cycle seems to be the least damaging place to
1247
+ // break the cycle because it allows read functions/custom scalars to
1248
+ // be applied to the feuding query while avoiding the endless cycle of
1249
+ // requests.
1250
+ if (environment_1.__DEV__ && !this.didWarnOnFeud) {
1251
+ this.didWarnOnFeud = true;
1252
+ warnOnFeud(this.query, diff);
1180
1253
  }
1254
+ return;
1181
1255
  }
1256
+ //If this diff did not come from an optimistic transaction
1257
+ // make the ObservableQuery "reobserve" the latest data
1258
+ // using a temporary fetch policy of "cache-first", so complete cache
1259
+ // results have a chance to be delivered without triggering additional
1260
+ // network requests, even when options.fetchPolicy is "network-only"
1261
+ // or "cache-and-network". All other fetch policies are preserved by
1262
+ // this method, and are handled by calling oq.reobserve(). If this
1263
+ // reobservation is spurious, distinctUntilChanged still has a
1264
+ // chance to catch it before delivery to ObservableQuery subscribers.
1265
+ this.reobserveCacheFirst();
1266
+ }
1267
+ deliverCacheDiff(diff) {
1268
+ const current = this.getCurrentResult();
1269
+ this.input.next({
1270
+ kind: "N",
1271
+ value: {
1272
+ data: diff.result,
1273
+ dataState: diff.dataState,
1274
+ networkStatus: current.networkStatus,
1275
+ loading: current.loading,
1276
+ error: undefined,
1277
+ partial: !diff.complete,
1278
+ },
1279
+ source: "cache",
1280
+ query: this.query,
1281
+ variables: this.variables,
1282
+ meta: {},
1283
+ });
1182
1284
  }
1183
1285
  activeOperations = new Set();
1184
1286
  pushOperation(networkStatus) {
@@ -1241,6 +1343,7 @@ class ObservableQuery {
1241
1343
  // exception for cache-only queries - we reset them into a "ready" state
1242
1344
  // as we won't trigger a refetch for them
1243
1345
  const resetToEmpty = this.options.fetchPolicy === "cache-only";
1346
+ this.lastMissing = undefined;
1244
1347
  this.setResult(resetToEmpty ? empty : uninitialized, {
1245
1348
  shouldEmit: resetToEmpty ? 1 /* EmitBehavior.force */ : 2 /* EmitBehavior.never */,
1246
1349
  });
@@ -1310,7 +1413,7 @@ class ObservableQuery {
1310
1413
  if (notification.source === "cache") {
1311
1414
  result = notification.value;
1312
1415
  if (result.networkStatus === networkStatus_js_1.NetworkStatus.ready &&
1313
- result.partial &&
1416
+ result.dataState === "partial" &&
1314
1417
  (!this.options.returnPartialData ||
1315
1418
  previous.result.networkStatus === networkStatus_js_1.NetworkStatus.error) &&
1316
1419
  this.options.fetchPolicy !== "cache-only") {
@@ -1385,7 +1488,10 @@ class ObservableQuery {
1385
1488
  reobserveCacheFirst() {
1386
1489
  const { fetchPolicy, nextFetchPolicy } = this.options;
1387
1490
  if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
1388
- this.reobserve({
1491
+ // Preserve this.lastMissing so a cache update that triggers this
1492
+ // reobserve doesn't reset feud detection. All user-initiated calls to
1493
+ // reobserve (refetch/poll/reobserve, etc) should clear it.
1494
+ this._reobserve({
1389
1495
  fetchPolicy: "cache-first",
1390
1496
  // Use a temporary nextFetchPolicy function that replaces itself with the
1391
1497
  // previous nextFetchPolicy value and returns the original fetchPolicy.
@@ -1401,10 +1507,10 @@ class ObservableQuery {
1401
1507
  // Otherwise go back to the original this.options.fetchPolicy.
1402
1508
  return fetchPolicy;
1403
1509
  },
1404
- });
1510
+ }, { keepLastMissing: true });
1405
1511
  }
1406
1512
  else {
1407
- this.reobserve();
1513
+ this._reobserve(undefined, { keepLastMissing: true });
1408
1514
  }
1409
1515
  }
1410
1516
  getVariablesWithDefaults(variables) {
@@ -1457,4 +1563,11 @@ function getTrackingOperatorPromise(defaultValue) {
1457
1563
  });
1458
1564
  return { promise, operator };
1459
1565
  }
1566
+ function warnOnFeud(query, diff) {
1567
+ __DEV__ && invariant_1.invariant.warn(
1568
+ 89,
1569
+ (0, internal_1.getOperationName)(query, "(anonymous)"),
1570
+ diff.missing?.missing
1571
+ );
1572
+ }
1460
1573
  //# sourceMappingURL=ObservableQuery.cjs.map