{"version":3,"sources":["webpack:///./node_modules/@apollo/client/cache/core/types/common.js","webpack:///./node_modules/@apollo/client/cache/core/types/Cache.js","webpack:///./node_modules/@apollo/client/cache/inmemory/entityStore.js","webpack:///./node_modules/@apollo/client/cache/inmemory/object-canon.js","webpack:///./node_modules/@apollo/client/cache/inmemory/readFromStore.js","webpack:///./node_modules/@apollo/client/cache/inmemory/key-extractor.js","webpack:///./node_modules/@apollo/client/cache/inmemory/policies.js","webpack:///./node_modules/@apollo/client/cache/inmemory/writeToStore.js","webpack:///./node_modules/@apollo/client/cache/inmemory/inMemoryCache.js","webpack:///./node_modules/@apollo/client/cache/inmemory/reactiveVars.js","webpack:///./node_modules/@apollo/client/cache/core/cache.js","webpack:///./node_modules/@apollo/client/cache/inmemory/helpers.js"],"names":["MissingFieldError","_super","message","path","query","variables","_a","_this","call","this","Array","isArray","missing","i","length","__proto__","prototype","Error","Cache","DELETE","Object","create","delModifier","INVALIDATE","EntityStore","policies","group","data","rootIds","refs","getFieldValue","objectOrReference","storeFieldName","maybeDeepFreeze","get","__ref","canRead","objOrRef","has","toReference","objOrIdOrRef","mergeIntoStore","id","identify","ref","merge","toObject","dataId","lookup","fieldName","depend","storeObject","rootTypenamesById","parent","dependOnExistence","older","newer","existing","incoming","merged","storeObjectReconciler","caching","fieldsToDirty_1","__exists","keys","forEach","hasKeyArgs","__typename","dirty","modify","fields","changedFields_1","needToMerge_1","allDeleted_1","sharedDetails_1","isReference","readField","fieldNameOrOptions","from","store","fieldValue","newValue","storage","getStorage","globalThis","__DEV__","checkReference","undefined","warn","seenReference","someNonReference","_i","newValue_1","value","delete","args","typename","getStoreFieldName","evict","options","limit","evicted","clear","replace","extract","obj","extraRootIds","getRootIdSet","push","__META","sort","newData","rest_1","retain","rootId","release","count","ids","Set","add","gc","snapshot","findChildRefIds","idsToRemove","root_1","found_1","root","workSet_1","key","child","makeCacheKey","keyMaker","lookupArray","arguments","CacheGroup","d","resetCaching","canUse","makeDepKey","maybeDependOnExistenceOfEntity","entityId","supportsResultCaching","Root","_b","resultCaching","seed","stump","storageTrie","addLayer","layerId","replay","removeLayer","Layer","ownStoreObject","parentStoreObject","fromParent","p","apply","Stump","existingObject","incomingObject","property","existingValue","incomingValue","shallowCopy","slice","getPrototypeOf","ObjectCanon","known","WeakSet","pool","passes","WeakMap","keysByJSON","Map","empty","admit","isKnown","pass","copy","set","original","proto","array","map","node","freeze","proto_1","array_1","sortedKeys","json","firstValueIndex_1","sorted","object","obj_1","JSON","stringify","execSelectionSetKeyArgs","selectionSet","context","canonizeResults","StoreReader","config","knownResults","compact","addTypename","canon","executeSelectionSet","peekArgs","other","peek","result","enclosingRef","execSelectionSetImpl","max","resultCacheMaxSize","keyArgs","varString","executeSubSelectedArray","execSubSelectedArrayImpl","field","resetCanon","diffQueryAgainstStore","_c","returnPartialData","_d","cache","rootRef","execResult","canonicalStringify","fragments","firstMissing","complete","isFresh","latest","concat","objectsToMerge","missingMerger","handleMissing","resultName","rootIdsByTypename","workSet","selections","selection","name","added","fragment","lookupFragment","kind","FRAGMENT_SPREAD","fragmentMatches","mergeDeep","finalResult","frozen","childResult","filter","item","assertSelectionSetForIdValue","tree","_","values","specifierInfoCache","lookupSpecifierInfo","spec","cacheKey","keyFieldsFnFromSpecifier","specifier","info","keyFieldsFn","keyObject","collectSpecifierPaths","schemaKeyPath","extracted","extractKeyPath","extractKey","join","keyArgsFnFromSpecifier","keyArgsFn","collected","keyPath","firstKey","firstChar","charAt","variableName","varKeyPath","directives","directiveName_1","find","directiveArgs","suffix","extractor","merger","getSpecifierPaths","reduce","toMerge","paths","paths_1","currentPath_1","s","normalize","reducer","argsFromFieldSpecifier","nullKeyFieldsFn","simpleKeyArgsFn","_args","mergeTrueFn","mergeObjects","mergeFalseFn","Policies","typePolicies","toBeAdded","supertypeMap","fuzzySubtypes","usingPossibleTypes","dataIdFromObject","setRootTypename","possibleTypes","addPossibleTypes","addTypePolicies","partialContext","ROOT_QUERY","normalizeReadFieldOptions","policy","getTypePolicy","keyFn","specifierOrId","String","queryType","mutationType","subscriptionType","updateTypePolicy","keyFields","setMerge","getFieldPolicy","read","which","toUpperCase","old","supertype","getSupertypeSet","subtype","match","RegExp","policy_1","supertypes_1","size","regExp","fuzzy","test","fuzzySupertypes","rest","assign","inbox","splice","createIfMissing","fieldPolicies","supertypeSet","typeCondition","typenameSupertypeSet","workQueue_1","maybeEnqueue_1","indexOf","needToCheckFuzzySubtypes","checkingFuzzySubtypes","fuzzyString","fieldSpec","specifierOrString","nameOrField","readOptions","makeFieldFunctionOptions","withValue","getReadFunction","getMergeFunction","parentTypename","childTypename","runMergeFunction","makeMergeObjectsFunction","overwrite","readFieldArgs","argc","stringifyForDisplay","eType","iType","typesDiffer","getContextFlavor","clientOnly","deferred","flavored","flavors","StoreWriter","reader","writeToStore","operationDefinition","written","incomingById","processSelectionSet","mergeTree","fieldNodeSet","entityRef","applied","applyMerges","fieldsWithSelectionSets_1","hasSelectionSet_1","hasMergeFunction_1","childTree","Boolean","warnAboutDataLoss","fragmentMap","result_1","flattenFields","resultFieldKey","getChildMergeTree","processFieldValue","maybeRecycleChildMergeTree","error","e","dataRef","sets","previous_1","mergeMergeTrees","mergeTreeIsEmpty","cloneDeep","fieldMap","limitingTrie","flatten","inheritedContext","visitedNode","visited","dir","if","getStorageArgs","e_1","i_1","getValue_1","eVal","iVal","aVal","pop","emptyMergeTreePool","left","right","needToMergeMaps","remainingRightKeys_1","leftTree","warnings","existingRef","incomingObj","getChild","every","parentType","typeDotName","childTypenames","includes","InMemoryCache","watches","addTypenameTransform","DocumentTransform","assumeImmutableResults","makeVar","txCount","init","rootStore","optimisticData","resetResultCache","resetResultIdentities","previousReader","storeReader","storeWriter","maybeBroadcastWatch","c","broadcastWatch","optimistic","callback","restore","write","broadcast","broadcastWatches","diff","watch","immediate","forget","reset","print","resetCache","resetCaches","discardWatches","Promise","resolve","removeOptimistic","idToRemove","newOptimisticData","batch","updateResult","update","onWatchUpdated","perform","layer","alreadyDirty","performTransaction","optimisticId","transformDocument","document","addTypenameToDocument","addFragmentsToDocument","transform","lastDiff","fromOptimisticTransaction","getMemoryInternals","cacheSlot","cacheInfoMap","getCacheInfo","vars","dep","forgetCache","rv","recallCache","attachCache","caches","listeners","oldListeners","listener","getValue","attach","onNextChange","ApolloCache","getFragmentDoc","recordOptimisticTransaction","transaction","transformForLink","readQuery","watchFragment","latestDiff","fragmentName","otherOptions","diffOptions","observer","next","readFragment","writeQuery","writeFragment","updateQuery","updateFragment","hasOwn","hasOwnProperty","isNullish","defaultDataIdFromObject","_id","defaultConfig","normalizeConfig","shouldCanonizeResults","getTypenameFromStoreObject","TypeOrFieldNameRegExp","fieldNameFromStoreName","selectionSetMatchesResult","storeValueIsStoreObject","makeProcessedFieldsMerger","extractFragmentContext","def"],"mappings":"wHAAA,kDACIA,EAAmC,SAAUC,GAE7C,SAASD,EAAkBE,EAASC,EAAMC,EAAOC,GAC7C,IAAIC,EAEAC,EAAQN,EAAOO,KAAKC,KAAMP,IAAYO,KAK1C,GAJAF,EAAML,QAAUA,EAChBK,EAAMJ,KAAOA,EACbI,EAAMH,MAAQA,EACdG,EAAMF,UAAYA,EACdK,MAAMC,QAAQJ,EAAMJ,MAAO,CAC3BI,EAAMK,QAAUL,EAAML,QACtB,IAAK,IAAIW,EAAIN,EAAMJ,KAAKW,OAAS,EAAGD,GAAK,IAAKA,EAC1CN,EAAMK,SAAWN,EAAK,GAAIA,EAAGC,EAAMJ,KAAKU,IAAMN,EAAMK,QAASN,QAIjEC,EAAMK,QAAUL,EAAMJ,KAK1B,OADAI,EAAMQ,UAAYf,EAAkBgB,UAC7BT,EAEX,OAvBA,eAAUP,EAAmBC,GAuBtBD,EAxB2B,CAyBpCiB,Q,oCC1BK,IAAIC,EAAX,kCAEGA,IAAUA,EAAQ,K,+VCKjBC,EAASC,OAAOC,OAAO,MACvBC,EAAc,WAAc,OAAOH,GACnCI,EAAaH,OAAOC,OAAO,MAC3B,EAA6B,WAC7B,SAASG,EAAYC,EAAU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,eAAYA,KAAW,eAAQA,GAE9D,SAAS8c,IACZ,OAAO,IAAI,OAER,SAASC,EAAuBvD,EAAU/Q,GAG7C,IAAIiL,EAAc,eAAkB,eAAuB8F,IAC3D,MAAO,CACH9F,YAAaA,EACbhK,eAAgB,SAAUH,GACtB,IAAIyT,EAAMtJ,EAAYnK,GAItB,OAHKyT,GAAOvU,IACRuU,EAAMvU,EAAUtL,OAAOoM,IAEpByT,GAAO","file":"js/chunk-vendors~13f63c66.f5854324.js","sourcesContent":["import { __extends } from \"tslib\";\nvar MissingFieldError = /** @class */ (function (_super) {\n __extends(MissingFieldError, _super);\n function MissingFieldError(message, path, query, variables) {\n var _a;\n // 'Error' breaks prototype chain here\n var _this = _super.call(this, message) || this;\n _this.message = message;\n _this.path = path;\n _this.query = query;\n _this.variables = variables;\n if (Array.isArray(_this.path)) {\n _this.missing = _this.message;\n for (var i = _this.path.length - 1; i >= 0; --i) {\n _this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);\n }\n }\n else {\n _this.missing = _this.path;\n }\n // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n // on Android (see issue #3236).\n _this.__proto__ = MissingFieldError.prototype;\n return _this;\n }\n return MissingFieldError;\n}(Error));\nexport { MissingFieldError };\n//# sourceMappingURL=common.js.map","export var Cache;\n(function (Cache) {\n})(Cache || (Cache = {}));\n//# sourceMappingURL=Cache.js.map","import { __assign, __extends, __rest } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { dep } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { isReference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName } from \"./helpers.js\";\nvar DELETE = Object.create(null);\nvar delModifier = function () { return DELETE; };\nvar INVALIDATE = Object.create(null);\nvar EntityStore = /** @class */ (function () {\n function EntityStore(policies, group) {\n var _this = this;\n this.policies = policies;\n this.group = group;\n this.data = Object.create(null);\n // Maps root entity IDs to the number of times they have been retained, minus\n // the number of times they have been released. Retained entities keep other\n // entities they reference (even indirectly) from being garbage collected.\n this.rootIds = Object.create(null);\n // Lazily tracks { __ref: } strings contained by this.data[dataId].\n this.refs = Object.create(null);\n // Bound function that can be passed around to provide easy access to fields\n // of Reference objects as well as ordinary objects.\n this.getFieldValue = function (objectOrReference, storeFieldName) {\n return maybeDeepFreeze(isReference(objectOrReference) ?\n _this.get(objectOrReference.__ref, storeFieldName)\n : objectOrReference && objectOrReference[storeFieldName]);\n };\n // Returns true for non-normalized StoreObjects and non-dangling\n // References, indicating that readField(name, objOrRef) has a chance of\n // working. Useful for filtering out dangling references from lists.\n this.canRead = function (objOrRef) {\n return isReference(objOrRef) ?\n _this.has(objOrRef.__ref)\n : typeof objOrRef === \"object\";\n };\n // Bound function that converts an id or an object with a __typename and\n // primary key fields to a Reference object. If called with a Reference object,\n // that same Reference object is returned. Pass true for mergeIntoStore to persist\n // an object into the store.\n this.toReference = function (objOrIdOrRef, mergeIntoStore) {\n if (typeof objOrIdOrRef === \"string\") {\n return makeReference(objOrIdOrRef);\n }\n if (isReference(objOrIdOrRef)) {\n return objOrIdOrRef;\n }\n var id = _this.policies.identify(objOrIdOrRef)[0];\n if (id) {\n var ref = makeReference(id);\n if (mergeIntoStore) {\n _this.merge(id, objOrIdOrRef);\n }\n return ref;\n }\n };\n }\n // Although the EntityStore class is abstract, it contains concrete\n // implementations of the various NormalizedCache interface methods that\n // are inherited by the Root and Layer subclasses.\n EntityStore.prototype.toObject = function () {\n return __assign({}, this.data);\n };\n EntityStore.prototype.has = function (dataId) {\n return this.lookup(dataId, true) !== void 0;\n };\n EntityStore.prototype.get = function (dataId, fieldName) {\n this.group.depend(dataId, fieldName);\n if (hasOwn.call(this.data, dataId)) {\n var storeObject = this.data[dataId];\n if (storeObject && hasOwn.call(storeObject, fieldName)) {\n return storeObject[fieldName];\n }\n }\n if (fieldName === \"__typename\" &&\n hasOwn.call(this.policies.rootTypenamesById, dataId)) {\n return this.policies.rootTypenamesById[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.get(dataId, fieldName);\n }\n };\n EntityStore.prototype.lookup = function (dataId, dependOnExistence) {\n // The has method (above) calls lookup with dependOnExistence = true, so\n // that it can later be invalidated when we add or remove a StoreObject for\n // this dataId. Any consumer who cares about the contents of the StoreObject\n // should not rely on this dependency, since the contents could change\n // without the object being added or removed.\n if (dependOnExistence)\n this.group.depend(dataId, \"__exists\");\n if (hasOwn.call(this.data, dataId)) {\n return this.data[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.lookup(dataId, dependOnExistence);\n }\n if (this.policies.rootTypenamesById[dataId]) {\n return Object.create(null);\n }\n };\n EntityStore.prototype.merge = function (older, newer) {\n var _this = this;\n var dataId;\n // Convert unexpected references to ID strings.\n if (isReference(older))\n older = older.__ref;\n if (isReference(newer))\n newer = newer.__ref;\n var existing = typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n var incoming = typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\n // If newer was a string ID, but that ID was not defined in this store,\n // then there are no fields to be merged, so we're done.\n if (!incoming)\n return;\n invariant(typeof dataId === \"string\", 1);\n var merged = new DeepMerger(storeObjectReconciler).merge(existing, incoming);\n // Even if merged === existing, existing may have come from a lower\n // layer, so we always need to set this.data[dataId] on this level.\n this.data[dataId] = merged;\n if (merged !== existing) {\n delete this.refs[dataId];\n if (this.group.caching) {\n var fieldsToDirty_1 = Object.create(null);\n // If we added a new StoreObject where there was previously none, dirty\n // anything that depended on the existence of this dataId, such as the\n // EntityStore#has method.\n if (!existing)\n fieldsToDirty_1.__exists = 1;\n // Now invalidate dependents who called getFieldValue for any fields\n // that are changing as a result of this merge.\n Object.keys(incoming).forEach(function (storeFieldName) {\n if (!existing ||\n existing[storeFieldName] !== merged[storeFieldName]) {\n // Always dirty the full storeFieldName, which may include\n // serialized arguments following the fieldName prefix.\n fieldsToDirty_1[storeFieldName] = 1;\n // Also dirty fieldNameFromStoreName(storeFieldName) if it's\n // different from storeFieldName and this field does not have\n // keyArgs configured, because that means the cache can't make\n // any assumptions about how field values with the same field\n // name but different arguments might be interrelated, so it\n // must err on the side of invalidating all field values that\n // share the same short fieldName, regardless of arguments.\n var fieldName = fieldNameFromStoreName(storeFieldName);\n if (fieldName !== storeFieldName &&\n !_this.policies.hasKeyArgs(merged.__typename, fieldName)) {\n fieldsToDirty_1[fieldName] = 1;\n }\n // If merged[storeFieldName] has become undefined, and this is the\n // Root layer, actually delete the property from the merged object,\n // which is guaranteed to have been created fresh in this method.\n if (merged[storeFieldName] === void 0 && !(_this instanceof Layer)) {\n delete merged[storeFieldName];\n }\n }\n });\n if (fieldsToDirty_1.__typename &&\n !(existing && existing.__typename) &&\n // Since we return default root __typename strings\n // automatically from store.get, we don't need to dirty the\n // ROOT_QUERY.__typename field if merged.__typename is equal\n // to the default string (usually \"Query\").\n this.policies.rootTypenamesById[dataId] === merged.__typename) {\n delete fieldsToDirty_1.__typename;\n }\n Object.keys(fieldsToDirty_1).forEach(function (fieldName) {\n return _this.group.dirty(dataId, fieldName);\n });\n }\n }\n };\n EntityStore.prototype.modify = function (dataId, fields) {\n var _this = this;\n var storeObject = this.lookup(dataId);\n if (storeObject) {\n var changedFields_1 = Object.create(null);\n var needToMerge_1 = false;\n var allDeleted_1 = true;\n var sharedDetails_1 = {\n DELETE: DELETE,\n INVALIDATE: INVALIDATE,\n isReference: isReference,\n toReference: this.toReference,\n canRead: this.canRead,\n readField: function (fieldNameOrOptions, from) {\n return _this.policies.readField(typeof fieldNameOrOptions === \"string\" ?\n {\n fieldName: fieldNameOrOptions,\n from: from || makeReference(dataId),\n }\n : fieldNameOrOptions, { store: _this });\n },\n };\n Object.keys(storeObject).forEach(function (storeFieldName) {\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var fieldValue = storeObject[storeFieldName];\n if (fieldValue === void 0)\n return;\n var modify = typeof fields === \"function\" ? fields : (fields[storeFieldName] || fields[fieldName]);\n if (modify) {\n var newValue = modify === delModifier ? DELETE : (modify(maybeDeepFreeze(fieldValue), __assign(__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));\n if (newValue === INVALIDATE) {\n _this.group.dirty(dataId, storeFieldName);\n }\n else {\n if (newValue === DELETE)\n newValue = void 0;\n if (newValue !== fieldValue) {\n changedFields_1[storeFieldName] = newValue;\n needToMerge_1 = true;\n fieldValue = newValue;\n if (globalThis.__DEV__ !== false) {\n var checkReference = function (ref) {\n if (_this.lookup(ref.__ref) === undefined) {\n globalThis.__DEV__ !== false && invariant.warn(2, ref);\n return true;\n }\n };\n if (isReference(newValue)) {\n checkReference(newValue);\n }\n else if (Array.isArray(newValue)) {\n // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n var seenReference = false;\n var someNonReference = void 0;\n for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {\n var value = newValue_1[_i];\n if (isReference(value)) {\n seenReference = true;\n if (checkReference(value))\n break;\n }\n else {\n // Do not warn on primitive values, since those could never be represented\n // by a reference. This is a valid (albeit uncommon) use case.\n if (typeof value === \"object\" && !!value) {\n var id = _this.policies.identify(value)[0];\n // check if object could even be referenced, otherwise we are not interested in it for this warning\n if (id) {\n someNonReference = value;\n }\n }\n }\n if (seenReference && someNonReference !== undefined) {\n globalThis.__DEV__ !== false && invariant.warn(3, someNonReference);\n break;\n }\n }\n }\n }\n }\n }\n }\n if (fieldValue !== void 0) {\n allDeleted_1 = false;\n }\n });\n if (needToMerge_1) {\n this.merge(dataId, changedFields_1);\n if (allDeleted_1) {\n if (this instanceof Layer) {\n this.data[dataId] = void 0;\n }\n else {\n delete this.data[dataId];\n }\n this.group.dirty(dataId, \"__exists\");\n }\n return true;\n }\n }\n return false;\n };\n // If called with only one argument, removes the entire entity\n // identified by dataId. If called with a fieldName as well, removes all\n // fields of that entity whose names match fieldName according to the\n // fieldNameFromStoreName helper function. If called with a fieldName\n // and variables, removes all fields of that entity whose names match fieldName\n // and whose arguments when cached exactly match the variables passed.\n EntityStore.prototype.delete = function (dataId, fieldName, args) {\n var _a;\n var storeObject = this.lookup(dataId);\n if (storeObject) {\n var typename = this.getFieldValue(storeObject, \"__typename\");\n var storeFieldName = fieldName && args ?\n this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })\n : fieldName;\n return this.modify(dataId, storeFieldName ? (_a = {},\n _a[storeFieldName] = delModifier,\n _a) : delModifier);\n }\n return false;\n };\n EntityStore.prototype.evict = function (options, limit) {\n var evicted = false;\n if (options.id) {\n if (hasOwn.call(this.data, options.id)) {\n evicted = this.delete(options.id, options.fieldName, options.args);\n }\n if (this instanceof Layer && this !== limit) {\n evicted = this.parent.evict(options, limit) || evicted;\n }\n // Always invalidate the field to trigger rereading of watched\n // queries, even if no cache data was modified by the eviction,\n // because queries may depend on computed fields with custom read\n // functions, whose values are not stored in the EntityStore.\n if (options.fieldName || evicted) {\n this.group.dirty(options.id, options.fieldName || \"__exists\");\n }\n }\n return evicted;\n };\n EntityStore.prototype.clear = function () {\n this.replace(null);\n };\n EntityStore.prototype.extract = function () {\n var _this = this;\n var obj = this.toObject();\n var extraRootIds = [];\n this.getRootIdSet().forEach(function (id) {\n if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {\n extraRootIds.push(id);\n }\n });\n if (extraRootIds.length) {\n obj.__META = { extraRootIds: extraRootIds.sort() };\n }\n return obj;\n };\n EntityStore.prototype.replace = function (newData) {\n var _this = this;\n Object.keys(this.data).forEach(function (dataId) {\n if (!(newData && hasOwn.call(newData, dataId))) {\n _this.delete(dataId);\n }\n });\n if (newData) {\n var __META = newData.__META, rest_1 = __rest(newData, [\"__META\"]);\n Object.keys(rest_1).forEach(function (dataId) {\n _this.merge(dataId, rest_1[dataId]);\n });\n if (__META) {\n __META.extraRootIds.forEach(this.retain, this);\n }\n }\n };\n EntityStore.prototype.retain = function (rootId) {\n return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n };\n EntityStore.prototype.release = function (rootId) {\n if (this.rootIds[rootId] > 0) {\n var count = --this.rootIds[rootId];\n if (!count)\n delete this.rootIds[rootId];\n return count;\n }\n return 0;\n };\n // Return a Set of all the ID strings that have been retained by\n // this layer/root *and* any layers/roots beneath it.\n EntityStore.prototype.getRootIdSet = function (ids) {\n if (ids === void 0) { ids = new Set(); }\n Object.keys(this.rootIds).forEach(ids.add, ids);\n if (this instanceof Layer) {\n this.parent.getRootIdSet(ids);\n }\n else {\n // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n // always considered roots for garbage collection, regardless of\n // their retainment counts in this.rootIds.\n Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n }\n return ids;\n };\n // The goal of garbage collection is to remove IDs from the Root layer of the\n // store that are no longer reachable starting from any IDs that have been\n // explicitly retained (see retain and release, above). Returns an array of\n // dataId strings that were removed from the store.\n EntityStore.prototype.gc = function () {\n var _this = this;\n var ids = this.getRootIdSet();\n var snapshot = this.toObject();\n ids.forEach(function (id) {\n if (hasOwn.call(snapshot, id)) {\n // Because we are iterating over an ECMAScript Set, the IDs we add here\n // will be visited in later iterations of the forEach loop only if they\n // were not previously contained by the Set.\n Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);\n // By removing IDs from the snapshot object here, we protect them from\n // getting removed from the root store layer below.\n delete snapshot[id];\n }\n });\n var idsToRemove = Object.keys(snapshot);\n if (idsToRemove.length) {\n var root_1 = this;\n while (root_1 instanceof Layer)\n root_1 = root_1.parent;\n idsToRemove.forEach(function (id) { return root_1.delete(id); });\n }\n return idsToRemove;\n };\n EntityStore.prototype.findChildRefIds = function (dataId) {\n if (!hasOwn.call(this.refs, dataId)) {\n var found_1 = (this.refs[dataId] = Object.create(null));\n var root = this.data[dataId];\n if (!root)\n return found_1;\n var workSet_1 = new Set([root]);\n // Within the store, only arrays and objects can contain child entity\n // references, so we can prune the traversal using this predicate:\n workSet_1.forEach(function (obj) {\n if (isReference(obj)) {\n found_1[obj.__ref] = true;\n // In rare cases, a { __ref } Reference object may have other fields.\n // This often indicates a mismerging of References with StoreObjects,\n // but garbage collection should not be fooled by a stray __ref\n // property in a StoreObject (ignoring all the other fields just\n // because the StoreObject looks like a Reference). To avoid this\n // premature termination of findChildRefIds recursion, we fall through\n // to the code below, which will handle any other properties of obj.\n }\n if (isNonNullObject(obj)) {\n Object.keys(obj).forEach(function (key) {\n var child = obj[key];\n // No need to add primitive values to the workSet, since they cannot\n // contain reference objects.\n if (isNonNullObject(child)) {\n workSet_1.add(child);\n }\n });\n }\n });\n }\n return this.refs[dataId];\n };\n EntityStore.prototype.makeCacheKey = function () {\n return this.group.keyMaker.lookupArray(arguments);\n };\n return EntityStore;\n}());\nexport { EntityStore };\n// A single CacheGroup represents a set of one or more EntityStore objects,\n// typically the Root store in a CacheGroup by itself, and all active Layer\n// stores in a group together. A single EntityStore object belongs to only\n// one CacheGroup, store.group. The CacheGroup is responsible for tracking\n// dependencies, so store.group is helpful for generating unique keys for\n// cached results that need to be invalidated when/if those dependencies\n// change. If we used the EntityStore objects themselves as cache keys (that\n// is, store rather than store.group), the cache would become unnecessarily\n// fragmented by all the different Layer objects. Instead, the CacheGroup\n// approach allows all optimistic Layer objects in the same linked list to\n// belong to one CacheGroup, with the non-optimistic Root object belonging\n// to another CacheGroup, allowing resultCaching dependencies to be tracked\n// separately for optimistic and non-optimistic entity data.\nvar CacheGroup = /** @class */ (function () {\n function CacheGroup(caching, parent) {\n if (parent === void 0) { parent = null; }\n this.caching = caching;\n this.parent = parent;\n this.d = null;\n this.resetCaching();\n }\n CacheGroup.prototype.resetCaching = function () {\n this.d = this.caching ? dep() : null;\n this.keyMaker = new Trie(canUseWeakMap);\n };\n CacheGroup.prototype.depend = function (dataId, storeFieldName) {\n if (this.d) {\n this.d(makeDepKey(dataId, storeFieldName));\n var fieldName = fieldNameFromStoreName(storeFieldName);\n if (fieldName !== storeFieldName) {\n // Fields with arguments that contribute extra identifying\n // information to the fieldName (thus forming the storeFieldName)\n // depend not only on the full storeFieldName but also on the\n // short fieldName, so the field can be invalidated using either\n // level of specificity.\n this.d(makeDepKey(dataId, fieldName));\n }\n if (this.parent) {\n this.parent.depend(dataId, storeFieldName);\n }\n }\n };\n CacheGroup.prototype.dirty = function (dataId, storeFieldName) {\n if (this.d) {\n this.d.dirty(makeDepKey(dataId, storeFieldName), \n // When storeFieldName === \"__exists\", that means the entity identified\n // by dataId has either disappeared from the cache or was newly added,\n // so the result caching system would do well to \"forget everything it\n // knows\" about that object. To achieve that kind of invalidation, we\n // not only dirty the associated result cache entry, but also remove it\n // completely from the dependency graph. For the optimism implementation\n // details, see https://github.com/benjamn/optimism/pull/195.\n storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\");\n }\n };\n return CacheGroup;\n}());\nfunction makeDepKey(dataId, storeFieldName) {\n // Since field names cannot have '#' characters in them, this method\n // of joining the field name and the ID should be unambiguous, and much\n // cheaper than JSON.stringify([dataId, fieldName]).\n return storeFieldName + \"#\" + dataId;\n}\nexport function maybeDependOnExistenceOfEntity(store, entityId) {\n if (supportsResultCaching(store)) {\n // We use this pseudo-field __exists elsewhere in the EntityStore code to\n // represent changes in the existence of the entity object identified by\n // entityId. This dependency gets reliably dirtied whenever an object with\n // this ID is deleted (or newly created) within this group, so any result\n // cache entries (for example, StoreReader#executeSelectionSet results) that\n // depend on __exists for this entityId will get dirtied as well, leading to\n // the eventual recomputation (instead of reuse) of those result objects the\n // next time someone reads them from the cache.\n store.group.depend(entityId, \"__exists\");\n }\n}\n(function (EntityStore) {\n // Refer to this class as EntityStore.Root outside this namespace.\n var Root = /** @class */ (function (_super) {\n __extends(Root, _super);\n function Root(_a) {\n var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;\n var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;\n _this.stump = new Stump(_this);\n _this.storageTrie = new Trie(canUseWeakMap);\n if (seed)\n _this.replace(seed);\n return _this;\n }\n Root.prototype.addLayer = function (layerId, replay) {\n // Adding an optimistic Layer on top of the Root actually adds the Layer\n // on top of the Stump, so the Stump always comes between the Root and\n // any Layer objects that we've added.\n return this.stump.addLayer(layerId, replay);\n };\n Root.prototype.removeLayer = function () {\n // Never remove the root layer.\n return this;\n };\n Root.prototype.getStorage = function () {\n return this.storageTrie.lookupArray(arguments);\n };\n return Root;\n }(EntityStore));\n EntityStore.Root = Root;\n})(EntityStore || (EntityStore = {}));\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nvar Layer = /** @class */ (function (_super) {\n __extends(Layer, _super);\n function Layer(id, parent, replay, group) {\n var _this = _super.call(this, parent.policies, group) || this;\n _this.id = id;\n _this.parent = parent;\n _this.replay = replay;\n _this.group = group;\n replay(_this);\n return _this;\n }\n Layer.prototype.addLayer = function (layerId, replay) {\n return new Layer(layerId, this, replay, this.group);\n };\n Layer.prototype.removeLayer = function (layerId) {\n var _this = this;\n // Remove all instances of the given id, not just the first one.\n var parent = this.parent.removeLayer(layerId);\n if (layerId === this.id) {\n if (this.group.caching) {\n // Dirty every ID we're removing. Technically we might be able to avoid\n // dirtying fields that have values in higher layers, but we don't have\n // easy access to higher layers here, and we're about to recreate those\n // layers anyway (see parent.addLayer below).\n Object.keys(this.data).forEach(function (dataId) {\n var ownStoreObject = _this.data[dataId];\n var parentStoreObject = parent[\"lookup\"](dataId);\n if (!parentStoreObject) {\n // The StoreObject identified by dataId was defined in this layer\n // but will be undefined in the parent layer, so we can delete the\n // whole entity using this.delete(dataId). Since we're about to\n // throw this layer away, the only goal of this deletion is to dirty\n // the removed fields.\n _this.delete(dataId);\n }\n else if (!ownStoreObject) {\n // This layer had an entry for dataId but it was undefined, which\n // means the entity was deleted in this layer, and it's about to\n // become undeleted when we remove this layer, so we need to dirty\n // all fields that are about to be reexposed.\n _this.group.dirty(dataId, \"__exists\");\n Object.keys(parentStoreObject).forEach(function (storeFieldName) {\n _this.group.dirty(dataId, storeFieldName);\n });\n }\n else if (ownStoreObject !== parentStoreObject) {\n // If ownStoreObject is not exactly the same as parentStoreObject,\n // dirty any fields whose values will change as a result of this\n // removal.\n Object.keys(ownStoreObject).forEach(function (storeFieldName) {\n if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {\n _this.group.dirty(dataId, storeFieldName);\n }\n });\n }\n });\n }\n return parent;\n }\n // No changes are necessary if the parent chain remains identical.\n if (parent === this.parent)\n return this;\n // Recreate this layer on top of the new parent.\n return parent.addLayer(this.id, this.replay);\n };\n Layer.prototype.toObject = function () {\n return __assign(__assign({}, this.parent.toObject()), this.data);\n };\n Layer.prototype.findChildRefIds = function (dataId) {\n var fromParent = this.parent.findChildRefIds(dataId);\n return hasOwn.call(this.data, dataId) ? __assign(__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;\n };\n Layer.prototype.getStorage = function () {\n var p = this.parent;\n while (p.parent)\n p = p.parent;\n return p.getStorage.apply(p, \n // @ts-expect-error\n arguments);\n };\n return Layer;\n}(EntityStore));\n// Represents a Layer permanently installed just above the Root, which allows\n// reading optimistically (and registering optimistic dependencies) even when\n// no optimistic layers are currently active. The stump.group CacheGroup object\n// is shared by any/all Layer objects added on top of the Stump.\nvar Stump = /** @class */ (function (_super) {\n __extends(Stump, _super);\n function Stump(root) {\n return _super.call(this, \"EntityStore.Stump\", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;\n }\n Stump.prototype.removeLayer = function () {\n // Never remove the Stump layer.\n return this;\n };\n Stump.prototype.merge = function (older, newer) {\n // We never want to write any data into the Stump, so we forward any merge\n // calls to the Root instead. Another option here would be to throw an\n // exception, but the toReference(object, true) function can sometimes\n // trigger Stump writes (which used to be Root writes, before the Stump\n // concept was introduced).\n return this.parent.merge(older, newer);\n };\n return Stump;\n}(Layer));\nfunction storeObjectReconciler(existingObject, incomingObject, property) {\n var existingValue = existingObject[property];\n var incomingValue = incomingObject[property];\n // Wherever there is a key collision, prefer the incoming value, unless\n // it is deeply equal to the existing value. It's worth checking deep\n // equality here (even though blindly returning incoming would be\n // logically correct) because preserving the referential identity of\n // existing data can prevent needless rereading and rerendering.\n return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\nexport function supportsResultCaching(store) {\n // When result caching is disabled, store.depend will be null.\n return !!(store instanceof EntityStore && store.group.caching);\n}\n//# sourceMappingURL=entityStore.js.map","import { __assign } from \"tslib\";\nimport { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet, isNonNullObject as isObjectOrArray, } from \"../../utilities/index.js\";\nimport { isArray } from \"./helpers.js\";\nfunction shallowCopy(value) {\n if (isObjectOrArray(value)) {\n return isArray(value) ?\n value.slice(0)\n : __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n }\n return value;\n}\n// When programmers talk about the \"canonical form\" of an object, they\n// usually have the following meaning in mind, which I've copied from\n// https://en.wiktionary.org/wiki/canonical_form:\n//\n// 1. A standard or normal presentation of a mathematical entity [or\n// object]. A canonical form is an element of a set of representatives\n// of equivalence classes of forms such that there is a function or\n// procedure which projects every element of each equivalence class\n// onto that one element, the canonical form of that equivalence\n// class. The canonical form is expected to be simpler than the rest of\n// the forms in some way.\n//\n// That's a long-winded way of saying any two objects that have the same\n// canonical form may be considered equivalent, even if they are !==,\n// which usually means the objects are structurally equivalent (deeply\n// equal), but don't necessarily use the same memory.\n//\n// Like a literary or musical canon, this ObjectCanon class represents a\n// collection of unique canonical items (JavaScript objects), with the\n// important property that canon.admit(a) === canon.admit(b) if a and b\n// are deeply equal to each other. In terms of the definition above, the\n// canon.admit method is the \"function or procedure which projects every\"\n// object \"onto that one element, the canonical form.\"\n//\n// In the worst case, the canonicalization process may involve looking at\n// every property in the provided object tree, so it takes the same order\n// of time as deep equality checking. Fortunately, already-canonicalized\n// objects are returned immediately from canon.admit, so the presence of\n// canonical subtrees tends to speed up canonicalization.\n//\n// Since consumers of canonical objects can check for deep equality in\n// constant time, canonicalizing cache results can massively improve the\n// performance of application code that skips re-rendering unchanged\n// results, such as \"pure\" UI components in a framework like React.\n//\n// Of course, since canonical objects may be shared widely between\n// unrelated consumers, it's important to think of them as immutable, even\n// though they are not actually frozen with Object.freeze in production,\n// due to the extra performance overhead that comes with frozen objects.\n//\n// Custom scalar objects whose internal class name is neither Array nor\n// Object can be included safely in the admitted tree, but they will not\n// be replaced with a canonical version (to put it another way, they are\n// assumed to be canonical already).\n//\n// If we ignore custom objects, no detection of cycles or repeated object\n// references is currently required by the StoreReader class, since\n// GraphQL result objects are JSON-serializable trees (and thus contain\n// neither cycles nor repeated subtrees), so we can avoid the complexity\n// of keeping track of objects we've already seen during the recursion of\n// the admit method.\n//\n// In the future, we may consider adding additional cases to the switch\n// statement to handle other common object types, such as \"[object Date]\"\n// objects, as needed.\nvar ObjectCanon = /** @class */ (function () {\n function ObjectCanon() {\n // Set of all canonical objects this ObjectCanon has admitted, allowing\n // canon.admit to return previously-canonicalized objects immediately.\n this.known = new (canUseWeakSet ? WeakSet : Set)();\n // Efficient storage/lookup structure for canonical objects.\n this.pool = new Trie(canUseWeakMap);\n // Make the ObjectCanon assume this value has already been\n // canonicalized.\n this.passes = new WeakMap();\n // Arrays that contain the same elements in a different order can share\n // the same SortedKeysInfo object, to save memory.\n this.keysByJSON = new Map();\n // This has to come last because it depends on keysByJSON.\n this.empty = this.admit({});\n }\n ObjectCanon.prototype.isKnown = function (value) {\n return isObjectOrArray(value) && this.known.has(value);\n };\n ObjectCanon.prototype.pass = function (value) {\n if (isObjectOrArray(value)) {\n var copy = shallowCopy(value);\n this.passes.set(copy, value);\n return copy;\n }\n return value;\n };\n ObjectCanon.prototype.admit = function (value) {\n var _this = this;\n if (isObjectOrArray(value)) {\n var original = this.passes.get(value);\n if (original)\n return original;\n var proto = Object.getPrototypeOf(value);\n switch (proto) {\n case Array.prototype: {\n if (this.known.has(value))\n return value;\n var array = value.map(this.admit, this);\n // Arrays are looked up in the Trie using their recursively\n // canonicalized elements, and the known version of the array is\n // preserved as node.array.\n var node = this.pool.lookupArray(array);\n if (!node.array) {\n this.known.add((node.array = array));\n // Since canonical arrays may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (globalThis.__DEV__ !== false) {\n Object.freeze(array);\n }\n }\n return node.array;\n }\n case null:\n case Object.prototype: {\n if (this.known.has(value))\n return value;\n var proto_1 = Object.getPrototypeOf(value);\n var array_1 = [proto_1];\n var keys = this.sortedKeys(value);\n array_1.push(keys.json);\n var firstValueIndex_1 = array_1.length;\n keys.sorted.forEach(function (key) {\n array_1.push(_this.admit(value[key]));\n });\n // Objects are looked up in the Trie by their prototype (which\n // is *not* recursively canonicalized), followed by a JSON\n // representation of their (sorted) keys, followed by the\n // sequence of recursively canonicalized values corresponding to\n // those keys. To keep the final results unambiguous with other\n // sequences (such as arrays that just happen to contain [proto,\n // keys.json, value1, value2, ...]), the known version of the\n // object is stored as node.object.\n var node = this.pool.lookupArray(array_1);\n if (!node.object) {\n var obj_1 = (node.object = Object.create(proto_1));\n this.known.add(obj_1);\n keys.sorted.forEach(function (key, i) {\n obj_1[key] = array_1[firstValueIndex_1 + i];\n });\n // Since canonical objects may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (globalThis.__DEV__ !== false) {\n Object.freeze(obj_1);\n }\n }\n return node.object;\n }\n }\n }\n return value;\n };\n // It's worthwhile to cache the sorting of arrays of strings, since the\n // same initial unsorted arrays tend to be encountered many times.\n // Fortunately, we can reuse the Trie machinery to look up the sorted\n // arrays in linear time (which is faster than sorting large arrays).\n ObjectCanon.prototype.sortedKeys = function (obj) {\n var keys = Object.keys(obj);\n var node = this.pool.lookupArray(keys);\n if (!node.keys) {\n keys.sort();\n var json = JSON.stringify(keys);\n if (!(node.keys = this.keysByJSON.get(json))) {\n this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));\n }\n }\n return node.keys;\n };\n return ObjectCanon;\n}());\nexport { ObjectCanon };\n//# sourceMappingURL=object-canon.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { Kind } from \"graphql\";\nimport { wrap } from \"optimism\";\nimport { isField, resultKeyNameFromField, isReference, makeReference, shouldInclude, addTypenameToDocument, getDefaultValues, getMainDefinition, getQueryDefinition, getFragmentFromSelection, maybeDeepFreeze, mergeDeepArray, DeepMerger, isNonNullObject, canUseWeakMap, compact, canonicalStringify, cacheSizes, } from \"../../utilities/index.js\";\nimport { maybeDependOnExistenceOfEntity, supportsResultCaching, } from \"./entityStore.js\";\nimport { isArray, extractFragmentContext, getTypenameFromStoreObject, shouldCanonizeResults, } from \"./helpers.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { ObjectCanon } from \"./object-canon.js\";\nfunction execSelectionSetKeyArgs(options) {\n return [\n options.selectionSet,\n options.objectOrReference,\n options.context,\n // We split out this property so we can pass different values\n // independently without modifying options.context itself.\n options.context.canonizeResults,\n ];\n}\nvar StoreReader = /** @class */ (function () {\n function StoreReader(config) {\n var _this = this;\n this.knownResults = new (canUseWeakMap ? WeakMap : Map)();\n this.config = compact(config, {\n addTypename: config.addTypename !== false,\n canonizeResults: shouldCanonizeResults(config),\n });\n this.canon = config.canon || new ObjectCanon();\n // memoized functions in this class will be \"garbage-collected\"\n // by recreating the whole `StoreReader` in\n // `InMemoryCache.resetResultsCache`\n // (triggered from `InMemoryCache.gc` with `resetResultCache: true`)\n this.executeSelectionSet = wrap(function (options) {\n var _a;\n var canonizeResults = options.context.canonizeResults;\n var peekArgs = execSelectionSetKeyArgs(options);\n // Negate this boolean option so we can find out if we've already read\n // this result using the other boolean value.\n peekArgs[3] = !canonizeResults;\n var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);\n if (other) {\n if (canonizeResults) {\n return __assign(__assign({}, other), { \n // If we previously read this result without canonizing it, we can\n // reuse that result simply by canonizing it now.\n result: _this.canon.admit(other.result) });\n }\n // If we previously read this result with canonization enabled, we can\n // return that canonized result as-is.\n return other;\n }\n maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n // Finally, if we didn't find any useful previous results, run the real\n // execSelectionSetImpl method with the given options.\n return _this.execSelectionSetImpl(options);\n }, {\n max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n 50000 /* defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"] */,\n keyArgs: execSelectionSetKeyArgs,\n // Note that the parameters of makeCacheKey are determined by the\n // array returned by keyArgs.\n makeCacheKey: function (selectionSet, parent, context, canonizeResults) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(selectionSet, isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);\n }\n },\n });\n this.executeSubSelectedArray = wrap(function (options) {\n maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n return _this.execSubSelectedArrayImpl(options);\n }, {\n max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n 10000 /* defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"] */,\n makeCacheKey: function (_a) {\n var field = _a.field, array = _a.array, context = _a.context;\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(field, array, context.varString);\n }\n },\n });\n }\n StoreReader.prototype.resetCanon = function () {\n this.canon = new ObjectCanon();\n };\n /**\n * Given a store and a query, return as much of the result as possible and\n * identify if any data was missing from the store.\n */\n StoreReader.prototype.diffQueryAgainstStore = function (_a) {\n 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;\n var policies = this.config.cache.policies;\n variables = __assign(__assign({}, getDefaultValues(getQueryDefinition(query))), variables);\n var rootRef = makeReference(rootId);\n var execResult = this.executeSelectionSet({\n selectionSet: getMainDefinition(query).selectionSet,\n objectOrReference: rootRef,\n enclosingRef: rootRef,\n context: __assign({ store: store, query: query, policies: policies, variables: variables, varString: canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),\n });\n var missing;\n if (execResult.missing) {\n // For backwards compatibility we still report an array of\n // MissingFieldError objects, even though there will only ever be at most\n // one of them, now that all missing field error messages are grouped\n // together in the execResult.missing tree.\n missing = [\n new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables),\n ];\n if (!returnPartialData) {\n throw missing[0];\n }\n }\n return {\n result: execResult.result,\n complete: !missing,\n missing: missing,\n };\n };\n StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {\n if (supportsResultCaching(context.store) &&\n this.knownResults.get(result) === selectionSet) {\n var latest = this.executeSelectionSet.peek(selectionSet, parent, context, \n // If result is canonical, then it could only have been previously\n // cached by the canonizing version of executeSelectionSet, so we can\n // avoid checking both possibilities here.\n this.canon.isKnown(result));\n if (latest && result === latest.result) {\n return true;\n }\n }\n return false;\n };\n // Uncached version of executeSelectionSet.\n StoreReader.prototype.execSelectionSetImpl = function (_a) {\n var _this = this;\n var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;\n if (isReference(objectOrReference) &&\n !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n !context.store.has(objectOrReference.__ref)) {\n return {\n result: this.canon.empty,\n missing: \"Dangling reference to missing \".concat(objectOrReference.__ref, \" object\"),\n };\n }\n var variables = context.variables, policies = context.policies, store = context.store;\n var typename = store.getFieldValue(objectOrReference, \"__typename\");\n var objectsToMerge = [];\n var missing;\n var missingMerger = new DeepMerger();\n if (this.config.addTypename &&\n typeof typename === \"string\" &&\n !policies.rootIdsByTypename[typename]) {\n // Ensure we always include a default value for the __typename\n // field, if we have one, and this.config.addTypename is true. Note\n // that this field can be overridden by other merged objects.\n objectsToMerge.push({ __typename: typename });\n }\n function handleMissing(result, resultName) {\n var _a;\n if (result.missing) {\n missing = missingMerger.merge(missing, (_a = {},\n _a[resultName] = result.missing,\n _a));\n }\n return result.result;\n }\n var workSet = new Set(selectionSet.selections);\n workSet.forEach(function (selection) {\n var _a, _b;\n // Omit fields with directives @skip(if: ) or\n // @include(if: ).\n if (!shouldInclude(selection, variables))\n return;\n if (isField(selection)) {\n var fieldValue = policies.readField({\n fieldName: selection.name.value,\n field: selection,\n variables: context.variables,\n from: objectOrReference,\n }, context);\n var resultName = resultKeyNameFromField(selection);\n if (fieldValue === void 0) {\n if (!addTypenameToDocument.added(selection)) {\n missing = missingMerger.merge(missing, (_a = {},\n _a[resultName] = \"Can't find field '\".concat(selection.name.value, \"' on \").concat(isReference(objectOrReference) ?\n objectOrReference.__ref + \" object\"\n : \"object \" + JSON.stringify(objectOrReference, null, 2)),\n _a));\n }\n }\n else if (isArray(fieldValue)) {\n if (fieldValue.length > 0) {\n fieldValue = handleMissing(_this.executeSubSelectedArray({\n field: selection,\n array: fieldValue,\n enclosingRef: enclosingRef,\n context: context,\n }), resultName);\n }\n }\n else if (!selection.selectionSet) {\n // If the field does not have a selection set, then we handle it\n // as a scalar value. To keep this.canon from canonicalizing\n // this value, we use this.canon.pass to wrap fieldValue in a\n // Pass object that this.canon.admit will later unwrap as-is.\n if (context.canonizeResults) {\n fieldValue = _this.canon.pass(fieldValue);\n }\n }\n else if (fieldValue != null) {\n // In this case, because we know the field has a selection set,\n // it must be trying to query a GraphQLObjectType, which is why\n // fieldValue must be != null.\n fieldValue = handleMissing(_this.executeSelectionSet({\n selectionSet: selection.selectionSet,\n objectOrReference: fieldValue,\n enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n context: context,\n }), resultName);\n }\n if (fieldValue !== void 0) {\n objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));\n }\n }\n else {\n var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(9, selection.name.value);\n }\n if (fragment && policies.fragmentMatches(fragment, typename)) {\n fragment.selectionSet.selections.forEach(workSet.add, workSet);\n }\n }\n });\n var result = mergeDeepArray(objectsToMerge);\n var finalResult = { result: result, missing: missing };\n var frozen = context.canonizeResults ?\n this.canon.admit(finalResult)\n // Since this.canon is normally responsible for freezing results (only in\n // development), freeze them manually if canonization is disabled.\n : maybeDeepFreeze(finalResult);\n // Store this result with its selection set so that we can quickly\n // recognize it again in the StoreReader#isFresh method.\n if (frozen.result) {\n this.knownResults.set(frozen.result, selectionSet);\n }\n return frozen;\n };\n // Uncached version of executeSubSelectedArray.\n StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {\n var _this = this;\n var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;\n var missing;\n var missingMerger = new DeepMerger();\n function handleMissing(childResult, i) {\n var _a;\n if (childResult.missing) {\n missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));\n }\n return childResult.result;\n }\n if (field.selectionSet) {\n array = array.filter(context.store.canRead);\n }\n array = array.map(function (item, i) {\n // null value in array\n if (item === null) {\n return null;\n }\n // This is a nested array, recurse\n if (isArray(item)) {\n return handleMissing(_this.executeSubSelectedArray({\n field: field,\n array: item,\n enclosingRef: enclosingRef,\n context: context,\n }), i);\n }\n // This is an object, run the selection set on it\n if (field.selectionSet) {\n return handleMissing(_this.executeSelectionSet({\n selectionSet: field.selectionSet,\n objectOrReference: item,\n enclosingRef: isReference(item) ? item : enclosingRef,\n context: context,\n }), i);\n }\n if (globalThis.__DEV__ !== false) {\n assertSelectionSetForIdValue(context.store, field, item);\n }\n return item;\n });\n return {\n result: context.canonizeResults ? this.canon.admit(array) : array,\n missing: missing,\n };\n };\n return StoreReader;\n}());\nexport { StoreReader };\nfunction firstMissing(tree) {\n try {\n JSON.stringify(tree, function (_, value) {\n if (typeof value === \"string\")\n throw value;\n return value;\n });\n }\n catch (result) {\n return result;\n }\n}\nfunction assertSelectionSetForIdValue(store, field, fieldValue) {\n if (!field.selectionSet) {\n var workSet_1 = new Set([fieldValue]);\n workSet_1.forEach(function (value) {\n if (isNonNullObject(value)) {\n invariant(\n !isReference(value),\n 10,\n getTypenameFromStoreObject(store, value),\n field.name.value\n );\n Object.values(value).forEach(workSet_1.add, workSet_1);\n }\n });\n }\n}\n//# sourceMappingURL=readFromStore.js.map","import { invariant } from \"../../utilities/globals/index.js\";\nimport { argumentsObjectFromField, DeepMerger, isNonEmptyArray, isNonNullObject, } from \"../../utilities/index.js\";\nimport { hasOwn, isArray } from \"./helpers.js\";\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nvar specifierInfoCache = Object.create(null);\nfunction lookupSpecifierInfo(spec) {\n // It's safe to encode KeySpecifier arrays with JSON.stringify, since they're\n // just arrays of strings or nested KeySpecifier arrays, and the order of the\n // array elements is important (and suitably preserved by JSON.stringify).\n var cacheKey = JSON.stringify(spec);\n return (specifierInfoCache[cacheKey] ||\n (specifierInfoCache[cacheKey] = Object.create(null)));\n}\nexport function keyFieldsFnFromSpecifier(specifier) {\n var info = lookupSpecifierInfo(specifier);\n return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {\n var extract = function (from, key) {\n return context.readField(key, from);\n };\n var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {\n var extracted = extractKeyPath(context.storeObject, schemaKeyPath, \n // Using context.readField to extract paths from context.storeObject\n // allows the extraction to see through Reference objects and respect\n // custom read functions.\n extract);\n if (extracted === void 0 &&\n object !== context.storeObject &&\n hasOwn.call(object, schemaKeyPath[0])) {\n // If context.storeObject fails to provide a value for the requested\n // path, fall back to the raw result object, if it has a top-level key\n // matching the first key in the path (schemaKeyPath[0]). This allows\n // key fields included in the written data to be saved in the cache\n // even if they are not selected explicitly in context.selectionSet.\n // Not being mentioned by context.selectionSet is convenient here,\n // since it means these extra fields cannot be affected by field\n // aliasing, which is why we can use extractKey instead of\n // context.readField for this extraction.\n extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n }\n invariant(extracted !== void 0, 4, schemaKeyPath.join(\".\"), object);\n return extracted;\n }));\n return \"\".concat(context.typename, \":\").concat(JSON.stringify(keyObject));\n }));\n}\n// The keyArgs extraction process is roughly analogous to keyFields extraction,\n// but there are no aliases involved, missing fields are tolerated (by merely\n// omitting them from the key), and drawing from field.directives or variables\n// is allowed (in addition to drawing from the field's arguments object).\n// Concretely, these differences mean passing a different key path extractor\n// function to collectSpecifierPaths, reusing the shared extractKeyPath helper\n// wherever possible.\nexport function keyArgsFnFromSpecifier(specifier) {\n var info = lookupSpecifierInfo(specifier);\n return (info.keyArgsFn ||\n (info.keyArgsFn = function (args, _a) {\n var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;\n var collected = collectSpecifierPaths(specifier, function (keyPath) {\n var firstKey = keyPath[0];\n var firstChar = firstKey.charAt(0);\n if (firstChar === \"@\") {\n if (field && isNonEmptyArray(field.directives)) {\n var directiveName_1 = firstKey.slice(1);\n // If the directive appears multiple times, only the first\n // occurrence's arguments will be used. TODO Allow repetition?\n // TODO Cache this work somehow, a la aliasMap?\n var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });\n // Fortunately argumentsObjectFromField works for DirectiveNode!\n var directiveArgs = d && argumentsObjectFromField(d, variables);\n // For directives without arguments (d defined, but directiveArgs ===\n // null), the presence or absence of the directive still counts as\n // part of the field key, so we return null in those cases. If no\n // directive with this name was found for this field (d undefined and\n // thus directiveArgs undefined), we return undefined, which causes\n // this value to be omitted from the key object returned by\n // collectSpecifierPaths.\n return (directiveArgs &&\n extractKeyPath(directiveArgs, \n // If keyPath.length === 1, this code calls extractKeyPath with an\n // empty path, which works because it uses directiveArgs as the\n // extracted value.\n keyPath.slice(1)));\n }\n // If the key started with @ but there was no corresponding directive,\n // we want to omit this value from the key object, not fall through to\n // treating @whatever as a normal argument name.\n return;\n }\n if (firstChar === \"$\") {\n var variableName = firstKey.slice(1);\n if (variables && hasOwn.call(variables, variableName)) {\n var varKeyPath = keyPath.slice(0);\n varKeyPath[0] = variableName;\n return extractKeyPath(variables, varKeyPath);\n }\n // If the key started with $ but there was no corresponding variable, we\n // want to omit this value from the key object, not fall through to\n // treating $whatever as a normal argument name.\n return;\n }\n if (args) {\n return extractKeyPath(args, keyPath);\n }\n });\n var suffix = JSON.stringify(collected);\n // If no arguments were passed to this field, and it didn't have any other\n // field key contributions from directives or variables, hide the empty\n // :{} suffix from the field key. However, a field passed no arguments can\n // still end up with a non-empty :{...} suffix if its key configuration\n // refers to directives or variables.\n if (args || suffix !== \"{}\") {\n fieldName += \":\" + suffix;\n }\n return fieldName;\n }));\n}\nexport function collectSpecifierPaths(specifier, extractor) {\n // For each path specified by specifier, invoke the extractor, and repeatedly\n // merge the results together, with appropriate ancestor context.\n var merger = new DeepMerger();\n return getSpecifierPaths(specifier).reduce(function (collected, path) {\n var _a;\n var toMerge = extractor(path);\n if (toMerge !== void 0) {\n // This path is not expected to contain array indexes, so the toMerge\n // reconstruction will not contain arrays. TODO Fix this?\n for (var i = path.length - 1; i >= 0; --i) {\n toMerge = (_a = {}, _a[path[i]] = toMerge, _a);\n }\n collected = merger.merge(collected, toMerge);\n }\n return collected;\n }, Object.create(null));\n}\nexport function getSpecifierPaths(spec) {\n var info = lookupSpecifierInfo(spec);\n if (!info.paths) {\n var paths_1 = (info.paths = []);\n var currentPath_1 = [];\n spec.forEach(function (s, i) {\n if (isArray(s)) {\n getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });\n currentPath_1.length = 0;\n }\n else {\n currentPath_1.push(s);\n if (!isArray(spec[i + 1])) {\n paths_1.push(currentPath_1.slice(0));\n currentPath_1.length = 0;\n }\n }\n });\n }\n return info.paths;\n}\nfunction extractKey(object, key) {\n return object[key];\n}\nexport function extractKeyPath(object, path, extract) {\n // For each key in path, extract the corresponding child property from obj,\n // flattening arrays if encountered (uncommon for keyFields and keyArgs, but\n // possible). The final result of path.reduce is normalized so unexpected leaf\n // objects have their keys safely sorted. That final result is difficult to\n // type as anything other than any. You're welcome to try to improve the\n // return type, but keep in mind extractKeyPath is not a public function\n // (exported only for testing), so the effort may not be worthwhile unless the\n // limited set of actual callers (see above) pass arguments that TypeScript\n // can statically type. If we know only that path is some array of strings\n // (and not, say, a specific tuple of statically known strings), any (or\n // possibly unknown) is the honest answer.\n extract = extract || extractKey;\n return normalize(path.reduce(function reducer(obj, key) {\n return isArray(obj) ?\n obj.map(function (child) { return reducer(child, key); })\n : obj && extract(obj, key);\n }, object));\n}\nfunction normalize(value) {\n // Usually the extracted value will be a scalar value, since most primary\n // key fields are scalar, but just in case we get an object or an array, we\n // need to do some normalization of the order of (nested) keys.\n if (isNonNullObject(value)) {\n if (isArray(value)) {\n return value.map(normalize);\n }\n return collectSpecifierPaths(Object.keys(value).sort(), function (path) {\n return extractKeyPath(value, path);\n });\n }\n return value;\n}\n//# sourceMappingURL=key-extractor.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { storeKeyNameFromField, argumentsObjectFromField, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from \"../../utilities/index.js\";\nimport { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, isArray, } from \"./helpers.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier, } from \"./key-extractor.js\";\nfunction argsFromFieldSpecifier(spec) {\n return (spec.args !== void 0 ? spec.args\n : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n : null);\n}\nvar nullKeyFieldsFn = function () { return void 0; };\nvar simpleKeyArgsFn = function (_args, context) { return context.fieldName; };\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nvar mergeTrueFn = function (existing, incoming, _a) {\n var mergeObjects = _a.mergeObjects;\n return mergeObjects(existing, incoming);\n};\nvar mergeFalseFn = function (_, incoming) { return incoming; };\nvar Policies = /** @class */ (function () {\n function Policies(config) {\n this.config = config;\n this.typePolicies = Object.create(null);\n this.toBeAdded = Object.create(null);\n // Map from subtype names to sets of supertype names. Note that this\n // representation inverts the structure of possibleTypes (whose keys are\n // supertypes and whose values are arrays of subtypes) because it tends\n // to be much more efficient to search upwards than downwards.\n this.supertypeMap = new Map();\n // Any fuzzy subtypes specified by possibleTypes will be converted to\n // RegExp objects and recorded here. Every key of this map can also be\n // found in supertypeMap. In many cases this Map will be empty, which\n // means no fuzzy subtype checking will happen in fragmentMatches.\n this.fuzzySubtypes = new Map();\n this.rootIdsByTypename = Object.create(null);\n this.rootTypenamesById = Object.create(null);\n this.usingPossibleTypes = false;\n this.config = __assign({ dataIdFromObject: defaultDataIdFromObject }, config);\n this.cache = this.config.cache;\n this.setRootTypename(\"Query\");\n this.setRootTypename(\"Mutation\");\n this.setRootTypename(\"Subscription\");\n if (config.possibleTypes) {\n this.addPossibleTypes(config.possibleTypes);\n }\n if (config.typePolicies) {\n this.addTypePolicies(config.typePolicies);\n }\n }\n Policies.prototype.identify = function (object, partialContext) {\n var _a;\n var policies = this;\n var typename = (partialContext &&\n (partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||\n object.__typename;\n // It should be possible to write root Query fields with writeFragment,\n // using { __typename: \"Query\", ... } as the data, but it does not make\n // sense to allow the same identification behavior for the Mutation and\n // Subscription types, since application code should never be writing\n // directly to (or reading directly from) those root objects.\n if (typename === this.rootTypenamesById.ROOT_QUERY) {\n return [\"ROOT_QUERY\"];\n }\n // Default context.storeObject to object if not otherwise provided.\n var storeObject = (partialContext && partialContext.storeObject) || object;\n var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||\n function () {\n var options = normalizeReadFieldOptions(arguments, storeObject);\n return policies.readField(options, {\n store: policies.cache[\"data\"],\n variables: options.variables,\n });\n } });\n var id;\n var policy = typename && this.getTypePolicy(typename);\n var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n while (keyFn) {\n var specifierOrId = keyFn(__assign(__assign({}, object), storeObject), context);\n if (isArray(specifierOrId)) {\n keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n }\n else {\n id = specifierOrId;\n break;\n }\n }\n id = id ? String(id) : void 0;\n return context.keyObject ? [id, context.keyObject] : [id];\n };\n Policies.prototype.addTypePolicies = function (typePolicies) {\n var _this = this;\n Object.keys(typePolicies).forEach(function (typename) {\n var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = __rest(_a, [\"queryType\", \"mutationType\", \"subscriptionType\"]);\n // Though {query,mutation,subscription}Type configurations are rare,\n // it's important to call setRootTypename as early as possible,\n // since these configurations should apply consistently for the\n // entire lifetime of the cache. Also, since only one __typename can\n // qualify as one of these root types, these three properties cannot\n // be inherited, unlike the rest of the incoming properties. That\n // restriction is convenient, because the purpose of this.toBeAdded\n // is to delay the processing of type/field policies until the first\n // time they're used, allowing policies to be added in any order as\n // long as all relevant policies (including policies for supertypes)\n // have been added by the time a given policy is used for the first\n // time. In other words, since inheritance doesn't matter for these\n // properties, there's also no need to delay their processing using\n // the this.toBeAdded queue.\n if (queryType)\n _this.setRootTypename(\"Query\", typename);\n if (mutationType)\n _this.setRootTypename(\"Mutation\", typename);\n if (subscriptionType)\n _this.setRootTypename(\"Subscription\", typename);\n if (hasOwn.call(_this.toBeAdded, typename)) {\n _this.toBeAdded[typename].push(incoming);\n }\n else {\n _this.toBeAdded[typename] = [incoming];\n }\n });\n };\n Policies.prototype.updateTypePolicy = function (typename, incoming) {\n var _this = this;\n var existing = this.getTypePolicy(typename);\n var keyFields = incoming.keyFields, fields = incoming.fields;\n function setMerge(existing, merge) {\n existing.merge =\n typeof merge === \"function\" ? merge\n // Pass merge:true as a shorthand for a merge implementation\n // that returns options.mergeObjects(existing, incoming).\n : merge === true ? mergeTrueFn\n // Pass merge:false to make incoming always replace existing\n // without any warnings about data clobbering.\n : merge === false ? mergeFalseFn\n : existing.merge;\n }\n // Type policies can define merge functions, as an alternative to\n // using field policies to merge child objects.\n setMerge(existing, incoming.merge);\n existing.keyFn =\n // Pass false to disable normalization for this typename.\n keyFields === false ? nullKeyFieldsFn\n // Pass an array of strings to use those fields to compute a\n // composite ID for objects of this typename.\n : isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)\n // Pass a function to take full control over identification.\n : typeof keyFields === \"function\" ? keyFields\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n if (fields) {\n Object.keys(fields).forEach(function (fieldName) {\n var existing = _this.getFieldPolicy(typename, fieldName, true);\n var incoming = fields[fieldName];\n if (typeof incoming === \"function\") {\n existing.read = incoming;\n }\n else {\n var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;\n existing.keyFn =\n // Pass false to disable argument-based differentiation of\n // field identities.\n keyArgs === false ? simpleKeyArgsFn\n // Pass an array of strings to use named arguments to\n // compute a composite identity for the field.\n : isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)\n // Pass a function to take full control over field identity.\n : typeof keyArgs === \"function\" ? keyArgs\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n if (typeof read === \"function\") {\n existing.read = read;\n }\n setMerge(existing, merge);\n }\n if (existing.read && existing.merge) {\n // If we have both a read and a merge function, assume\n // keyArgs:false, because read and merge together can take\n // responsibility for interpreting arguments in and out. This\n // default assumption can always be overridden by specifying\n // keyArgs explicitly in the FieldPolicy.\n existing.keyFn = existing.keyFn || simpleKeyArgsFn;\n }\n });\n }\n };\n Policies.prototype.setRootTypename = function (which, typename) {\n if (typename === void 0) { typename = which; }\n var rootId = \"ROOT_\" + which.toUpperCase();\n var old = this.rootTypenamesById[rootId];\n if (typename !== old) {\n invariant(!old || old === which, 5, which);\n // First, delete any old __typename associated with this rootId from\n // rootIdsByTypename.\n if (old)\n delete this.rootIdsByTypename[old];\n // Now make this the only __typename that maps to this rootId.\n this.rootIdsByTypename[typename] = rootId;\n // Finally, update the __typename associated with this rootId.\n this.rootTypenamesById[rootId] = typename;\n }\n };\n Policies.prototype.addPossibleTypes = function (possibleTypes) {\n var _this = this;\n this.usingPossibleTypes = true;\n Object.keys(possibleTypes).forEach(function (supertype) {\n // Make sure all types have an entry in this.supertypeMap, even if\n // their supertype set is empty, so we can return false immediately\n // from policies.fragmentMatches for unknown supertypes.\n _this.getSupertypeSet(supertype, true);\n possibleTypes[supertype].forEach(function (subtype) {\n _this.getSupertypeSet(subtype, true).add(supertype);\n var match = subtype.match(TypeOrFieldNameRegExp);\n if (!match || match[0] !== subtype) {\n // TODO Don't interpret just any invalid typename as a RegExp.\n _this.fuzzySubtypes.set(subtype, new RegExp(subtype));\n }\n });\n });\n };\n Policies.prototype.getTypePolicy = function (typename) {\n var _this = this;\n if (!hasOwn.call(this.typePolicies, typename)) {\n var policy_1 = (this.typePolicies[typename] = Object.create(null));\n policy_1.fields = Object.create(null);\n // When the TypePolicy for typename is first accessed, instead of\n // starting with an empty policy object, inherit any properties or\n // fields from the type policies of the supertypes of typename.\n //\n // Any properties or fields defined explicitly within the TypePolicy\n // for typename will take precedence, and if there are multiple\n // supertypes, the properties of policies whose types were added\n // later via addPossibleTypes will take precedence over those of\n // earlier supertypes. TODO Perhaps we should warn about these\n // conflicts in development, and recommend defining the property\n // explicitly in the subtype policy?\n //\n // Field policy inheritance is atomic/shallow: you can't inherit a\n // field policy and then override just its read function, since read\n // and merge functions often need to cooperate, so changing only one\n // of them would be a recipe for inconsistency.\n //\n // Once the TypePolicy for typename has been accessed, its properties can\n // still be updated directly using addTypePolicies, but future changes to\n // inherited supertype policies will not be reflected in this subtype\n // policy, because this code runs at most once per typename.\n var supertypes_1 = this.supertypeMap.get(typename);\n if (!supertypes_1 && this.fuzzySubtypes.size) {\n // To make the inheritance logic work for unknown typename strings that\n // may have fuzzy supertypes, we give this typename an empty supertype\n // set and then populate it with any fuzzy supertypes that match.\n supertypes_1 = this.getSupertypeSet(typename, true);\n // This only works for typenames that are directly matched by a fuzzy\n // supertype. What if there is an intermediate chain of supertypes?\n // While possible, that situation can only be solved effectively by\n // specifying the intermediate relationships via possibleTypes, manually\n // and in a non-fuzzy way.\n this.fuzzySubtypes.forEach(function (regExp, fuzzy) {\n if (regExp.test(typename)) {\n // The fuzzy parameter is just the original string version of regExp\n // (not a valid __typename string), but we can look up the\n // associated supertype(s) in this.supertypeMap.\n var fuzzySupertypes = _this.supertypeMap.get(fuzzy);\n if (fuzzySupertypes) {\n fuzzySupertypes.forEach(function (supertype) {\n return supertypes_1.add(supertype);\n });\n }\n }\n });\n }\n if (supertypes_1 && supertypes_1.size) {\n supertypes_1.forEach(function (supertype) {\n var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = __rest(_a, [\"fields\"]);\n Object.assign(policy_1, rest);\n Object.assign(policy_1.fields, fields);\n });\n }\n }\n var inbox = this.toBeAdded[typename];\n if (inbox && inbox.length) {\n // Merge the pending policies into this.typePolicies, in the order they\n // were originally passed to addTypePolicy.\n inbox.splice(0).forEach(function (policy) {\n _this.updateTypePolicy(typename, policy);\n });\n }\n return this.typePolicies[typename];\n };\n Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {\n if (typename) {\n var fieldPolicies = this.getTypePolicy(typename).fields;\n return (fieldPolicies[fieldName] ||\n (createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));\n }\n };\n Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {\n var supertypeSet = this.supertypeMap.get(subtype);\n if (!supertypeSet && createIfMissing) {\n this.supertypeMap.set(subtype, (supertypeSet = new Set()));\n }\n return supertypeSet;\n };\n Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {\n var _this = this;\n if (!fragment.typeCondition)\n return true;\n // If the fragment has a type condition but the object we're matching\n // against does not have a __typename, the fragment cannot match.\n if (!typename)\n return false;\n var supertype = fragment.typeCondition.name.value;\n // Common case: fragment type condition and __typename are the same.\n if (typename === supertype)\n return true;\n if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n var typenameSupertypeSet = this.getSupertypeSet(typename, true);\n var workQueue_1 = [typenameSupertypeSet];\n var maybeEnqueue_1 = function (subtype) {\n var supertypeSet = _this.getSupertypeSet(subtype, false);\n if (supertypeSet &&\n supertypeSet.size &&\n workQueue_1.indexOf(supertypeSet) < 0) {\n workQueue_1.push(supertypeSet);\n }\n };\n // We need to check fuzzy subtypes only if we encountered fuzzy\n // subtype strings in addPossibleTypes, and only while writing to\n // the cache, since that's when selectionSetMatchesResult gives a\n // strong signal of fragment matching. The StoreReader class calls\n // policies.fragmentMatches without passing a result object, so\n // needToCheckFuzzySubtypes is always false while reading.\n var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n var checkingFuzzySubtypes = false;\n // It's important to keep evaluating workQueue.length each time through\n // the loop, because the queue can grow while we're iterating over it.\n for (var i = 0; i < workQueue_1.length; ++i) {\n var supertypeSet = workQueue_1[i];\n if (supertypeSet.has(supertype)) {\n if (!typenameSupertypeSet.has(supertype)) {\n if (checkingFuzzySubtypes) {\n globalThis.__DEV__ !== false && invariant.warn(6, typename, supertype);\n }\n // Record positive results for faster future lookup.\n // Unfortunately, we cannot safely cache negative results,\n // because new possibleTypes data could always be added to the\n // Policies class.\n typenameSupertypeSet.add(supertype);\n }\n return true;\n }\n supertypeSet.forEach(maybeEnqueue_1);\n if (needToCheckFuzzySubtypes &&\n // Start checking fuzzy subtypes only after exhausting all\n // non-fuzzy subtypes (after the final iteration of the loop).\n i === workQueue_1.length - 1 &&\n // We could wait to compare fragment.selectionSet to result\n // after we verify the supertype, but this check is often less\n // expensive than that search, and we will have to do the\n // comparison anyway whenever we find a potential match.\n selectionSetMatchesResult(fragment.selectionSet, result, variables)) {\n // We don't always need to check fuzzy subtypes (if no result\n // was provided, or !this.fuzzySubtypes.size), but, when we do,\n // we only want to check them once.\n needToCheckFuzzySubtypes = false;\n checkingFuzzySubtypes = true;\n // If we find any fuzzy subtypes that match typename, extend the\n // workQueue to search through the supertypes of those fuzzy\n // subtypes. Otherwise the for-loop will terminate and we'll\n // return false below.\n this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {\n var match = typename.match(regExp);\n if (match && match[0] === typename) {\n maybeEnqueue_1(fuzzyString);\n }\n });\n }\n }\n }\n return false;\n };\n Policies.prototype.hasKeyArgs = function (typename, fieldName) {\n var policy = this.getFieldPolicy(typename, fieldName, false);\n return !!(policy && policy.keyFn);\n };\n Policies.prototype.getStoreFieldName = function (fieldSpec) {\n var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;\n var policy = this.getFieldPolicy(typename, fieldName, false);\n var storeFieldName;\n var keyFn = policy && policy.keyFn;\n if (keyFn && typename) {\n var context = {\n typename: typename,\n fieldName: fieldName,\n field: fieldSpec.field || null,\n variables: fieldSpec.variables,\n };\n var args = argsFromFieldSpecifier(fieldSpec);\n while (keyFn) {\n var specifierOrString = keyFn(args, context);\n if (isArray(specifierOrString)) {\n keyFn = keyArgsFnFromSpecifier(specifierOrString);\n }\n else {\n // If the custom keyFn returns a falsy value, fall back to\n // fieldName instead.\n storeFieldName = specifierOrString || fieldName;\n break;\n }\n }\n }\n if (storeFieldName === void 0) {\n storeFieldName =\n fieldSpec.field ?\n storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n }\n // Returning false from a keyArgs function is like configuring\n // keyArgs: false, but more dynamic.\n if (storeFieldName === false) {\n return fieldName;\n }\n // Make sure custom field names start with the actual field.name.value\n // of the field, so we can always figure out which properties of a\n // StoreObject correspond to which original field names.\n return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName\n : fieldName + \":\" + storeFieldName;\n };\n Policies.prototype.readField = function (options, context) {\n var objectOrReference = options.from;\n if (!objectOrReference)\n return;\n var nameOrField = options.field || options.fieldName;\n if (!nameOrField)\n return;\n if (options.typename === void 0) {\n var typename = context.store.getFieldValue(objectOrReference, \"__typename\");\n if (typename)\n options.typename = typename;\n }\n var storeFieldName = this.getStoreFieldName(options);\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var existing = context.store.getFieldValue(objectOrReference, storeFieldName);\n var policy = this.getFieldPolicy(options.typename, fieldName, false);\n var read = policy && policy.read;\n if (read) {\n var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(isReference(objectOrReference) ?\n objectOrReference.__ref\n : objectOrReference, storeFieldName));\n // Call read(existing, readOptions) with cacheSlot holding this.cache.\n return cacheSlot.withValue(this.cache, read, [\n existing,\n readOptions,\n ]);\n }\n return existing;\n };\n Policies.prototype.getReadFunction = function (typename, fieldName) {\n var policy = this.getFieldPolicy(typename, fieldName, false);\n return policy && policy.read;\n };\n Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {\n var policy = this.getFieldPolicy(parentTypename, fieldName, false);\n var merge = policy && policy.merge;\n if (!merge && childTypename) {\n policy = this.getTypePolicy(childTypename);\n merge = policy && policy.merge;\n }\n return merge;\n };\n Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {\n var field = _a.field, typename = _a.typename, merge = _a.merge;\n if (merge === mergeTrueFn) {\n // Instead of going to the trouble of creating a full\n // FieldFunctionOptions object and calling mergeTrueFn, we can\n // simply call mergeObjects, as mergeTrueFn would.\n return makeMergeObjectsFunction(context.store)(existing, incoming);\n }\n if (merge === mergeFalseFn) {\n // Likewise for mergeFalseFn, whose implementation is even simpler.\n return incoming;\n }\n // If cache.writeQuery or cache.writeFragment was called with\n // options.overwrite set to true, we still call merge functions, but\n // the existing data is always undefined, so the merge function will\n // not attempt to combine the incoming data with the existing data.\n if (context.overwrite) {\n existing = void 0;\n }\n return merge(existing, incoming, makeFieldFunctionOptions(this, \n // Unlike options.readField for read functions, we do not fall\n // back to the current object if no foreignObjOrRef is provided,\n // because it's not clear what the current object should be for\n // merge functions: the (possibly undefined) existing object, or\n // the incoming object? If you think your merge function needs\n // to read sibling fields in order to produce a new value for\n // the current field, you might want to rethink your strategy,\n // because that's a recipe for making merge behavior sensitive\n // to the order in which fields are written into the cache.\n // However, readField(name, ref) is useful for merge functions\n // that need to deduplicate child objects and references.\n void 0, {\n typename: typename,\n fieldName: field.name.value,\n field: field,\n variables: context.variables,\n }, context, storage || Object.create(null)));\n };\n return Policies;\n}());\nexport { Policies };\nfunction makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {\n var storeFieldName = policies.getStoreFieldName(fieldSpec);\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var variables = fieldSpec.variables || context.variables;\n var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;\n return {\n args: argsFromFieldSpecifier(fieldSpec),\n field: fieldSpec.field || null,\n fieldName: fieldName,\n storeFieldName: storeFieldName,\n variables: variables,\n isReference: isReference,\n toReference: toReference,\n storage: storage,\n cache: policies.cache,\n canRead: canRead,\n readField: function () {\n return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);\n },\n mergeObjects: makeMergeObjectsFunction(context.store),\n };\n}\nexport function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {\n var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;\n var options;\n if (typeof fieldNameOrOptions === \"string\") {\n options = {\n fieldName: fieldNameOrOptions,\n // Default to objectOrReference only when no second argument was\n // passed for the from parameter, not when undefined is explicitly\n // passed as the second argument.\n from: argc > 1 ? from : objectOrReference,\n };\n }\n else {\n options = __assign({}, fieldNameOrOptions);\n // Default to objectOrReference only when fieldNameOrOptions.from is\n // actually omitted, rather than just undefined.\n if (!hasOwn.call(options, \"from\")) {\n options.from = objectOrReference;\n }\n }\n if (globalThis.__DEV__ !== false && options.from === void 0) {\n globalThis.__DEV__ !== false && invariant.warn(7, stringifyForDisplay(Array.from(readFieldArgs)));\n }\n if (void 0 === options.variables) {\n options.variables = variables;\n }\n return options;\n}\nfunction makeMergeObjectsFunction(store) {\n return function mergeObjects(existing, incoming) {\n if (isArray(existing) || isArray(incoming)) {\n throw newInvariantError(8);\n }\n // These dynamic checks are necessary because the parameters of a\n // custom merge function can easily have the any type, so the type\n // system cannot always enforce the StoreObject | Reference parameter\n // types of options.mergeObjects.\n if (isNonNullObject(existing) && isNonNullObject(incoming)) {\n var eType = store.getFieldValue(existing, \"__typename\");\n var iType = store.getFieldValue(incoming, \"__typename\");\n var typesDiffer = eType && iType && eType !== iType;\n if (typesDiffer) {\n return incoming;\n }\n if (isReference(existing) && storeValueIsStoreObject(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // existing.__ref, preferring/overwriting any fields contributed by the\n // newer incoming StoreObject.\n store.merge(existing.__ref, incoming);\n return existing;\n }\n if (storeValueIsStoreObject(existing) && isReference(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // incoming.__ref, taking fields from the older existing object only if\n // those fields are not already present in the newer StoreObject\n // identified by incoming.__ref.\n store.merge(existing, incoming.__ref);\n return incoming;\n }\n if (storeValueIsStoreObject(existing) &&\n storeValueIsStoreObject(incoming)) {\n return __assign(__assign({}, existing), incoming);\n }\n }\n return incoming;\n };\n}\n//# sourceMappingURL=policies.js.map","import { __assign } from \"tslib\";\nimport { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport { Kind } from \"graphql\";\nimport { getFragmentFromSelection, getDefaultValues, getOperationDefinition, getTypenameFromResult, makeReference, isField, resultKeyNameFromField, isReference, shouldInclude, cloneDeep, addTypenameToDocument, isNonEmptyArray, argumentsObjectFromField, canonicalStringify, } from \"../../utilities/index.js\";\nimport { isArray, makeProcessedFieldsMerger, fieldNameFromStoreName, storeValueIsStoreObject, extractFragmentContext, } from \"./helpers.js\";\nimport { normalizeReadFieldOptions } from \"./policies.js\";\n// Since there are only four possible combinations of context.clientOnly and\n// context.deferred values, we should need at most four \"flavors\" of any given\n// WriteContext. To avoid creating multiple copies of the same context, we cache\n// the contexts in the context.flavors Map (shared by all flavors) according to\n// their clientOnly and deferred values (always in that order).\nfunction getContextFlavor(context, clientOnly, deferred) {\n var key = \"\".concat(clientOnly).concat(deferred);\n var flavored = context.flavors.get(key);\n if (!flavored) {\n context.flavors.set(key, (flavored =\n context.clientOnly === clientOnly && context.deferred === deferred ?\n context\n : __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));\n }\n return flavored;\n}\nvar StoreWriter = /** @class */ (function () {\n function StoreWriter(cache, reader, fragments) {\n this.cache = cache;\n this.reader = reader;\n this.fragments = fragments;\n }\n StoreWriter.prototype.writeToStore = function (store, _a) {\n var _this = this;\n var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;\n var operationDefinition = getOperationDefinition(query);\n var merger = makeProcessedFieldsMerger();\n variables = __assign(__assign({}, getDefaultValues(operationDefinition)), variables);\n var context = __assign(__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {\n return merger.merge(existing, incoming);\n }, variables: variables, varString: canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });\n var ref = this.processSelectionSet({\n result: result || Object.create(null),\n dataId: dataId,\n selectionSet: operationDefinition.selectionSet,\n mergeTree: { map: new Map() },\n context: context,\n });\n if (!isReference(ref)) {\n throw newInvariantError(11, result);\n }\n // So far, the store has not been modified, so now it's time to process\n // context.incomingById and merge those incoming fields into context.store.\n context.incomingById.forEach(function (_a, dataId) {\n var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;\n var entityRef = makeReference(dataId);\n if (mergeTree && mergeTree.map.size) {\n var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);\n if (isReference(applied)) {\n // Assume References returned by applyMerges have already been merged\n // into the store. See makeMergeObjectsFunction in policies.ts for an\n // example of how this can happen.\n return;\n }\n // Otherwise, applyMerges returned a StoreObject, whose fields we should\n // merge into the store (see store.merge statement below).\n storeObject = applied;\n }\n if (globalThis.__DEV__ !== false && !context.overwrite) {\n var fieldsWithSelectionSets_1 = Object.create(null);\n fieldNodeSet.forEach(function (field) {\n if (field.selectionSet) {\n fieldsWithSelectionSets_1[field.name.value] = true;\n }\n });\n var hasSelectionSet_1 = function (storeFieldName) {\n return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===\n true;\n };\n var hasMergeFunction_1 = function (storeFieldName) {\n var childTree = mergeTree && mergeTree.map.get(storeFieldName);\n return Boolean(childTree && childTree.info && childTree.info.merge);\n };\n Object.keys(storeObject).forEach(function (storeFieldName) {\n // If a merge function was defined for this field, trust that it\n // did the right thing about (not) clobbering data. If the field\n // has no selection set, it's a scalar field, so it doesn't need\n // a merge function (even if it's an object, like JSON data).\n if (hasSelectionSet_1(storeFieldName) &&\n !hasMergeFunction_1(storeFieldName)) {\n warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);\n }\n });\n }\n store.merge(dataId, storeObject);\n });\n // Any IDs written explicitly to the cache will be retained as\n // reachable root IDs for garbage collection purposes. Although this\n // logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their\n // retainment counts are effectively ignored because cache.gc() always\n // includes them in its root ID set.\n store.retain(ref.__ref);\n return ref;\n };\n StoreWriter.prototype.processSelectionSet = function (_a) {\n var _this = this;\n var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, \n // This object allows processSelectionSet to report useful information\n // to its callers without explicitly returning that information.\n mergeTree = _a.mergeTree;\n var policies = this.cache.policies;\n // This variable will be repeatedly updated using context.merge to\n // accumulate all fields that need to be written into the store.\n var incoming = Object.create(null);\n // If typename was not passed in, infer it. Note that typename is\n // always passed in for tricky-to-infer cases such as \"Query\" for\n // ROOT_QUERY.\n var typename = (dataId && policies.rootTypenamesById[dataId]) ||\n getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n (dataId && context.store.get(dataId, \"__typename\"));\n if (\"string\" === typeof typename) {\n incoming.__typename = typename;\n }\n // This readField function will be passed as context.readField in the\n // KeyFieldsContext object created within policies.identify (called below).\n // In addition to reading from the existing context.store (thanks to the\n // policies.readField(options, context) line at the very bottom), this\n // version of readField can read from Reference objects that are currently\n // pending in context.incomingById, which is important whenever keyFields\n // need to be extracted from a child object that processSelectionSet has\n // turned into a Reference.\n var readField = function () {\n var options = normalizeReadFieldOptions(arguments, incoming, context.variables);\n if (isReference(options.from)) {\n var info = context.incomingById.get(options.from.__ref);\n if (info) {\n var result_1 = policies.readField(__assign(__assign({}, options), { from: info.storeObject }), context);\n if (result_1 !== void 0) {\n return result_1;\n }\n }\n }\n return policies.readField(options, context);\n };\n var fieldNodeSet = new Set();\n this.flattenFields(selectionSet, result, \n // This WriteContext will be the default context value for fields returned\n // by the flattenFields method, but some fields may be assigned a modified\n // context, depending on the presence of @client and other directives.\n context, typename).forEach(function (context, field) {\n var _a;\n var resultFieldKey = resultKeyNameFromField(field);\n var value = result[resultFieldKey];\n fieldNodeSet.add(field);\n if (value !== void 0) {\n var storeFieldName = policies.getStoreFieldName({\n typename: typename,\n fieldName: field.name.value,\n field: field,\n variables: context.variables,\n });\n var childTree = getChildMergeTree(mergeTree, storeFieldName);\n var incomingValue = _this.processFieldValue(value, field, \n // Reset context.clientOnly and context.deferred to their default\n // values before processing nested selection sets.\n field.selectionSet ?\n getContextFlavor(context, false, false)\n : context, childTree);\n // To determine if this field holds a child object with a merge function\n // defined in its type policy (see PR #7070), we need to figure out the\n // child object's __typename.\n var childTypename = void 0;\n // The field's value can be an object that has a __typename only if the\n // field has a selection set. Otherwise incomingValue is scalar.\n if (field.selectionSet &&\n (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {\n childTypename = readField(\"__typename\", incomingValue);\n }\n var merge = policies.getMergeFunction(typename, field.name.value, childTypename);\n if (merge) {\n childTree.info = {\n // TODO Check compatibility against any existing childTree.field?\n field: field,\n typename: typename,\n merge: merge,\n };\n }\n else {\n maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n }\n incoming = context.merge(incoming, (_a = {},\n _a[storeFieldName] = incomingValue,\n _a));\n }\n else if (globalThis.__DEV__ !== false &&\n !context.clientOnly &&\n !context.deferred &&\n !addTypenameToDocument.added(field) &&\n // If the field has a read function, it may be a synthetic field or\n // provide a default value, so its absence from the written data should\n // not be cause for alarm.\n !policies.getReadFunction(typename, field.name.value)) {\n globalThis.__DEV__ !== false && invariant.error(12, resultKeyNameFromField(field), result);\n }\n });\n // Identify the result object, even if dataId was already provided,\n // since we always need keyObject below.\n try {\n var _b = policies.identify(result, {\n typename: typename,\n selectionSet: selectionSet,\n fragmentMap: context.fragmentMap,\n storeObject: incoming,\n readField: readField,\n }), id = _b[0], keyObject = _b[1];\n // If dataId was not provided, fall back to the id just generated by\n // policies.identify.\n dataId = dataId || id;\n // Write any key fields that were used during identification, even if\n // they were not mentioned in the original query.\n if (keyObject) {\n // TODO Reverse the order of the arguments?\n incoming = context.merge(incoming, keyObject);\n }\n }\n catch (e) {\n // If dataId was provided, tolerate failure of policies.identify.\n if (!dataId)\n throw e;\n }\n if (\"string\" === typeof dataId) {\n var dataRef = makeReference(dataId);\n // Avoid processing the same entity object using the same selection\n // set more than once. We use an array instead of a Set since most\n // entity IDs will be written using only one selection set, so the\n // size of this array is likely to be very small, meaning indexOf is\n // likely to be faster than Set.prototype.has.\n var sets = context.written[dataId] || (context.written[dataId] = []);\n if (sets.indexOf(selectionSet) >= 0)\n return dataRef;\n sets.push(selectionSet);\n // If we're about to write a result object into the store, but we\n // happen to know that the exact same (===) result object would be\n // returned if we were to reread the result with the same inputs,\n // then we can skip the rest of the processSelectionSet work for\n // this object, and immediately return a Reference to it.\n if (this.reader &&\n this.reader.isFresh(result, dataRef, selectionSet, context)) {\n return dataRef;\n }\n var previous_1 = context.incomingById.get(dataId);\n if (previous_1) {\n previous_1.storeObject = context.merge(previous_1.storeObject, incoming);\n previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);\n fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });\n }\n else {\n context.incomingById.set(dataId, {\n storeObject: incoming,\n // Save a reference to mergeTree only if it is not empty, because\n // empty MergeTrees may be recycled by maybeRecycleChildMergeTree and\n // reused for entirely different parts of the result tree.\n mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,\n fieldNodeSet: fieldNodeSet,\n });\n }\n return dataRef;\n }\n return incoming;\n };\n StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {\n var _this = this;\n if (!field.selectionSet || value === null) {\n // In development, we need to clone scalar values so that they can be\n // safely frozen with maybeDeepFreeze in readFromStore.ts. In production,\n // it's cheaper to store the scalar values directly in the cache.\n return globalThis.__DEV__ !== false ? cloneDeep(value) : value;\n }\n if (isArray(value)) {\n return value.map(function (item, i) {\n var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));\n maybeRecycleChildMergeTree(mergeTree, i);\n return value;\n });\n }\n return this.processSelectionSet({\n result: value,\n selectionSet: field.selectionSet,\n context: context,\n mergeTree: mergeTree,\n });\n };\n // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n // some additions for tracking @client and @defer directives.\n StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {\n if (typename === void 0) { typename = getTypenameFromResult(result, selectionSet, context.fragmentMap); }\n var fieldMap = new Map();\n var policies = this.cache.policies;\n var limitingTrie = new Trie(false); // No need for WeakMap, since limitingTrie does not escape.\n (function flatten(selectionSet, inheritedContext) {\n var visitedNode = limitingTrie.lookup(selectionSet, \n // Because we take inheritedClientOnly and inheritedDeferred into\n // consideration here (in addition to selectionSet), it's possible for\n // the same selection set to be flattened more than once, if it appears\n // in the query with different @client and/or @directive configurations.\n inheritedContext.clientOnly, inheritedContext.deferred);\n if (visitedNode.visited)\n return;\n visitedNode.visited = true;\n selectionSet.selections.forEach(function (selection) {\n if (!shouldInclude(selection, context.variables))\n return;\n var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;\n if (\n // Since the presence of @client or @defer on this field can only\n // cause clientOnly or deferred to become true, we can skip the\n // forEach loop if both clientOnly and deferred are already true.\n !(clientOnly && deferred) &&\n isNonEmptyArray(selection.directives)) {\n selection.directives.forEach(function (dir) {\n var name = dir.name.value;\n if (name === \"client\")\n clientOnly = true;\n if (name === \"defer\") {\n var args = argumentsObjectFromField(dir, context.variables);\n // The @defer directive takes an optional args.if boolean\n // argument, similar to @include(if: boolean). Note that\n // @defer(if: false) does not make context.deferred false, but\n // instead behaves as if there was no @defer directive.\n if (!args || args.if !== false) {\n deferred = true;\n }\n // TODO In the future, we may want to record args.label using\n // context.deferred, if a label is specified.\n }\n });\n }\n if (isField(selection)) {\n var existing = fieldMap.get(selection);\n if (existing) {\n // If this field has been visited along another recursive path\n // before, the final context should have clientOnly or deferred set\n // to true only if *all* paths have the directive (hence the &&).\n clientOnly = clientOnly && existing.clientOnly;\n deferred = deferred && existing.deferred;\n }\n fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));\n }\n else {\n var fragment = getFragmentFromSelection(selection, context.lookupFragment);\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(13, selection.name.value);\n }\n if (fragment &&\n policies.fragmentMatches(fragment, typename, result, context.variables)) {\n flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));\n }\n }\n });\n })(selectionSet, context);\n return fieldMap;\n };\n StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {\n var _a;\n var _this = this;\n if (mergeTree.map.size && !isReference(incoming)) {\n var e_1 = \n // Items in the same position in different arrays are not\n // necessarily related to each other, so when incoming is an array\n // we process its elements as if there was no existing data.\n (!isArray(incoming) &&\n // Likewise, existing must be either a Reference or a StoreObject\n // in order for its fields to be safe to merge with the fields of\n // the incoming object.\n (isReference(existing) || storeValueIsStoreObject(existing))) ?\n existing\n : void 0;\n // This narrowing is implied by mergeTree.map.size > 0 and\n // !isReference(incoming), though TypeScript understandably cannot\n // hope to infer this type.\n var i_1 = incoming;\n // The options.storage objects provided to read and merge functions\n // are derived from the identity of the parent object plus a\n // sequence of storeFieldName strings/numbers identifying the nested\n // field name path of each field value to be merged.\n if (e_1 && !getStorageArgs) {\n getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];\n }\n // It's possible that applying merge functions to this subtree will\n // not change the incoming data, so this variable tracks the fields\n // that did change, so we can create a new incoming object when (and\n // only when) at least one incoming field has changed. We use a Map\n // to preserve the type of numeric keys.\n var changedFields_1;\n var getValue_1 = function (from, name) {\n return (isArray(from) ?\n typeof name === \"number\" ?\n from[name]\n : void 0\n : context.store.getFieldValue(from, String(name)));\n };\n mergeTree.map.forEach(function (childTree, storeFieldName) {\n var eVal = getValue_1(e_1, storeFieldName);\n var iVal = getValue_1(i_1, storeFieldName);\n // If we have no incoming data, leave any existing data untouched.\n if (void 0 === iVal)\n return;\n if (getStorageArgs) {\n getStorageArgs.push(storeFieldName);\n }\n var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);\n if (aVal !== iVal) {\n changedFields_1 = changedFields_1 || new Map();\n changedFields_1.set(storeFieldName, aVal);\n }\n if (getStorageArgs) {\n invariant(getStorageArgs.pop() === storeFieldName);\n }\n });\n if (changedFields_1) {\n // Shallow clone i so we can add changed fields to it.\n incoming = (isArray(i_1) ? i_1.slice(0) : __assign({}, i_1));\n changedFields_1.forEach(function (value, name) {\n incoming[name] = value;\n });\n }\n }\n if (mergeTree.info) {\n return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));\n }\n return incoming;\n };\n return StoreWriter;\n}());\nexport { StoreWriter };\nvar emptyMergeTreePool = [];\nfunction getChildMergeTree(_a, name) {\n var map = _a.map;\n if (!map.has(name)) {\n map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n }\n return map.get(name);\n}\nfunction mergeMergeTrees(left, right) {\n if (left === right || !right || mergeTreeIsEmpty(right))\n return left;\n if (!left || mergeTreeIsEmpty(left))\n return right;\n var info = left.info && right.info ? __assign(__assign({}, left.info), right.info) : left.info || right.info;\n var needToMergeMaps = left.map.size && right.map.size;\n var map = needToMergeMaps ? new Map()\n : left.map.size ? left.map\n : right.map;\n var merged = { info: info, map: map };\n if (needToMergeMaps) {\n var remainingRightKeys_1 = new Set(right.map.keys());\n left.map.forEach(function (leftTree, key) {\n merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n remainingRightKeys_1.delete(key);\n });\n remainingRightKeys_1.forEach(function (key) {\n merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));\n });\n }\n return merged;\n}\nfunction mergeTreeIsEmpty(tree) {\n return !tree || !(tree.info || tree.map.size);\n}\nfunction maybeRecycleChildMergeTree(_a, name) {\n var map = _a.map;\n var childTree = map.get(name);\n if (childTree && mergeTreeIsEmpty(childTree)) {\n emptyMergeTreePool.push(childTree);\n map.delete(name);\n }\n}\nvar warnings = new Set();\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {\n var getChild = function (objOrRef) {\n var child = store.getFieldValue(objOrRef, storeFieldName);\n return typeof child === \"object\" && child;\n };\n var existing = getChild(existingRef);\n if (!existing)\n return;\n var incoming = getChild(incomingObj);\n if (!incoming)\n return;\n // It's always safe to replace a reference, since it refers to data\n // safely stored elsewhere.\n if (isReference(existing))\n return;\n // If the values are structurally equivalent, we do not need to worry\n // about incoming replacing existing.\n if (equal(existing, incoming))\n return;\n // If we're replacing every key of the existing object, then the\n // existing data would be overwritten even if the objects were\n // normalized, so warning would not be helpful here.\n if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {\n return;\n }\n var parentType = store.getFieldValue(existingRef, \"__typename\") ||\n store.getFieldValue(incomingObj, \"__typename\");\n var fieldName = fieldNameFromStoreName(storeFieldName);\n var typeDotName = \"\".concat(parentType, \".\").concat(fieldName);\n // Avoid warning more than once for the same type and field name.\n if (warnings.has(typeDotName))\n return;\n warnings.add(typeDotName);\n var childTypenames = [];\n // Arrays do not have __typename fields, and always need a custom merge\n // function, even if their elements are normalized entities.\n if (!isArray(existing) && !isArray(incoming)) {\n [existing, incoming].forEach(function (child) {\n var typename = store.getFieldValue(child, \"__typename\");\n if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n childTypenames.push(typename);\n }\n });\n }\n globalThis.__DEV__ !== false && invariant.warn(14, fieldName, parentType, childTypenames.length ?\n \"either ensure all objects of type \" +\n childTypenames.join(\" and \") +\n \" have an ID or a custom merge function, or \"\n : \"\", typeDotName, __assign({}, existing), __assign({}, incoming));\n}\n//# sourceMappingURL=writeToStore.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n// Make builtins like Map and Set safe to use with non-extensible objects.\nimport \"./fixPolyfills.js\";\nimport { wrap } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { ApolloCache } from \"../core/cache.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { addTypenameToDocument, isReference, DocumentTransform, canonicalStringify, print, cacheSizes, } from \"../../utilities/index.js\";\nimport { StoreReader } from \"./readFromStore.js\";\nimport { StoreWriter } from \"./writeToStore.js\";\nimport { EntityStore, supportsResultCaching } from \"./entityStore.js\";\nimport { makeVar, forgetCache, recallCache } from \"./reactiveVars.js\";\nimport { Policies } from \"./policies.js\";\nimport { hasOwn, normalizeConfig, shouldCanonizeResults } from \"./helpers.js\";\nimport { getInMemoryCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nvar InMemoryCache = /** @class */ (function (_super) {\n __extends(InMemoryCache, _super);\n function InMemoryCache(config) {\n if (config === void 0) { config = {}; }\n var _this = _super.call(this) || this;\n _this.watches = new Set();\n _this.addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n // Override the default value, since InMemoryCache result objects are frozen\n // in development and expected to remain logically immutable in production.\n _this.assumeImmutableResults = true;\n _this.makeVar = makeVar;\n _this.txCount = 0;\n _this.config = normalizeConfig(config);\n _this.addTypename = !!_this.config.addTypename;\n _this.policies = new Policies({\n cache: _this,\n dataIdFromObject: _this.config.dataIdFromObject,\n possibleTypes: _this.config.possibleTypes,\n typePolicies: _this.config.typePolicies,\n });\n _this.init();\n return _this;\n }\n InMemoryCache.prototype.init = function () {\n // Passing { resultCaching: false } in the InMemoryCache constructor options\n // will completely disable dependency tracking, which will improve memory\n // usage but worsen the performance of repeated reads.\n var rootStore = (this.data = new EntityStore.Root({\n policies: this.policies,\n resultCaching: this.config.resultCaching,\n }));\n // When no optimistic writes are currently active, cache.optimisticData ===\n // cache.data, so there are no additional layers on top of the actual data.\n // When an optimistic update happens, this.optimisticData will become a\n // linked list of EntityStore Layer objects that terminates with the\n // original this.data cache object.\n this.optimisticData = rootStore.stump;\n this.resetResultCache();\n };\n InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {\n var _this = this;\n var previousReader = this.storeReader;\n var fragments = this.config.fragments;\n // The StoreWriter is mostly stateless and so doesn't really need to be\n // reset, but it does need to have its writer.storeReader reference updated,\n // so it's simpler to update this.storeWriter as well.\n this.storeWriter = new StoreWriter(this, (this.storeReader = new StoreReader({\n cache: this,\n addTypename: this.addTypename,\n resultCacheMaxSize: this.config.resultCacheMaxSize,\n canonizeResults: shouldCanonizeResults(this.config),\n canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),\n fragments: fragments,\n })), fragments);\n this.maybeBroadcastWatch = wrap(function (c, options) {\n return _this.broadcastWatch(c, options);\n }, {\n max: this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n 5000 /* defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] */,\n makeCacheKey: function (c) {\n // Return a cache key (thus enabling result caching) only if we're\n // currently using a data store that can track cache dependencies.\n var store = c.optimistic ? _this.optimisticData : _this.data;\n if (supportsResultCaching(store)) {\n var optimistic = c.optimistic, id = c.id, variables = c.variables;\n return store.makeCacheKey(c.query, \n // Different watches can have the same query, optimistic\n // status, rootId, and variables, but if their callbacks are\n // different, the (identical) result needs to be delivered to\n // each distinct callback. The easiest way to achieve that\n // separation is to include c.callback in the cache key for\n // maybeBroadcastWatch calls. See issue #5733.\n c.callback, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));\n }\n },\n });\n // Since we have thrown away all the cached functions that depend on the\n // CacheGroup dependencies maintained by EntityStore, we should also reset\n // all CacheGroup dependency information.\n new Set([this.data.group, this.optimisticData.group]).forEach(function (group) {\n return group.resetCaching();\n });\n };\n InMemoryCache.prototype.restore = function (data) {\n this.init();\n // Since calling this.init() discards/replaces the entire StoreReader, along\n // with the result caches it maintains, this.data.replace(data) won't have\n // to bother deleting the old data.\n if (data)\n this.data.replace(data);\n return this;\n };\n InMemoryCache.prototype.extract = function (optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return (optimistic ? this.optimisticData : this.data).extract();\n };\n InMemoryCache.prototype.read = function (options) {\n var \n // Since read returns data or null, without any additional metadata\n // about whether/where there might have been missing fields, the\n // default behavior cannot be returnPartialData = true (like it is\n // for the diff method), since defaulting to true would violate the\n // integrity of the T in the return type. However, partial data may\n // be useful in some cases, so returnPartialData:true may be\n // specified explicitly.\n _a = options.returnPartialData, \n // Since read returns data or null, without any additional metadata\n // about whether/where there might have been missing fields, the\n // default behavior cannot be returnPartialData = true (like it is\n // for the diff method), since defaulting to true would violate the\n // integrity of the T in the return type. However, partial data may\n // be useful in some cases, so returnPartialData:true may be\n // specified explicitly.\n returnPartialData = _a === void 0 ? false : _a;\n try {\n return (this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null);\n }\n catch (e) {\n if (e instanceof MissingFieldError) {\n // Swallow MissingFieldError and return null, so callers do not need to\n // worry about catching \"normal\" exceptions resulting from incomplete\n // cache data. Unexpected errors will be re-thrown. If you need more\n // information about which fields were missing, use cache.diff instead,\n // and examine diffResult.missing.\n return null;\n }\n throw e;\n }\n };\n InMemoryCache.prototype.write = function (options) {\n try {\n ++this.txCount;\n return this.storeWriter.writeToStore(this.data, options);\n }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.modify = function (options) {\n if (hasOwn.call(options, \"id\") && !options.id) {\n // To my knowledge, TypeScript does not currently provide a way to\n // enforce that an optional property?:type must *not* be undefined\n // when present. That ability would be useful here, because we want\n // options.id to default to ROOT_QUERY only when no options.id was\n // provided. If the caller attempts to pass options.id with a\n // falsy/undefined value (perhaps because cache.identify failed), we\n // should not assume the goal was to modify the ROOT_QUERY object.\n // We could throw, but it seems natural to return false to indicate\n // that nothing was modified.\n return false;\n }\n var store = ((options.optimistic) // Defaults to false.\n ) ?\n this.optimisticData\n : this.data;\n try {\n ++this.txCount;\n return store.modify(options.id || \"ROOT_QUERY\", options.fields);\n }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.diff = function (options) {\n return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || \"ROOT_QUERY\", config: this.config }));\n };\n InMemoryCache.prototype.watch = function (watch) {\n var _this = this;\n if (!this.watches.size) {\n // In case we previously called forgetCache(this) because\n // this.watches became empty (see below), reattach this cache to any\n // reactive variables on which it previously depended. It might seem\n // paradoxical that we're able to recall something we supposedly\n // forgot, but the point of calling forgetCache(this) is to silence\n // useless broadcasts while this.watches is empty, and to allow the\n // cache to be garbage collected. If, however, we manage to call\n // recallCache(this) here, this cache object must not have been\n // garbage collected yet, and should resume receiving updates from\n // reactive variables, now that it has a watcher to notify.\n recallCache(this);\n }\n this.watches.add(watch);\n if (watch.immediate) {\n this.maybeBroadcastWatch(watch);\n }\n return function () {\n // Once we remove the last watch from this.watches, cache.broadcastWatches\n // no longer does anything, so we preemptively tell the reactive variable\n // system to exclude this cache from future broadcasts.\n if (_this.watches.delete(watch) && !_this.watches.size) {\n forgetCache(_this);\n }\n // Remove this watch from the LRU cache managed by the\n // maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory\n // leaks involving the closure of watch.callback.\n _this.maybeBroadcastWatch.forget(watch);\n };\n };\n InMemoryCache.prototype.gc = function (options) {\n var _a;\n canonicalStringify.reset();\n print.reset();\n this.addTypenameTransform.resetCache();\n (_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();\n var ids = this.optimisticData.gc();\n if (options && !this.txCount) {\n if (options.resetResultCache) {\n this.resetResultCache(options.resetResultIdentities);\n }\n else if (options.resetResultIdentities) {\n this.storeReader.resetCanon();\n }\n }\n return ids;\n };\n // Call this method to ensure the given root ID remains in the cache after\n // garbage collection, along with its transitive child entities. Note that\n // the cache automatically retains all directly written entities. By default,\n // the retainment persists after optimistic updates are removed. Pass true\n // for the optimistic argument if you would prefer for the retainment to be\n // discarded when the top-most optimistic layer is removed. Returns the\n // resulting (non-negative) retainment count.\n InMemoryCache.prototype.retain = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).retain(rootId);\n };\n // Call this method to undo the effect of the retain method, above. Once the\n // retainment count falls to zero, the given ID will no longer be preserved\n // during garbage collection, though it may still be preserved by other safe\n // entities that refer to it. Returns the resulting (non-negative) retainment\n // count, in case that's useful.\n InMemoryCache.prototype.release = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).release(rootId);\n };\n // Returns the canonical ID for a given StoreObject, obeying typePolicies\n // and keyFields (and dataIdFromObject, if you still use that). At minimum,\n // the object must contain a __typename and any primary key fields required\n // to identify entities of that type. If you pass a query result object, be\n // sure that none of the primary key fields have been renamed by aliasing.\n // If you pass a Reference object, its __ref ID string will be returned.\n InMemoryCache.prototype.identify = function (object) {\n if (isReference(object))\n return object.__ref;\n try {\n return this.policies.identify(object)[0];\n }\n catch (e) {\n globalThis.__DEV__ !== false && invariant.warn(e);\n }\n };\n InMemoryCache.prototype.evict = function (options) {\n if (!options.id) {\n if (hasOwn.call(options, \"id\")) {\n // See comment in modify method about why we return false when\n // options.id exists but is falsy/undefined.\n return false;\n }\n options = __assign(__assign({}, options), { id: \"ROOT_QUERY\" });\n }\n try {\n // It's unlikely that the eviction will end up invoking any other\n // cache update operations while it's running, but {in,de}crementing\n // this.txCount still seems like a good idea, for uniformity with\n // the other update methods.\n ++this.txCount;\n // Pass this.data as a limit on the depth of the eviction, so evictions\n // during optimistic updates (when this.data is temporarily set equal to\n // this.optimisticData) do not escape their optimistic Layer.\n return this.optimisticData.evict(options, this.data);\n }\n finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n };\n InMemoryCache.prototype.reset = function (options) {\n var _this = this;\n this.init();\n canonicalStringify.reset();\n if (options && options.discardWatches) {\n // Similar to what happens in the unsubscribe function returned by\n // cache.watch, applied to all current watches.\n this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });\n this.watches.clear();\n forgetCache(this);\n }\n else {\n // Calling this.init() above unblocks all maybeBroadcastWatch caching, so\n // this.broadcastWatches() triggers a broadcast to every current watcher\n // (letting them know their data is now missing). This default behavior is\n // convenient because it means the watches do not have to be manually\n // reestablished after resetting the cache. To prevent this broadcast and\n // cancel all watches, pass true for options.discardWatches.\n this.broadcastWatches();\n }\n return Promise.resolve();\n };\n InMemoryCache.prototype.removeOptimistic = function (idToRemove) {\n var newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n if (newOptimisticData !== this.optimisticData) {\n this.optimisticData = newOptimisticData;\n this.broadcastWatches();\n }\n };\n InMemoryCache.prototype.batch = function (options) {\n var _this = this;\n var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;\n var updateResult;\n var perform = function (layer) {\n var _a = _this, data = _a.data, optimisticData = _a.optimisticData;\n ++_this.txCount;\n if (layer) {\n _this.data = _this.optimisticData = layer;\n }\n try {\n return (updateResult = update(_this));\n }\n finally {\n --_this.txCount;\n _this.data = data;\n _this.optimisticData = optimisticData;\n }\n };\n var alreadyDirty = new Set();\n if (onWatchUpdated && !this.txCount) {\n // If an options.onWatchUpdated callback is provided, we want to call it\n // with only the Cache.WatchOptions objects affected by options.update,\n // but there might be dirty watchers already waiting to be broadcast that\n // have nothing to do with the update. To prevent including those watchers\n // in the post-update broadcast, we perform this initial broadcast to\n // collect the dirty watchers, so we can re-dirty them later, after the\n // post-update broadcast, allowing them to receive their pending\n // broadcasts the next time broadcastWatches is called, just as they would\n // if we never called cache.batch.\n this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch) {\n alreadyDirty.add(watch);\n return false;\n } }));\n }\n if (typeof optimistic === \"string\") {\n // Note that there can be multiple layers with the same optimistic ID.\n // When removeOptimistic(id) is called for that id, all matching layers\n // will be removed, and the remaining layers will be reapplied.\n this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n }\n else if (optimistic === false) {\n // Ensure both this.data and this.optimisticData refer to the root\n // (non-optimistic) layer of the cache during the update. Note that\n // this.data could be a Layer if we are currently executing an optimistic\n // update function, but otherwise will always be an EntityStore.Root\n // instance.\n perform(this.data);\n }\n else {\n // Otherwise, leave this.data and this.optimisticData unchanged and run\n // the update with broadcast batching.\n perform();\n }\n if (typeof removeOptimistic === \"string\") {\n this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n }\n // Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code\n // takes the else branch and calls this.broadcastWatches(options), which\n // does nothing when this.txCount > 0.\n if (onWatchUpdated && alreadyDirty.size) {\n this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch, diff) {\n var result = onWatchUpdated.call(this, watch, diff);\n if (result !== false) {\n // Since onWatchUpdated did not return false, this diff is\n // about to be broadcast to watch.callback, so we don't need\n // to re-dirty it with the other alreadyDirty watches below.\n alreadyDirty.delete(watch);\n }\n return result;\n } }));\n // Silently re-dirty any watches that were already dirty before the update\n // was performed, and were not broadcast just now.\n if (alreadyDirty.size) {\n alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });\n }\n }\n else {\n // If alreadyDirty is empty or we don't have an onWatchUpdated\n // function, we don't need to go to the trouble of wrapping\n // options.onWatchUpdated.\n this.broadcastWatches(options);\n }\n return updateResult;\n };\n InMemoryCache.prototype.performTransaction = function (update, optimisticId) {\n return this.batch({\n update: update,\n optimistic: optimisticId || optimisticId !== null,\n });\n };\n InMemoryCache.prototype.transformDocument = function (document) {\n return this.addTypenameToDocument(this.addFragmentsToDocument(document));\n };\n InMemoryCache.prototype.broadcastWatches = function (options) {\n var _this = this;\n if (!this.txCount) {\n this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });\n }\n };\n InMemoryCache.prototype.addFragmentsToDocument = function (document) {\n var fragments = this.config.fragments;\n return fragments ? fragments.transform(document) : document;\n };\n InMemoryCache.prototype.addTypenameToDocument = function (document) {\n if (this.addTypename) {\n return this.addTypenameTransform.transformDocument(document);\n }\n return document;\n };\n // This method is wrapped by maybeBroadcastWatch, which is called by\n // broadcastWatches, so that we compute and broadcast results only when\n // the data that would be broadcast might have changed. It would be\n // simpler to check for changes after recomputing a result but before\n // broadcasting it, but this wrapping approach allows us to skip both\n // the recomputation and the broadcast, in most cases.\n InMemoryCache.prototype.broadcastWatch = function (c, options) {\n var lastDiff = c.lastDiff;\n // Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions\n // currently requires no additional properties, so we can use c (a\n // WatchOptions object) as DiffOptions, without having to allocate a new\n // object, and without having to enumerate the relevant properties (query,\n // variables, etc.) explicitly. There will be some additional properties\n // (lastDiff, callback, etc.), but cache.diff ignores them.\n var diff = this.diff(c);\n if (options) {\n if (c.optimistic && typeof options.optimistic === \"string\") {\n diff.fromOptimisticTransaction = true;\n }\n if (options.onWatchUpdated &&\n options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {\n // Returning false from the onWatchUpdated callback will prevent\n // calling c.callback(diff) for this watcher.\n return;\n }\n }\n if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n c.callback((c.lastDiff = diff), lastDiff);\n }\n };\n return InMemoryCache;\n}(ApolloCache));\nexport { InMemoryCache };\nif (globalThis.__DEV__ !== false) {\n InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n//# sourceMappingURL=inMemoryCache.js.map","import { dep, Slot } from \"optimism\";\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport var cacheSlot = new Slot();\nvar cacheInfoMap = new WeakMap();\nfunction getCacheInfo(cache) {\n var info = cacheInfoMap.get(cache);\n if (!info) {\n cacheInfoMap.set(cache, (info = {\n vars: new Set(),\n dep: dep(),\n }));\n }\n return info;\n}\nexport function forgetCache(cache) {\n getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });\n}\n// Calling forgetCache(cache) serves to silence broadcasts and allows the\n// cache to be garbage collected. However, the varsByCache WeakMap\n// preserves the set of reactive variables that were previously associated\n// with this cache, which makes it possible to \"recall\" the cache at a\n// later time, by reattaching it to those variables. If the cache has been\n// garbage collected in the meantime, because it is no longer reachable,\n// you won't be able to call recallCache(cache), and the cache will\n// automatically disappear from the varsByCache WeakMap.\nexport function recallCache(cache) {\n getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });\n}\nexport function makeVar(value) {\n var caches = new Set();\n var listeners = new Set();\n var rv = function (newValue) {\n if (arguments.length > 0) {\n if (value !== newValue) {\n value = newValue;\n caches.forEach(function (cache) {\n // Invalidate any fields with custom read functions that\n // consumed this variable, so query results involving those\n // fields will be recomputed the next time we read them.\n getCacheInfo(cache).dep.dirty(rv);\n // Broadcast changes to any caches that have previously read\n // from this variable.\n broadcast(cache);\n });\n // Finally, notify any listeners added via rv.onNextChange.\n var oldListeners = Array.from(listeners);\n listeners.clear();\n oldListeners.forEach(function (listener) { return listener(value); });\n }\n }\n else {\n // When reading from the variable, obtain the current cache from\n // context via cacheSlot. This isn't entirely foolproof, but it's\n // the same system that powers varDep.\n var cache = cacheSlot.getValue();\n if (cache) {\n attach(cache);\n getCacheInfo(cache).dep(rv);\n }\n }\n return value;\n };\n rv.onNextChange = function (listener) {\n listeners.add(listener);\n return function () {\n listeners.delete(listener);\n };\n };\n var attach = (rv.attachCache = function (cache) {\n caches.add(cache);\n getCacheInfo(cache).vars.add(rv);\n return rv;\n });\n rv.forgetCache = function (cache) { return caches.delete(cache); };\n return rv;\n}\nfunction broadcast(cache) {\n if (cache.broadcastWatches) {\n cache.broadcastWatches();\n }\n}\n//# sourceMappingURL=reactiveVars.js.map","import { __assign, __rest } from \"tslib\";\nimport { wrap } from \"optimism\";\nimport { Observable, cacheSizes, getFragmentQueryDocument, mergeDeepArray, } from \"../../utilities/index.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { getApolloCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nimport { equalByQuery } from \"../../core/equalByQuery.js\";\nvar ApolloCache = /** @class */ (function () {\n function ApolloCache() {\n this.assumeImmutableResults = false;\n // Make sure we compute the same (===) fragment query document every\n // time we receive the same fragment in readFragment.\n this.getFragmentDoc = wrap(getFragmentQueryDocument, {\n max: cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n 1000 /* defaultCacheSizes[\"cache.fragmentQueryDocuments\"] */,\n cache: WeakCache,\n });\n }\n // Transactional API\n // The batch method is intended to replace/subsume both performTransaction\n // and recordOptimisticTransaction, but performTransaction came first, so we\n // provide a default batch implementation that's just another way of calling\n // performTransaction. Subclasses of ApolloCache (such as InMemoryCache) can\n // override the batch method to do more interesting things with its options.\n ApolloCache.prototype.batch = function (options) {\n var _this = this;\n var optimisticId = typeof options.optimistic === \"string\" ? options.optimistic\n : options.optimistic === false ? null\n : void 0;\n var updateResult;\n this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);\n return updateResult;\n };\n ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {\n this.performTransaction(transaction, optimisticId);\n };\n // Optional API\n // Called once per input document, allowing the cache to make static changes\n // to the query, such as adding __typename fields.\n ApolloCache.prototype.transformDocument = function (document) {\n return document;\n };\n // Called before each ApolloLink request, allowing the cache to make dynamic\n // changes to the query, such as filling in missing fragment definitions.\n ApolloCache.prototype.transformForLink = function (document) {\n return document;\n };\n ApolloCache.prototype.identify = function (object) {\n return;\n };\n ApolloCache.prototype.gc = function () {\n return [];\n };\n ApolloCache.prototype.modify = function (options) {\n return false;\n };\n // DataProxy API\n ApolloCache.prototype.readQuery = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = !!options.optimistic; }\n return this.read(__assign(__assign({}, options), { rootId: options.id || \"ROOT_QUERY\", optimistic: optimistic }));\n };\n /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n ApolloCache.prototype.watchFragment = function (options) {\n var _this = this;\n var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, otherOptions = __rest(options, [\"fragment\", \"fragmentName\", \"from\", \"optimistic\"]);\n var query = this.getFragmentDoc(fragment, fragmentName);\n var diffOptions = __assign(__assign({}, otherOptions), { returnPartialData: true, id: \n // While our TypeScript types do not allow for `undefined` as a valid\n // `from`, its possible `useFragment` gives us an `undefined` since it\n // calls` cache.identify` and provides that value to `from`. We are\n // adding this fix here however to ensure those using plain JavaScript\n // and using `cache.identify` themselves will avoid seeing the obscure\n // warning.\n typeof from === \"undefined\" || typeof from === \"string\" ?\n from\n : this.identify(from), query: query, optimistic: optimistic });\n var latestDiff;\n return new Observable(function (observer) {\n return _this.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {\n if (\n // Always ensure we deliver the first result\n latestDiff &&\n equalByQuery(query, { data: latestDiff === null || latestDiff === void 0 ? void 0 : latestDiff.result }, { data: diff.result })) {\n return;\n }\n var result = {\n data: diff.result,\n complete: !!diff.complete,\n };\n if (diff.missing) {\n result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));\n }\n latestDiff = diff;\n observer.next(result);\n } }));\n });\n };\n ApolloCache.prototype.readFragment = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = !!options.optimistic; }\n return this.read(__assign(__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));\n };\n ApolloCache.prototype.writeQuery = function (_a) {\n var id = _a.id, data = _a.data, options = __rest(_a, [\"id\", \"data\"]);\n return this.write(Object.assign(options, {\n dataId: id || \"ROOT_QUERY\",\n result: data,\n }));\n };\n ApolloCache.prototype.writeFragment = function (_a) {\n var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = __rest(_a, [\"id\", \"data\", \"fragment\", \"fragmentName\"]);\n return this.write(Object.assign(options, {\n query: this.getFragmentDoc(fragment, fragmentName),\n dataId: id,\n result: data,\n }));\n };\n ApolloCache.prototype.updateQuery = function (options, update) {\n return this.batch({\n update: function (cache) {\n var value = cache.readQuery(options);\n var data = update(value);\n if (data === void 0 || data === null)\n return value;\n cache.writeQuery(__assign(__assign({}, options), { data: data }));\n return data;\n },\n });\n };\n ApolloCache.prototype.updateFragment = function (options, update) {\n return this.batch({\n update: function (cache) {\n var value = cache.readFragment(options);\n var data = update(value);\n if (data === void 0 || data === null)\n return value;\n cache.writeFragment(__assign(__assign({}, options), { data: data }));\n return data;\n },\n });\n };\n return ApolloCache;\n}());\nexport { ApolloCache };\nif (globalThis.__DEV__ !== false) {\n ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n//# sourceMappingURL=cache.js.map","import { isReference, isField, DeepMerger, resultKeyNameFromField, shouldInclude, isNonNullObject, compact, createFragmentMap, getFragmentDefinitions, isArray, } from \"../../utilities/index.js\";\nexport var hasOwn = Object.prototype.hasOwnProperty;\nexport function isNullish(value) {\n return value === null || value === void 0;\n}\nexport { isArray };\nexport function defaultDataIdFromObject(_a, context) {\n var __typename = _a.__typename, id = _a.id, _id = _a._id;\n if (typeof __typename === \"string\") {\n if (context) {\n context.keyObject =\n !isNullish(id) ? { id: id }\n : !isNullish(_id) ? { _id: _id }\n : void 0;\n }\n // If there is no object.id, fall back to object._id.\n if (isNullish(id) && !isNullish(_id)) {\n id = _id;\n }\n if (!isNullish(id)) {\n return \"\".concat(__typename, \":\").concat(typeof id === \"number\" || typeof id === \"string\" ?\n id\n : JSON.stringify(id));\n }\n }\n}\nvar defaultConfig = {\n dataIdFromObject: defaultDataIdFromObject,\n addTypename: true,\n resultCaching: true,\n // Thanks to the shouldCanonizeResults helper, this should be the only line\n // you have to change to reenable canonization by default in the future.\n canonizeResults: false,\n};\nexport function normalizeConfig(config) {\n return compact(defaultConfig, config);\n}\nexport function shouldCanonizeResults(config) {\n var value = config.canonizeResults;\n return value === void 0 ? defaultConfig.canonizeResults : value;\n}\nexport function getTypenameFromStoreObject(store, objectOrReference) {\n return isReference(objectOrReference) ?\n store.get(objectOrReference.__ref, \"__typename\")\n : objectOrReference && objectOrReference.__typename;\n}\nexport var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\nexport function fieldNameFromStoreName(storeFieldName) {\n var match = storeFieldName.match(TypeOrFieldNameRegExp);\n return match ? match[0] : storeFieldName;\n}\nexport function selectionSetMatchesResult(selectionSet, result, variables) {\n if (isNonNullObject(result)) {\n return isArray(result) ?\n result.every(function (item) {\n return selectionSetMatchesResult(selectionSet, item, variables);\n })\n : selectionSet.selections.every(function (field) {\n if (isField(field) && shouldInclude(field, variables)) {\n var key = resultKeyNameFromField(field);\n return (hasOwn.call(result, key) &&\n (!field.selectionSet ||\n selectionSetMatchesResult(field.selectionSet, result[key], variables)));\n }\n // If the selection has been skipped with @skip(true) or\n // @include(false), it should not count against the matching. If\n // the selection is not a field, it must be a fragment (inline or\n // named). We will determine if selectionSetMatchesResult for that\n // fragment when we get to it, so for now we return true.\n return true;\n });\n }\n return false;\n}\nexport function storeValueIsStoreObject(value) {\n return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\nexport function makeProcessedFieldsMerger() {\n return new DeepMerger();\n}\nexport function extractFragmentContext(document, fragments) {\n // FragmentMap consisting only of fragments defined directly in document, not\n // including other fragments registered in the FragmentRegistry.\n var fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n return {\n fragmentMap: fragmentMap,\n lookupFragment: function (name) {\n var def = fragmentMap[name];\n if (!def && fragments) {\n def = fragments.lookup(name);\n }\n return def || null;\n },\n };\n}\n//# sourceMappingURL=helpers.js.map"],"sourceRoot":""}