UNPKG

112 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var globals = require('../utilities/globals');
6var tslib = require('tslib');
7var optimism = require('optimism');
8var utilities = require('../utilities');
9var caches = require('@wry/caches');
10var equal = require('@wry/equality');
11var trie = require('@wry/trie');
12var graphql = require('graphql');
13
14function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
15
16var equal__default = /*#__PURE__*/_interopDefaultLegacy(equal);
17
18var getInMemoryCacheMemoryInternals = globalThis.__DEV__ !== false ?
19 _getInMemoryCacheMemoryInternals
20 : undefined;
21var getApolloCacheMemoryInternals = globalThis.__DEV__ !== false ?
22 _getApolloCacheMemoryInternals
23 : undefined;
24function _getApolloCacheMemoryInternals() {
25 return {
26 cache: {
27 fragmentQueryDocuments: getWrapperInformation(this["getFragmentDoc"]),
28 },
29 };
30}
31function _getInMemoryCacheMemoryInternals() {
32 var fragments = this.config.fragments;
33 return tslib.__assign(tslib.__assign({}, _getApolloCacheMemoryInternals.apply(this)), { addTypenameDocumentTransform: transformInfo(this["addTypenameTransform"]), inMemoryCache: {
34 executeSelectionSet: getWrapperInformation(this["storeReader"]["executeSelectionSet"]),
35 executeSubSelectedArray: getWrapperInformation(this["storeReader"]["executeSubSelectedArray"]),
36 maybeBroadcastWatch: getWrapperInformation(this["maybeBroadcastWatch"]),
37 }, fragmentRegistry: {
38 findFragmentSpreads: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.findFragmentSpreads),
39 lookup: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.lookup),
40 transform: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.transform),
41 } });
42}
43function isWrapper(f) {
44 return !!f && "dirtyKey" in f;
45}
46function getWrapperInformation(f) {
47 return isWrapper(f) ? f.size : undefined;
48}
49function isDefined(value) {
50 return value != null;
51}
52function transformInfo(transform) {
53 return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
54}
55function recurseTransformInfo(transform) {
56 return transform ?
57 tslib.__spreadArray(tslib.__spreadArray([
58 getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
59 ], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
60 : [];
61}
62
63function equalByQuery(query, _a, _b, variables) {
64 var aData = _a.data, aRest = tslib.__rest(_a, ["data"]);
65 var bData = _b.data, bRest = tslib.__rest(_b, ["data"]);
66 return (equal__default(aRest, bRest) &&
67 equalBySelectionSet(utilities.getMainDefinition(query).selectionSet, aData, bData, {
68 fragmentMap: utilities.createFragmentMap(utilities.getFragmentDefinitions(query)),
69 variables: variables,
70 }));
71}
72function equalBySelectionSet(selectionSet, aResult, bResult, context) {
73 if (aResult === bResult) {
74 return true;
75 }
76 var seenSelections = new Set();
77 return selectionSet.selections.every(function (selection) {
78 if (seenSelections.has(selection))
79 return true;
80 seenSelections.add(selection);
81 if (!utilities.shouldInclude(selection, context.variables))
82 return true;
83 if (selectionHasNonreactiveDirective(selection))
84 return true;
85 if (utilities.isField(selection)) {
86 var resultKey = utilities.resultKeyNameFromField(selection);
87 var aResultChild = aResult && aResult[resultKey];
88 var bResultChild = bResult && bResult[resultKey];
89 var childSelectionSet = selection.selectionSet;
90 if (!childSelectionSet) {
91 return equal__default(aResultChild, bResultChild);
92 }
93 var aChildIsArray = Array.isArray(aResultChild);
94 var bChildIsArray = Array.isArray(bResultChild);
95 if (aChildIsArray !== bChildIsArray)
96 return false;
97 if (aChildIsArray && bChildIsArray) {
98 var length_1 = aResultChild.length;
99 if (bResultChild.length !== length_1) {
100 return false;
101 }
102 for (var i = 0; i < length_1; ++i) {
103 if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {
104 return false;
105 }
106 }
107 return true;
108 }
109 return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);
110 }
111 else {
112 var fragment = utilities.getFragmentFromSelection(selection, context.fragmentMap);
113 if (fragment) {
114 if (selectionHasNonreactiveDirective(fragment))
115 return true;
116 return equalBySelectionSet(fragment.selectionSet,
117 aResult, bResult, context);
118 }
119 }
120 });
121}
122function selectionHasNonreactiveDirective(selection) {
123 return (!!selection.directives && selection.directives.some(directiveIsNonreactive));
124}
125function directiveIsNonreactive(dir) {
126 return dir.name.value === "nonreactive";
127}
128
129var ApolloCache = (function () {
130 function ApolloCache() {
131 this.assumeImmutableResults = false;
132 this.getFragmentDoc = optimism.wrap(utilities.getFragmentQueryDocument, {
133 max: utilities.cacheSizes["cache.fragmentQueryDocuments"] ||
134 1000 ,
135 cache: caches.WeakCache,
136 });
137 }
138 ApolloCache.prototype.batch = function (options) {
139 var _this = this;
140 var optimisticId = typeof options.optimistic === "string" ? options.optimistic
141 : options.optimistic === false ? null
142 : void 0;
143 var updateResult;
144 this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);
145 return updateResult;
146 };
147 ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {
148 this.performTransaction(transaction, optimisticId);
149 };
150 ApolloCache.prototype.transformDocument = function (document) {
151 return document;
152 };
153 ApolloCache.prototype.transformForLink = function (document) {
154 return document;
155 };
156 ApolloCache.prototype.identify = function (object) {
157 return;
158 };
159 ApolloCache.prototype.gc = function () {
160 return [];
161 };
162 ApolloCache.prototype.modify = function (options) {
163 return false;
164 };
165 ApolloCache.prototype.readQuery = function (options, optimistic) {
166 if (optimistic === void 0) { optimistic = !!options.optimistic; }
167 return this.read(tslib.__assign(tslib.__assign({}, options), { rootId: options.id || "ROOT_QUERY", optimistic: optimistic }));
168 };
169 ApolloCache.prototype.watchFragment = function (options) {
170 var _this = this;
171 var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, otherOptions = tslib.__rest(options, ["fragment", "fragmentName", "from", "optimistic"]);
172 var query = this.getFragmentDoc(fragment, fragmentName);
173 var diffOptions = tslib.__assign(tslib.__assign({}, otherOptions), { returnPartialData: true, id: typeof from === "string" ? from : this.identify(from), query: query, optimistic: optimistic });
174 var latestDiff;
175 return new utilities.Observable(function (observer) {
176 return _this.watch(tslib.__assign(tslib.__assign({}, diffOptions), { immediate: true, callback: function (diff) {
177 if (
178 latestDiff &&
179 equalByQuery(query, { data: latestDiff === null || latestDiff === void 0 ? void 0 : latestDiff.result }, { data: diff.result })) {
180 return;
181 }
182 var result = {
183 data: diff.result,
184 complete: !!diff.complete,
185 };
186 if (diff.missing) {
187 result.missing = utilities.mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
188 }
189 latestDiff = diff;
190 observer.next(result);
191 } }));
192 });
193 };
194 ApolloCache.prototype.readFragment = function (options, optimistic) {
195 if (optimistic === void 0) { optimistic = !!options.optimistic; }
196 return this.read(tslib.__assign(tslib.__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));
197 };
198 ApolloCache.prototype.writeQuery = function (_a) {
199 var id = _a.id, data = _a.data, options = tslib.__rest(_a, ["id", "data"]);
200 return this.write(Object.assign(options, {
201 dataId: id || "ROOT_QUERY",
202 result: data,
203 }));
204 };
205 ApolloCache.prototype.writeFragment = function (_a) {
206 var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = tslib.__rest(_a, ["id", "data", "fragment", "fragmentName"]);
207 return this.write(Object.assign(options, {
208 query: this.getFragmentDoc(fragment, fragmentName),
209 dataId: id,
210 result: data,
211 }));
212 };
213 ApolloCache.prototype.updateQuery = function (options, update) {
214 return this.batch({
215 update: function (cache) {
216 var value = cache.readQuery(options);
217 var data = update(value);
218 if (data === void 0 || data === null)
219 return value;
220 cache.writeQuery(tslib.__assign(tslib.__assign({}, options), { data: data }));
221 return data;
222 },
223 });
224 };
225 ApolloCache.prototype.updateFragment = function (options, update) {
226 return this.batch({
227 update: function (cache) {
228 var value = cache.readFragment(options);
229 var data = update(value);
230 if (data === void 0 || data === null)
231 return value;
232 cache.writeFragment(tslib.__assign(tslib.__assign({}, options), { data: data }));
233 return data;
234 },
235 });
236 };
237 return ApolloCache;
238}());
239if (globalThis.__DEV__ !== false) {
240 ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;
241}
242
243exports.Cache = void 0;
244(function (Cache) {
245})(exports.Cache || (exports.Cache = {}));
246
247var MissingFieldError = (function (_super) {
248 tslib.__extends(MissingFieldError, _super);
249 function MissingFieldError(message, path, query, variables) {
250 var _a;
251 var _this = _super.call(this, message) || this;
252 _this.message = message;
253 _this.path = path;
254 _this.query = query;
255 _this.variables = variables;
256 if (Array.isArray(_this.path)) {
257 _this.missing = _this.message;
258 for (var i = _this.path.length - 1; i >= 0; --i) {
259 _this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);
260 }
261 }
262 else {
263 _this.missing = _this.path;
264 }
265 _this.__proto__ = MissingFieldError.prototype;
266 return _this;
267 }
268 return MissingFieldError;
269}(Error));
270
271var hasOwn = Object.prototype.hasOwnProperty;
272function isNullish(value) {
273 return value === null || value === void 0;
274}
275function defaultDataIdFromObject(_a, context) {
276 var __typename = _a.__typename, id = _a.id, _id = _a._id;
277 if (typeof __typename === "string") {
278 if (context) {
279 context.keyObject =
280 !isNullish(id) ? { id: id }
281 : !isNullish(_id) ? { _id: _id }
282 : void 0;
283 }
284 if (isNullish(id) && !isNullish(_id)) {
285 id = _id;
286 }
287 if (!isNullish(id)) {
288 return "".concat(__typename, ":").concat(typeof id === "number" || typeof id === "string" ?
289 id
290 : JSON.stringify(id));
291 }
292 }
293}
294var defaultConfig = {
295 dataIdFromObject: defaultDataIdFromObject,
296 addTypename: true,
297 resultCaching: true,
298 canonizeResults: false,
299};
300function normalizeConfig(config) {
301 return utilities.compact(defaultConfig, config);
302}
303function shouldCanonizeResults(config) {
304 var value = config.canonizeResults;
305 return value === void 0 ? defaultConfig.canonizeResults : value;
306}
307function getTypenameFromStoreObject(store, objectOrReference) {
308 return utilities.isReference(objectOrReference) ?
309 store.get(objectOrReference.__ref, "__typename")
310 : objectOrReference && objectOrReference.__typename;
311}
312var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;
313function fieldNameFromStoreName(storeFieldName) {
314 var match = storeFieldName.match(TypeOrFieldNameRegExp);
315 return match ? match[0] : storeFieldName;
316}
317function selectionSetMatchesResult(selectionSet, result, variables) {
318 if (utilities.isNonNullObject(result)) {
319 return utilities.isArray(result) ?
320 result.every(function (item) {
321 return selectionSetMatchesResult(selectionSet, item, variables);
322 })
323 : selectionSet.selections.every(function (field) {
324 if (utilities.isField(field) && utilities.shouldInclude(field, variables)) {
325 var key = utilities.resultKeyNameFromField(field);
326 return (hasOwn.call(result, key) &&
327 (!field.selectionSet ||
328 selectionSetMatchesResult(field.selectionSet, result[key], variables)));
329 }
330 return true;
331 });
332 }
333 return false;
334}
335function storeValueIsStoreObject(value) {
336 return utilities.isNonNullObject(value) && !utilities.isReference(value) && !utilities.isArray(value);
337}
338function makeProcessedFieldsMerger() {
339 return new utilities.DeepMerger();
340}
341function extractFragmentContext(document, fragments) {
342 var fragmentMap = utilities.createFragmentMap(utilities.getFragmentDefinitions(document));
343 return {
344 fragmentMap: fragmentMap,
345 lookupFragment: function (name) {
346 var def = fragmentMap[name];
347 if (!def && fragments) {
348 def = fragments.lookup(name);
349 }
350 return def || null;
351 },
352 };
353}
354
355var DELETE = Object.create(null);
356var delModifier = function () { return DELETE; };
357var INVALIDATE = Object.create(null);
358exports.EntityStore = (function () {
359 function EntityStore(policies, group) {
360 var _this = this;
361 this.policies = policies;
362 this.group = group;
363 this.data = Object.create(null);
364 this.rootIds = Object.create(null);
365 this.refs = Object.create(null);
366 this.getFieldValue = function (objectOrReference, storeFieldName) {
367 return utilities.maybeDeepFreeze(utilities.isReference(objectOrReference) ?
368 _this.get(objectOrReference.__ref, storeFieldName)
369 : objectOrReference && objectOrReference[storeFieldName]);
370 };
371 this.canRead = function (objOrRef) {
372 return utilities.isReference(objOrRef) ?
373 _this.has(objOrRef.__ref)
374 : typeof objOrRef === "object";
375 };
376 this.toReference = function (objOrIdOrRef, mergeIntoStore) {
377 if (typeof objOrIdOrRef === "string") {
378 return utilities.makeReference(objOrIdOrRef);
379 }
380 if (utilities.isReference(objOrIdOrRef)) {
381 return objOrIdOrRef;
382 }
383 var id = _this.policies.identify(objOrIdOrRef)[0];
384 if (id) {
385 var ref = utilities.makeReference(id);
386 if (mergeIntoStore) {
387 _this.merge(id, objOrIdOrRef);
388 }
389 return ref;
390 }
391 };
392 }
393 EntityStore.prototype.toObject = function () {
394 return tslib.__assign({}, this.data);
395 };
396 EntityStore.prototype.has = function (dataId) {
397 return this.lookup(dataId, true) !== void 0;
398 };
399 EntityStore.prototype.get = function (dataId, fieldName) {
400 this.group.depend(dataId, fieldName);
401 if (hasOwn.call(this.data, dataId)) {
402 var storeObject = this.data[dataId];
403 if (storeObject && hasOwn.call(storeObject, fieldName)) {
404 return storeObject[fieldName];
405 }
406 }
407 if (fieldName === "__typename" &&
408 hasOwn.call(this.policies.rootTypenamesById, dataId)) {
409 return this.policies.rootTypenamesById[dataId];
410 }
411 if (this instanceof Layer) {
412 return this.parent.get(dataId, fieldName);
413 }
414 };
415 EntityStore.prototype.lookup = function (dataId, dependOnExistence) {
416 if (dependOnExistence)
417 this.group.depend(dataId, "__exists");
418 if (hasOwn.call(this.data, dataId)) {
419 return this.data[dataId];
420 }
421 if (this instanceof Layer) {
422 return this.parent.lookup(dataId, dependOnExistence);
423 }
424 if (this.policies.rootTypenamesById[dataId]) {
425 return Object.create(null);
426 }
427 };
428 EntityStore.prototype.merge = function (older, newer) {
429 var _this = this;
430 var dataId;
431 if (utilities.isReference(older))
432 older = older.__ref;
433 if (utilities.isReference(newer))
434 newer = newer.__ref;
435 var existing = typeof older === "string" ? this.lookup((dataId = older)) : older;
436 var incoming = typeof newer === "string" ? this.lookup((dataId = newer)) : newer;
437 if (!incoming)
438 return;
439 globals.invariant(typeof dataId === "string", 1);
440 var merged = new utilities.DeepMerger(storeObjectReconciler).merge(existing, incoming);
441 this.data[dataId] = merged;
442 if (merged !== existing) {
443 delete this.refs[dataId];
444 if (this.group.caching) {
445 var fieldsToDirty_1 = Object.create(null);
446 if (!existing)
447 fieldsToDirty_1.__exists = 1;
448 Object.keys(incoming).forEach(function (storeFieldName) {
449 if (!existing ||
450 existing[storeFieldName] !== merged[storeFieldName]) {
451 fieldsToDirty_1[storeFieldName] = 1;
452 var fieldName = fieldNameFromStoreName(storeFieldName);
453 if (fieldName !== storeFieldName &&
454 !_this.policies.hasKeyArgs(merged.__typename, fieldName)) {
455 fieldsToDirty_1[fieldName] = 1;
456 }
457 if (merged[storeFieldName] === void 0 && !(_this instanceof Layer)) {
458 delete merged[storeFieldName];
459 }
460 }
461 });
462 if (fieldsToDirty_1.__typename &&
463 !(existing && existing.__typename) &&
464 this.policies.rootTypenamesById[dataId] === merged.__typename) {
465 delete fieldsToDirty_1.__typename;
466 }
467 Object.keys(fieldsToDirty_1).forEach(function (fieldName) {
468 return _this.group.dirty(dataId, fieldName);
469 });
470 }
471 }
472 };
473 EntityStore.prototype.modify = function (dataId, fields) {
474 var _this = this;
475 var storeObject = this.lookup(dataId);
476 if (storeObject) {
477 var changedFields_1 = Object.create(null);
478 var needToMerge_1 = false;
479 var allDeleted_1 = true;
480 var sharedDetails_1 = {
481 DELETE: DELETE,
482 INVALIDATE: INVALIDATE,
483 isReference: utilities.isReference,
484 toReference: this.toReference,
485 canRead: this.canRead,
486 readField: function (fieldNameOrOptions, from) {
487 return _this.policies.readField(typeof fieldNameOrOptions === "string" ?
488 {
489 fieldName: fieldNameOrOptions,
490 from: from || utilities.makeReference(dataId),
491 }
492 : fieldNameOrOptions, { store: _this });
493 },
494 };
495 Object.keys(storeObject).forEach(function (storeFieldName) {
496 var fieldName = fieldNameFromStoreName(storeFieldName);
497 var fieldValue = storeObject[storeFieldName];
498 if (fieldValue === void 0)
499 return;
500 var modify = typeof fields === "function" ? fields : (fields[storeFieldName] || fields[fieldName]);
501 if (modify) {
502 var newValue = modify === delModifier ? DELETE : (modify(utilities.maybeDeepFreeze(fieldValue), tslib.__assign(tslib.__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));
503 if (newValue === INVALIDATE) {
504 _this.group.dirty(dataId, storeFieldName);
505 }
506 else {
507 if (newValue === DELETE)
508 newValue = void 0;
509 if (newValue !== fieldValue) {
510 changedFields_1[storeFieldName] = newValue;
511 needToMerge_1 = true;
512 fieldValue = newValue;
513 if (globalThis.__DEV__ !== false) {
514 var checkReference = function (ref) {
515 if (_this.lookup(ref.__ref) === undefined) {
516 globalThis.__DEV__ !== false && globals.invariant.warn(2, ref);
517 return true;
518 }
519 };
520 if (utilities.isReference(newValue)) {
521 checkReference(newValue);
522 }
523 else if (Array.isArray(newValue)) {
524 var seenReference = false;
525 var someNonReference = void 0;
526 for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {
527 var value = newValue_1[_i];
528 if (utilities.isReference(value)) {
529 seenReference = true;
530 if (checkReference(value))
531 break;
532 }
533 else {
534 if (typeof value === "object" && !!value) {
535 var id = _this.policies.identify(value)[0];
536 if (id) {
537 someNonReference = value;
538 }
539 }
540 }
541 if (seenReference && someNonReference !== undefined) {
542 globalThis.__DEV__ !== false && globals.invariant.warn(3, someNonReference);
543 break;
544 }
545 }
546 }
547 }
548 }
549 }
550 }
551 if (fieldValue !== void 0) {
552 allDeleted_1 = false;
553 }
554 });
555 if (needToMerge_1) {
556 this.merge(dataId, changedFields_1);
557 if (allDeleted_1) {
558 if (this instanceof Layer) {
559 this.data[dataId] = void 0;
560 }
561 else {
562 delete this.data[dataId];
563 }
564 this.group.dirty(dataId, "__exists");
565 }
566 return true;
567 }
568 }
569 return false;
570 };
571 EntityStore.prototype.delete = function (dataId, fieldName, args) {
572 var _a;
573 var storeObject = this.lookup(dataId);
574 if (storeObject) {
575 var typename = this.getFieldValue(storeObject, "__typename");
576 var storeFieldName = fieldName && args ?
577 this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })
578 : fieldName;
579 return this.modify(dataId, storeFieldName ? (_a = {},
580 _a[storeFieldName] = delModifier,
581 _a) : delModifier);
582 }
583 return false;
584 };
585 EntityStore.prototype.evict = function (options, limit) {
586 var evicted = false;
587 if (options.id) {
588 if (hasOwn.call(this.data, options.id)) {
589 evicted = this.delete(options.id, options.fieldName, options.args);
590 }
591 if (this instanceof Layer && this !== limit) {
592 evicted = this.parent.evict(options, limit) || evicted;
593 }
594 if (options.fieldName || evicted) {
595 this.group.dirty(options.id, options.fieldName || "__exists");
596 }
597 }
598 return evicted;
599 };
600 EntityStore.prototype.clear = function () {
601 this.replace(null);
602 };
603 EntityStore.prototype.extract = function () {
604 var _this = this;
605 var obj = this.toObject();
606 var extraRootIds = [];
607 this.getRootIdSet().forEach(function (id) {
608 if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {
609 extraRootIds.push(id);
610 }
611 });
612 if (extraRootIds.length) {
613 obj.__META = { extraRootIds: extraRootIds.sort() };
614 }
615 return obj;
616 };
617 EntityStore.prototype.replace = function (newData) {
618 var _this = this;
619 Object.keys(this.data).forEach(function (dataId) {
620 if (!(newData && hasOwn.call(newData, dataId))) {
621 _this.delete(dataId);
622 }
623 });
624 if (newData) {
625 var __META = newData.__META, rest_1 = tslib.__rest(newData, ["__META"]);
626 Object.keys(rest_1).forEach(function (dataId) {
627 _this.merge(dataId, rest_1[dataId]);
628 });
629 if (__META) {
630 __META.extraRootIds.forEach(this.retain, this);
631 }
632 }
633 };
634 EntityStore.prototype.retain = function (rootId) {
635 return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);
636 };
637 EntityStore.prototype.release = function (rootId) {
638 if (this.rootIds[rootId] > 0) {
639 var count = --this.rootIds[rootId];
640 if (!count)
641 delete this.rootIds[rootId];
642 return count;
643 }
644 return 0;
645 };
646 EntityStore.prototype.getRootIdSet = function (ids) {
647 if (ids === void 0) { ids = new Set(); }
648 Object.keys(this.rootIds).forEach(ids.add, ids);
649 if (this instanceof Layer) {
650 this.parent.getRootIdSet(ids);
651 }
652 else {
653 Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);
654 }
655 return ids;
656 };
657 EntityStore.prototype.gc = function () {
658 var _this = this;
659 var ids = this.getRootIdSet();
660 var snapshot = this.toObject();
661 ids.forEach(function (id) {
662 if (hasOwn.call(snapshot, id)) {
663 Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);
664 delete snapshot[id];
665 }
666 });
667 var idsToRemove = Object.keys(snapshot);
668 if (idsToRemove.length) {
669 var root_1 = this;
670 while (root_1 instanceof Layer)
671 root_1 = root_1.parent;
672 idsToRemove.forEach(function (id) { return root_1.delete(id); });
673 }
674 return idsToRemove;
675 };
676 EntityStore.prototype.findChildRefIds = function (dataId) {
677 if (!hasOwn.call(this.refs, dataId)) {
678 var found_1 = (this.refs[dataId] = Object.create(null));
679 var root = this.data[dataId];
680 if (!root)
681 return found_1;
682 var workSet_1 = new Set([root]);
683 workSet_1.forEach(function (obj) {
684 if (utilities.isReference(obj)) {
685 found_1[obj.__ref] = true;
686 }
687 if (utilities.isNonNullObject(obj)) {
688 Object.keys(obj).forEach(function (key) {
689 var child = obj[key];
690 if (utilities.isNonNullObject(child)) {
691 workSet_1.add(child);
692 }
693 });
694 }
695 });
696 }
697 return this.refs[dataId];
698 };
699 EntityStore.prototype.makeCacheKey = function () {
700 return this.group.keyMaker.lookupArray(arguments);
701 };
702 return EntityStore;
703}());
704var CacheGroup = (function () {
705 function CacheGroup(caching, parent) {
706 if (parent === void 0) { parent = null; }
707 this.caching = caching;
708 this.parent = parent;
709 this.d = null;
710 this.resetCaching();
711 }
712 CacheGroup.prototype.resetCaching = function () {
713 this.d = this.caching ? optimism.dep() : null;
714 this.keyMaker = new trie.Trie(utilities.canUseWeakMap);
715 };
716 CacheGroup.prototype.depend = function (dataId, storeFieldName) {
717 if (this.d) {
718 this.d(makeDepKey(dataId, storeFieldName));
719 var fieldName = fieldNameFromStoreName(storeFieldName);
720 if (fieldName !== storeFieldName) {
721 this.d(makeDepKey(dataId, fieldName));
722 }
723 if (this.parent) {
724 this.parent.depend(dataId, storeFieldName);
725 }
726 }
727 };
728 CacheGroup.prototype.dirty = function (dataId, storeFieldName) {
729 if (this.d) {
730 this.d.dirty(makeDepKey(dataId, storeFieldName),
731 storeFieldName === "__exists" ? "forget" : "setDirty");
732 }
733 };
734 return CacheGroup;
735}());
736function makeDepKey(dataId, storeFieldName) {
737 return storeFieldName + "#" + dataId;
738}
739function maybeDependOnExistenceOfEntity(store, entityId) {
740 if (supportsResultCaching(store)) {
741 store.group.depend(entityId, "__exists");
742 }
743}
744(function (EntityStore) {
745 var Root = (function (_super) {
746 tslib.__extends(Root, _super);
747 function Root(_a) {
748 var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;
749 var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;
750 _this.stump = new Stump(_this);
751 _this.storageTrie = new trie.Trie(utilities.canUseWeakMap);
752 if (seed)
753 _this.replace(seed);
754 return _this;
755 }
756 Root.prototype.addLayer = function (layerId, replay) {
757 return this.stump.addLayer(layerId, replay);
758 };
759 Root.prototype.removeLayer = function () {
760 return this;
761 };
762 Root.prototype.getStorage = function () {
763 return this.storageTrie.lookupArray(arguments);
764 };
765 return Root;
766 }(EntityStore));
767 EntityStore.Root = Root;
768})(exports.EntityStore || (exports.EntityStore = {}));
769var Layer = (function (_super) {
770 tslib.__extends(Layer, _super);
771 function Layer(id, parent, replay, group) {
772 var _this = _super.call(this, parent.policies, group) || this;
773 _this.id = id;
774 _this.parent = parent;
775 _this.replay = replay;
776 _this.group = group;
777 replay(_this);
778 return _this;
779 }
780 Layer.prototype.addLayer = function (layerId, replay) {
781 return new Layer(layerId, this, replay, this.group);
782 };
783 Layer.prototype.removeLayer = function (layerId) {
784 var _this = this;
785 var parent = this.parent.removeLayer(layerId);
786 if (layerId === this.id) {
787 if (this.group.caching) {
788 Object.keys(this.data).forEach(function (dataId) {
789 var ownStoreObject = _this.data[dataId];
790 var parentStoreObject = parent["lookup"](dataId);
791 if (!parentStoreObject) {
792 _this.delete(dataId);
793 }
794 else if (!ownStoreObject) {
795 _this.group.dirty(dataId, "__exists");
796 Object.keys(parentStoreObject).forEach(function (storeFieldName) {
797 _this.group.dirty(dataId, storeFieldName);
798 });
799 }
800 else if (ownStoreObject !== parentStoreObject) {
801 Object.keys(ownStoreObject).forEach(function (storeFieldName) {
802 if (!equal.equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {
803 _this.group.dirty(dataId, storeFieldName);
804 }
805 });
806 }
807 });
808 }
809 return parent;
810 }
811 if (parent === this.parent)
812 return this;
813 return parent.addLayer(this.id, this.replay);
814 };
815 Layer.prototype.toObject = function () {
816 return tslib.__assign(tslib.__assign({}, this.parent.toObject()), this.data);
817 };
818 Layer.prototype.findChildRefIds = function (dataId) {
819 var fromParent = this.parent.findChildRefIds(dataId);
820 return hasOwn.call(this.data, dataId) ? tslib.__assign(tslib.__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;
821 };
822 Layer.prototype.getStorage = function () {
823 var p = this.parent;
824 while (p.parent)
825 p = p.parent;
826 return p.getStorage.apply(p,
827 arguments);
828 };
829 return Layer;
830}(exports.EntityStore));
831var Stump = (function (_super) {
832 tslib.__extends(Stump, _super);
833 function Stump(root) {
834 return _super.call(this, "EntityStore.Stump", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;
835 }
836 Stump.prototype.removeLayer = function () {
837 return this;
838 };
839 Stump.prototype.merge = function (older, newer) {
840 return this.parent.merge(older, newer);
841 };
842 return Stump;
843}(Layer));
844function storeObjectReconciler(existingObject, incomingObject, property) {
845 var existingValue = existingObject[property];
846 var incomingValue = incomingObject[property];
847 return equal.equal(existingValue, incomingValue) ? existingValue : incomingValue;
848}
849function supportsResultCaching(store) {
850 return !!(store instanceof exports.EntityStore && store.group.caching);
851}
852
853function shallowCopy(value) {
854 if (utilities.isNonNullObject(value)) {
855 return utilities.isArray(value) ?
856 value.slice(0)
857 : tslib.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
858 }
859 return value;
860}
861var ObjectCanon = (function () {
862 function ObjectCanon() {
863 this.known = new (utilities.canUseWeakSet ? WeakSet : Set)();
864 this.pool = new trie.Trie(utilities.canUseWeakMap);
865 this.passes = new WeakMap();
866 this.keysByJSON = new Map();
867 this.empty = this.admit({});
868 }
869 ObjectCanon.prototype.isKnown = function (value) {
870 return utilities.isNonNullObject(value) && this.known.has(value);
871 };
872 ObjectCanon.prototype.pass = function (value) {
873 if (utilities.isNonNullObject(value)) {
874 var copy = shallowCopy(value);
875 this.passes.set(copy, value);
876 return copy;
877 }
878 return value;
879 };
880 ObjectCanon.prototype.admit = function (value) {
881 var _this = this;
882 if (utilities.isNonNullObject(value)) {
883 var original = this.passes.get(value);
884 if (original)
885 return original;
886 var proto = Object.getPrototypeOf(value);
887 switch (proto) {
888 case Array.prototype: {
889 if (this.known.has(value))
890 return value;
891 var array = value.map(this.admit, this);
892 var node = this.pool.lookupArray(array);
893 if (!node.array) {
894 this.known.add((node.array = array));
895 if (globalThis.__DEV__ !== false) {
896 Object.freeze(array);
897 }
898 }
899 return node.array;
900 }
901 case null:
902 case Object.prototype: {
903 if (this.known.has(value))
904 return value;
905 var proto_1 = Object.getPrototypeOf(value);
906 var array_1 = [proto_1];
907 var keys = this.sortedKeys(value);
908 array_1.push(keys.json);
909 var firstValueIndex_1 = array_1.length;
910 keys.sorted.forEach(function (key) {
911 array_1.push(_this.admit(value[key]));
912 });
913 var node = this.pool.lookupArray(array_1);
914 if (!node.object) {
915 var obj_1 = (node.object = Object.create(proto_1));
916 this.known.add(obj_1);
917 keys.sorted.forEach(function (key, i) {
918 obj_1[key] = array_1[firstValueIndex_1 + i];
919 });
920 if (globalThis.__DEV__ !== false) {
921 Object.freeze(obj_1);
922 }
923 }
924 return node.object;
925 }
926 }
927 }
928 return value;
929 };
930 ObjectCanon.prototype.sortedKeys = function (obj) {
931 var keys = Object.keys(obj);
932 var node = this.pool.lookupArray(keys);
933 if (!node.keys) {
934 keys.sort();
935 var json = JSON.stringify(keys);
936 if (!(node.keys = this.keysByJSON.get(json))) {
937 this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));
938 }
939 }
940 return node.keys;
941 };
942 return ObjectCanon;
943}());
944
945function execSelectionSetKeyArgs(options) {
946 return [
947 options.selectionSet,
948 options.objectOrReference,
949 options.context,
950 options.context.canonizeResults,
951 ];
952}
953var StoreReader = (function () {
954 function StoreReader(config) {
955 var _this = this;
956 this.knownResults = new (utilities.canUseWeakMap ? WeakMap : Map)();
957 this.config = utilities.compact(config, {
958 addTypename: config.addTypename !== false,
959 canonizeResults: shouldCanonizeResults(config),
960 });
961 this.canon = config.canon || new ObjectCanon();
962 this.executeSelectionSet = optimism.wrap(function (options) {
963 var _a;
964 var canonizeResults = options.context.canonizeResults;
965 var peekArgs = execSelectionSetKeyArgs(options);
966 peekArgs[3] = !canonizeResults;
967 var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);
968 if (other) {
969 if (canonizeResults) {
970 return tslib.__assign(tslib.__assign({}, other), {
971 result: _this.canon.admit(other.result) });
972 }
973 return other;
974 }
975 maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
976 return _this.execSelectionSetImpl(options);
977 }, {
978 max: this.config.resultCacheMaxSize ||
979 utilities.cacheSizes["inMemoryCache.executeSelectionSet"] ||
980 50000 ,
981 keyArgs: execSelectionSetKeyArgs,
982 makeCacheKey: function (selectionSet, parent, context, canonizeResults) {
983 if (supportsResultCaching(context.store)) {
984 return context.store.makeCacheKey(selectionSet, utilities.isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);
985 }
986 },
987 });
988 this.executeSubSelectedArray = optimism.wrap(function (options) {
989 maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
990 return _this.execSubSelectedArrayImpl(options);
991 }, {
992 max: this.config.resultCacheMaxSize ||
993 utilities.cacheSizes["inMemoryCache.executeSubSelectedArray"] ||
994 10000 ,
995 makeCacheKey: function (_a) {
996 var field = _a.field, array = _a.array, context = _a.context;
997 if (supportsResultCaching(context.store)) {
998 return context.store.makeCacheKey(field, array, context.varString);
999 }
1000 },
1001 });
1002 }
1003 StoreReader.prototype.resetCanon = function () {
1004 this.canon = new ObjectCanon();
1005 };
1006 StoreReader.prototype.diffQueryAgainstStore = function (_a) {
1007 var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? "ROOT_QUERY" : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;
1008 var policies = this.config.cache.policies;
1009 variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(utilities.getQueryDefinition(query))), variables);
1010 var rootRef = utilities.makeReference(rootId);
1011 var execResult = this.executeSelectionSet({
1012 selectionSet: utilities.getMainDefinition(query).selectionSet,
1013 objectOrReference: rootRef,
1014 enclosingRef: rootRef,
1015 context: tslib.__assign({ store: store, query: query, policies: policies, variables: variables, varString: utilities.canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),
1016 });
1017 var missing;
1018 if (execResult.missing) {
1019 missing = [
1020 new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables),
1021 ];
1022 if (!returnPartialData) {
1023 throw missing[0];
1024 }
1025 }
1026 return {
1027 result: execResult.result,
1028 complete: !missing,
1029 missing: missing,
1030 };
1031 };
1032 StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {
1033 if (supportsResultCaching(context.store) &&
1034 this.knownResults.get(result) === selectionSet) {
1035 var latest = this.executeSelectionSet.peek(selectionSet, parent, context,
1036 this.canon.isKnown(result));
1037 if (latest && result === latest.result) {
1038 return true;
1039 }
1040 }
1041 return false;
1042 };
1043 StoreReader.prototype.execSelectionSetImpl = function (_a) {
1044 var _this = this;
1045 var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;
1046 if (utilities.isReference(objectOrReference) &&
1047 !context.policies.rootTypenamesById[objectOrReference.__ref] &&
1048 !context.store.has(objectOrReference.__ref)) {
1049 return {
1050 result: this.canon.empty,
1051 missing: "Dangling reference to missing ".concat(objectOrReference.__ref, " object"),
1052 };
1053 }
1054 var variables = context.variables, policies = context.policies, store = context.store;
1055 var typename = store.getFieldValue(objectOrReference, "__typename");
1056 var objectsToMerge = [];
1057 var missing;
1058 var missingMerger = new utilities.DeepMerger();
1059 if (this.config.addTypename &&
1060 typeof typename === "string" &&
1061 !policies.rootIdsByTypename[typename]) {
1062 objectsToMerge.push({ __typename: typename });
1063 }
1064 function handleMissing(result, resultName) {
1065 var _a;
1066 if (result.missing) {
1067 missing = missingMerger.merge(missing, (_a = {},
1068 _a[resultName] = result.missing,
1069 _a));
1070 }
1071 return result.result;
1072 }
1073 var workSet = new Set(selectionSet.selections);
1074 workSet.forEach(function (selection) {
1075 var _a, _b;
1076 if (!utilities.shouldInclude(selection, variables))
1077 return;
1078 if (utilities.isField(selection)) {
1079 var fieldValue = policies.readField({
1080 fieldName: selection.name.value,
1081 field: selection,
1082 variables: context.variables,
1083 from: objectOrReference,
1084 }, context);
1085 var resultName = utilities.resultKeyNameFromField(selection);
1086 if (fieldValue === void 0) {
1087 if (!utilities.addTypenameToDocument.added(selection)) {
1088 missing = missingMerger.merge(missing, (_a = {},
1089 _a[resultName] = "Can't find field '".concat(selection.name.value, "' on ").concat(utilities.isReference(objectOrReference) ?
1090 objectOrReference.__ref + " object"
1091 : "object " + JSON.stringify(objectOrReference, null, 2)),
1092 _a));
1093 }
1094 }
1095 else if (utilities.isArray(fieldValue)) {
1096 if (fieldValue.length > 0) {
1097 fieldValue = handleMissing(_this.executeSubSelectedArray({
1098 field: selection,
1099 array: fieldValue,
1100 enclosingRef: enclosingRef,
1101 context: context,
1102 }), resultName);
1103 }
1104 }
1105 else if (!selection.selectionSet) {
1106 if (context.canonizeResults) {
1107 fieldValue = _this.canon.pass(fieldValue);
1108 }
1109 }
1110 else if (fieldValue != null) {
1111 fieldValue = handleMissing(_this.executeSelectionSet({
1112 selectionSet: selection.selectionSet,
1113 objectOrReference: fieldValue,
1114 enclosingRef: utilities.isReference(fieldValue) ? fieldValue : enclosingRef,
1115 context: context,
1116 }), resultName);
1117 }
1118 if (fieldValue !== void 0) {
1119 objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));
1120 }
1121 }
1122 else {
1123 var fragment = utilities.getFragmentFromSelection(selection, context.lookupFragment);
1124 if (!fragment && selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
1125 throw globals.newInvariantError(9, selection.name.value);
1126 }
1127 if (fragment && policies.fragmentMatches(fragment, typename)) {
1128 fragment.selectionSet.selections.forEach(workSet.add, workSet);
1129 }
1130 }
1131 });
1132 var result = utilities.mergeDeepArray(objectsToMerge);
1133 var finalResult = { result: result, missing: missing };
1134 var frozen = context.canonizeResults ?
1135 this.canon.admit(finalResult)
1136 : utilities.maybeDeepFreeze(finalResult);
1137 if (frozen.result) {
1138 this.knownResults.set(frozen.result, selectionSet);
1139 }
1140 return frozen;
1141 };
1142 StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {
1143 var _this = this;
1144 var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;
1145 var missing;
1146 var missingMerger = new utilities.DeepMerger();
1147 function handleMissing(childResult, i) {
1148 var _a;
1149 if (childResult.missing) {
1150 missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));
1151 }
1152 return childResult.result;
1153 }
1154 if (field.selectionSet) {
1155 array = array.filter(context.store.canRead);
1156 }
1157 array = array.map(function (item, i) {
1158 if (item === null) {
1159 return null;
1160 }
1161 if (utilities.isArray(item)) {
1162 return handleMissing(_this.executeSubSelectedArray({
1163 field: field,
1164 array: item,
1165 enclosingRef: enclosingRef,
1166 context: context,
1167 }), i);
1168 }
1169 if (field.selectionSet) {
1170 return handleMissing(_this.executeSelectionSet({
1171 selectionSet: field.selectionSet,
1172 objectOrReference: item,
1173 enclosingRef: utilities.isReference(item) ? item : enclosingRef,
1174 context: context,
1175 }), i);
1176 }
1177 if (globalThis.__DEV__ !== false) {
1178 assertSelectionSetForIdValue(context.store, field, item);
1179 }
1180 return item;
1181 });
1182 return {
1183 result: context.canonizeResults ? this.canon.admit(array) : array,
1184 missing: missing,
1185 };
1186 };
1187 return StoreReader;
1188}());
1189function firstMissing(tree) {
1190 try {
1191 JSON.stringify(tree, function (_, value) {
1192 if (typeof value === "string")
1193 throw value;
1194 return value;
1195 });
1196 }
1197 catch (result) {
1198 return result;
1199 }
1200}
1201function assertSelectionSetForIdValue(store, field, fieldValue) {
1202 if (!field.selectionSet) {
1203 var workSet_1 = new Set([fieldValue]);
1204 workSet_1.forEach(function (value) {
1205 if (utilities.isNonNullObject(value)) {
1206 globals.invariant(
1207 !utilities.isReference(value),
1208 10,
1209 getTypenameFromStoreObject(store, value),
1210 field.name.value
1211 );
1212 Object.values(value).forEach(workSet_1.add, workSet_1);
1213 }
1214 });
1215 }
1216}
1217
1218var cacheSlot = new optimism.Slot();
1219var cacheInfoMap = new WeakMap();
1220function getCacheInfo(cache) {
1221 var info = cacheInfoMap.get(cache);
1222 if (!info) {
1223 cacheInfoMap.set(cache, (info = {
1224 vars: new Set(),
1225 dep: optimism.dep(),
1226 }));
1227 }
1228 return info;
1229}
1230function forgetCache(cache) {
1231 getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });
1232}
1233function recallCache(cache) {
1234 getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });
1235}
1236function makeVar(value) {
1237 var caches = new Set();
1238 var listeners = new Set();
1239 var rv = function (newValue) {
1240 if (arguments.length > 0) {
1241 if (value !== newValue) {
1242 value = newValue;
1243 caches.forEach(function (cache) {
1244 getCacheInfo(cache).dep.dirty(rv);
1245 broadcast(cache);
1246 });
1247 var oldListeners = Array.from(listeners);
1248 listeners.clear();
1249 oldListeners.forEach(function (listener) { return listener(value); });
1250 }
1251 }
1252 else {
1253 var cache = cacheSlot.getValue();
1254 if (cache) {
1255 attach(cache);
1256 getCacheInfo(cache).dep(rv);
1257 }
1258 }
1259 return value;
1260 };
1261 rv.onNextChange = function (listener) {
1262 listeners.add(listener);
1263 return function () {
1264 listeners.delete(listener);
1265 };
1266 };
1267 var attach = (rv.attachCache = function (cache) {
1268 caches.add(cache);
1269 getCacheInfo(cache).vars.add(rv);
1270 return rv;
1271 });
1272 rv.forgetCache = function (cache) { return caches.delete(cache); };
1273 return rv;
1274}
1275function broadcast(cache) {
1276 if (cache.broadcastWatches) {
1277 cache.broadcastWatches();
1278 }
1279}
1280
1281var specifierInfoCache = Object.create(null);
1282function lookupSpecifierInfo(spec) {
1283 var cacheKey = JSON.stringify(spec);
1284 return (specifierInfoCache[cacheKey] ||
1285 (specifierInfoCache[cacheKey] = Object.create(null)));
1286}
1287function keyFieldsFnFromSpecifier(specifier) {
1288 var info = lookupSpecifierInfo(specifier);
1289 return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {
1290 var extract = function (from, key) {
1291 return context.readField(key, from);
1292 };
1293 var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {
1294 var extracted = extractKeyPath(context.storeObject, schemaKeyPath,
1295 extract);
1296 if (extracted === void 0 &&
1297 object !== context.storeObject &&
1298 hasOwn.call(object, schemaKeyPath[0])) {
1299 extracted = extractKeyPath(object, schemaKeyPath, extractKey);
1300 }
1301 globals.invariant(extracted !== void 0, 4, schemaKeyPath.join("."), object);
1302 return extracted;
1303 }));
1304 return "".concat(context.typename, ":").concat(JSON.stringify(keyObject));
1305 }));
1306}
1307function keyArgsFnFromSpecifier(specifier) {
1308 var info = lookupSpecifierInfo(specifier);
1309 return (info.keyArgsFn ||
1310 (info.keyArgsFn = function (args, _a) {
1311 var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;
1312 var collected = collectSpecifierPaths(specifier, function (keyPath) {
1313 var firstKey = keyPath[0];
1314 var firstChar = firstKey.charAt(0);
1315 if (firstChar === "@") {
1316 if (field && utilities.isNonEmptyArray(field.directives)) {
1317 var directiveName_1 = firstKey.slice(1);
1318 var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
1319 var directiveArgs = d && utilities.argumentsObjectFromField(d, variables);
1320 return (directiveArgs &&
1321 extractKeyPath(directiveArgs,
1322 keyPath.slice(1)));
1323 }
1324 return;
1325 }
1326 if (firstChar === "$") {
1327 var variableName = firstKey.slice(1);
1328 if (variables && hasOwn.call(variables, variableName)) {
1329 var varKeyPath = keyPath.slice(0);
1330 varKeyPath[0] = variableName;
1331 return extractKeyPath(variables, varKeyPath);
1332 }
1333 return;
1334 }
1335 if (args) {
1336 return extractKeyPath(args, keyPath);
1337 }
1338 });
1339 var suffix = JSON.stringify(collected);
1340 if (args || suffix !== "{}") {
1341 fieldName += ":" + suffix;
1342 }
1343 return fieldName;
1344 }));
1345}
1346function collectSpecifierPaths(specifier, extractor) {
1347 var merger = new utilities.DeepMerger();
1348 return getSpecifierPaths(specifier).reduce(function (collected, path) {
1349 var _a;
1350 var toMerge = extractor(path);
1351 if (toMerge !== void 0) {
1352 for (var i = path.length - 1; i >= 0; --i) {
1353 toMerge = (_a = {}, _a[path[i]] = toMerge, _a);
1354 }
1355 collected = merger.merge(collected, toMerge);
1356 }
1357 return collected;
1358 }, Object.create(null));
1359}
1360function getSpecifierPaths(spec) {
1361 var info = lookupSpecifierInfo(spec);
1362 if (!info.paths) {
1363 var paths_1 = (info.paths = []);
1364 var currentPath_1 = [];
1365 spec.forEach(function (s, i) {
1366 if (utilities.isArray(s)) {
1367 getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });
1368 currentPath_1.length = 0;
1369 }
1370 else {
1371 currentPath_1.push(s);
1372 if (!utilities.isArray(spec[i + 1])) {
1373 paths_1.push(currentPath_1.slice(0));
1374 currentPath_1.length = 0;
1375 }
1376 }
1377 });
1378 }
1379 return info.paths;
1380}
1381function extractKey(object, key) {
1382 return object[key];
1383}
1384function extractKeyPath(object, path, extract) {
1385 extract = extract || extractKey;
1386 return normalize(path.reduce(function reducer(obj, key) {
1387 return utilities.isArray(obj) ?
1388 obj.map(function (child) { return reducer(child, key); })
1389 : obj && extract(obj, key);
1390 }, object));
1391}
1392function normalize(value) {
1393 if (utilities.isNonNullObject(value)) {
1394 if (utilities.isArray(value)) {
1395 return value.map(normalize);
1396 }
1397 return collectSpecifierPaths(Object.keys(value).sort(), function (path) {
1398 return extractKeyPath(value, path);
1399 });
1400 }
1401 return value;
1402}
1403
1404function argsFromFieldSpecifier(spec) {
1405 return (spec.args !== void 0 ? spec.args
1406 : spec.field ? utilities.argumentsObjectFromField(spec.field, spec.variables)
1407 : null);
1408}
1409var nullKeyFieldsFn = function () { return void 0; };
1410var simpleKeyArgsFn = function (_args, context) { return context.fieldName; };
1411var mergeTrueFn = function (existing, incoming, _a) {
1412 var mergeObjects = _a.mergeObjects;
1413 return mergeObjects(existing, incoming);
1414};
1415var mergeFalseFn = function (_, incoming) { return incoming; };
1416var Policies = (function () {
1417 function Policies(config) {
1418 this.config = config;
1419 this.typePolicies = Object.create(null);
1420 this.toBeAdded = Object.create(null);
1421 this.supertypeMap = new Map();
1422 this.fuzzySubtypes = new Map();
1423 this.rootIdsByTypename = Object.create(null);
1424 this.rootTypenamesById = Object.create(null);
1425 this.usingPossibleTypes = false;
1426 this.config = tslib.__assign({ dataIdFromObject: defaultDataIdFromObject }, config);
1427 this.cache = this.config.cache;
1428 this.setRootTypename("Query");
1429 this.setRootTypename("Mutation");
1430 this.setRootTypename("Subscription");
1431 if (config.possibleTypes) {
1432 this.addPossibleTypes(config.possibleTypes);
1433 }
1434 if (config.typePolicies) {
1435 this.addTypePolicies(config.typePolicies);
1436 }
1437 }
1438 Policies.prototype.identify = function (object, partialContext) {
1439 var _a;
1440 var policies = this;
1441 var typename = (partialContext &&
1442 (partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||
1443 object.__typename;
1444 if (typename === this.rootTypenamesById.ROOT_QUERY) {
1445 return ["ROOT_QUERY"];
1446 }
1447 var storeObject = (partialContext && partialContext.storeObject) || object;
1448 var context = tslib.__assign(tslib.__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||
1449 function () {
1450 var options = normalizeReadFieldOptions(arguments, storeObject);
1451 return policies.readField(options, {
1452 store: policies.cache["data"],
1453 variables: options.variables,
1454 });
1455 } });
1456 var id;
1457 var policy = typename && this.getTypePolicy(typename);
1458 var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;
1459 while (keyFn) {
1460 var specifierOrId = keyFn(tslib.__assign(tslib.__assign({}, object), storeObject), context);
1461 if (utilities.isArray(specifierOrId)) {
1462 keyFn = keyFieldsFnFromSpecifier(specifierOrId);
1463 }
1464 else {
1465 id = specifierOrId;
1466 break;
1467 }
1468 }
1469 id = id ? String(id) : void 0;
1470 return context.keyObject ? [id, context.keyObject] : [id];
1471 };
1472 Policies.prototype.addTypePolicies = function (typePolicies) {
1473 var _this = this;
1474 Object.keys(typePolicies).forEach(function (typename) {
1475 var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = tslib.__rest(_a, ["queryType", "mutationType", "subscriptionType"]);
1476 if (queryType)
1477 _this.setRootTypename("Query", typename);
1478 if (mutationType)
1479 _this.setRootTypename("Mutation", typename);
1480 if (subscriptionType)
1481 _this.setRootTypename("Subscription", typename);
1482 if (hasOwn.call(_this.toBeAdded, typename)) {
1483 _this.toBeAdded[typename].push(incoming);
1484 }
1485 else {
1486 _this.toBeAdded[typename] = [incoming];
1487 }
1488 });
1489 };
1490 Policies.prototype.updateTypePolicy = function (typename, incoming) {
1491 var _this = this;
1492 var existing = this.getTypePolicy(typename);
1493 var keyFields = incoming.keyFields, fields = incoming.fields;
1494 function setMerge(existing, merge) {
1495 existing.merge =
1496 typeof merge === "function" ? merge
1497 : merge === true ? mergeTrueFn
1498 : merge === false ? mergeFalseFn
1499 : existing.merge;
1500 }
1501 setMerge(existing, incoming.merge);
1502 existing.keyFn =
1503 keyFields === false ? nullKeyFieldsFn
1504 : utilities.isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)
1505 : typeof keyFields === "function" ? keyFields
1506 : existing.keyFn;
1507 if (fields) {
1508 Object.keys(fields).forEach(function (fieldName) {
1509 var existing = _this.getFieldPolicy(typename, fieldName, true);
1510 var incoming = fields[fieldName];
1511 if (typeof incoming === "function") {
1512 existing.read = incoming;
1513 }
1514 else {
1515 var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;
1516 existing.keyFn =
1517 keyArgs === false ? simpleKeyArgsFn
1518 : utilities.isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)
1519 : typeof keyArgs === "function" ? keyArgs
1520 : existing.keyFn;
1521 if (typeof read === "function") {
1522 existing.read = read;
1523 }
1524 setMerge(existing, merge);
1525 }
1526 if (existing.read && existing.merge) {
1527 existing.keyFn = existing.keyFn || simpleKeyArgsFn;
1528 }
1529 });
1530 }
1531 };
1532 Policies.prototype.setRootTypename = function (which, typename) {
1533 if (typename === void 0) { typename = which; }
1534 var rootId = "ROOT_" + which.toUpperCase();
1535 var old = this.rootTypenamesById[rootId];
1536 if (typename !== old) {
1537 globals.invariant(!old || old === which, 5, which);
1538 if (old)
1539 delete this.rootIdsByTypename[old];
1540 this.rootIdsByTypename[typename] = rootId;
1541 this.rootTypenamesById[rootId] = typename;
1542 }
1543 };
1544 Policies.prototype.addPossibleTypes = function (possibleTypes) {
1545 var _this = this;
1546 this.usingPossibleTypes = true;
1547 Object.keys(possibleTypes).forEach(function (supertype) {
1548 _this.getSupertypeSet(supertype, true);
1549 possibleTypes[supertype].forEach(function (subtype) {
1550 _this.getSupertypeSet(subtype, true).add(supertype);
1551 var match = subtype.match(TypeOrFieldNameRegExp);
1552 if (!match || match[0] !== subtype) {
1553 _this.fuzzySubtypes.set(subtype, new RegExp(subtype));
1554 }
1555 });
1556 });
1557 };
1558 Policies.prototype.getTypePolicy = function (typename) {
1559 var _this = this;
1560 if (!hasOwn.call(this.typePolicies, typename)) {
1561 var policy_1 = (this.typePolicies[typename] = Object.create(null));
1562 policy_1.fields = Object.create(null);
1563 var supertypes_1 = this.supertypeMap.get(typename);
1564 if (!supertypes_1 && this.fuzzySubtypes.size) {
1565 supertypes_1 = this.getSupertypeSet(typename, true);
1566 this.fuzzySubtypes.forEach(function (regExp, fuzzy) {
1567 if (regExp.test(typename)) {
1568 var fuzzySupertypes = _this.supertypeMap.get(fuzzy);
1569 if (fuzzySupertypes) {
1570 fuzzySupertypes.forEach(function (supertype) {
1571 return supertypes_1.add(supertype);
1572 });
1573 }
1574 }
1575 });
1576 }
1577 if (supertypes_1 && supertypes_1.size) {
1578 supertypes_1.forEach(function (supertype) {
1579 var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = tslib.__rest(_a, ["fields"]);
1580 Object.assign(policy_1, rest);
1581 Object.assign(policy_1.fields, fields);
1582 });
1583 }
1584 }
1585 var inbox = this.toBeAdded[typename];
1586 if (inbox && inbox.length) {
1587 inbox.splice(0).forEach(function (policy) {
1588 _this.updateTypePolicy(typename, policy);
1589 });
1590 }
1591 return this.typePolicies[typename];
1592 };
1593 Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {
1594 if (typename) {
1595 var fieldPolicies = this.getTypePolicy(typename).fields;
1596 return (fieldPolicies[fieldName] ||
1597 (createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));
1598 }
1599 };
1600 Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {
1601 var supertypeSet = this.supertypeMap.get(subtype);
1602 if (!supertypeSet && createIfMissing) {
1603 this.supertypeMap.set(subtype, (supertypeSet = new Set()));
1604 }
1605 return supertypeSet;
1606 };
1607 Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {
1608 var _this = this;
1609 if (!fragment.typeCondition)
1610 return true;
1611 if (!typename)
1612 return false;
1613 var supertype = fragment.typeCondition.name.value;
1614 if (typename === supertype)
1615 return true;
1616 if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {
1617 var typenameSupertypeSet = this.getSupertypeSet(typename, true);
1618 var workQueue_1 = [typenameSupertypeSet];
1619 var maybeEnqueue_1 = function (subtype) {
1620 var supertypeSet = _this.getSupertypeSet(subtype, false);
1621 if (supertypeSet &&
1622 supertypeSet.size &&
1623 workQueue_1.indexOf(supertypeSet) < 0) {
1624 workQueue_1.push(supertypeSet);
1625 }
1626 };
1627 var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);
1628 var checkingFuzzySubtypes = false;
1629 for (var i = 0; i < workQueue_1.length; ++i) {
1630 var supertypeSet = workQueue_1[i];
1631 if (supertypeSet.has(supertype)) {
1632 if (!typenameSupertypeSet.has(supertype)) {
1633 if (checkingFuzzySubtypes) {
1634 globalThis.__DEV__ !== false && globals.invariant.warn(6, typename, supertype);
1635 }
1636 typenameSupertypeSet.add(supertype);
1637 }
1638 return true;
1639 }
1640 supertypeSet.forEach(maybeEnqueue_1);
1641 if (needToCheckFuzzySubtypes &&
1642 i === workQueue_1.length - 1 &&
1643 selectionSetMatchesResult(fragment.selectionSet, result, variables)) {
1644 needToCheckFuzzySubtypes = false;
1645 checkingFuzzySubtypes = true;
1646 this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {
1647 var match = typename.match(regExp);
1648 if (match && match[0] === typename) {
1649 maybeEnqueue_1(fuzzyString);
1650 }
1651 });
1652 }
1653 }
1654 }
1655 return false;
1656 };
1657 Policies.prototype.hasKeyArgs = function (typename, fieldName) {
1658 var policy = this.getFieldPolicy(typename, fieldName, false);
1659 return !!(policy && policy.keyFn);
1660 };
1661 Policies.prototype.getStoreFieldName = function (fieldSpec) {
1662 var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;
1663 var policy = this.getFieldPolicy(typename, fieldName, false);
1664 var storeFieldName;
1665 var keyFn = policy && policy.keyFn;
1666 if (keyFn && typename) {
1667 var context = {
1668 typename: typename,
1669 fieldName: fieldName,
1670 field: fieldSpec.field || null,
1671 variables: fieldSpec.variables,
1672 };
1673 var args = argsFromFieldSpecifier(fieldSpec);
1674 while (keyFn) {
1675 var specifierOrString = keyFn(args, context);
1676 if (utilities.isArray(specifierOrString)) {
1677 keyFn = keyArgsFnFromSpecifier(specifierOrString);
1678 }
1679 else {
1680 storeFieldName = specifierOrString || fieldName;
1681 break;
1682 }
1683 }
1684 }
1685 if (storeFieldName === void 0) {
1686 storeFieldName =
1687 fieldSpec.field ?
1688 utilities.storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)
1689 : utilities.getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));
1690 }
1691 if (storeFieldName === false) {
1692 return fieldName;
1693 }
1694 return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName
1695 : fieldName + ":" + storeFieldName;
1696 };
1697 Policies.prototype.readField = function (options, context) {
1698 var objectOrReference = options.from;
1699 if (!objectOrReference)
1700 return;
1701 var nameOrField = options.field || options.fieldName;
1702 if (!nameOrField)
1703 return;
1704 if (options.typename === void 0) {
1705 var typename = context.store.getFieldValue(objectOrReference, "__typename");
1706 if (typename)
1707 options.typename = typename;
1708 }
1709 var storeFieldName = this.getStoreFieldName(options);
1710 var fieldName = fieldNameFromStoreName(storeFieldName);
1711 var existing = context.store.getFieldValue(objectOrReference, storeFieldName);
1712 var policy = this.getFieldPolicy(options.typename, fieldName, false);
1713 var read = policy && policy.read;
1714 if (read) {
1715 var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(utilities.isReference(objectOrReference) ?
1716 objectOrReference.__ref
1717 : objectOrReference, storeFieldName));
1718 return cacheSlot.withValue(this.cache, read, [
1719 existing,
1720 readOptions,
1721 ]);
1722 }
1723 return existing;
1724 };
1725 Policies.prototype.getReadFunction = function (typename, fieldName) {
1726 var policy = this.getFieldPolicy(typename, fieldName, false);
1727 return policy && policy.read;
1728 };
1729 Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {
1730 var policy = this.getFieldPolicy(parentTypename, fieldName, false);
1731 var merge = policy && policy.merge;
1732 if (!merge && childTypename) {
1733 policy = this.getTypePolicy(childTypename);
1734 merge = policy && policy.merge;
1735 }
1736 return merge;
1737 };
1738 Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {
1739 var field = _a.field, typename = _a.typename, merge = _a.merge;
1740 if (merge === mergeTrueFn) {
1741 return makeMergeObjectsFunction(context.store)(existing, incoming);
1742 }
1743 if (merge === mergeFalseFn) {
1744 return incoming;
1745 }
1746 if (context.overwrite) {
1747 existing = void 0;
1748 }
1749 return merge(existing, incoming, makeFieldFunctionOptions(this,
1750 void 0, {
1751 typename: typename,
1752 fieldName: field.name.value,
1753 field: field,
1754 variables: context.variables,
1755 }, context, storage || Object.create(null)));
1756 };
1757 return Policies;
1758}());
1759function makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {
1760 var storeFieldName = policies.getStoreFieldName(fieldSpec);
1761 var fieldName = fieldNameFromStoreName(storeFieldName);
1762 var variables = fieldSpec.variables || context.variables;
1763 var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;
1764 return {
1765 args: argsFromFieldSpecifier(fieldSpec),
1766 field: fieldSpec.field || null,
1767 fieldName: fieldName,
1768 storeFieldName: storeFieldName,
1769 variables: variables,
1770 isReference: utilities.isReference,
1771 toReference: toReference,
1772 storage: storage,
1773 cache: policies.cache,
1774 canRead: canRead,
1775 readField: function () {
1776 return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);
1777 },
1778 mergeObjects: makeMergeObjectsFunction(context.store),
1779 };
1780}
1781function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {
1782 var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;
1783 var options;
1784 if (typeof fieldNameOrOptions === "string") {
1785 options = {
1786 fieldName: fieldNameOrOptions,
1787 from: argc > 1 ? from : objectOrReference,
1788 };
1789 }
1790 else {
1791 options = tslib.__assign({}, fieldNameOrOptions);
1792 if (!hasOwn.call(options, "from")) {
1793 options.from = objectOrReference;
1794 }
1795 }
1796 if (globalThis.__DEV__ !== false && options.from === void 0) {
1797 globalThis.__DEV__ !== false && globals.invariant.warn(7, utilities.stringifyForDisplay(Array.from(readFieldArgs)));
1798 }
1799 if (void 0 === options.variables) {
1800 options.variables = variables;
1801 }
1802 return options;
1803}
1804function makeMergeObjectsFunction(store) {
1805 return function mergeObjects(existing, incoming) {
1806 if (utilities.isArray(existing) || utilities.isArray(incoming)) {
1807 throw globals.newInvariantError(8);
1808 }
1809 if (utilities.isNonNullObject(existing) && utilities.isNonNullObject(incoming)) {
1810 var eType = store.getFieldValue(existing, "__typename");
1811 var iType = store.getFieldValue(incoming, "__typename");
1812 var typesDiffer = eType && iType && eType !== iType;
1813 if (typesDiffer) {
1814 return incoming;
1815 }
1816 if (utilities.isReference(existing) && storeValueIsStoreObject(incoming)) {
1817 store.merge(existing.__ref, incoming);
1818 return existing;
1819 }
1820 if (storeValueIsStoreObject(existing) && utilities.isReference(incoming)) {
1821 store.merge(existing, incoming.__ref);
1822 return incoming;
1823 }
1824 if (storeValueIsStoreObject(existing) &&
1825 storeValueIsStoreObject(incoming)) {
1826 return tslib.__assign(tslib.__assign({}, existing), incoming);
1827 }
1828 }
1829 return incoming;
1830 };
1831}
1832
1833function getContextFlavor(context, clientOnly, deferred) {
1834 var key = "".concat(clientOnly).concat(deferred);
1835 var flavored = context.flavors.get(key);
1836 if (!flavored) {
1837 context.flavors.set(key, (flavored =
1838 context.clientOnly === clientOnly && context.deferred === deferred ?
1839 context
1840 : tslib.__assign(tslib.__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));
1841 }
1842 return flavored;
1843}
1844var StoreWriter = (function () {
1845 function StoreWriter(cache, reader, fragments) {
1846 this.cache = cache;
1847 this.reader = reader;
1848 this.fragments = fragments;
1849 }
1850 StoreWriter.prototype.writeToStore = function (store, _a) {
1851 var _this = this;
1852 var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
1853 var operationDefinition = utilities.getOperationDefinition(query);
1854 var merger = makeProcessedFieldsMerger();
1855 variables = tslib.__assign(tslib.__assign({}, utilities.getDefaultValues(operationDefinition)), variables);
1856 var context = tslib.__assign(tslib.__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {
1857 return merger.merge(existing, incoming);
1858 }, variables: variables, varString: utilities.canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });
1859 var ref = this.processSelectionSet({
1860 result: result || Object.create(null),
1861 dataId: dataId,
1862 selectionSet: operationDefinition.selectionSet,
1863 mergeTree: { map: new Map() },
1864 context: context,
1865 });
1866 if (!utilities.isReference(ref)) {
1867 throw globals.newInvariantError(11, result);
1868 }
1869 context.incomingById.forEach(function (_a, dataId) {
1870 var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;
1871 var entityRef = utilities.makeReference(dataId);
1872 if (mergeTree && mergeTree.map.size) {
1873 var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);
1874 if (utilities.isReference(applied)) {
1875 return;
1876 }
1877 storeObject = applied;
1878 }
1879 if (globalThis.__DEV__ !== false && !context.overwrite) {
1880 var fieldsWithSelectionSets_1 = Object.create(null);
1881 fieldNodeSet.forEach(function (field) {
1882 if (field.selectionSet) {
1883 fieldsWithSelectionSets_1[field.name.value] = true;
1884 }
1885 });
1886 var hasSelectionSet_1 = function (storeFieldName) {
1887 return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===
1888 true;
1889 };
1890 var hasMergeFunction_1 = function (storeFieldName) {
1891 var childTree = mergeTree && mergeTree.map.get(storeFieldName);
1892 return Boolean(childTree && childTree.info && childTree.info.merge);
1893 };
1894 Object.keys(storeObject).forEach(function (storeFieldName) {
1895 if (hasSelectionSet_1(storeFieldName) &&
1896 !hasMergeFunction_1(storeFieldName)) {
1897 warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);
1898 }
1899 });
1900 }
1901 store.merge(dataId, storeObject);
1902 });
1903 store.retain(ref.__ref);
1904 return ref;
1905 };
1906 StoreWriter.prototype.processSelectionSet = function (_a) {
1907 var _this = this;
1908 var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context,
1909 mergeTree = _a.mergeTree;
1910 var policies = this.cache.policies;
1911 var incoming = Object.create(null);
1912 var typename = (dataId && policies.rootTypenamesById[dataId]) ||
1913 utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
1914 (dataId && context.store.get(dataId, "__typename"));
1915 if ("string" === typeof typename) {
1916 incoming.__typename = typename;
1917 }
1918 var readField = function () {
1919 var options = normalizeReadFieldOptions(arguments, incoming, context.variables);
1920 if (utilities.isReference(options.from)) {
1921 var info = context.incomingById.get(options.from.__ref);
1922 if (info) {
1923 var result_1 = policies.readField(tslib.__assign(tslib.__assign({}, options), { from: info.storeObject }), context);
1924 if (result_1 !== void 0) {
1925 return result_1;
1926 }
1927 }
1928 }
1929 return policies.readField(options, context);
1930 };
1931 var fieldNodeSet = new Set();
1932 this.flattenFields(selectionSet, result,
1933 context, typename).forEach(function (context, field) {
1934 var _a;
1935 var resultFieldKey = utilities.resultKeyNameFromField(field);
1936 var value = result[resultFieldKey];
1937 fieldNodeSet.add(field);
1938 if (value !== void 0) {
1939 var storeFieldName = policies.getStoreFieldName({
1940 typename: typename,
1941 fieldName: field.name.value,
1942 field: field,
1943 variables: context.variables,
1944 });
1945 var childTree = getChildMergeTree(mergeTree, storeFieldName);
1946 var incomingValue = _this.processFieldValue(value, field,
1947 field.selectionSet ?
1948 getContextFlavor(context, false, false)
1949 : context, childTree);
1950 var childTypename = void 0;
1951 if (field.selectionSet &&
1952 (utilities.isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {
1953 childTypename = readField("__typename", incomingValue);
1954 }
1955 var merge = policies.getMergeFunction(typename, field.name.value, childTypename);
1956 if (merge) {
1957 childTree.info = {
1958 field: field,
1959 typename: typename,
1960 merge: merge,
1961 };
1962 }
1963 else {
1964 maybeRecycleChildMergeTree(mergeTree, storeFieldName);
1965 }
1966 incoming = context.merge(incoming, (_a = {},
1967 _a[storeFieldName] = incomingValue,
1968 _a));
1969 }
1970 else if (globalThis.__DEV__ !== false &&
1971 !context.clientOnly &&
1972 !context.deferred &&
1973 !utilities.addTypenameToDocument.added(field) &&
1974 !policies.getReadFunction(typename, field.name.value)) {
1975 globalThis.__DEV__ !== false && globals.invariant.error(12, utilities.resultKeyNameFromField(field), result);
1976 }
1977 });
1978 try {
1979 var _b = policies.identify(result, {
1980 typename: typename,
1981 selectionSet: selectionSet,
1982 fragmentMap: context.fragmentMap,
1983 storeObject: incoming,
1984 readField: readField,
1985 }), id = _b[0], keyObject = _b[1];
1986 dataId = dataId || id;
1987 if (keyObject) {
1988 incoming = context.merge(incoming, keyObject);
1989 }
1990 }
1991 catch (e) {
1992 if (!dataId)
1993 throw e;
1994 }
1995 if ("string" === typeof dataId) {
1996 var dataRef = utilities.makeReference(dataId);
1997 var sets = context.written[dataId] || (context.written[dataId] = []);
1998 if (sets.indexOf(selectionSet) >= 0)
1999 return dataRef;
2000 sets.push(selectionSet);
2001 if (this.reader &&
2002 this.reader.isFresh(result, dataRef, selectionSet, context)) {
2003 return dataRef;
2004 }
2005 var previous_1 = context.incomingById.get(dataId);
2006 if (previous_1) {
2007 previous_1.storeObject = context.merge(previous_1.storeObject, incoming);
2008 previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);
2009 fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });
2010 }
2011 else {
2012 context.incomingById.set(dataId, {
2013 storeObject: incoming,
2014 mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
2015 fieldNodeSet: fieldNodeSet,
2016 });
2017 }
2018 return dataRef;
2019 }
2020 return incoming;
2021 };
2022 StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
2023 var _this = this;
2024 if (!field.selectionSet || value === null) {
2025 return globalThis.__DEV__ !== false ? utilities.cloneDeep(value) : value;
2026 }
2027 if (utilities.isArray(value)) {
2028 return value.map(function (item, i) {
2029 var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
2030 maybeRecycleChildMergeTree(mergeTree, i);
2031 return value;
2032 });
2033 }
2034 return this.processSelectionSet({
2035 result: value,
2036 selectionSet: field.selectionSet,
2037 context: context,
2038 mergeTree: mergeTree,
2039 });
2040 };
2041 StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {
2042 if (typename === void 0) { typename = utilities.getTypenameFromResult(result, selectionSet, context.fragmentMap); }
2043 var fieldMap = new Map();
2044 var policies = this.cache.policies;
2045 var limitingTrie = new trie.Trie(false);
2046 (function flatten(selectionSet, inheritedContext) {
2047 var visitedNode = limitingTrie.lookup(selectionSet,
2048 inheritedContext.clientOnly, inheritedContext.deferred);
2049 if (visitedNode.visited)
2050 return;
2051 visitedNode.visited = true;
2052 selectionSet.selections.forEach(function (selection) {
2053 if (!utilities.shouldInclude(selection, context.variables))
2054 return;
2055 var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;
2056 if (
2057 !(clientOnly && deferred) &&
2058 utilities.isNonEmptyArray(selection.directives)) {
2059 selection.directives.forEach(function (dir) {
2060 var name = dir.name.value;
2061 if (name === "client")
2062 clientOnly = true;
2063 if (name === "defer") {
2064 var args = utilities.argumentsObjectFromField(dir, context.variables);
2065 if (!args || args.if !== false) {
2066 deferred = true;
2067 }
2068 }
2069 });
2070 }
2071 if (utilities.isField(selection)) {
2072 var existing = fieldMap.get(selection);
2073 if (existing) {
2074 clientOnly = clientOnly && existing.clientOnly;
2075 deferred = deferred && existing.deferred;
2076 }
2077 fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));
2078 }
2079 else {
2080 var fragment = utilities.getFragmentFromSelection(selection, context.lookupFragment);
2081 if (!fragment && selection.kind === graphql.Kind.FRAGMENT_SPREAD) {
2082 throw globals.newInvariantError(13, selection.name.value);
2083 }
2084 if (fragment &&
2085 policies.fragmentMatches(fragment, typename, result, context.variables)) {
2086 flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));
2087 }
2088 }
2089 });
2090 })(selectionSet, context);
2091 return fieldMap;
2092 };
2093 StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
2094 var _a;
2095 var _this = this;
2096 if (mergeTree.map.size && !utilities.isReference(incoming)) {
2097 var e_1 =
2098 (!utilities.isArray(incoming) &&
2099 (utilities.isReference(existing) || storeValueIsStoreObject(existing))) ?
2100 existing
2101 : void 0;
2102 var i_1 = incoming;
2103 if (e_1 && !getStorageArgs) {
2104 getStorageArgs = [utilities.isReference(e_1) ? e_1.__ref : e_1];
2105 }
2106 var changedFields_1;
2107 var getValue_1 = function (from, name) {
2108 return (utilities.isArray(from) ?
2109 typeof name === "number" ?
2110 from[name]
2111 : void 0
2112 : context.store.getFieldValue(from, String(name)));
2113 };
2114 mergeTree.map.forEach(function (childTree, storeFieldName) {
2115 var eVal = getValue_1(e_1, storeFieldName);
2116 var iVal = getValue_1(i_1, storeFieldName);
2117 if (void 0 === iVal)
2118 return;
2119 if (getStorageArgs) {
2120 getStorageArgs.push(storeFieldName);
2121 }
2122 var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
2123 if (aVal !== iVal) {
2124 changedFields_1 = changedFields_1 || new Map();
2125 changedFields_1.set(storeFieldName, aVal);
2126 }
2127 if (getStorageArgs) {
2128 globals.invariant(getStorageArgs.pop() === storeFieldName);
2129 }
2130 });
2131 if (changedFields_1) {
2132 incoming = (utilities.isArray(i_1) ? i_1.slice(0) : tslib.__assign({}, i_1));
2133 changedFields_1.forEach(function (value, name) {
2134 incoming[name] = value;
2135 });
2136 }
2137 }
2138 if (mergeTree.info) {
2139 return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
2140 }
2141 return incoming;
2142 };
2143 return StoreWriter;
2144}());
2145var emptyMergeTreePool = [];
2146function getChildMergeTree(_a, name) {
2147 var map = _a.map;
2148 if (!map.has(name)) {
2149 map.set(name, emptyMergeTreePool.pop() || { map: new Map() });
2150 }
2151 return map.get(name);
2152}
2153function mergeMergeTrees(left, right) {
2154 if (left === right || !right || mergeTreeIsEmpty(right))
2155 return left;
2156 if (!left || mergeTreeIsEmpty(left))
2157 return right;
2158 var info = left.info && right.info ? tslib.__assign(tslib.__assign({}, left.info), right.info) : left.info || right.info;
2159 var needToMergeMaps = left.map.size && right.map.size;
2160 var map = needToMergeMaps ? new Map()
2161 : left.map.size ? left.map
2162 : right.map;
2163 var merged = { info: info, map: map };
2164 if (needToMergeMaps) {
2165 var remainingRightKeys_1 = new Set(right.map.keys());
2166 left.map.forEach(function (leftTree, key) {
2167 merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
2168 remainingRightKeys_1.delete(key);
2169 });
2170 remainingRightKeys_1.forEach(function (key) {
2171 merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
2172 });
2173 }
2174 return merged;
2175}
2176function mergeTreeIsEmpty(tree) {
2177 return !tree || !(tree.info || tree.map.size);
2178}
2179function maybeRecycleChildMergeTree(_a, name) {
2180 var map = _a.map;
2181 var childTree = map.get(name);
2182 if (childTree && mergeTreeIsEmpty(childTree)) {
2183 emptyMergeTreePool.push(childTree);
2184 map.delete(name);
2185 }
2186}
2187var warnings = new Set();
2188function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
2189 var getChild = function (objOrRef) {
2190 var child = store.getFieldValue(objOrRef, storeFieldName);
2191 return typeof child === "object" && child;
2192 };
2193 var existing = getChild(existingRef);
2194 if (!existing)
2195 return;
2196 var incoming = getChild(incomingObj);
2197 if (!incoming)
2198 return;
2199 if (utilities.isReference(existing))
2200 return;
2201 if (equal.equal(existing, incoming))
2202 return;
2203 if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
2204 return;
2205 }
2206 var parentType = store.getFieldValue(existingRef, "__typename") ||
2207 store.getFieldValue(incomingObj, "__typename");
2208 var fieldName = fieldNameFromStoreName(storeFieldName);
2209 var typeDotName = "".concat(parentType, ".").concat(fieldName);
2210 if (warnings.has(typeDotName))
2211 return;
2212 warnings.add(typeDotName);
2213 var childTypenames = [];
2214 if (!utilities.isArray(existing) && !utilities.isArray(incoming)) {
2215 [existing, incoming].forEach(function (child) {
2216 var typename = store.getFieldValue(child, "__typename");
2217 if (typeof typename === "string" && !childTypenames.includes(typename)) {
2218 childTypenames.push(typename);
2219 }
2220 });
2221 }
2222 globalThis.__DEV__ !== false && globals.invariant.warn(14, fieldName, parentType, childTypenames.length ?
2223 "either ensure all objects of type " +
2224 childTypenames.join(" and ") +
2225 " have an ID or a custom merge function, or "
2226 : "", typeDotName, tslib.__assign({}, existing), tslib.__assign({}, incoming));
2227}
2228
2229var InMemoryCache = (function (_super) {
2230 tslib.__extends(InMemoryCache, _super);
2231 function InMemoryCache(config) {
2232 if (config === void 0) { config = {}; }
2233 var _this = _super.call(this) || this;
2234 _this.watches = new Set();
2235 _this.addTypenameTransform = new utilities.DocumentTransform(utilities.addTypenameToDocument);
2236 _this.assumeImmutableResults = true;
2237 _this.makeVar = makeVar;
2238 _this.txCount = 0;
2239 _this.config = normalizeConfig(config);
2240 _this.addTypename = !!_this.config.addTypename;
2241 _this.policies = new Policies({
2242 cache: _this,
2243 dataIdFromObject: _this.config.dataIdFromObject,
2244 possibleTypes: _this.config.possibleTypes,
2245 typePolicies: _this.config.typePolicies,
2246 });
2247 _this.init();
2248 return _this;
2249 }
2250 InMemoryCache.prototype.init = function () {
2251 var rootStore = (this.data = new exports.EntityStore.Root({
2252 policies: this.policies,
2253 resultCaching: this.config.resultCaching,
2254 }));
2255 this.optimisticData = rootStore.stump;
2256 this.resetResultCache();
2257 };
2258 InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {
2259 var _this = this;
2260 var previousReader = this.storeReader;
2261 var fragments = this.config.fragments;
2262 this.storeWriter = new StoreWriter(this, (this.storeReader = new StoreReader({
2263 cache: this,
2264 addTypename: this.addTypename,
2265 resultCacheMaxSize: this.config.resultCacheMaxSize,
2266 canonizeResults: shouldCanonizeResults(this.config),
2267 canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),
2268 fragments: fragments,
2269 })), fragments);
2270 this.maybeBroadcastWatch = optimism.wrap(function (c, options) {
2271 return _this.broadcastWatch(c, options);
2272 }, {
2273 max: this.config.resultCacheMaxSize ||
2274 utilities.cacheSizes["inMemoryCache.maybeBroadcastWatch"] ||
2275 5000 ,
2276 makeCacheKey: function (c) {
2277 var store = c.optimistic ? _this.optimisticData : _this.data;
2278 if (supportsResultCaching(store)) {
2279 var optimistic = c.optimistic, id = c.id, variables = c.variables;
2280 return store.makeCacheKey(c.query,
2281 c.callback, utilities.canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));
2282 }
2283 },
2284 });
2285 new Set([this.data.group, this.optimisticData.group]).forEach(function (group) {
2286 return group.resetCaching();
2287 });
2288 };
2289 InMemoryCache.prototype.restore = function (data) {
2290 this.init();
2291 if (data)
2292 this.data.replace(data);
2293 return this;
2294 };
2295 InMemoryCache.prototype.extract = function (optimistic) {
2296 if (optimistic === void 0) { optimistic = false; }
2297 return (optimistic ? this.optimisticData : this.data).extract();
2298 };
2299 InMemoryCache.prototype.read = function (options) {
2300 var
2301 _a = options.returnPartialData,
2302 returnPartialData = _a === void 0 ? false : _a;
2303 try {
2304 return (this.storeReader.diffQueryAgainstStore(tslib.__assign(tslib.__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null);
2305 }
2306 catch (e) {
2307 if (e instanceof MissingFieldError) {
2308 return null;
2309 }
2310 throw e;
2311 }
2312 };
2313 InMemoryCache.prototype.write = function (options) {
2314 try {
2315 ++this.txCount;
2316 return this.storeWriter.writeToStore(this.data, options);
2317 }
2318 finally {
2319 if (!--this.txCount && options.broadcast !== false) {
2320 this.broadcastWatches();
2321 }
2322 }
2323 };
2324 InMemoryCache.prototype.modify = function (options) {
2325 if (hasOwn.call(options, "id") && !options.id) {
2326 return false;
2327 }
2328 var store = ((options.optimistic)
2329 ) ?
2330 this.optimisticData
2331 : this.data;
2332 try {
2333 ++this.txCount;
2334 return store.modify(options.id || "ROOT_QUERY", options.fields);
2335 }
2336 finally {
2337 if (!--this.txCount && options.broadcast !== false) {
2338 this.broadcastWatches();
2339 }
2340 }
2341 };
2342 InMemoryCache.prototype.diff = function (options) {
2343 return this.storeReader.diffQueryAgainstStore(tslib.__assign(tslib.__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || "ROOT_QUERY", config: this.config }));
2344 };
2345 InMemoryCache.prototype.watch = function (watch) {
2346 var _this = this;
2347 if (!this.watches.size) {
2348 recallCache(this);
2349 }
2350 this.watches.add(watch);
2351 if (watch.immediate) {
2352 this.maybeBroadcastWatch(watch);
2353 }
2354 return function () {
2355 if (_this.watches.delete(watch) && !_this.watches.size) {
2356 forgetCache(_this);
2357 }
2358 _this.maybeBroadcastWatch.forget(watch);
2359 };
2360 };
2361 InMemoryCache.prototype.gc = function (options) {
2362 var _a;
2363 utilities.canonicalStringify.reset();
2364 utilities.print.reset();
2365 this.addTypenameTransform.resetCache();
2366 (_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();
2367 var ids = this.optimisticData.gc();
2368 if (options && !this.txCount) {
2369 if (options.resetResultCache) {
2370 this.resetResultCache(options.resetResultIdentities);
2371 }
2372 else if (options.resetResultIdentities) {
2373 this.storeReader.resetCanon();
2374 }
2375 }
2376 return ids;
2377 };
2378 InMemoryCache.prototype.retain = function (rootId, optimistic) {
2379 return (optimistic ? this.optimisticData : this.data).retain(rootId);
2380 };
2381 InMemoryCache.prototype.release = function (rootId, optimistic) {
2382 return (optimistic ? this.optimisticData : this.data).release(rootId);
2383 };
2384 InMemoryCache.prototype.identify = function (object) {
2385 if (utilities.isReference(object))
2386 return object.__ref;
2387 try {
2388 return this.policies.identify(object)[0];
2389 }
2390 catch (e) {
2391 globalThis.__DEV__ !== false && globals.invariant.warn(e);
2392 }
2393 };
2394 InMemoryCache.prototype.evict = function (options) {
2395 if (!options.id) {
2396 if (hasOwn.call(options, "id")) {
2397 return false;
2398 }
2399 options = tslib.__assign(tslib.__assign({}, options), { id: "ROOT_QUERY" });
2400 }
2401 try {
2402 ++this.txCount;
2403 return this.optimisticData.evict(options, this.data);
2404 }
2405 finally {
2406 if (!--this.txCount && options.broadcast !== false) {
2407 this.broadcastWatches();
2408 }
2409 }
2410 };
2411 InMemoryCache.prototype.reset = function (options) {
2412 var _this = this;
2413 this.init();
2414 utilities.canonicalStringify.reset();
2415 if (options && options.discardWatches) {
2416 this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });
2417 this.watches.clear();
2418 forgetCache(this);
2419 }
2420 else {
2421 this.broadcastWatches();
2422 }
2423 return Promise.resolve();
2424 };
2425 InMemoryCache.prototype.removeOptimistic = function (idToRemove) {
2426 var newOptimisticData = this.optimisticData.removeLayer(idToRemove);
2427 if (newOptimisticData !== this.optimisticData) {
2428 this.optimisticData = newOptimisticData;
2429 this.broadcastWatches();
2430 }
2431 };
2432 InMemoryCache.prototype.batch = function (options) {
2433 var _this = this;
2434 var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;
2435 var updateResult;
2436 var perform = function (layer) {
2437 var _a = _this, data = _a.data, optimisticData = _a.optimisticData;
2438 ++_this.txCount;
2439 if (layer) {
2440 _this.data = _this.optimisticData = layer;
2441 }
2442 try {
2443 return (updateResult = update(_this));
2444 }
2445 finally {
2446 --_this.txCount;
2447 _this.data = data;
2448 _this.optimisticData = optimisticData;
2449 }
2450 };
2451 var alreadyDirty = new Set();
2452 if (onWatchUpdated && !this.txCount) {
2453 this.broadcastWatches(tslib.__assign(tslib.__assign({}, options), { onWatchUpdated: function (watch) {
2454 alreadyDirty.add(watch);
2455 return false;
2456 } }));
2457 }
2458 if (typeof optimistic === "string") {
2459 this.optimisticData = this.optimisticData.addLayer(optimistic, perform);
2460 }
2461 else if (optimistic === false) {
2462 perform(this.data);
2463 }
2464 else {
2465 perform();
2466 }
2467 if (typeof removeOptimistic === "string") {
2468 this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);
2469 }
2470 if (onWatchUpdated && alreadyDirty.size) {
2471 this.broadcastWatches(tslib.__assign(tslib.__assign({}, options), { onWatchUpdated: function (watch, diff) {
2472 var result = onWatchUpdated.call(this, watch, diff);
2473 if (result !== false) {
2474 alreadyDirty.delete(watch);
2475 }
2476 return result;
2477 } }));
2478 if (alreadyDirty.size) {
2479 alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });
2480 }
2481 }
2482 else {
2483 this.broadcastWatches(options);
2484 }
2485 return updateResult;
2486 };
2487 InMemoryCache.prototype.performTransaction = function (update, optimisticId) {
2488 return this.batch({
2489 update: update,
2490 optimistic: optimisticId || optimisticId !== null,
2491 });
2492 };
2493 InMemoryCache.prototype.transformDocument = function (document) {
2494 return this.addTypenameToDocument(this.addFragmentsToDocument(document));
2495 };
2496 InMemoryCache.prototype.broadcastWatches = function (options) {
2497 var _this = this;
2498 if (!this.txCount) {
2499 this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });
2500 }
2501 };
2502 InMemoryCache.prototype.addFragmentsToDocument = function (document) {
2503 var fragments = this.config.fragments;
2504 return fragments ? fragments.transform(document) : document;
2505 };
2506 InMemoryCache.prototype.addTypenameToDocument = function (document) {
2507 if (this.addTypename) {
2508 return this.addTypenameTransform.transformDocument(document);
2509 }
2510 return document;
2511 };
2512 InMemoryCache.prototype.broadcastWatch = function (c, options) {
2513 var lastDiff = c.lastDiff;
2514 var diff = this.diff(c);
2515 if (options) {
2516 if (c.optimistic && typeof options.optimistic === "string") {
2517 diff.fromOptimisticTransaction = true;
2518 }
2519 if (options.onWatchUpdated &&
2520 options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {
2521 return;
2522 }
2523 }
2524 if (!lastDiff || !equal.equal(lastDiff.result, diff.result)) {
2525 c.callback((c.lastDiff = diff), lastDiff);
2526 }
2527 };
2528 return InMemoryCache;
2529}(ApolloCache));
2530if (globalThis.__DEV__ !== false) {
2531 InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;
2532}
2533
2534function createFragmentRegistry() {
2535 var fragments = [];
2536 for (var _i = 0; _i < arguments.length; _i++) {
2537 fragments[_i] = arguments[_i];
2538 }
2539 return new (FragmentRegistry.bind.apply(FragmentRegistry, tslib.__spreadArray([void 0], fragments, false)))();
2540}
2541var FragmentRegistry = (function () {
2542 function FragmentRegistry() {
2543 var fragments = [];
2544 for (var _i = 0; _i < arguments.length; _i++) {
2545 fragments[_i] = arguments[_i];
2546 }
2547 this.registry = Object.create(null);
2548 this.resetCaches();
2549 if (fragments.length) {
2550 this.register.apply(this, fragments);
2551 }
2552 }
2553 FragmentRegistry.prototype.register = function () {
2554 var _this = this;
2555 var fragments = [];
2556 for (var _i = 0; _i < arguments.length; _i++) {
2557 fragments[_i] = arguments[_i];
2558 }
2559 var definitions = new Map();
2560 fragments.forEach(function (doc) {
2561 utilities.getFragmentDefinitions(doc).forEach(function (node) {
2562 definitions.set(node.name.value, node);
2563 });
2564 });
2565 definitions.forEach(function (node, name) {
2566 if (node !== _this.registry[name]) {
2567 _this.registry[name] = node;
2568 _this.invalidate(name);
2569 }
2570 });
2571 return this;
2572 };
2573 FragmentRegistry.prototype.invalidate = function (name) { };
2574 FragmentRegistry.prototype.resetCaches = function () {
2575 var proto = FragmentRegistry.prototype;
2576 this.invalidate = (this.lookup = optimism.wrap(proto.lookup.bind(this), {
2577 makeCacheKey: function (arg) { return arg; },
2578 max: utilities.cacheSizes["fragmentRegistry.lookup"] ||
2579 1000 ,
2580 })).dirty;
2581 this.transform = optimism.wrap(proto.transform.bind(this), {
2582 cache: caches.WeakCache,
2583 max: utilities.cacheSizes["fragmentRegistry.transform"] ||
2584 2000 ,
2585 });
2586 this.findFragmentSpreads = optimism.wrap(proto.findFragmentSpreads.bind(this), {
2587 cache: caches.WeakCache,
2588 max: utilities.cacheSizes["fragmentRegistry.findFragmentSpreads"] ||
2589 4000 ,
2590 });
2591 };
2592 FragmentRegistry.prototype.lookup = function (fragmentName) {
2593 return this.registry[fragmentName] || null;
2594 };
2595 FragmentRegistry.prototype.transform = function (document) {
2596 var _this = this;
2597 var defined = new Map();
2598 utilities.getFragmentDefinitions(document).forEach(function (def) {
2599 defined.set(def.name.value, def);
2600 });
2601 var unbound = new Set();
2602 var enqueue = function (spreadName) {
2603 if (!defined.has(spreadName)) {
2604 unbound.add(spreadName);
2605 }
2606 };
2607 var enqueueChildSpreads = function (node) {
2608 return Object.keys(_this.findFragmentSpreads(node)).forEach(enqueue);
2609 };
2610 enqueueChildSpreads(document);
2611 var missing = [];
2612 var map = Object.create(null);
2613 unbound.forEach(function (fragmentName) {
2614 var knownFragmentDef = defined.get(fragmentName);
2615 if (knownFragmentDef) {
2616 enqueueChildSpreads((map[fragmentName] = knownFragmentDef));
2617 }
2618 else {
2619 missing.push(fragmentName);
2620 var def = _this.lookup(fragmentName);
2621 if (def) {
2622 enqueueChildSpreads((map[fragmentName] = def));
2623 }
2624 }
2625 });
2626 if (missing.length) {
2627 var defsToAppend_1 = [];
2628 missing.forEach(function (name) {
2629 var def = map[name];
2630 if (def) {
2631 defsToAppend_1.push(def);
2632 }
2633 });
2634 if (defsToAppend_1.length) {
2635 document = tslib.__assign(tslib.__assign({}, document), { definitions: document.definitions.concat(defsToAppend_1) });
2636 }
2637 }
2638 return document;
2639 };
2640 FragmentRegistry.prototype.findFragmentSpreads = function (root) {
2641 var spreads = Object.create(null);
2642 graphql.visit(root, {
2643 FragmentSpread: function (node) {
2644 spreads[node.name.value] = node;
2645 },
2646 });
2647 return spreads;
2648 };
2649 return FragmentRegistry;
2650}());
2651
2652exports.canonicalStringify = utilities.canonicalStringify;
2653exports.isReference = utilities.isReference;
2654exports.makeReference = utilities.makeReference;
2655exports.ApolloCache = ApolloCache;
2656exports.InMemoryCache = InMemoryCache;
2657exports.MissingFieldError = MissingFieldError;
2658exports.Policies = Policies;
2659exports.cacheSlot = cacheSlot;
2660exports.createFragmentRegistry = createFragmentRegistry;
2661exports.defaultDataIdFromObject = defaultDataIdFromObject;
2662exports.fieldNameFromStoreName = fieldNameFromStoreName;
2663exports.makeVar = makeVar;
2664//# sourceMappingURL=cache.cjs.map