@apollo/client 3.5.0-rc.0 → 3.5.0

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 (87) hide show
  1. package/apollo-client.cjs +565 -496
  2. package/apollo-client.cjs.map +1 -1
  3. package/apollo-client.min.cjs +1 -1
  4. package/cache/cache.cjs +526 -458
  5. package/cache/cache.cjs.map +1 -1
  6. package/cache/inmemory/key-extractor.d.ts +9 -0
  7. package/cache/inmemory/key-extractor.d.ts.map +1 -0
  8. package/cache/inmemory/key-extractor.js +118 -0
  9. package/cache/inmemory/key-extractor.js.map +1 -0
  10. package/cache/inmemory/policies.d.ts +11 -8
  11. package/cache/inmemory/policies.d.ts.map +1 -1
  12. package/cache/inmemory/policies.js +42 -156
  13. package/cache/inmemory/policies.js.map +1 -1
  14. package/cache/inmemory/writeToStore.d.ts +8 -3
  15. package/cache/inmemory/writeToStore.d.ts.map +1 -1
  16. package/cache/inmemory/writeToStore.js +162 -93
  17. package/cache/inmemory/writeToStore.js.map +1 -1
  18. package/core/ApolloClient.d.ts +1 -0
  19. package/core/ApolloClient.d.ts.map +1 -1
  20. package/core/ApolloClient.js +6 -2
  21. package/core/ApolloClient.js.map +1 -1
  22. package/core/ObservableQuery.d.ts +1 -0
  23. package/core/ObservableQuery.d.ts.map +1 -1
  24. package/core/QueryInfo.d.ts +2 -2
  25. package/core/QueryInfo.d.ts.map +1 -1
  26. package/core/QueryManager.d.ts +3 -3
  27. package/core/QueryManager.d.ts.map +1 -1
  28. package/core/QueryManager.js +6 -9
  29. package/core/QueryManager.js.map +1 -1
  30. package/core/core.cjs +13 -12
  31. package/core/core.cjs.map +1 -1
  32. package/invariantErrorCodes.js +5 -5
  33. package/link/batch/batchLink.d.ts +1 -0
  34. package/link/batch/batchLink.d.ts.map +1 -1
  35. package/link/batch/batching.d.ts +1 -0
  36. package/link/batch/batching.d.ts.map +1 -1
  37. package/link/batch-http/batchHttpLink.d.ts +1 -0
  38. package/link/batch-http/batchHttpLink.d.ts.map +1 -1
  39. package/link/core/ApolloLink.d.ts +1 -0
  40. package/link/core/ApolloLink.d.ts.map +1 -1
  41. package/link/core/types.d.ts +5 -6
  42. package/link/core/types.d.ts.map +1 -1
  43. package/link/core/types.js.map +1 -1
  44. package/link/error/index.d.ts +1 -0
  45. package/link/error/index.d.ts.map +1 -1
  46. package/link/retry/retryLink.d.ts +1 -0
  47. package/link/retry/retryLink.d.ts.map +1 -1
  48. package/link/schema/index.d.ts +1 -0
  49. package/link/schema/index.d.ts.map +1 -1
  50. package/link/schema/index.js +8 -1
  51. package/link/schema/index.js.map +1 -1
  52. package/link/schema/schema.cjs +8 -1
  53. package/link/schema/schema.cjs.map +1 -1
  54. package/link/utils/fromError.d.ts +1 -0
  55. package/link/utils/fromError.d.ts.map +1 -1
  56. package/link/utils/fromPromise.d.ts +1 -0
  57. package/link/utils/fromPromise.d.ts.map +1 -1
  58. package/link/utils/toPromise.d.ts +1 -0
  59. package/link/utils/toPromise.d.ts.map +1 -1
  60. package/link/ws/index.d.ts +1 -0
  61. package/link/ws/index.d.ts.map +1 -1
  62. package/package.json +21 -21
  63. package/react/types/types.d.ts +1 -0
  64. package/react/types/types.d.ts.map +1 -1
  65. package/testing/core/mocking/mockLink.d.ts +1 -0
  66. package/testing/core/mocking/mockLink.d.ts.map +1 -1
  67. package/testing/core/mocking/mockSubscriptionLink.d.ts +2 -3
  68. package/testing/core/mocking/mockSubscriptionLink.d.ts.map +1 -1
  69. package/utilities/common/errorHandling.d.ts +1 -1
  70. package/utilities/common/errorHandling.d.ts.map +1 -1
  71. package/utilities/common/errorHandling.js.map +1 -1
  72. package/utilities/globals/fix-graphql.d.ts.map +1 -1
  73. package/utilities/globals/fix-graphql.js +2 -3
  74. package/utilities/globals/fix-graphql.js.map +1 -1
  75. package/utilities/globals/globals.cjs +1 -2
  76. package/utilities/globals/globals.cjs.map +1 -1
  77. package/utilities/graphql/fragments.d.ts.map +1 -1
  78. package/utilities/graphql/fragments.js.map +1 -1
  79. package/utilities/graphql/transform.d.ts.map +1 -1
  80. package/utilities/graphql/transform.js.map +1 -1
  81. package/utilities/observables/Concast.d.ts +1 -0
  82. package/utilities/observables/Concast.d.ts.map +1 -1
  83. package/utilities/observables/asyncMap.d.ts +1 -0
  84. package/utilities/observables/asyncMap.d.ts.map +1 -1
  85. package/utilities/observables/subclassing.d.ts +1 -0
  86. package/utilities/observables/subclassing.d.ts.map +1 -1
  87. package/version.js +1 -1
package/cache/cache.cjs CHANGED
@@ -1005,330 +1005,6 @@ function assertSelectionSetForIdValue(store, field, fieldValue) {
1005
1005
  }
1006
1006
  }
1007
1007
 
1008
- var StoreWriter = (function () {
1009
- function StoreWriter(cache, reader) {
1010
- this.cache = cache;
1011
- this.reader = reader;
1012
- }
1013
- StoreWriter.prototype.writeToStore = function (store, _a) {
1014
- var _this = this;
1015
- var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
1016
- var operationDefinition = utilities.getOperationDefinition(query);
1017
- var merger = makeProcessedFieldsMerger();
1018
- variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(operationDefinition)), variables);
1019
- var context = {
1020
- store: store,
1021
- written: Object.create(null),
1022
- merge: function (existing, incoming) {
1023
- return merger.merge(existing, incoming);
1024
- },
1025
- variables: variables,
1026
- varString: canonicalStringify(variables),
1027
- fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
1028
- overwrite: !!overwrite,
1029
- incomingById: new Map,
1030
- clientOnly: false,
1031
- };
1032
- var ref = this.processSelectionSet({
1033
- result: result || Object.create(null),
1034
- dataId: dataId,
1035
- selectionSet: operationDefinition.selectionSet,
1036
- mergeTree: { map: new Map },
1037
- context: context,
1038
- });
1039
- if (!utilities.isReference(ref)) {
1040
- throw __DEV__ ? new globals.InvariantError("Could not identify object " + JSON.stringify(result)) : new globals.InvariantError(6);
1041
- }
1042
- context.incomingById.forEach(function (_a, dataId) {
1043
- var fields = _a.fields, mergeTree = _a.mergeTree, selections = _a.selections;
1044
- var entityRef = utilities.makeReference(dataId);
1045
- if (mergeTree && mergeTree.map.size) {
1046
- var applied = _this.applyMerges(mergeTree, entityRef, fields, context);
1047
- if (utilities.isReference(applied)) {
1048
- return;
1049
- }
1050
- fields = applied;
1051
- }
1052
- if (__DEV__ && !context.overwrite) {
1053
- var hasSelectionSet_1 = function (storeFieldName) {
1054
- return fieldsWithSelectionSets_1.has(fieldNameFromStoreName(storeFieldName));
1055
- };
1056
- var fieldsWithSelectionSets_1 = new Set();
1057
- selections.forEach(function (selection) {
1058
- if (utilities.isField(selection) && selection.selectionSet) {
1059
- fieldsWithSelectionSets_1.add(selection.name.value);
1060
- }
1061
- });
1062
- var hasMergeFunction_1 = function (storeFieldName) {
1063
- var childTree = mergeTree && mergeTree.map.get(storeFieldName);
1064
- return Boolean(childTree && childTree.info && childTree.info.merge);
1065
- };
1066
- Object.keys(fields).forEach(function (storeFieldName) {
1067
- if (hasSelectionSet_1(storeFieldName) &&
1068
- !hasMergeFunction_1(storeFieldName)) {
1069
- warnAboutDataLoss(entityRef, fields, storeFieldName, context.store);
1070
- }
1071
- });
1072
- }
1073
- store.merge(dataId, fields);
1074
- });
1075
- store.retain(ref.__ref);
1076
- return ref;
1077
- };
1078
- StoreWriter.prototype.processSelectionSet = function (_a) {
1079
- var _this = this;
1080
- var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, mergeTree = _a.mergeTree;
1081
- var policies = this.cache.policies;
1082
- var _b = policies.identify(result, selectionSet, context.fragmentMap), id = _b[0], keyObject = _b[1];
1083
- dataId = dataId || id;
1084
- if ("string" === typeof dataId) {
1085
- var sets = context.written[dataId] || (context.written[dataId] = []);
1086
- var ref = utilities.makeReference(dataId);
1087
- if (sets.indexOf(selectionSet) >= 0)
1088
- return ref;
1089
- sets.push(selectionSet);
1090
- if (this.reader && this.reader.isFresh(result, ref, selectionSet, context)) {
1091
- return ref;
1092
- }
1093
- }
1094
- var incomingFields = Object.create(null);
1095
- if (keyObject) {
1096
- incomingFields = context.merge(incomingFields, keyObject);
1097
- }
1098
- var typename = (dataId && policies.rootTypenamesById[dataId]) ||
1099
- utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
1100
- (dataId && context.store.get(dataId, "__typename"));
1101
- if ("string" === typeof typename) {
1102
- incomingFields.__typename = typename;
1103
- }
1104
- var selections = new Set(selectionSet.selections);
1105
- selections.forEach(function (selection) {
1106
- var _a;
1107
- if (!utilities.shouldInclude(selection, context.variables))
1108
- return;
1109
- if (utilities.isField(selection)) {
1110
- var resultFieldKey = utilities.resultKeyNameFromField(selection);
1111
- var value = result[resultFieldKey];
1112
- var wasClientOnly = context.clientOnly;
1113
- context.clientOnly = wasClientOnly || !!(selection.directives &&
1114
- selection.directives.some(function (d) { return d.name.value === "client"; }));
1115
- if (value !== void 0) {
1116
- var storeFieldName = policies.getStoreFieldName({
1117
- typename: typename,
1118
- fieldName: selection.name.value,
1119
- field: selection,
1120
- variables: context.variables,
1121
- });
1122
- var childTree = getChildMergeTree(mergeTree, storeFieldName);
1123
- var incomingValue = _this.processFieldValue(value, selection, context, childTree);
1124
- var childTypename = void 0;
1125
- if (selection.selectionSet) {
1126
- childTypename = context.store.getFieldValue(incomingValue, "__typename");
1127
- if (!childTypename && utilities.isReference(incomingValue)) {
1128
- var info = context.incomingById.get(incomingValue.__ref);
1129
- childTypename = info && info.fields.__typename;
1130
- }
1131
- }
1132
- var merge = policies.getMergeFunction(typename, selection.name.value, childTypename);
1133
- if (merge) {
1134
- childTree.info = {
1135
- field: selection,
1136
- typename: typename,
1137
- merge: merge,
1138
- };
1139
- }
1140
- else {
1141
- maybeRecycleChildMergeTree(mergeTree, storeFieldName);
1142
- }
1143
- incomingFields = context.merge(incomingFields, (_a = {},
1144
- _a[storeFieldName] = incomingValue,
1145
- _a));
1146
- }
1147
- else if (__DEV__ &&
1148
- !context.clientOnly &&
1149
- !utilities.addTypenameToDocument.added(selection) &&
1150
- !policies.getReadFunction(typename, selection.name.value)) {
1151
- __DEV__ && globals.invariant.error(("Missing field '" + utilities.resultKeyNameFromField(selection) + "' while writing result " + JSON.stringify(result, null, 2)).substring(0, 1000));
1152
- }
1153
- context.clientOnly = wasClientOnly;
1154
- }
1155
- else {
1156
- var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
1157
- if (fragment &&
1158
- policies.fragmentMatches(fragment, typename, result, context.variables)) {
1159
- fragment.selectionSet.selections.forEach(selections.add, selections);
1160
- }
1161
- }
1162
- });
1163
- if ("string" === typeof dataId) {
1164
- var previous = context.incomingById.get(dataId);
1165
- if (previous) {
1166
- previous.fields = context.merge(previous.fields, incomingFields);
1167
- previous.mergeTree = mergeMergeTrees(previous.mergeTree, mergeTree);
1168
- previous.selections.forEach(selections.add, selections);
1169
- previous.selections = selections;
1170
- }
1171
- else {
1172
- context.incomingById.set(dataId, {
1173
- fields: incomingFields,
1174
- mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
1175
- selections: selections,
1176
- });
1177
- }
1178
- return utilities.makeReference(dataId);
1179
- }
1180
- return incomingFields;
1181
- };
1182
- StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
1183
- var _this = this;
1184
- if (!field.selectionSet || value === null) {
1185
- return __DEV__ ? utilities.cloneDeep(value) : value;
1186
- }
1187
- if (Array.isArray(value)) {
1188
- return value.map(function (item, i) {
1189
- var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
1190
- maybeRecycleChildMergeTree(mergeTree, i);
1191
- return value;
1192
- });
1193
- }
1194
- return this.processSelectionSet({
1195
- result: value,
1196
- selectionSet: field.selectionSet,
1197
- context: context,
1198
- mergeTree: mergeTree,
1199
- });
1200
- };
1201
- StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
1202
- var _a;
1203
- var _this = this;
1204
- if (mergeTree.map.size && !utilities.isReference(incoming)) {
1205
- var e_1 = (!Array.isArray(incoming) &&
1206
- (utilities.isReference(existing) || storeValueIsStoreObject(existing))) ? existing : void 0;
1207
- var i_1 = incoming;
1208
- if (e_1 && !getStorageArgs) {
1209
- getStorageArgs = [utilities.isReference(e_1) ? e_1.__ref : e_1];
1210
- }
1211
- var changedFields_1;
1212
- var getValue_1 = function (from, name) {
1213
- return Array.isArray(from)
1214
- ? (typeof name === "number" ? from[name] : void 0)
1215
- : context.store.getFieldValue(from, String(name));
1216
- };
1217
- mergeTree.map.forEach(function (childTree, storeFieldName) {
1218
- var eVal = getValue_1(e_1, storeFieldName);
1219
- var iVal = getValue_1(i_1, storeFieldName);
1220
- if (void 0 === iVal)
1221
- return;
1222
- if (getStorageArgs) {
1223
- getStorageArgs.push(storeFieldName);
1224
- }
1225
- var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
1226
- if (aVal !== iVal) {
1227
- changedFields_1 = changedFields_1 || new Map;
1228
- changedFields_1.set(storeFieldName, aVal);
1229
- }
1230
- if (getStorageArgs) {
1231
- globals.invariant(getStorageArgs.pop() === storeFieldName);
1232
- }
1233
- });
1234
- if (changedFields_1) {
1235
- incoming = (Array.isArray(i_1) ? i_1.slice(0) : tslib.__assign({}, i_1));
1236
- changedFields_1.forEach(function (value, name) {
1237
- incoming[name] = value;
1238
- });
1239
- }
1240
- }
1241
- if (mergeTree.info) {
1242
- return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
1243
- }
1244
- return incoming;
1245
- };
1246
- return StoreWriter;
1247
- }());
1248
- var emptyMergeTreePool = [];
1249
- function getChildMergeTree(_a, name) {
1250
- var map = _a.map;
1251
- if (!map.has(name)) {
1252
- map.set(name, emptyMergeTreePool.pop() || { map: new Map });
1253
- }
1254
- return map.get(name);
1255
- }
1256
- function mergeMergeTrees(left, right) {
1257
- if (left === right || !right || mergeTreeIsEmpty(right))
1258
- return left;
1259
- if (!left || mergeTreeIsEmpty(left))
1260
- return right;
1261
- var info = left.info && right.info ? tslib.__assign(tslib.__assign({}, left.info), right.info) : left.info || right.info;
1262
- var needToMergeMaps = left.map.size && right.map.size;
1263
- var map = needToMergeMaps ? new Map :
1264
- left.map.size ? left.map : right.map;
1265
- var merged = { info: info, map: map };
1266
- if (needToMergeMaps) {
1267
- var remainingRightKeys_1 = new Set(right.map.keys());
1268
- left.map.forEach(function (leftTree, key) {
1269
- merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
1270
- remainingRightKeys_1.delete(key);
1271
- });
1272
- remainingRightKeys_1.forEach(function (key) {
1273
- merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
1274
- });
1275
- }
1276
- return merged;
1277
- }
1278
- function mergeTreeIsEmpty(tree) {
1279
- return !tree || !(tree.info || tree.map.size);
1280
- }
1281
- function maybeRecycleChildMergeTree(_a, name) {
1282
- var map = _a.map;
1283
- var childTree = map.get(name);
1284
- if (childTree && mergeTreeIsEmpty(childTree)) {
1285
- emptyMergeTreePool.push(childTree);
1286
- map.delete(name);
1287
- }
1288
- }
1289
- var warnings = new Set();
1290
- function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
1291
- var getChild = function (objOrRef) {
1292
- var child = store.getFieldValue(objOrRef, storeFieldName);
1293
- return typeof child === "object" && child;
1294
- };
1295
- var existing = getChild(existingRef);
1296
- if (!existing)
1297
- return;
1298
- var incoming = getChild(incomingObj);
1299
- if (!incoming)
1300
- return;
1301
- if (utilities.isReference(existing))
1302
- return;
1303
- if (equality.equal(existing, incoming))
1304
- return;
1305
- if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
1306
- return;
1307
- }
1308
- var parentType = store.getFieldValue(existingRef, "__typename") ||
1309
- store.getFieldValue(incomingObj, "__typename");
1310
- var fieldName = fieldNameFromStoreName(storeFieldName);
1311
- var typeDotName = parentType + "." + fieldName;
1312
- if (warnings.has(typeDotName))
1313
- return;
1314
- warnings.add(typeDotName);
1315
- var childTypenames = [];
1316
- if (!Array.isArray(existing) &&
1317
- !Array.isArray(incoming)) {
1318
- [existing, incoming].forEach(function (child) {
1319
- var typename = store.getFieldValue(child, "__typename");
1320
- if (typeof typename === "string" &&
1321
- !childTypenames.includes(typename)) {
1322
- childTypenames.push(typename);
1323
- }
1324
- });
1325
- }
1326
- __DEV__ && globals.invariant.warn("Cache data may be lost when replacing the " + fieldName + " field of a " + parentType + " object.\n\nTo address this problem (which is not a bug in Apollo Client), " + (childTypenames.length
1327
- ? "either ensure all objects of type " +
1328
- childTypenames.join(" and ") + " have an ID or a custom merge function, or "
1329
- : "") + "define a custom merge function for the " + typeDotName + " field, so InMemoryCache can safely merge these objects:\n\n existing: " + JSON.stringify(existing).slice(0, 1000) + "\n incoming: " + JSON.stringify(incoming).slice(0, 1000) + "\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n");
1330
- }
1331
-
1332
1008
  var cacheSlot = new context.Slot();
1333
1009
  var cacheInfoMap = new WeakMap();
1334
1010
  function getCacheInfo(cache) {
@@ -1392,7 +1068,122 @@ function broadcast(cache) {
1392
1068
  }
1393
1069
  }
1394
1070
 
1395
- utilities.getStoreKeyName.setStringify(canonicalStringify);
1071
+ var specifierInfoCache = Object.create(null);
1072
+ function lookupSpecifierInfo(spec) {
1073
+ var cacheKey = JSON.stringify(spec);
1074
+ return specifierInfoCache[cacheKey] ||
1075
+ (specifierInfoCache[cacheKey] = Object.create(null));
1076
+ }
1077
+ function keyFieldsFnFromSpecifier(specifier) {
1078
+ var info = lookupSpecifierInfo(specifier);
1079
+ return info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {
1080
+ var extract = function (from, key) { return context.readField(key, from); };
1081
+ var keyObject = context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {
1082
+ var extracted = extractKeyPath(context.storeObject, schemaKeyPath, extract);
1083
+ if (extracted === void 0 &&
1084
+ object !== context.storeObject &&
1085
+ hasOwn.call(object, schemaKeyPath[0])) {
1086
+ extracted = extractKeyPath(object, schemaKeyPath, extractKey);
1087
+ }
1088
+ __DEV__ ? globals.invariant(extracted !== void 0, "Missing field '" + schemaKeyPath.join('.') + "' while extracting keyFields from " + JSON.stringify(object)) : globals.invariant(extracted !== void 0, 2);
1089
+ return extracted;
1090
+ });
1091
+ return context.typename + ":" + JSON.stringify(keyObject);
1092
+ });
1093
+ }
1094
+ function keyArgsFnFromSpecifier(specifier) {
1095
+ var info = lookupSpecifierInfo(specifier);
1096
+ return info.keyArgsFn || (info.keyArgsFn = function (args, _a) {
1097
+ var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;
1098
+ var collected = collectSpecifierPaths(specifier, function (keyPath) {
1099
+ var firstKey = keyPath[0];
1100
+ var firstChar = firstKey.charAt(0);
1101
+ if (firstChar === "@") {
1102
+ if (field && utilities.isNonEmptyArray(field.directives)) {
1103
+ var directiveName_1 = firstKey.slice(1);
1104
+ var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
1105
+ var directiveArgs = d && utilities.argumentsObjectFromField(d, variables);
1106
+ return directiveArgs && extractKeyPath(directiveArgs, keyPath.slice(1));
1107
+ }
1108
+ return;
1109
+ }
1110
+ if (firstChar === "$") {
1111
+ var variableName = firstKey.slice(1);
1112
+ if (variables && hasOwn.call(variables, variableName)) {
1113
+ var varKeyPath = keyPath.slice(0);
1114
+ varKeyPath[0] = variableName;
1115
+ return extractKeyPath(variables, varKeyPath);
1116
+ }
1117
+ return;
1118
+ }
1119
+ if (args) {
1120
+ return extractKeyPath(args, keyPath);
1121
+ }
1122
+ });
1123
+ var suffix = JSON.stringify(collected);
1124
+ if (args || suffix !== "{}") {
1125
+ fieldName += ":" + suffix;
1126
+ }
1127
+ return fieldName;
1128
+ });
1129
+ }
1130
+ function collectSpecifierPaths(specifier, extractor) {
1131
+ var merger = new utilities.DeepMerger;
1132
+ return getSpecifierPaths(specifier).reduce(function (collected, path) {
1133
+ var _a;
1134
+ var toMerge = extractor(path);
1135
+ if (toMerge !== void 0) {
1136
+ for (var i = path.length - 1; i >= 0; --i) {
1137
+ toMerge = (_a = {}, _a[path[i]] = toMerge, _a);
1138
+ }
1139
+ collected = merger.merge(collected, toMerge);
1140
+ }
1141
+ return collected;
1142
+ }, Object.create(null));
1143
+ }
1144
+ function getSpecifierPaths(spec) {
1145
+ var info = lookupSpecifierInfo(spec);
1146
+ if (!info.paths) {
1147
+ var paths_1 = info.paths = [];
1148
+ var currentPath_1 = [];
1149
+ spec.forEach(function (s, i) {
1150
+ if (Array.isArray(s)) {
1151
+ getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });
1152
+ currentPath_1.length = 0;
1153
+ }
1154
+ else {
1155
+ currentPath_1.push(s);
1156
+ if (!Array.isArray(spec[i + 1])) {
1157
+ paths_1.push(currentPath_1.slice(0));
1158
+ currentPath_1.length = 0;
1159
+ }
1160
+ }
1161
+ });
1162
+ }
1163
+ return info.paths;
1164
+ }
1165
+ function extractKey(object, key) {
1166
+ return object[key];
1167
+ }
1168
+ function extractKeyPath(object, path, extract) {
1169
+ extract = extract || extractKey;
1170
+ return normalize(path.reduce(function reducer(obj, key) {
1171
+ return Array.isArray(obj)
1172
+ ? obj.map(function (child) { return reducer(child, key); })
1173
+ : obj && extract(obj, key);
1174
+ }, object));
1175
+ }
1176
+ function normalize(value) {
1177
+ if (utilities.isNonNullObject(value)) {
1178
+ if (Array.isArray(value)) {
1179
+ return value.map(normalize);
1180
+ }
1181
+ return collectSpecifierPaths(Object.keys(value).sort(), function (path) { return extractKeyPath(value, path); });
1182
+ }
1183
+ return value;
1184
+ }
1185
+
1186
+ utilities.getStoreKeyName.setStringify(canonicalStringify);
1396
1187
  function argsFromFieldSpecifier(spec) {
1397
1188
  return spec.args !== void 0 ? spec.args :
1398
1189
  spec.field ? utilities.argumentsObjectFromField(spec.field, spec.variables) : null;
@@ -1426,18 +1217,22 @@ var Policies = (function () {
1426
1217
  this.addTypePolicies(config.typePolicies);
1427
1218
  }
1428
1219
  }
1429
- Policies.prototype.identify = function (object, selectionSet, fragmentMap) {
1430
- var typename = selectionSet && fragmentMap
1431
- ? utilities.getTypenameFromResult(object, selectionSet, fragmentMap)
1432
- : object.__typename;
1220
+ Policies.prototype.identify = function (object, partialContext) {
1221
+ var _a;
1222
+ var policies = this;
1223
+ var typename = partialContext && (partialContext.typename ||
1224
+ ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename)) || object.__typename;
1433
1225
  if (typename === this.rootTypenamesById.ROOT_QUERY) {
1434
1226
  return ["ROOT_QUERY"];
1435
1227
  }
1436
- var context = {
1437
- typename: typename,
1438
- selectionSet: selectionSet,
1439
- fragmentMap: fragmentMap,
1440
- };
1228
+ var storeObject = partialContext && partialContext.storeObject || object;
1229
+ var context = tslib.__assign(tslib.__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: partialContext && partialContext.readField || function () {
1230
+ var options = normalizeReadFieldOptions(arguments, storeObject);
1231
+ return policies.readField(options, {
1232
+ store: policies.cache["data"],
1233
+ variables: options.variables,
1234
+ });
1235
+ } });
1441
1236
  var id;
1442
1237
  var policy = typename && this.getTypePolicy(typename);
1443
1238
  var keyFn = policy && policy.keyFn || this.config.dataIdFromObject;
@@ -1519,7 +1314,7 @@ var Policies = (function () {
1519
1314
  var rootId = "ROOT_" + which.toUpperCase();
1520
1315
  var old = this.rootTypenamesById[rootId];
1521
1316
  if (typename !== old) {
1522
- __DEV__ ? globals.invariant(!old || old === which, "Cannot change root " + which + " __typename more than once") : globals.invariant(!old || old === which, 2);
1317
+ __DEV__ ? globals.invariant(!old || old === which, "Cannot change root " + which + " __typename more than once") : globals.invariant(!old || old === which, 3);
1523
1318
  if (old)
1524
1319
  delete this.rootIdsByTypename[old];
1525
1320
  this.rootIdsByTypename[typename] = rootId;
@@ -1735,39 +1530,39 @@ function makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, contex
1735
1530
  storage: storage,
1736
1531
  cache: policies.cache,
1737
1532
  canRead: canRead,
1738
- readField: function (fieldNameOrOptions, from) {
1739
- var options;
1740
- if (typeof fieldNameOrOptions === "string") {
1741
- options = {
1742
- fieldName: fieldNameOrOptions,
1743
- from: arguments.length > 1 ? from : objectOrReference,
1744
- };
1745
- }
1746
- else if (utilities.isNonNullObject(fieldNameOrOptions)) {
1747
- options = tslib.__assign({}, fieldNameOrOptions);
1748
- if (!hasOwn.call(fieldNameOrOptions, "from")) {
1749
- options.from = objectOrReference;
1750
- }
1751
- }
1752
- else {
1753
- __DEV__ && globals.invariant.warn("Unexpected readField arguments: " + utilities.stringifyForDisplay(Array.from(arguments)));
1754
- return;
1755
- }
1756
- if (__DEV__ && options.from === void 0) {
1757
- __DEV__ && globals.invariant.warn("Undefined 'from' passed to readField with arguments " + utilities.stringifyForDisplay(Array.from(arguments)));
1758
- }
1759
- if (void 0 === options.variables) {
1760
- options.variables = variables;
1761
- }
1762
- return policies.readField(options, context);
1533
+ readField: function () {
1534
+ return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, context), context);
1763
1535
  },
1764
1536
  mergeObjects: makeMergeObjectsFunction(context.store),
1765
1537
  };
1766
1538
  }
1539
+ function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {
1540
+ var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;
1541
+ var options;
1542
+ if (typeof fieldNameOrOptions === "string") {
1543
+ options = {
1544
+ fieldName: fieldNameOrOptions,
1545
+ from: argc > 1 ? from : objectOrReference,
1546
+ };
1547
+ }
1548
+ else {
1549
+ options = tslib.__assign({}, fieldNameOrOptions);
1550
+ if (!hasOwn.call(options, "from")) {
1551
+ options.from = objectOrReference;
1552
+ }
1553
+ }
1554
+ if (__DEV__ && options.from === void 0) {
1555
+ __DEV__ && globals.invariant.warn("Undefined 'from' passed to readField with arguments " + utilities.stringifyForDisplay(Array.from(readFieldArgs)));
1556
+ }
1557
+ if (void 0 === options.variables) {
1558
+ options.variables = variables;
1559
+ }
1560
+ return options;
1561
+ }
1767
1562
  function makeMergeObjectsFunction(store) {
1768
1563
  return function mergeObjects(existing, incoming) {
1769
1564
  if (Array.isArray(existing) || Array.isArray(incoming)) {
1770
- throw __DEV__ ? new globals.InvariantError("Cannot automatically merge arrays") : new globals.InvariantError(3);
1565
+ throw __DEV__ ? new globals.InvariantError("Cannot automatically merge arrays") : new globals.InvariantError(4);
1771
1566
  }
1772
1567
  if (utilities.isNonNullObject(existing) &&
1773
1568
  utilities.isNonNullObject(incoming)) {
@@ -1795,123 +1590,396 @@ function makeMergeObjectsFunction(store) {
1795
1590
  return incoming;
1796
1591
  };
1797
1592
  }
1798
- function keyArgsFnFromSpecifier(specifier) {
1799
- return function (args, context) {
1800
- var key = context.fieldName;
1801
- var suffix = JSON.stringify(computeKeyArgsObject(specifier, context.field, args, context.variables));
1802
- if (args || suffix !== "{}") {
1803
- key += ":" + suffix;
1804
- }
1805
- return key;
1806
- };
1593
+
1594
+ function getContextFlavor(context, clientOnly, deferred) {
1595
+ var key = "" + clientOnly + deferred;
1596
+ var flavored = context.flavors.get(key);
1597
+ if (!flavored) {
1598
+ context.flavors.set(key, flavored = (context.clientOnly === clientOnly &&
1599
+ context.deferred === deferred) ? context : tslib.__assign(tslib.__assign({}, context), { clientOnly: clientOnly, deferred: deferred }));
1600
+ }
1601
+ return flavored;
1807
1602
  }
1808
- function keyFieldsFnFromSpecifier(specifier) {
1809
- var trie$1 = new trie.Trie(utilities.canUseWeakMap);
1810
- return function (object, context) {
1811
- var aliasMap;
1812
- if (context.selectionSet && context.fragmentMap) {
1813
- var info = trie$1.lookupArray([
1814
- context.selectionSet,
1815
- context.fragmentMap,
1816
- ]);
1817
- aliasMap = info.aliasMap || (info.aliasMap = makeAliasMap(context.selectionSet, context.fragmentMap));
1818
- }
1819
- var keyObject = context.keyObject =
1820
- computeKeyFieldsObject(specifier, object, aliasMap);
1821
- return context.typename + ":" + JSON.stringify(keyObject);
1603
+ var StoreWriter = (function () {
1604
+ function StoreWriter(cache, reader) {
1605
+ this.cache = cache;
1606
+ this.reader = reader;
1607
+ }
1608
+ StoreWriter.prototype.writeToStore = function (store, _a) {
1609
+ var _this = this;
1610
+ var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
1611
+ var operationDefinition = utilities.getOperationDefinition(query);
1612
+ var merger = makeProcessedFieldsMerger();
1613
+ variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(operationDefinition)), variables);
1614
+ var context = {
1615
+ store: store,
1616
+ written: Object.create(null),
1617
+ merge: function (existing, incoming) {
1618
+ return merger.merge(existing, incoming);
1619
+ },
1620
+ variables: variables,
1621
+ varString: canonicalStringify(variables),
1622
+ fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
1623
+ overwrite: !!overwrite,
1624
+ incomingById: new Map,
1625
+ clientOnly: false,
1626
+ deferred: false,
1627
+ flavors: new Map,
1628
+ };
1629
+ var ref = this.processSelectionSet({
1630
+ result: result || Object.create(null),
1631
+ dataId: dataId,
1632
+ selectionSet: operationDefinition.selectionSet,
1633
+ mergeTree: { map: new Map },
1634
+ context: context,
1635
+ });
1636
+ if (!utilities.isReference(ref)) {
1637
+ throw __DEV__ ? new globals.InvariantError("Could not identify object " + JSON.stringify(result)) : new globals.InvariantError(6);
1638
+ }
1639
+ context.incomingById.forEach(function (_a, dataId) {
1640
+ var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;
1641
+ var entityRef = utilities.makeReference(dataId);
1642
+ if (mergeTree && mergeTree.map.size) {
1643
+ var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);
1644
+ if (utilities.isReference(applied)) {
1645
+ return;
1646
+ }
1647
+ storeObject = applied;
1648
+ }
1649
+ if (__DEV__ && !context.overwrite) {
1650
+ var fieldsWithSelectionSets_1 = Object.create(null);
1651
+ fieldNodeSet.forEach(function (field) {
1652
+ if (field.selectionSet) {
1653
+ fieldsWithSelectionSets_1[field.name.value] = true;
1654
+ }
1655
+ });
1656
+ var hasSelectionSet_1 = function (storeFieldName) {
1657
+ return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] === true;
1658
+ };
1659
+ var hasMergeFunction_1 = function (storeFieldName) {
1660
+ var childTree = mergeTree && mergeTree.map.get(storeFieldName);
1661
+ return Boolean(childTree && childTree.info && childTree.info.merge);
1662
+ };
1663
+ Object.keys(storeObject).forEach(function (storeFieldName) {
1664
+ if (hasSelectionSet_1(storeFieldName) &&
1665
+ !hasMergeFunction_1(storeFieldName)) {
1666
+ warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);
1667
+ }
1668
+ });
1669
+ }
1670
+ store.merge(dataId, storeObject);
1671
+ });
1672
+ store.retain(ref.__ref);
1673
+ return ref;
1822
1674
  };
1823
- }
1824
- function makeAliasMap(selectionSet, fragmentMap) {
1825
- var map = Object.create(null);
1826
- var workQueue = new Set([selectionSet]);
1827
- workQueue.forEach(function (selectionSet) {
1828
- selectionSet.selections.forEach(function (selection) {
1829
- if (utilities.isField(selection)) {
1830
- if (selection.alias) {
1831
- var responseKey = selection.alias.value;
1832
- var storeKey = selection.name.value;
1833
- if (storeKey !== responseKey) {
1834
- var aliases = map.aliases || (map.aliases = Object.create(null));
1835
- aliases[storeKey] = responseKey;
1675
+ StoreWriter.prototype.processSelectionSet = function (_a) {
1676
+ var _this = this;
1677
+ var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, mergeTree = _a.mergeTree;
1678
+ var policies = this.cache.policies;
1679
+ var incoming = Object.create(null);
1680
+ var typename = (dataId && policies.rootTypenamesById[dataId]) ||
1681
+ utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
1682
+ (dataId && context.store.get(dataId, "__typename"));
1683
+ if ("string" === typeof typename) {
1684
+ incoming.__typename = typename;
1685
+ }
1686
+ var readField = function () {
1687
+ var options = normalizeReadFieldOptions(arguments, incoming, context.variables);
1688
+ if (utilities.isReference(options.from)) {
1689
+ var info = context.incomingById.get(options.from.__ref);
1690
+ if (info) {
1691
+ var result_1 = policies.readField(tslib.__assign(tslib.__assign({}, options), { from: info.storeObject }), context);
1692
+ if (result_1 !== void 0) {
1693
+ return result_1;
1836
1694
  }
1837
1695
  }
1838
- if (selection.selectionSet) {
1839
- var subsets = map.subsets || (map.subsets = Object.create(null));
1840
- subsets[selection.name.value] =
1841
- makeAliasMap(selection.selectionSet, fragmentMap);
1842
- }
1843
1696
  }
1844
- else {
1845
- var fragment = utilities.getFragmentFromSelection(selection, fragmentMap);
1846
- if (fragment) {
1847
- workQueue.add(fragment.selectionSet);
1697
+ return policies.readField(options, context);
1698
+ };
1699
+ var fieldNodeSet = new Set();
1700
+ this.flattenFields(selectionSet, result, context, typename).forEach(function (context, field) {
1701
+ var _a;
1702
+ var resultFieldKey = utilities.resultKeyNameFromField(field);
1703
+ var value = result[resultFieldKey];
1704
+ fieldNodeSet.add(field);
1705
+ if (value !== void 0) {
1706
+ var storeFieldName = policies.getStoreFieldName({
1707
+ typename: typename,
1708
+ fieldName: field.name.value,
1709
+ field: field,
1710
+ variables: context.variables,
1711
+ });
1712
+ var childTree = getChildMergeTree(mergeTree, storeFieldName);
1713
+ var incomingValue = _this.processFieldValue(value, field, field.selectionSet
1714
+ ? getContextFlavor(context, false, false)
1715
+ : context, childTree);
1716
+ var childTypename = void 0;
1717
+ if (field.selectionSet &&
1718
+ (utilities.isReference(incomingValue) ||
1719
+ storeValueIsStoreObject(incomingValue))) {
1720
+ childTypename = readField("__typename", incomingValue);
1721
+ }
1722
+ var merge = policies.getMergeFunction(typename, field.name.value, childTypename);
1723
+ if (merge) {
1724
+ childTree.info = {
1725
+ field: field,
1726
+ typename: typename,
1727
+ merge: merge,
1728
+ };
1729
+ }
1730
+ else {
1731
+ maybeRecycleChildMergeTree(mergeTree, storeFieldName);
1848
1732
  }
1733
+ incoming = context.merge(incoming, (_a = {},
1734
+ _a[storeFieldName] = incomingValue,
1735
+ _a));
1736
+ }
1737
+ else if (__DEV__ &&
1738
+ !context.clientOnly &&
1739
+ !context.deferred &&
1740
+ !utilities.addTypenameToDocument.added(field) &&
1741
+ !policies.getReadFunction(typename, field.name.value)) {
1742
+ __DEV__ && globals.invariant.error(("Missing field '" + utilities.resultKeyNameFromField(field) + "' while writing result " + JSON.stringify(result, null, 2)).substring(0, 1000));
1849
1743
  }
1850
1744
  });
1851
- });
1852
- return map;
1853
- }
1854
- function computeKeyFieldsObject(specifier, response, aliasMap) {
1855
- var keyObj = Object.create(null);
1856
- var lastResponseKey;
1857
- var lastActualKey;
1858
- var aliases = aliasMap && aliasMap.aliases;
1859
- var subsets = aliasMap && aliasMap.subsets;
1860
- specifier.forEach(function (s) {
1861
- if (Array.isArray(s)) {
1862
- if (typeof lastActualKey === "string" &&
1863
- typeof lastResponseKey === "string") {
1864
- keyObj[lastActualKey] = computeKeyFieldsObject(s, response[lastResponseKey], subsets && subsets[lastActualKey]);
1745
+ try {
1746
+ var _b = policies.identify(result, {
1747
+ typename: typename,
1748
+ selectionSet: selectionSet,
1749
+ fragmentMap: context.fragmentMap,
1750
+ storeObject: incoming,
1751
+ readField: readField,
1752
+ }), id = _b[0], keyObject = _b[1];
1753
+ dataId = dataId || id;
1754
+ if (keyObject) {
1755
+ incoming = context.merge(incoming, keyObject);
1865
1756
  }
1866
1757
  }
1867
- else {
1868
- var responseKey = aliases && aliases[s] || s;
1869
- __DEV__ ? globals.invariant(hasOwn.call(response, responseKey), "Missing field '" + responseKey + "' while extracting keyFields from " + JSON.stringify(response)) : globals.invariant(hasOwn.call(response, responseKey), 4);
1870
- keyObj[lastActualKey = s] = response[lastResponseKey = responseKey];
1758
+ catch (e) {
1759
+ if (!dataId)
1760
+ throw e;
1871
1761
  }
1872
- });
1873
- return keyObj;
1874
- }
1875
- function computeKeyArgsObject(specifier, field, source, variables) {
1876
- var keyObj = Object.create(null);
1877
- var last;
1878
- specifier.forEach(function (key) {
1879
- if (Array.isArray(key)) {
1880
- if (last) {
1881
- keyObj[last.key] =
1882
- computeKeyArgsObject(key, field, last.source, variables);
1762
+ if ("string" === typeof dataId) {
1763
+ var dataRef = utilities.makeReference(dataId);
1764
+ var sets = context.written[dataId] || (context.written[dataId] = []);
1765
+ if (sets.indexOf(selectionSet) >= 0)
1766
+ return dataRef;
1767
+ sets.push(selectionSet);
1768
+ if (this.reader && this.reader.isFresh(result, dataRef, selectionSet, context)) {
1769
+ return dataRef;
1770
+ }
1771
+ var previous_1 = context.incomingById.get(dataId);
1772
+ if (previous_1) {
1773
+ previous_1.storeObject = context.merge(previous_1.storeObject, incoming);
1774
+ previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);
1775
+ fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });
1776
+ }
1777
+ else {
1778
+ context.incomingById.set(dataId, {
1779
+ storeObject: incoming,
1780
+ mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
1781
+ fieldNodeSet: fieldNodeSet,
1782
+ });
1883
1783
  }
1784
+ return dataRef;
1884
1785
  }
1885
- else {
1886
- var firstChar = key.charAt(0);
1887
- if (firstChar === "@") {
1888
- if (field && utilities.isNonEmptyArray(field.directives)) {
1889
- var directiveName_1 = key.slice(1);
1890
- var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
1891
- if (d) {
1892
- last = {
1893
- key: key,
1894
- source: keyObj[key] = utilities.argumentsObjectFromField(d, variables),
1895
- };
1896
- return;
1786
+ return incoming;
1787
+ };
1788
+ StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
1789
+ var _this = this;
1790
+ if (!field.selectionSet || value === null) {
1791
+ return __DEV__ ? utilities.cloneDeep(value) : value;
1792
+ }
1793
+ if (Array.isArray(value)) {
1794
+ return value.map(function (item, i) {
1795
+ var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
1796
+ maybeRecycleChildMergeTree(mergeTree, i);
1797
+ return value;
1798
+ });
1799
+ }
1800
+ return this.processSelectionSet({
1801
+ result: value,
1802
+ selectionSet: field.selectionSet,
1803
+ context: context,
1804
+ mergeTree: mergeTree,
1805
+ });
1806
+ };
1807
+ StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {
1808
+ if (typename === void 0) { typename = utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap); }
1809
+ var fieldMap = new Map();
1810
+ var policies = this.cache.policies;
1811
+ var limitingTrie = new trie.Trie(false);
1812
+ (function flatten(selectionSet, inheritedContext) {
1813
+ var visitedNode = limitingTrie.lookup(selectionSet, inheritedContext.clientOnly, inheritedContext.deferred);
1814
+ if (visitedNode.visited)
1815
+ return;
1816
+ visitedNode.visited = true;
1817
+ selectionSet.selections.forEach(function (selection) {
1818
+ if (!utilities.shouldInclude(selection, context.variables))
1819
+ return;
1820
+ var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;
1821
+ if (!(clientOnly && deferred) &&
1822
+ utilities.isNonEmptyArray(selection.directives)) {
1823
+ selection.directives.forEach(function (dir) {
1824
+ var name = dir.name.value;
1825
+ if (name === "client")
1826
+ clientOnly = true;
1827
+ if (name === "defer") {
1828
+ var args = utilities.argumentsObjectFromField(dir, context.variables);
1829
+ if (!args || args.if !== false) {
1830
+ deferred = true;
1831
+ }
1832
+ }
1833
+ });
1834
+ }
1835
+ if (utilities.isField(selection)) {
1836
+ var existing = fieldMap.get(selection);
1837
+ if (existing) {
1838
+ clientOnly = clientOnly && existing.clientOnly;
1839
+ deferred = deferred && existing.deferred;
1840
+ }
1841
+ fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));
1842
+ }
1843
+ else {
1844
+ var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
1845
+ if (fragment &&
1846
+ policies.fragmentMatches(fragment, typename, result, context.variables)) {
1847
+ flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));
1897
1848
  }
1898
1849
  }
1850
+ });
1851
+ })(selectionSet, context);
1852
+ return fieldMap;
1853
+ };
1854
+ StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
1855
+ var _a;
1856
+ var _this = this;
1857
+ if (mergeTree.map.size && !utilities.isReference(incoming)) {
1858
+ var e_1 = (!Array.isArray(incoming) &&
1859
+ (utilities.isReference(existing) || storeValueIsStoreObject(existing))) ? existing : void 0;
1860
+ var i_1 = incoming;
1861
+ if (e_1 && !getStorageArgs) {
1862
+ getStorageArgs = [utilities.isReference(e_1) ? e_1.__ref : e_1];
1899
1863
  }
1900
- else if (firstChar === "$") {
1901
- var variableName = key.slice(1);
1902
- if (variables && hasOwn.call(variables, variableName)) {
1903
- last = { key: key, source: keyObj[key] = variables[variableName] };
1864
+ var changedFields_1;
1865
+ var getValue_1 = function (from, name) {
1866
+ return Array.isArray(from)
1867
+ ? (typeof name === "number" ? from[name] : void 0)
1868
+ : context.store.getFieldValue(from, String(name));
1869
+ };
1870
+ mergeTree.map.forEach(function (childTree, storeFieldName) {
1871
+ var eVal = getValue_1(e_1, storeFieldName);
1872
+ var iVal = getValue_1(i_1, storeFieldName);
1873
+ if (void 0 === iVal)
1904
1874
  return;
1875
+ if (getStorageArgs) {
1876
+ getStorageArgs.push(storeFieldName);
1905
1877
  }
1878
+ var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
1879
+ if (aVal !== iVal) {
1880
+ changedFields_1 = changedFields_1 || new Map;
1881
+ changedFields_1.set(storeFieldName, aVal);
1882
+ }
1883
+ if (getStorageArgs) {
1884
+ globals.invariant(getStorageArgs.pop() === storeFieldName);
1885
+ }
1886
+ });
1887
+ if (changedFields_1) {
1888
+ incoming = (Array.isArray(i_1) ? i_1.slice(0) : tslib.__assign({}, i_1));
1889
+ changedFields_1.forEach(function (value, name) {
1890
+ incoming[name] = value;
1891
+ });
1906
1892
  }
1907
- else if (source && hasOwn.call(source, key)) {
1908
- last = { key: key, source: keyObj[key] = source[key] };
1909
- return;
1910
- }
1911
- last = void 0;
1912
1893
  }
1913
- });
1914
- return keyObj;
1894
+ if (mergeTree.info) {
1895
+ return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
1896
+ }
1897
+ return incoming;
1898
+ };
1899
+ return StoreWriter;
1900
+ }());
1901
+ var emptyMergeTreePool = [];
1902
+ function getChildMergeTree(_a, name) {
1903
+ var map = _a.map;
1904
+ if (!map.has(name)) {
1905
+ map.set(name, emptyMergeTreePool.pop() || { map: new Map });
1906
+ }
1907
+ return map.get(name);
1908
+ }
1909
+ function mergeMergeTrees(left, right) {
1910
+ if (left === right || !right || mergeTreeIsEmpty(right))
1911
+ return left;
1912
+ if (!left || mergeTreeIsEmpty(left))
1913
+ return right;
1914
+ var info = left.info && right.info ? tslib.__assign(tslib.__assign({}, left.info), right.info) : left.info || right.info;
1915
+ var needToMergeMaps = left.map.size && right.map.size;
1916
+ var map = needToMergeMaps ? new Map :
1917
+ left.map.size ? left.map : right.map;
1918
+ var merged = { info: info, map: map };
1919
+ if (needToMergeMaps) {
1920
+ var remainingRightKeys_1 = new Set(right.map.keys());
1921
+ left.map.forEach(function (leftTree, key) {
1922
+ merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
1923
+ remainingRightKeys_1.delete(key);
1924
+ });
1925
+ remainingRightKeys_1.forEach(function (key) {
1926
+ merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
1927
+ });
1928
+ }
1929
+ return merged;
1930
+ }
1931
+ function mergeTreeIsEmpty(tree) {
1932
+ return !tree || !(tree.info || tree.map.size);
1933
+ }
1934
+ function maybeRecycleChildMergeTree(_a, name) {
1935
+ var map = _a.map;
1936
+ var childTree = map.get(name);
1937
+ if (childTree && mergeTreeIsEmpty(childTree)) {
1938
+ emptyMergeTreePool.push(childTree);
1939
+ map.delete(name);
1940
+ }
1941
+ }
1942
+ var warnings = new Set();
1943
+ function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
1944
+ var getChild = function (objOrRef) {
1945
+ var child = store.getFieldValue(objOrRef, storeFieldName);
1946
+ return typeof child === "object" && child;
1947
+ };
1948
+ var existing = getChild(existingRef);
1949
+ if (!existing)
1950
+ return;
1951
+ var incoming = getChild(incomingObj);
1952
+ if (!incoming)
1953
+ return;
1954
+ if (utilities.isReference(existing))
1955
+ return;
1956
+ if (equality.equal(existing, incoming))
1957
+ return;
1958
+ if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
1959
+ return;
1960
+ }
1961
+ var parentType = store.getFieldValue(existingRef, "__typename") ||
1962
+ store.getFieldValue(incomingObj, "__typename");
1963
+ var fieldName = fieldNameFromStoreName(storeFieldName);
1964
+ var typeDotName = parentType + "." + fieldName;
1965
+ if (warnings.has(typeDotName))
1966
+ return;
1967
+ warnings.add(typeDotName);
1968
+ var childTypenames = [];
1969
+ if (!Array.isArray(existing) &&
1970
+ !Array.isArray(incoming)) {
1971
+ [existing, incoming].forEach(function (child) {
1972
+ var typename = store.getFieldValue(child, "__typename");
1973
+ if (typeof typename === "string" &&
1974
+ !childTypenames.includes(typename)) {
1975
+ childTypenames.push(typename);
1976
+ }
1977
+ });
1978
+ }
1979
+ __DEV__ && globals.invariant.warn("Cache data may be lost when replacing the " + fieldName + " field of a " + parentType + " object.\n\nTo address this problem (which is not a bug in Apollo Client), " + (childTypenames.length
1980
+ ? "either ensure all objects of type " +
1981
+ childTypenames.join(" and ") + " have an ID or a custom merge function, or "
1982
+ : "") + "define a custom merge function for the " + typeDotName + " field, so InMemoryCache can safely merge these objects:\n\n existing: " + JSON.stringify(existing).slice(0, 1000) + "\n incoming: " + JSON.stringify(incoming).slice(0, 1000) + "\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n");
1915
1983
  }
1916
1984
 
1917
1985
  var InMemoryCache = (function (_super) {