653 kBSource Map (JSON)View Raw
1{"version":3,"file":"apollo-client.cjs","sources":["utilities/globals/maybe.js","utilities/graphql/directives.js","utilities/graphql/fragments.js","utilities/common/objects.js","utilities/graphql/storeUtils.js","utilities/graphql/getFromAST.js","utilities/common/arrays.js","utilities/graphql/transform.js","utilities/common/mergeDeep.js","utilities/common/cloneDeep.js","utilities/common/maybeDeepFreeze.js","utilities/observables/iteration.js","utilities/observables/asyncMap.js","utilities/common/canUse.js","utilities/observables/subclassing.js","utilities/observables/Concast.js","utilities/common/incrementalResult.js","utilities/common/errorHandling.js","utilities/common/compact.js","utilities/common/makeUniqueId.js","utilities/common/stringifyForDisplay.js","utilities/common/mergeOptions.js","link/utils/fromError.js","link/utils/toPromise.js","link/utils/fromPromise.js","link/utils/throwServerError.js","link/utils/validateOperation.js","link/utils/createOperation.js","link/utils/transformOperation.js","link/core/ApolloLink.js","link/core/empty.js","link/core/from.js","link/core/split.js","link/core/concat.js","link/core/execute.js","version.js","utilities/common/responseIterator.js","link/http/iterators/async.js","link/http/iterators/nodeStream.js","link/http/iterators/promise.js","link/http/iterators/reader.js","link/http/responseIterator.js","link/http/parseAndCheckHttpResponse.js","link/http/serializeFetchParameter.js","link/http/selectHttpOptionsAndBody.js","link/http/checkFetcher.js","link/http/createSignalIfSupported.js","link/http/selectURI.js","link/http/rewriteURIForGET.js","link/http/createHttpLink.js","link/http/HttpLink.js","cache/core/cache.js","cache/core/types/Cache.js","cache/core/types/common.js","cache/inmemory/helpers.js","cache/inmemory/entityStore.js","cache/inmemory/object-canon.js","cache/inmemory/readFromStore.js","cache/inmemory/reactiveVars.js","cache/inmemory/key-extractor.js","cache/inmemory/policies.js","cache/inmemory/writeToStore.js","cache/inmemory/inMemoryCache.js","errors/index.js","core/networkStatus.js","core/ObservableQuery.js","core/LocalState.js","core/QueryInfo.js","core/QueryManager.js","core/ApolloClient.js","react/context/ApolloContext.js","react/context/ApolloConsumer.js","react/context/ApolloProvider.js","react/hooks/useApolloClient.js","react/hooks/useSyncExternalStore.js","react/parser/index.js","react/hooks/useQuery.js","react/hooks/useLazyQuery.js","react/hooks/useMutation.js","react/hooks/useSubscription.js","react/hooks/useReactiveVar.js","react/hooks/useFragment.js"],"sourcesContent":["export function maybe(thunk) {\n try {\n return thunk();\n }\n catch (_a) { }\n}\n//# sourceMappingURL=maybe.js.map","import { invariant } from '../globals';\nimport { visit, BREAK, } from 'graphql';\nexport function shouldInclude(_a, variables) {\n var directives = _a.directives;\n if (!directives || !directives.length) {\n return true;\n }\n return getInclusionDirectives(directives).every(function (_a) {\n var directive = _a.directive, ifArgument = _a.ifArgument;\n var evaledValue = false;\n if (ifArgument.value.kind === 'Variable') {\n evaledValue = variables && variables[ifArgument.value.name.value];\n __DEV__ ? invariant(evaledValue !== void 0, \"Invalid variable referenced in @\".concat(directive.name.value, \" directive.\")) : invariant(evaledValue !== void 0, 40);\n }\n else {\n evaledValue = ifArgument.value.value;\n }\n return directive.name.value === 'skip' ? !evaledValue : evaledValue;\n });\n}\nexport function getDirectiveNames(root) {\n var names = [];\n visit(root, {\n Directive: function (node) {\n names.push(node.name.value);\n },\n });\n return names;\n}\nexport var hasAnyDirectives = function (names, root) { return hasDirectives(names, root, false); };\nexport var hasAllDirectives = function (names, root) { return hasDirectives(names, root, true); };\nexport function hasDirectives(names, root, all) {\n var nameSet = new Set(names);\n var uniqueCount = nameSet.size;\n visit(root, {\n Directive: function (node) {\n if (nameSet.delete(node.name.value) &&\n (!all || !nameSet.size)) {\n return BREAK;\n }\n },\n });\n return all ? !nameSet.size : nameSet.size < uniqueCount;\n}\nexport function hasClientExports(document) {\n return document && hasDirectives(['client', 'export'], document, true);\n}\nfunction isInclusionDirective(_a) {\n var value = _a.name.value;\n return value === 'skip' || value === 'include';\n}\nexport function getInclusionDirectives(directives) {\n var result = [];\n if (directives && directives.length) {\n directives.forEach(function (directive) {\n if (!isInclusionDirective(directive))\n return;\n var directiveArguments = directive.arguments;\n var directiveName = directive.name.value;\n __DEV__ ? invariant(directiveArguments && directiveArguments.length === 1, \"Incorrect number of arguments for the @\".concat(directiveName, \" directive.\")) : invariant(directiveArguments && directiveArguments.length === 1, 41);\n var ifArgument = directiveArguments[0];\n __DEV__ ? invariant(ifArgument.name && ifArgument.name.value === 'if', \"Invalid argument for the @\".concat(directiveName, \" directive.\")) : invariant(ifArgument.name && ifArgument.name.value === 'if', 42);\n var ifValue = ifArgument.value;\n __DEV__ ? invariant(ifValue &&\n (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), \"Argument for the @\".concat(directiveName, \" directive must be a variable or a boolean value.\")) : invariant(ifValue &&\n (ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), 43);\n result.push({ directive: directive, ifArgument: ifArgument });\n });\n }\n return result;\n}\n//# sourceMappingURL=directives.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { invariant, InvariantError } from '../globals';\nexport function getFragmentQueryDocument(document, fragmentName) {\n var actualFragmentName = fragmentName;\n var fragments = [];\n document.definitions.forEach(function (definition) {\n if (definition.kind === 'OperationDefinition') {\n throw __DEV__ ? new InvariantError(\"Found a \".concat(definition.operation, \" operation\").concat(definition.name ? \" named '\".concat(definition.name.value, \"'\") : '', \". \") +\n 'No operations are allowed when using a fragment as a query. Only fragments are allowed.') : new InvariantError(44);\n }\n if (definition.kind === 'FragmentDefinition') {\n fragments.push(definition);\n }\n });\n if (typeof actualFragmentName === 'undefined') {\n __DEV__ ? invariant(fragments.length === 1, \"Found \".concat(fragments.length, \" fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\")) : invariant(fragments.length === 1, 45);\n actualFragmentName = fragments[0].name.value;\n }\n var query = __assign(__assign({}, document), { definitions: __spreadArray([\n {\n kind: 'OperationDefinition',\n operation: 'query',\n selectionSet: {\n kind: 'SelectionSet',\n selections: [\n {\n kind: 'FragmentSpread',\n name: {\n kind: 'Name',\n value: actualFragmentName,\n },\n },\n ],\n },\n }\n ], document.definitions, true) });\n return query;\n}\nexport function createFragmentMap(fragments) {\n if (fragments === void 0) { fragments = []; }\n var symTable = {};\n fragments.forEach(function (fragment) {\n symTable[fragment.name.value] = fragment;\n });\n return symTable;\n}\nexport function getFragmentFromSelection(selection, fragmentMap) {\n switch (selection.kind) {\n case 'InlineFragment':\n return selection;\n case 'FragmentSpread': {\n var fragmentName = selection.name.value;\n if (typeof fragmentMap === \"function\") {\n return fragmentMap(fragmentName);\n }\n var fragment = fragmentMap && fragmentMap[fragmentName];\n __DEV__ ? invariant(fragment, \"No fragment named \".concat(fragmentName)) : invariant(fragment, 46);\n return fragment || null;\n }\n default:\n return null;\n }\n}\n//# sourceMappingURL=fragments.js.map","export function isNonNullObject(obj) {\n return obj !== null && typeof obj === 'object';\n}\n//# sourceMappingURL=objects.js.map","import { InvariantError } from '../globals';\nimport { isNonNullObject } from '../common/objects';\nimport { getFragmentFromSelection } from './fragments';\nexport function makeReference(id) {\n return { __ref: String(id) };\n}\nexport function isReference(obj) {\n return Boolean(obj && typeof obj === 'object' && typeof obj.__ref === 'string');\n}\nexport function isDocumentNode(value) {\n return (isNonNullObject(value) &&\n value.kind === \"Document\" &&\n Array.isArray(value.definitions));\n}\nfunction isStringValue(value) {\n return value.kind === 'StringValue';\n}\nfunction isBooleanValue(value) {\n return value.kind === 'BooleanValue';\n}\nfunction isIntValue(value) {\n return value.kind === 'IntValue';\n}\nfunction isFloatValue(value) {\n return value.kind === 'FloatValue';\n}\nfunction isVariable(value) {\n return value.kind === 'Variable';\n}\nfunction isObjectValue(value) {\n return value.kind === 'ObjectValue';\n}\nfunction isListValue(value) {\n return value.kind === 'ListValue';\n}\nfunction isEnumValue(value) {\n return value.kind === 'EnumValue';\n}\nfunction isNullValue(value) {\n return value.kind === 'NullValue';\n}\nexport function valueToObjectRepresentation(argObj, name, value, variables) {\n if (isIntValue(value) || isFloatValue(value)) {\n argObj[name.value] = Number(value.value);\n }\n else if (isBooleanValue(value) || isStringValue(value)) {\n argObj[name.value] = value.value;\n }\n else if (isObjectValue(value)) {\n var nestedArgObj_1 = {};\n value.fields.map(function (obj) {\n return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);\n });\n argObj[name.value] = nestedArgObj_1;\n }\n else if (isVariable(value)) {\n var variableValue = (variables || {})[value.name.value];\n argObj[name.value] = variableValue;\n }\n else if (isListValue(value)) {\n argObj[name.value] = value.values.map(function (listValue) {\n var nestedArgArrayObj = {};\n valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);\n return nestedArgArrayObj[name.value];\n });\n }\n else if (isEnumValue(value)) {\n argObj[name.value] = value.value;\n }\n else if (isNullValue(value)) {\n argObj[name.value] = null;\n }\n else {\n throw __DEV__ ? new InvariantError(\"The inline argument \\\"\".concat(name.value, \"\\\" of kind \\\"\").concat(value.kind, \"\\\"\") +\n 'is not supported. Use variables instead of inline arguments to ' +\n 'overcome this limitation.') : new InvariantError(55);\n }\n}\nexport function storeKeyNameFromField(field, variables) {\n var directivesObj = null;\n if (field.directives) {\n directivesObj = {};\n field.directives.forEach(function (directive) {\n directivesObj[directive.name.value] = {};\n if (directive.arguments) {\n directive.arguments.forEach(function (_a) {\n var name = _a.name, value = _a.value;\n return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);\n });\n }\n });\n }\n var argObj = null;\n if (field.arguments && field.arguments.length) {\n argObj = {};\n field.arguments.forEach(function (_a) {\n var name = _a.name, value = _a.value;\n return valueToObjectRepresentation(argObj, name, value, variables);\n });\n }\n return getStoreKeyName(field.name.value, argObj, directivesObj);\n}\nvar KNOWN_DIRECTIVES = [\n 'connection',\n 'include',\n 'skip',\n 'client',\n 'rest',\n 'export',\n];\nexport var getStoreKeyName = Object.assign(function (fieldName, args, directives) {\n if (args &&\n directives &&\n directives['connection'] &&\n directives['connection']['key']) {\n if (directives['connection']['filter'] &&\n directives['connection']['filter'].length > 0) {\n var filterKeys = directives['connection']['filter']\n ? directives['connection']['filter']\n : [];\n filterKeys.sort();\n var filteredArgs_1 = {};\n filterKeys.forEach(function (key) {\n filteredArgs_1[key] = args[key];\n });\n return \"\".concat(directives['connection']['key'], \"(\").concat(stringify(filteredArgs_1), \")\");\n }\n else {\n return directives['connection']['key'];\n }\n }\n var completeFieldName = fieldName;\n if (args) {\n var stringifiedArgs = stringify(args);\n completeFieldName += \"(\".concat(stringifiedArgs, \")\");\n }\n if (directives) {\n Object.keys(directives).forEach(function (key) {\n if (KNOWN_DIRECTIVES.indexOf(key) !== -1)\n return;\n if (directives[key] && Object.keys(directives[key]).length) {\n completeFieldName += \"@\".concat(key, \"(\").concat(stringify(directives[key]), \")\");\n }\n else {\n completeFieldName += \"@\".concat(key);\n }\n });\n }\n return completeFieldName;\n}, {\n setStringify: function (s) {\n var previous = stringify;\n stringify = s;\n return previous;\n },\n});\nvar stringify = function defaultStringify(value) {\n return JSON.stringify(value, stringifyReplacer);\n};\nfunction stringifyReplacer(_key, value) {\n if (isNonNullObject(value) && !Array.isArray(value)) {\n value = Object.keys(value).sort().reduce(function (copy, key) {\n copy[key] = value[key];\n return copy;\n }, {});\n }\n return value;\n}\nexport function argumentsObjectFromField(field, variables) {\n if (field.arguments && field.arguments.length) {\n var argObj_1 = {};\n field.arguments.forEach(function (_a) {\n var name = _a.name, value = _a.value;\n return valueToObjectRepresentation(argObj_1, name, value, variables);\n });\n return argObj_1;\n }\n return null;\n}\nexport function resultKeyNameFromField(field) {\n return field.alias ? field.alias.value : field.name.value;\n}\nexport function getTypenameFromResult(result, selectionSet, fragmentMap) {\n if (typeof result.__typename === 'string') {\n return result.__typename;\n }\n for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {\n var selection = _a[_i];\n if (isField(selection)) {\n if (selection.name.value === '__typename') {\n return result[resultKeyNameFromField(selection)];\n }\n }\n else {\n var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);\n if (typeof typename === 'string') {\n return typename;\n }\n }\n }\n}\nexport function isField(selection) {\n return selection.kind === 'Field';\n}\nexport function isInlineFragment(selection) {\n return selection.kind === 'InlineFragment';\n}\n//# sourceMappingURL=storeUtils.js.map","import { invariant, InvariantError } from '../globals';\nimport { valueToObjectRepresentation } from './storeUtils';\nexport function checkDocument(doc) {\n __DEV__ ? invariant(doc && doc.kind === 'Document', \"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\") : invariant(doc && doc.kind === 'Document', 47);\n var operations = doc.definitions\n .filter(function (d) { return d.kind !== 'FragmentDefinition'; })\n .map(function (definition) {\n if (definition.kind !== 'OperationDefinition') {\n throw __DEV__ ? new InvariantError(\"Schema type definitions not allowed in queries. Found: \\\"\".concat(definition.kind, \"\\\"\")) : new InvariantError(48);\n }\n return definition;\n });\n __DEV__ ? invariant(operations.length <= 1, \"Ambiguous GraphQL document: contains \".concat(operations.length, \" operations\")) : invariant(operations.length <= 1, 49);\n return doc;\n}\nexport function getOperationDefinition(doc) {\n checkDocument(doc);\n return doc.definitions.filter(function (definition) {\n return definition.kind === 'OperationDefinition';\n })[0];\n}\nexport function getOperationName(doc) {\n return (doc.definitions\n .filter(function (definition) {\n return definition.kind === 'OperationDefinition' && !!definition.name;\n })\n .map(function (x) { return x.name.value; })[0] || null);\n}\nexport function getFragmentDefinitions(doc) {\n return doc.definitions.filter(function (definition) {\n return definition.kind === 'FragmentDefinition';\n });\n}\nexport function getQueryDefinition(doc) {\n var queryDef = getOperationDefinition(doc);\n __DEV__ ? invariant(queryDef && queryDef.operation === 'query', 'Must contain a query definition.') : invariant(queryDef && queryDef.operation === 'query', 50);\n return queryDef;\n}\nexport function getFragmentDefinition(doc) {\n __DEV__ ? invariant(doc.kind === 'Document', \"Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \\\"gql\\\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\") : invariant(doc.kind === 'Document', 51);\n __DEV__ ? invariant(doc.definitions.length <= 1, 'Fragment must have exactly one definition.') : invariant(doc.definitions.length <= 1, 52);\n var fragmentDef = doc.definitions[0];\n __DEV__ ? invariant(fragmentDef.kind === 'FragmentDefinition', 'Must be a fragment definition.') : invariant(fragmentDef.kind === 'FragmentDefinition', 53);\n return fragmentDef;\n}\nexport function getMainDefinition(queryDoc) {\n checkDocument(queryDoc);\n var fragmentDefinition;\n for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {\n var definition = _a[_i];\n if (definition.kind === 'OperationDefinition') {\n var operation = definition.operation;\n if (operation === 'query' ||\n operation === 'mutation' ||\n operation === 'subscription') {\n return definition;\n }\n }\n if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {\n fragmentDefinition = definition;\n }\n }\n if (fragmentDefinition) {\n return fragmentDefinition;\n }\n throw __DEV__ ? new InvariantError('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.') : new InvariantError(54);\n}\nexport function getDefaultValues(definition) {\n var defaultValues = Object.create(null);\n var defs = definition && definition.variableDefinitions;\n if (defs && defs.length) {\n defs.forEach(function (def) {\n if (def.defaultValue) {\n valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);\n }\n });\n }\n return defaultValues;\n}\n//# sourceMappingURL=getFromAST.js.map","export var isArray = Array.isArray;\nexport function isNonEmptyArray(value) {\n return Array.isArray(value) && value.length > 0;\n}\n//# sourceMappingURL=arrays.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { invariant } from '../globals';\nimport { visit, Kind, } from 'graphql';\nimport { checkDocument, getOperationDefinition, getFragmentDefinition, getFragmentDefinitions, getMainDefinition, } from './getFromAST';\nimport { isField } from './storeUtils';\nimport { createFragmentMap, } from './fragments';\nimport { isArray } from '../common/arrays';\nvar TYPENAME_FIELD = {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: '__typename',\n },\n};\nfunction isEmpty(op, fragmentMap) {\n return !op || op.selectionSet.selections.every(function (selection) { return selection.kind === Kind.FRAGMENT_SPREAD &&\n isEmpty(fragmentMap[selection.name.value], fragmentMap); });\n}\nfunction nullIfDocIsEmpty(doc) {\n return isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))\n ? null\n : doc;\n}\nfunction getDirectiveMatcher(directives) {\n var nameSet = new Set();\n var tests = [];\n directives.forEach(function (directive) {\n if (directive.name) {\n nameSet.add(directive.name);\n }\n else if (directive.test) {\n tests.push(directive.test);\n }\n });\n return function (directive) { return (nameSet.has(directive.name.value) ||\n tests.some(function (test) { return test(directive); })); };\n}\nfunction makeInUseGetterFunction(defaultKey) {\n var map = new Map();\n return function inUseGetterFunction(key) {\n if (key === void 0) { key = defaultKey; }\n var inUse = map.get(key);\n if (!inUse) {\n map.set(key, inUse = {\n variables: new Set,\n fragmentSpreads: new Set,\n });\n }\n return inUse;\n };\n}\nexport function removeDirectivesFromDocument(directives, doc) {\n var getInUseByOperationName = makeInUseGetterFunction(\"\");\n var getInUseByFragmentName = makeInUseGetterFunction(\"\");\n var getInUse = function (ancestors) {\n for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {\n if (isArray(ancestor))\n continue;\n if (ancestor.kind === Kind.OPERATION_DEFINITION) {\n return getInUseByOperationName(ancestor.name && ancestor.name.value);\n }\n if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {\n return getInUseByFragmentName(ancestor.name.value);\n }\n }\n __DEV__ && invariant.error(\"Could not find operation or fragment\");\n return null;\n };\n var operationCount = 0;\n for (var i = doc.definitions.length - 1; i >= 0; --i) {\n if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n ++operationCount;\n }\n }\n var directiveMatcher = getDirectiveMatcher(directives);\n var hasRemoveDirective = directives.some(function (directive) { return directive.remove; });\n var shouldRemoveField = function (nodeDirectives) { return (hasRemoveDirective &&\n nodeDirectives &&\n nodeDirectives.some(directiveMatcher)); };\n var originalFragmentDefsByPath = new Map();\n var firstVisitMadeChanges = false;\n var fieldOrInlineFragmentVisitor = {\n enter: function (node) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n };\n var docWithoutDirectiveSubtrees = visit(doc, {\n Field: fieldOrInlineFragmentVisitor,\n InlineFragment: fieldOrInlineFragmentVisitor,\n VariableDefinition: {\n enter: function () {\n return false;\n },\n },\n Variable: {\n enter: function (node, _key, _parent, _path, ancestors) {\n var inUse = getInUse(ancestors);\n if (inUse) {\n inUse.variables.add(node.name.value);\n }\n },\n },\n FragmentSpread: {\n enter: function (node, _key, _parent, _path, ancestors) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n var inUse = getInUse(ancestors);\n if (inUse) {\n inUse.fragmentSpreads.add(node.name.value);\n }\n },\n },\n FragmentDefinition: {\n enter: function (node, _key, _parent, path) {\n originalFragmentDefsByPath.set(JSON.stringify(path), node);\n },\n leave: function (node, _key, _parent, path) {\n var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));\n if (node === originalNode) {\n return node;\n }\n if (operationCount > 0 &&\n node.selectionSet.selections.every(function (selection) { return (selection.kind === Kind.FIELD &&\n selection.name.value === '__typename'); })) {\n getInUseByFragmentName(node.name.value).removed = true;\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n Directive: {\n leave: function (node) {\n if (directiveMatcher(node)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n });\n if (!firstVisitMadeChanges) {\n return doc;\n }\n var populateTransitiveVars = function (inUse) {\n if (!inUse.transitiveVars) {\n inUse.transitiveVars = new Set(inUse.variables);\n if (!inUse.removed) {\n inUse.fragmentSpreads.forEach(function (childFragmentName) {\n populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {\n inUse.transitiveVars.add(varName);\n });\n });\n }\n }\n return inUse;\n };\n var allFragmentNamesUsed = new Set();\n docWithoutDirectiveSubtrees.definitions.forEach(function (def) {\n if (def.kind === Kind.OPERATION_DEFINITION) {\n populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {\n allFragmentNamesUsed.add(childFragmentName);\n });\n }\n else if (def.kind === Kind.FRAGMENT_DEFINITION &&\n operationCount === 0 &&\n !getInUseByFragmentName(def.name.value).removed) {\n allFragmentNamesUsed.add(def.name.value);\n }\n });\n allFragmentNamesUsed.forEach(function (fragmentName) {\n populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {\n allFragmentNamesUsed.add(childFragmentName);\n });\n });\n var fragmentWillBeRemoved = function (fragmentName) { return !!(!allFragmentNamesUsed.has(fragmentName) ||\n getInUseByFragmentName(fragmentName).removed); };\n var enterVisitor = {\n enter: function (node) {\n if (fragmentWillBeRemoved(node.name.value)) {\n return null;\n }\n },\n };\n return nullIfDocIsEmpty(visit(docWithoutDirectiveSubtrees, {\n FragmentSpread: enterVisitor,\n FragmentDefinition: enterVisitor,\n OperationDefinition: {\n leave: function (node) {\n if (node.variableDefinitions) {\n var usedVariableNames_1 = populateTransitiveVars(getInUseByOperationName(node.name && node.name.value)).transitiveVars;\n if (usedVariableNames_1.size < node.variableDefinitions.length) {\n return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) { return usedVariableNames_1.has(varDef.variable.name.value); }) });\n }\n }\n },\n },\n }));\n}\nexport var addTypenameToDocument = Object.assign(function (doc) {\n return visit(doc, {\n SelectionSet: {\n enter: function (node, _key, parent) {\n if (parent &&\n parent.kind === Kind.OPERATION_DEFINITION) {\n return;\n }\n var selections = node.selections;\n if (!selections) {\n return;\n }\n var skip = selections.some(function (selection) {\n return (isField(selection) &&\n (selection.name.value === '__typename' ||\n selection.name.value.lastIndexOf('__', 0) === 0));\n });\n if (skip) {\n return;\n }\n var field = parent;\n if (isField(field) &&\n field.directives &&\n field.directives.some(function (d) { return d.name.value === 'export'; })) {\n return;\n }\n return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });\n },\n },\n });\n}, {\n added: function (field) {\n return field === TYPENAME_FIELD;\n },\n});\nvar connectionRemoveConfig = {\n test: function (directive) {\n var willRemove = directive.name.value === 'connection';\n if (willRemove) {\n if (!directive.arguments ||\n !directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) {\n __DEV__ && invariant.warn('Removing an @connection directive even though it does not have a key. ' +\n 'You may want to use the key parameter to specify a store key.');\n }\n }\n return willRemove;\n },\n};\nexport function removeConnectionDirectiveFromDocument(doc) {\n return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));\n}\nfunction hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {\n if (nestedCheck === void 0) { nestedCheck = true; }\n return (!!selectionSet &&\n selectionSet.selections &&\n selectionSet.selections.some(function (selection) {\n return hasDirectivesInSelection(directives, selection, nestedCheck);\n }));\n}\nfunction hasDirectivesInSelection(directives, selection, nestedCheck) {\n if (nestedCheck === void 0) { nestedCheck = true; }\n if (!isField(selection)) {\n return true;\n }\n if (!selection.directives) {\n return false;\n }\n return (selection.directives.some(getDirectiveMatcher(directives)) ||\n (nestedCheck &&\n hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));\n}\nfunction getArgumentMatcher(config) {\n return function argumentMatcher(argument) {\n return config.some(function (aConfig) {\n return argument.value &&\n argument.value.kind === Kind.VARIABLE &&\n argument.value.name &&\n (aConfig.name === argument.value.name.value ||\n (aConfig.test && aConfig.test(argument)));\n });\n };\n}\nexport function removeArgumentsFromDocument(config, doc) {\n var argMatcher = getArgumentMatcher(config);\n return nullIfDocIsEmpty(visit(doc, {\n OperationDefinition: {\n enter: function (node) {\n return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions ? node.variableDefinitions.filter(function (varDef) {\n return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });\n }) : [] });\n },\n },\n Field: {\n enter: function (node) {\n var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });\n if (shouldRemoveField) {\n var argMatchCount_1 = 0;\n if (node.arguments) {\n node.arguments.forEach(function (arg) {\n if (argMatcher(arg)) {\n argMatchCount_1 += 1;\n }\n });\n }\n if (argMatchCount_1 === 1) {\n return null;\n }\n }\n },\n },\n Argument: {\n enter: function (node) {\n if (argMatcher(node)) {\n return null;\n }\n },\n },\n }));\n}\nexport function removeFragmentSpreadFromDocument(config, doc) {\n function enter(node) {\n if (config.some(function (def) { return def.name === node.name.value; })) {\n return null;\n }\n }\n return nullIfDocIsEmpty(visit(doc, {\n FragmentSpread: { enter: enter },\n FragmentDefinition: { enter: enter },\n }));\n}\nexport function buildQueryFromSelectionSet(document) {\n var definition = getMainDefinition(document);\n var definitionOperation = definition.operation;\n if (definitionOperation === 'query') {\n return document;\n }\n var modifiedDoc = visit(document, {\n OperationDefinition: {\n enter: function (node) {\n return __assign(__assign({}, node), { operation: 'query' });\n },\n },\n });\n return modifiedDoc;\n}\nexport function removeClientSetsFromDocument(document) {\n checkDocument(document);\n var modifiedDoc = removeDirectivesFromDocument([\n {\n test: function (directive) { return directive.name.value === 'client'; },\n remove: true,\n },\n ], document);\n return modifiedDoc;\n}\n//# sourceMappingURL=transform.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { isNonNullObject } from \"./objects\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function mergeDeep() {\n var sources = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n sources[_i] = arguments[_i];\n }\n return mergeDeepArray(sources);\n}\nexport function mergeDeepArray(sources) {\n var target = sources[0] || {};\n var count = sources.length;\n if (count > 1) {\n var merger = new DeepMerger();\n for (var i = 1; i < count; ++i) {\n target = merger.merge(target, sources[i]);\n }\n }\n return target;\n}\nvar defaultReconciler = function (target, source, property) {\n return this.merge(target[property], source[property]);\n};\nvar DeepMerger = (function () {\n function DeepMerger(reconciler) {\n if (reconciler === void 0) { reconciler = defaultReconciler; }\n this.reconciler = reconciler;\n this.isObject = isNonNullObject;\n this.pastCopies = new Set();\n }\n DeepMerger.prototype.merge = function (target, source) {\n var _this = this;\n var context = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n context[_i - 2] = arguments[_i];\n }\n if (isNonNullObject(source) && isNonNullObject(target)) {\n Object.keys(source).forEach(function (sourceKey) {\n if (hasOwnProperty.call(target, sourceKey)) {\n var targetValue = target[sourceKey];\n if (source[sourceKey] !== targetValue) {\n var result = _this.reconciler.apply(_this, __spreadArray([target, source, sourceKey], context, false));\n if (result !== targetValue) {\n target = _this.shallowCopyForMerge(target);\n target[sourceKey] = result;\n }\n }\n }\n else {\n target = _this.shallowCopyForMerge(target);\n target[sourceKey] = source[sourceKey];\n }\n });\n return target;\n }\n return source;\n };\n DeepMerger.prototype.shallowCopyForMerge = function (value) {\n if (isNonNullObject(value)) {\n if (!this.pastCopies.has(value)) {\n if (Array.isArray(value)) {\n value = value.slice(0);\n }\n else {\n value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);\n }\n this.pastCopies.add(value);\n }\n }\n return value;\n };\n return DeepMerger;\n}());\nexport { DeepMerger };\n//# sourceMappingURL=mergeDeep.js.map","var toString = Object.prototype.toString;\nexport function cloneDeep(value) {\n return cloneDeepHelper(value);\n}\nfunction cloneDeepHelper(val, seen) {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n seen = seen || new Map;\n if (seen.has(val))\n return seen.get(val);\n var copy_1 = val.slice(0);\n seen.set(val, copy_1);\n copy_1.forEach(function (child, i) {\n copy_1[i] = cloneDeepHelper(child, seen);\n });\n return copy_1;\n }\n case \"[object Object]\": {\n seen = seen || new Map;\n if (seen.has(val))\n return seen.get(val);\n var copy_2 = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy_2);\n Object.keys(val).forEach(function (key) {\n copy_2[key] = cloneDeepHelper(val[key], seen);\n });\n return copy_2;\n }\n default:\n return val;\n }\n}\n//# sourceMappingURL=cloneDeep.js.map","import '../globals';\nimport { isNonNullObject } from './objects';\nfunction deepFreeze(value) {\n var workSet = new Set([value]);\n workSet.forEach(function (obj) {\n if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n Object.getOwnPropertyNames(obj).forEach(function (name) {\n if (isNonNullObject(obj[name]))\n workSet.add(obj[name]);\n });\n }\n });\n return value;\n}\nfunction shallowFreeze(obj) {\n if (__DEV__ && !Object.isFrozen(obj)) {\n try {\n Object.freeze(obj);\n }\n catch (e) {\n if (e instanceof TypeError)\n return null;\n throw e;\n }\n }\n return obj;\n}\nexport function maybeDeepFreeze(obj) {\n if (__DEV__) {\n deepFreeze(obj);\n }\n return obj;\n}\n//# sourceMappingURL=maybeDeepFreeze.js.map","export function iterateObserversSafely(observers, method, argument) {\n var observersWithMethod = [];\n observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });\n observersWithMethod.forEach(function (obs) { return obs[method](argument); });\n}\n//# sourceMappingURL=iteration.js.map","import { Observable } from \"./Observable\";\nexport function asyncMap(observable, mapFn, catchFn) {\n return new Observable(function (observer) {\n var next = observer.next, error = observer.error, complete = observer.complete;\n var activeCallbackCount = 0;\n var completed = false;\n var promiseQueue = {\n then: function (callback) {\n return new Promise(function (resolve) { return resolve(callback()); });\n },\n };\n function makeCallback(examiner, delegate) {\n if (examiner) {\n return function (arg) {\n ++activeCallbackCount;\n var both = function () { return examiner(arg); };\n promiseQueue = promiseQueue.then(both, both).then(function (result) {\n --activeCallbackCount;\n next && next.call(observer, result);\n if (completed) {\n handler.complete();\n }\n }, function (error) {\n --activeCallbackCount;\n throw error;\n }).catch(function (caught) {\n error && error.call(observer, caught);\n });\n };\n }\n else {\n return function (arg) { return delegate && delegate.call(observer, arg); };\n }\n }\n var handler = {\n next: makeCallback(mapFn, next),\n error: makeCallback(catchFn, error),\n complete: function () {\n completed = true;\n if (!activeCallbackCount) {\n complete && complete.call(observer);\n }\n },\n };\n var sub = observable.subscribe(handler);\n return function () { return sub.unsubscribe(); };\n });\n}\n//# sourceMappingURL=asyncMap.js.map","import { maybe } from \"../globals\";\nexport var canUseWeakMap = typeof WeakMap === 'function' &&\n maybe(function () { return navigator.product; }) !== 'ReactNative';\nexport var canUseWeakSet = typeof WeakSet === 'function';\nexport var canUseSymbol = typeof Symbol === 'function' &&\n typeof Symbol.for === 'function';\nexport var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;\nexport var canUseDOM = typeof maybe(function () { return window.document.createElement; }) === \"function\";\nvar usingJSDOM = maybe(function () { return navigator.userAgent.indexOf(\"jsdom\") >= 0; }) || false;\nexport var canUseLayoutEffect = canUseDOM && !usingJSDOM;\n//# sourceMappingURL=canUse.js.map","import { Observable } from \"./Observable\";\nimport { canUseSymbol } from \"../common/canUse\";\nexport function fixObservableSubclass(subclass) {\n function set(key) {\n Object.defineProperty(subclass, key, { value: Observable });\n }\n if (canUseSymbol && Symbol.species) {\n set(Symbol.species);\n }\n set(\"@@species\");\n return subclass;\n}\n//# sourceMappingURL=subclassing.js.map","import { __extends } from \"tslib\";\nimport { Observable } from \"./Observable\";\nimport { iterateObserversSafely } from \"./iteration\";\nimport { fixObservableSubclass } from \"./subclassing\";\nfunction isPromiseLike(value) {\n return value && typeof value.then === \"function\";\n}\nvar Concast = (function (_super) {\n __extends(Concast, _super);\n function Concast(sources) {\n var _this = _super.call(this, function (observer) {\n _this.addObserver(observer);\n return function () { return _this.removeObserver(observer); };\n }) || this;\n _this.observers = new Set();\n _this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n _this.handlers = {\n next: function (result) {\n if (_this.sub !== null) {\n _this.latest = [\"next\", result];\n _this.notify(\"next\", result);\n iterateObserversSafely(_this.observers, \"next\", result);\n }\n },\n error: function (error) {\n var sub = _this.sub;\n if (sub !== null) {\n if (sub)\n setTimeout(function () { return sub.unsubscribe(); });\n _this.sub = null;\n _this.latest = [\"error\", error];\n _this.reject(error);\n _this.notify(\"error\", error);\n iterateObserversSafely(_this.observers, \"error\", error);\n }\n },\n complete: function () {\n var _a = _this, sub = _a.sub, _b = _a.sources, sources = _b === void 0 ? [] : _b;\n if (sub !== null) {\n var value = sources.shift();\n if (!value) {\n if (sub)\n setTimeout(function () { return sub.unsubscribe(); });\n _this.sub = null;\n if (_this.latest &&\n _this.latest[0] === \"next\") {\n _this.resolve(_this.latest[1]);\n }\n else {\n _this.resolve();\n }\n _this.notify(\"complete\");\n iterateObserversSafely(_this.observers, \"complete\");\n }\n else if (isPromiseLike(value)) {\n value.then(function (obs) { return _this.sub = obs.subscribe(_this.handlers); });\n }\n else {\n _this.sub = value.subscribe(_this.handlers);\n }\n }\n },\n };\n _this.nextResultListeners = new Set();\n _this.cancel = function (reason) {\n _this.reject(reason);\n _this.sources = [];\n _this.handlers.complete();\n };\n _this.promise.catch(function (_) { });\n if (typeof sources === \"function\") {\n sources = [new Observable(sources)];\n }\n if (isPromiseLike(sources)) {\n sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);\n }\n else {\n _this.start(sources);\n }\n return _this;\n }\n Concast.prototype.start = function (sources) {\n if (this.sub !== void 0)\n return;\n this.sources = Array.from(sources);\n this.handlers.complete();\n };\n Concast.prototype.deliverLastMessage = function (observer) {\n if (this.latest) {\n var nextOrError = this.latest[0];\n var method = observer[nextOrError];\n if (method) {\n method.call(observer, this.latest[1]);\n }\n if (this.sub === null &&\n nextOrError === \"next\" &&\n observer.complete) {\n observer.complete();\n }\n }\n };\n Concast.prototype.addObserver = function (observer) {\n if (!this.observers.has(observer)) {\n this.deliverLastMessage(observer);\n this.observers.add(observer);\n }\n };\n Concast.prototype.removeObserver = function (observer) {\n if (this.observers.delete(observer) &&\n this.observers.size < 1) {\n this.handlers.complete();\n }\n };\n Concast.prototype.notify = function (method, arg) {\n var nextResultListeners = this.nextResultListeners;\n if (nextResultListeners.size) {\n this.nextResultListeners = new Set;\n nextResultListeners.forEach(function (listener) { return listener(method, arg); });\n }\n };\n Concast.prototype.beforeNext = function (callback) {\n var called = false;\n this.nextResultListeners.add(function (method, arg) {\n if (!called) {\n called = true;\n callback(method, arg);\n }\n });\n };\n return Concast;\n}(Observable));\nexport { Concast };\nfixObservableSubclass(Concast);\n//# sourceMappingURL=Concast.js.map","import { isNonEmptyArray } from \"./arrays\";\nimport { DeepMerger } from \"./mergeDeep\";\nexport function isExecutionPatchIncrementalResult(value) {\n return \"incremental\" in value;\n}\nexport function isExecutionPatchInitialResult(value) {\n return \"hasNext\" in value && \"data\" in value;\n}\nexport function isExecutionPatchResult(value) {\n return (isExecutionPatchIncrementalResult(value) ||\n isExecutionPatchInitialResult(value));\n}\nexport function mergeIncrementalData(prevResult, result) {\n var mergedData = prevResult;\n var merger = new DeepMerger();\n if (isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)) {\n result.incremental.forEach(function (_a) {\n var data = _a.data, path = _a.path;\n for (var i = path.length - 1; i >= 0; --i) {\n var key = path[i];\n var isNumericKey = !isNaN(+key);\n var parent_1 = isNumericKey ? [] : {};\n parent_1[key] = data;\n data = parent_1;\n }\n mergedData = merger.merge(mergedData, data);\n });\n }\n return mergedData;\n}\n//# sourceMappingURL=incrementalResult.js.map","import { isNonEmptyArray } from \"../../utilities/common/arrays\";\nimport { isExecutionPatchIncrementalResult } from \"../../utilities/common/incrementalResult\";\nexport function graphQLResultHasError(result) {\n var errors = getGraphQLErrorsFromResult(result);\n return isNonEmptyArray(errors);\n}\nexport function getGraphQLErrorsFromResult(result) {\n var graphQLErrors = isNonEmptyArray(result.errors)\n ? result.errors.slice(0)\n : [];\n if (isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)) {\n result.incremental.forEach(function (incrementalResult) {\n if (incrementalResult.errors) {\n graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);\n }\n });\n }\n return graphQLErrors;\n}\n//# sourceMappingURL=errorHandling.js.map","export function compact() {\n var objects = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n objects[_i] = arguments[_i];\n }\n var result = Object.create(null);\n objects.forEach(function (obj) {\n if (!obj)\n return;\n Object.keys(obj).forEach(function (key) {\n var value = obj[key];\n if (value !== void 0) {\n result[key] = value;\n }\n });\n });\n return result;\n}\n//# sourceMappingURL=compact.js.map","var prefixCounts = new Map();\nexport function makeUniqueId(prefix) {\n var count = prefixCounts.get(prefix) || 1;\n prefixCounts.set(prefix, count + 1);\n return \"\".concat(prefix, \":\").concat(count, \":\").concat(Math.random().toString(36).slice(2));\n}\n//# sourceMappingURL=makeUniqueId.js.map","import { makeUniqueId } from \"./makeUniqueId\";\nexport function stringifyForDisplay(value) {\n var undefId = makeUniqueId(\"stringifyForDisplay\");\n return JSON.stringify(value, function (key, value) {\n return value === void 0 ? undefId : value;\n }).split(JSON.stringify(undefId)).join(\"<undefined>\");\n}\n//# sourceMappingURL=stringifyForDisplay.js.map","import { __assign } from \"tslib\";\nimport { compact } from \"./compact\";\nexport function mergeOptions(defaults, options) {\n return compact(defaults, options, options.variables && {\n variables: __assign(__assign({}, (defaults && defaults.variables)), options.variables),\n });\n}\n//# sourceMappingURL=mergeOptions.js.map","import { Observable } from '../../utilities';\nexport function fromError(errorValue) {\n return new Observable(function (observer) {\n observer.error(errorValue);\n });\n}\n//# sourceMappingURL=fromError.js.map","import { invariant } from '../../utilities/globals';\nexport function toPromise(observable) {\n var completed = false;\n return new Promise(function (resolve, reject) {\n observable.subscribe({\n next: function (data) {\n if (completed) {\n __DEV__ && invariant.warn(\"Promise Wrapper does not support multiple results from Observable\");\n }\n else {\n completed = true;\n resolve(data);\n }\n },\n error: reject,\n });\n });\n}\n//# sourceMappingURL=toPromise.js.map","import { Observable } from '../../utilities';\nexport function fromPromise(promise) {\n return new Observable(function (observer) {\n promise\n .then(function (value) {\n observer.next(value);\n observer.complete();\n })\n .catch(observer.error.bind(observer));\n });\n}\n//# sourceMappingURL=fromPromise.js.map","export var throwServerError = function (response, result, message) {\n var error = new Error(message);\n error.name = 'ServerError';\n error.response = response;\n error.statusCode = response.status;\n error.result = result;\n throw error;\n};\n//# sourceMappingURL=throwServerError.js.map","import { InvariantError } from '../../utilities/globals';\nexport function validateOperation(operation) {\n var OPERATION_FIELDS = [\n 'query',\n 'operationName',\n 'variables',\n 'extensions',\n 'context',\n ];\n for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {\n var key = _a[_i];\n if (OPERATION_FIELDS.indexOf(key) < 0) {\n throw __DEV__ ? new InvariantError(\"illegal argument: \".concat(key)) : new InvariantError(27);\n }\n }\n return operation;\n}\n//# sourceMappingURL=validateOperation.js.map","import { __assign } from \"tslib\";\nexport function createOperation(starting, operation) {\n var context = __assign({}, starting);\n var setContext = function (next) {\n if (typeof next === 'function') {\n context = __assign(__assign({}, context), next(context));\n }\n else {\n context = __assign(__assign({}, context), next);\n }\n };\n var getContext = function () { return (__assign({}, context)); };\n Object.defineProperty(operation, 'setContext', {\n enumerable: false,\n value: setContext,\n });\n Object.defineProperty(operation, 'getContext', {\n enumerable: false,\n value: getContext,\n });\n return operation;\n}\n//# sourceMappingURL=createOperation.js.map","import { getOperationName } from '../../utilities';\nexport function transformOperation(operation) {\n var transformedOperation = {\n variables: operation.variables || {},\n extensions: operation.extensions || {},\n operationName: operation.operationName,\n query: operation.query,\n };\n if (!transformedOperation.operationName) {\n transformedOperation.operationName =\n typeof transformedOperation.query !== 'string'\n ? getOperationName(transformedOperation.query) || undefined\n : '';\n }\n return transformedOperation;\n}\n//# sourceMappingURL=transformOperation.js.map","import { __extends } from \"tslib\";\nimport { InvariantError, invariant } from '../../utilities/globals';\nimport { Observable } from '../../utilities';\nimport { validateOperation, createOperation, transformOperation, } from '../utils';\nfunction passthrough(op, forward) {\n return (forward ? forward(op) : Observable.of());\n}\nfunction toLink(handler) {\n return typeof handler === 'function' ? new ApolloLink(handler) : handler;\n}\nfunction isTerminating(link) {\n return link.request.length <= 1;\n}\nvar LinkError = (function (_super) {\n __extends(LinkError, _super);\n function LinkError(message, link) {\n var _this = _super.call(this, message) || this;\n _this.link = link;\n return _this;\n }\n return LinkError;\n}(Error));\nvar ApolloLink = (function () {\n function ApolloLink(request) {\n if (request)\n this.request = request;\n }\n ApolloLink.empty = function () {\n return new ApolloLink(function () { return Observable.of(); });\n };\n ApolloLink.from = function (links) {\n if (links.length === 0)\n return ApolloLink.empty();\n return links.map(toLink).reduce(function (x, y) { return x.concat(y); });\n };\n ApolloLink.split = function (test, left, right) {\n var leftLink = toLink(left);\n var rightLink = toLink(right || new ApolloLink(passthrough));\n if (isTerminating(leftLink) && isTerminating(rightLink)) {\n return new ApolloLink(function (operation) {\n return test(operation)\n ? leftLink.request(operation) || Observable.of()\n : rightLink.request(operation) || Observable.of();\n });\n }\n else {\n return new ApolloLink(function (operation, forward) {\n return test(operation)\n ? leftLink.request(operation, forward) || Observable.of()\n : rightLink.request(operation, forward) || Observable.of();\n });\n }\n };\n ApolloLink.execute = function (link, operation) {\n return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());\n };\n ApolloLink.concat = function (first, second) {\n var firstLink = toLink(first);\n if (isTerminating(firstLink)) {\n __DEV__ && invariant.warn(new LinkError(\"You are calling concat on a terminating link, which will have no effect\", firstLink));\n return firstLink;\n }\n var nextLink = toLink(second);\n if (isTerminating(nextLink)) {\n return new ApolloLink(function (operation) {\n return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();\n });\n }\n else {\n return new ApolloLink(function (operation, forward) {\n return (firstLink.request(operation, function (op) {\n return nextLink.request(op, forward) || Observable.of();\n }) || Observable.of());\n });\n }\n };\n ApolloLink.prototype.split = function (test, left, right) {\n return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));\n };\n ApolloLink.prototype.concat = function (next) {\n return ApolloLink.concat(this, next);\n };\n ApolloLink.prototype.request = function (operation, forward) {\n throw __DEV__ ? new InvariantError('request is not implemented') : new InvariantError(22);\n };\n ApolloLink.prototype.onError = function (error, observer) {\n if (observer && observer.error) {\n observer.error(error);\n return false;\n }\n throw error;\n };\n ApolloLink.prototype.setOnError = function (fn) {\n this.onError = fn;\n return this;\n };\n return ApolloLink;\n}());\nexport { ApolloLink };\n//# sourceMappingURL=ApolloLink.js.map","import { ApolloLink } from './ApolloLink';\nexport var empty = ApolloLink.empty;\n//# sourceMappingURL=empty.js.map","import { ApolloLink } from './ApolloLink';\nexport var from = ApolloLink.from;\n//# sourceMappingURL=from.js.map","import { ApolloLink } from './ApolloLink';\nexport var split = ApolloLink.split;\n//# sourceMappingURL=split.js.map","import { ApolloLink } from './ApolloLink';\nexport var concat = ApolloLink.concat;\n//# sourceMappingURL=concat.js.map","import { ApolloLink } from './ApolloLink';\nexport var execute = ApolloLink.execute;\n//# sourceMappingURL=execute.js.map","export var version = '3.7.10';\n//# sourceMappingURL=version.js.map","import { canUseAsyncIteratorSymbol } from \"./canUse\";\nexport function isNodeResponse(value) {\n return !!value.body;\n}\nexport function isReadableStream(value) {\n return !!value.getReader;\n}\nexport function isAsyncIterableIterator(value) {\n return !!(canUseAsyncIteratorSymbol &&\n value[Symbol.asyncIterator]);\n}\nexport function isStreamableBlob(value) {\n return !!value.stream;\n}\nexport function isBlob(value) {\n return !!value.arrayBuffer;\n}\nexport function isNodeReadableStream(value) {\n return !!value.pipe;\n}\n//# sourceMappingURL=responseIterator.js.map","export default function asyncIterator(source) {\n var _a;\n var iterator = source[Symbol.asyncIterator]();\n return _a = {\n next: function () {\n return iterator.next();\n }\n },\n _a[Symbol.asyncIterator] = function () {\n return this;\n },\n _a;\n}\n//# sourceMappingURL=async.js.map","import { canUseAsyncIteratorSymbol } from \"../../../utilities\";\nexport default function nodeStreamIterator(stream) {\n var cleanup = null;\n var error = null;\n var done = false;\n var data = [];\n var waiting = [];\n function onData(chunk) {\n if (error)\n return;\n if (waiting.length) {\n var shiftedArr = waiting.shift();\n if (Array.isArray(shiftedArr) && shiftedArr[0]) {\n return shiftedArr[0]({ value: chunk, done: false });\n }\n }\n data.push(chunk);\n }\n function onError(err) {\n error = err;\n var all = waiting.slice();\n all.forEach(function (pair) {\n pair[1](err);\n });\n !cleanup || cleanup();\n }\n function onEnd() {\n done = true;\n var all = waiting.slice();\n all.forEach(function (pair) {\n pair[0]({ value: undefined, done: true });\n });\n !cleanup || cleanup();\n }\n cleanup = function () {\n cleanup = null;\n stream.removeListener(\"data\", onData);\n stream.removeListener(\"error\", onError);\n stream.removeListener(\"end\", onEnd);\n stream.removeListener(\"finish\", onEnd);\n stream.removeListener(\"close\", onEnd);\n };\n stream.on(\"data\", onData);\n stream.on(\"error\", onError);\n stream.on(\"end\", onEnd);\n stream.on(\"finish\", onEnd);\n stream.on(\"close\", onEnd);\n function getNext() {\n return new Promise(function (resolve, reject) {\n if (error)\n return reject(error);\n if (data.length)\n return resolve({ value: data.shift(), done: false });\n if (done)\n return resolve({ value: undefined, done: true });\n waiting.push([resolve, reject]);\n });\n }\n var iterator = {\n next: function () {\n return getNext();\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=nodeStream.js.map","import { canUseAsyncIteratorSymbol } from \"../../../utilities\";\nexport default function promiseIterator(promise) {\n var resolved = false;\n var iterator = {\n next: function () {\n if (resolved)\n return Promise.resolve({\n value: undefined,\n done: true,\n });\n resolved = true;\n return new Promise(function (resolve, reject) {\n promise\n .then(function (value) {\n resolve({ value: value, done: false });\n })\n .catch(reject);\n });\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=promise.js.map","import { canUseAsyncIteratorSymbol } from \"../../../utilities\";\nexport default function readerIterator(reader) {\n var iterator = {\n next: function () {\n return reader.read();\n },\n };\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function () {\n return this;\n };\n }\n return iterator;\n}\n//# sourceMappingURL=reader.js.map","import { isAsyncIterableIterator, isBlob, isNodeResponse, isNodeReadableStream, isReadableStream, isStreamableBlob, } from \"../../utilities/common/responseIterator\";\nimport asyncIterator from \"./iterators/async\";\nimport nodeStreamIterator from \"./iterators/nodeStream\";\nimport promiseIterator from \"./iterators/promise\";\nimport readerIterator from \"./iterators/reader\";\nexport function responseIterator(response) {\n var body = response;\n if (isNodeResponse(response))\n body = response.body;\n if (isAsyncIterableIterator(body))\n return asyncIterator(body);\n if (isReadableStream(body))\n return readerIterator(body.getReader());\n if (isStreamableBlob(body)) {\n return readerIterator(body.stream().getReader());\n }\n if (isBlob(body))\n return promiseIterator(body.arrayBuffer());\n if (isNodeReadableStream(body))\n return nodeStreamIterator(body);\n throw new Error(\"Unknown body type for responseIterator. Please pass a streamable response.\");\n}\n//# sourceMappingURL=responseIterator.js.map","import { __awaiter, __generator } from \"tslib\";\nimport { responseIterator } from \"./responseIterator\";\nimport { throwServerError } from \"../utils\";\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function readMultipartBody(response, observer) {\n var _a, _b, _c;\n return __awaiter(this, void 0, void 0, function () {\n var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _d, value, done, chunk, bi, message, i, headers, contentType_1, body, result;\n var _e;\n return __generator(this, function (_f) {\n switch (_f.label) {\n case 0:\n if (TextDecoder === undefined) {\n throw new Error(\"TextDecoder must be defined in the environment: please import a polyfill.\");\n }\n decoder = new TextDecoder(\"utf-8\");\n contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('content-type');\n delimiter = \"boundary=\";\n boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter))\n ? contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['\"]/g, \"\").replace(/\\;(.*)/gm, \"\").trim()\n : \"-\";\n boundary = \"--\".concat(boundaryVal);\n buffer = \"\";\n iterator = responseIterator(response);\n running = true;\n _f.label = 1;\n case 1:\n if (!running) return [3, 3];\n return [4, iterator.next()];\n case 2:\n _d = _f.sent(), value = _d.value, done = _d.done;\n chunk = typeof value === \"string\" ? value : decoder.decode(value);\n running = !done;\n buffer += chunk;\n bi = buffer.indexOf(boundary);\n while (bi > -1) {\n message = void 0;\n _e = [\n buffer.slice(0, bi),\n buffer.slice(bi + boundary.length),\n ], message = _e[0], buffer = _e[1];\n if (message.trim()) {\n i = message.indexOf(\"\\r\\n\\r\\n\");\n headers = parseHeaders(message.slice(0, i));\n contentType_1 = headers[\"content-type\"];\n if (contentType_1 &&\n contentType_1.toLowerCase().indexOf(\"application/json\") === -1) {\n throw new Error(\"Unsupported patch content type: application/json is required.\");\n }\n body = message.slice(i);\n try {\n result = parseJsonBody(response, body.replace(\"\\r\\n\", \"\"));\n if (Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result) {\n (_b = observer.next) === null || _b === void 0 ? void 0 : _b.call(observer, result);\n }\n }\n catch (err) {\n handleError(err, observer);\n }\n }\n bi = buffer.indexOf(boundary);\n }\n return [3, 1];\n case 3:\n (_c = observer.complete) === null || _c === void 0 ? void 0 : _c.call(observer);\n return [2];\n }\n });\n });\n}\nexport function parseHeaders(headerText) {\n var headersInit = {};\n headerText.split(\"\\n\").forEach(function (line) {\n var i = line.indexOf(\":\");\n if (i > -1) {\n var name_1 = line.slice(0, i).trim().toLowerCase();\n var value = line.slice(i + 1).trim();\n headersInit[name_1] = value;\n }\n });\n return headersInit;\n}\nexport function parseJsonBody(response, bodyText) {\n if (response.status >= 300) {\n var getResult = function () {\n try {\n return JSON.parse(bodyText);\n }\n catch (err) {\n return bodyText;\n }\n };\n throwServerError(response, getResult(), \"Response not successful: Received status code \".concat(response.status));\n }\n try {\n return JSON.parse(bodyText);\n }\n catch (err) {\n var parseError = err;\n parseError.name = \"ServerParseError\";\n parseError.response = response;\n parseError.statusCode = response.status;\n parseError.bodyText = bodyText;\n throw parseError;\n }\n}\nexport function handleError(err, observer) {\n var _a, _b;\n if (err.name === \"AbortError\")\n return;\n if (err.result && err.result.errors && err.result.data) {\n (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, err.result);\n }\n (_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, err);\n}\nexport function readJsonBody(response, operation, observer) {\n parseAndCheckHttpResponse(operation)(response)\n .then(function (result) {\n var _a, _b;\n (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, result);\n (_b = observer.complete) === null || _b === void 0 ? void 0 : _b.call(observer);\n })\n .catch(function (err) { return handleError(err, observer); });\n}\nexport function parseAndCheckHttpResponse(operations) {\n return function (response) {\n return response\n .text()\n .then(function (bodyText) { return parseJsonBody(response, bodyText); })\n .then(function (result) {\n if (response.status >= 300) {\n throwServerError(response, result, \"Response not successful: Received status code \".concat(response.status));\n }\n if (!Array.isArray(result) &&\n !hasOwnProperty.call(result, \"data\") &&\n !hasOwnProperty.call(result, \"errors\")) {\n throwServerError(response, result, \"Server response was missing for query '\".concat(Array.isArray(operations)\n ? operations.map(function (op) { return op.operationName; })\n : operations.operationName, \"'.\"));\n }\n return result;\n });\n };\n}\n//# sourceMappingURL=parseAndCheckHttpResponse.js.map","import { InvariantError } from '../../utilities/globals';\nexport var serializeFetchParameter = function (p, label) {\n var serialized;\n try {\n serialized = JSON.stringify(p);\n }\n catch (e) {\n var parseError = __DEV__ ? new InvariantError(\"Network request failed. \".concat(label, \" is not serializable: \").concat(e.message)) : new InvariantError(24);\n parseError.parseError = e;\n throw parseError;\n }\n return serialized;\n};\n//# sourceMappingURL=serializeFetchParameter.js.map","import { __assign, __spreadArray } from \"tslib\";\nimport { print } from 'graphql';\n;\nvar defaultHttpOptions = {\n includeQuery: true,\n includeExtensions: false,\n preserveHeaderCase: false,\n};\nvar defaultHeaders = {\n accept: '*/*',\n 'content-type': 'application/json',\n};\nvar defaultOptions = {\n method: 'POST',\n};\nexport var fallbackHttpConfig = {\n http: defaultHttpOptions,\n headers: defaultHeaders,\n options: defaultOptions,\n};\nexport var defaultPrinter = function (ast, printer) { return printer(ast); };\nexport function selectHttpOptionsAndBody(operation, fallbackConfig) {\n var configs = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n configs[_i - 2] = arguments[_i];\n }\n configs.unshift(fallbackConfig);\n return selectHttpOptionsAndBodyInternal.apply(void 0, __spreadArray([operation,\n defaultPrinter], configs, false));\n}\nexport function selectHttpOptionsAndBodyInternal(operation, printer) {\n var configs = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n configs[_i - 2] = arguments[_i];\n }\n var options = {};\n var http = {};\n configs.forEach(function (config) {\n options = __assign(__assign(__assign({}, options), config.options), { headers: __assign(__assign({}, options.headers), config.headers) });\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n http = __assign(__assign({}, http), config.http);\n });\n if (options.headers) {\n options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);\n }\n var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;\n var body = { operationName: operationName, variables: variables };\n if (http.includeExtensions)\n body.extensions = extensions;\n if (http.includeQuery)\n body.query = printer(query, print);\n return {\n options: options,\n body: body,\n };\n}\n;\nfunction removeDuplicateHeaders(headers, preserveHeaderCase) {\n if (!preserveHeaderCase) {\n var normalizedHeaders_1 = Object.create(null);\n Object.keys(Object(headers)).forEach(function (name) {\n normalizedHeaders_1[name.toLowerCase()] = headers[name];\n });\n return normalizedHeaders_1;\n }\n var headerData = Object.create(null);\n Object.keys(Object(headers)).forEach(function (name) {\n headerData[name.toLowerCase()] = { originalName: name, value: headers[name] };\n });\n var normalizedHeaders = Object.create(null);\n Object.keys(headerData).forEach(function (name) {\n normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n });\n return normalizedHeaders;\n}\n//# sourceMappingURL=selectHttpOptionsAndBody.js.map","import { InvariantError } from '../../utilities/globals';\nexport var checkFetcher = function (fetcher) {\n if (!fetcher && typeof fetch === 'undefined') {\n throw __DEV__ ? new InvariantError(\"\\n\\\"fetch\\\" has not been found globally and no fetcher has been configured. To fix this, install a fetch package (like https://www.npmjs.com/package/cross-fetch), instantiate the fetcher, and pass it into your HttpLink constructor. For example:\\n\\nimport fetch from 'cross-fetch';\\nimport { ApolloClient, HttpLink } from '@apollo/client';\\nconst client = new ApolloClient({\\n link: new HttpLink({ uri: '/graphql', fetch })\\n});\\n \") : new InvariantError(23);\n }\n};\n//# sourceMappingURL=checkFetcher.js.map","export var createSignalIfSupported = function () {\n if (typeof AbortController === 'undefined')\n return { controller: false, signal: false };\n var controller = new AbortController();\n var signal = controller.signal;\n return { controller: controller, signal: signal };\n};\n//# sourceMappingURL=createSignalIfSupported.js.map","export var selectURI = function (operation, fallbackURI) {\n var context = operation.getContext();\n var contextURI = context.uri;\n if (contextURI) {\n return contextURI;\n }\n else if (typeof fallbackURI === 'function') {\n return fallbackURI(operation);\n }\n else {\n return fallbackURI || '/graphql';\n }\n};\n//# sourceMappingURL=selectURI.js.map","import { serializeFetchParameter } from './serializeFetchParameter';\nexport function rewriteURIForGET(chosenURI, body) {\n var queryParams = [];\n var addQueryParam = function (key, value) {\n queryParams.push(\"\".concat(key, \"=\").concat(encodeURIComponent(value)));\n };\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n var serializedVariables = void 0;\n try {\n serializedVariables = serializeFetchParameter(body.variables, 'Variables map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n var serializedExtensions = void 0;\n try {\n serializedExtensions = serializeFetchParameter(body.extensions, 'Extensions map');\n }\n catch (parseError) {\n return { parseError: parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n var fragment = '', preFragment = chosenURI;\n var fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI: newURI };\n}\n//# sourceMappingURL=rewriteURIForGET.js.map","import { __assign, __rest } from \"tslib\";\nimport '../../utilities/globals';\nimport { visit } from 'graphql';\nimport { ApolloLink } from '../core';\nimport { Observable, hasDirectives } from '../../utilities';\nimport { serializeFetchParameter } from './serializeFetchParameter';\nimport { selectURI } from './selectURI';\nimport { handleError, readMultipartBody, readJsonBody } from './parseAndCheckHttpResponse';\nimport { checkFetcher } from './checkFetcher';\nimport { selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig } from './selectHttpOptionsAndBody';\nimport { createSignalIfSupported } from './createSignalIfSupported';\nimport { rewriteURIForGET } from './rewriteURIForGET';\nimport { fromError } from '../utils';\nimport { maybe } from '../../utilities';\nvar backupFetch = maybe(function () { return fetch; });\nexport var createHttpLink = function (linkOptions) {\n if (linkOptions === void 0) { linkOptions = {}; }\n var _a = linkOptions.uri, uri = _a === void 0 ? '/graphql' : _a, preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = __rest(linkOptions, [\"uri\", \"fetch\", \"print\", \"includeExtensions\", \"preserveHeaderCase\", \"useGETForQueries\", \"includeUnusedVariables\"]);\n if (__DEV__) {\n checkFetcher(preferredFetch || backupFetch);\n }\n var linkConfig = {\n http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n return new ApolloLink(function (operation) {\n var chosenURI = selectURI(operation, uri);\n var context = operation.getContext();\n var clientAwarenessHeaders = {};\n if (context.clientAwareness) {\n var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;\n if (name_1) {\n clientAwarenessHeaders['apollographql-client-name'] = name_1;\n }\n if (version) {\n clientAwarenessHeaders['apollographql-client-version'] = version;\n }\n }\n var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);\n var contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: contextHeaders,\n };\n var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;\n if (body.variables && !includeUnusedVariables) {\n var unusedNames_1 = new Set(Object.keys(body.variables));\n visit(operation.query, {\n Variable: function (node, _key, parent) {\n if (parent && parent.kind !== 'VariableDefinition') {\n unusedNames_1.delete(node.name.value);\n }\n },\n });\n if (unusedNames_1.size) {\n body.variables = __assign({}, body.variables);\n unusedNames_1.forEach(function (name) {\n delete body.variables[name];\n });\n }\n }\n var controller;\n if (!options.signal) {\n var _c = createSignalIfSupported(), _controller = _c.controller, signal = _c.signal;\n controller = _controller;\n if (controller)\n options.signal = signal;\n }\n var definitionIsMutation = function (d) {\n return d.kind === 'OperationDefinition' && d.operation === 'mutation';\n };\n if (useGETForQueries &&\n !operation.query.definitions.some(definitionIsMutation)) {\n options.method = 'GET';\n }\n if (hasDirectives(['defer'], operation.query)) {\n options.headers = options.headers || {};\n options.headers.accept = \"multipart/mixed; deferSpec=20220824, application/json\";\n }\n if (options.method === 'GET') {\n var _d = rewriteURIForGET(chosenURI, body), newURI = _d.newURI, parseError = _d.parseError;\n if (parseError) {\n return fromError(parseError);\n }\n chosenURI = newURI;\n }\n else {\n try {\n options.body = serializeFetchParameter(body, 'Payload');\n }\n catch (parseError) {\n return fromError(parseError);\n }\n }\n return new Observable(function (observer) {\n var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;\n currentFetch(chosenURI, options)\n .then(function (response) {\n var _a;\n operation.setContext({ response: response });\n var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('content-type');\n if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n return readMultipartBody(response, observer);\n }\n else {\n return readJsonBody(response, operation, observer);\n }\n })\n .catch(function (err) { return handleError(err, observer); });\n return function () {\n if (controller)\n controller.abort();\n };\n });\n });\n};\n//# sourceMappingURL=createHttpLink.js.map","import { __extends } from \"tslib\";\nimport { ApolloLink } from '../core';\nimport { createHttpLink } from './createHttpLink';\nvar HttpLink = (function (_super) {\n __extends(HttpLink, _super);\n function HttpLink(options) {\n if (options === void 0) { options = {}; }\n var _this = _super.call(this, createHttpLink(options).request) || this;\n _this.options = options;\n return _this;\n }\n return HttpLink;\n}(ApolloLink));\nexport { HttpLink };\n//# sourceMappingURL=HttpLink.js.map","import { __assign, __rest } from \"tslib\";\nimport { wrap } from 'optimism';\nimport { getFragmentQueryDocument, } from '../../utilities';\nvar ApolloCache = (function () {\n function ApolloCache() {\n this.getFragmentDoc = wrap(getFragmentQueryDocument);\n }\n ApolloCache.prototype.batch = function (options) {\n var _this = this;\n var optimisticId = typeof options.optimistic === \"string\" ? options.optimistic :\n options.optimistic === false ? null : 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 ApolloCache.prototype.transformDocument = function (document) {\n return document;\n };\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 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 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 };\n//# sourceMappingURL=cache.js.map","export var Cache;\n(function (Cache) {\n})(Cache || (Cache = {}));\n//# sourceMappingURL=Cache.js.map","import { __extends } from \"tslib\";\nvar MissingFieldError = (function (_super) {\n __extends(MissingFieldError, _super);\n function MissingFieldError(message, path, query, variables) {\n var _a;\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 _this.__proto__ = MissingFieldError.prototype;\n return _this;\n }\n return MissingFieldError;\n}(Error));\nexport { MissingFieldError };\n//# sourceMappingURL=common.js.map","import { isReference, isField, DeepMerger, resultKeyNameFromField, shouldInclude, isNonNullObject, compact, createFragmentMap, getFragmentDefinitions, isArray, } from '../../utilities';\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 (isNullish(id) && !isNullish(_id)) {\n id = _id;\n }\n if (!isNullish(id)) {\n return \"\".concat(__typename, \":\").concat((typeof id === \"number\" ||\n typeof id === \"string\") ? id : JSON.stringify(id));\n }\n }\n}\nvar defaultConfig = {\n dataIdFromObject: defaultDataIdFromObject,\n addTypename: true,\n resultCaching: true,\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) { return selectionSetMatchesResult(selectionSet, item, variables); })\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 return true;\n });\n }\n return false;\n}\nexport function storeValueIsStoreObject(value) {\n return isNonNullObject(value) &&\n !isReference(value) &&\n !isArray(value);\n}\nexport function makeProcessedFieldsMerger() {\n return new DeepMerger;\n}\nexport function extractFragmentContext(document, fragments) {\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","import { __assign, __extends, __rest } from \"tslib\";\nimport { invariant } from '../../utilities/globals';\nimport { dep } from 'optimism';\nimport { equal } from '@wry/equality';\nimport { Trie } from '@wry/trie';\nimport { isReference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from '../../utilities';\nimport { hasOwn, fieldNameFromStoreName } from './helpers';\nvar DELETE = Object.create(null);\nvar delModifier = function () { return DELETE; };\nvar INVALIDATE = Object.create(null);\nvar EntityStore = (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 this.rootIds = Object.create(null);\n this.refs = Object.create(null);\n this.getFieldValue = function (objectOrReference, storeFieldName) { return maybeDeepFreeze(isReference(objectOrReference)\n ? _this.get(objectOrReference.__ref, storeFieldName)\n : objectOrReference && objectOrReference[storeFieldName]); };\n this.canRead = function (objOrRef) {\n return isReference(objOrRef)\n ? _this.has(objOrRef.__ref)\n : typeof objOrRef === \"object\";\n };\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 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 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 if (isReference(older))\n older = older.__ref;\n if (isReference(newer))\n newer = newer.__ref;\n var existing = typeof older === \"string\"\n ? this.lookup(dataId = older)\n : older;\n var incoming = typeof newer === \"string\"\n ? this.lookup(dataId = newer)\n : newer;\n if (!incoming)\n return;\n __DEV__ ? invariant(typeof dataId === \"string\", \"store.merge expects a string ID\") : invariant(typeof dataId === \"string\", 1);\n var merged = new DeepMerger(storeObjectReconciler).merge(existing, incoming);\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 (!existing)\n fieldsToDirty_1.__exists = 1;\n Object.keys(incoming).forEach(function (storeFieldName) {\n if (!existing || existing[storeFieldName] !== merged[storeFieldName]) {\n fieldsToDirty_1[storeFieldName] = 1;\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] === void 0 && !(_this instanceof Layer)) {\n delete merged[storeFieldName];\n }\n }\n });\n if (fieldsToDirty_1.__typename &&\n !(existing && existing.__typename) &&\n this.policies.rootTypenamesById[dataId] === merged.__typename) {\n delete fieldsToDirty_1.__typename;\n }\n Object.keys(fieldsToDirty_1).forEach(function (fieldName) { return _this.group.dirty(dataId, fieldName); });\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) { return _this.policies.readField(typeof fieldNameOrOptions === \"string\" ? {\n fieldName: fieldNameOrOptions,\n from: from || makeReference(dataId),\n } : fieldNameOrOptions, { store: _this }); },\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\"\n ? fields\n : fields[storeFieldName] || fields[fieldName];\n if (modify) {\n var newValue = modify === delModifier ? DELETE :\n 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 }\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 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 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 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 Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n }\n return ids;\n };\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 Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);\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 workSet_1.forEach(function (obj) {\n if (isReference(obj)) {\n found_1[obj.__ref] = true;\n }\n if (isNonNullObject(obj)) {\n Object.keys(obj).forEach(function (key) {\n var child = obj[key];\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 };\nvar CacheGroup = (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 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), storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\");\n }\n };\n return CacheGroup;\n}());\nfunction makeDepKey(dataId, storeFieldName) {\n return storeFieldName + '#' + dataId;\n}\nexport function maybeDependOnExistenceOfEntity(store, entityId) {\n if (supportsResultCaching(store)) {\n store.group.depend(entityId, \"__exists\");\n }\n}\n(function (EntityStore) {\n var Root = (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 return this.stump.addLayer(layerId, replay);\n };\n Root.prototype.removeLayer = function () {\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 = {}));\nvar Layer = (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 var parent = this.parent.removeLayer(layerId);\n if (layerId === this.id) {\n if (this.group.caching) {\n Object.keys(this.data).forEach(function (dataId) {\n var ownStoreObject = _this.data[dataId];\n var parentStoreObject = parent[\"lookup\"](dataId);\n if (!parentStoreObject) {\n _this.delete(dataId);\n }\n else if (!ownStoreObject) {\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 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 if (parent === this.parent)\n return this;\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, arguments);\n };\n return Layer;\n}(EntityStore));\nvar Stump = (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 return this;\n };\n Stump.prototype.merge = function () {\n return this.parent.merge.apply(this.parent, arguments);\n };\n return Stump;\n}(Layer));\nfunction storeObjectReconciler(existingObject, incomingObject, property) {\n var existingValue = existingObject[property];\n var incomingValue = incomingObject[property];\n return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\nexport function supportsResultCaching(store) {\n return !!(store instanceof EntityStore && store.group.caching);\n}\n//# sourceMappingURL=entityStore.js.map","import { __assign } from \"tslib\";\nimport \"../../utilities/globals\";\nimport { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet, isNonNullObject as isObjectOrArray, } from \"../../utilities\";\nimport { isArray } from \"./helpers\";\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}\nvar ObjectCanon = (function () {\n function ObjectCanon() {\n this.known = new (canUseWeakSet ? WeakSet : Set)();\n this.pool = new Trie(canUseWeakMap);\n this.passes = new WeakMap();\n this.keysByJSON = new Map();\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 var node = this.pool.lookupArray(array);\n if (!node.array) {\n this.known.add(node.array = array);\n if (__DEV__) {\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 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 if (__DEV__) {\n Object.freeze(obj_1);\n }\n }\n return node.object;\n }\n }\n }\n return value;\n };\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 };\nexport var canonicalStringify = Object.assign(function (value) {\n if (isObjectOrArray(value)) {\n if (stringifyCanon === void 0) {\n resetCanonicalStringify();\n }\n var canonical = stringifyCanon.admit(value);\n var json = stringifyCache.get(canonical);\n if (json === void 0) {\n stringifyCache.set(canonical, json = JSON.stringify(canonical));\n }\n return json;\n }\n return JSON.stringify(value);\n}, {\n reset: resetCanonicalStringify,\n});\nvar stringifyCanon;\nvar stringifyCache;\nfunction resetCanonicalStringify() {\n stringifyCanon = new ObjectCanon;\n stringifyCache = new (canUseWeakMap ? WeakMap : Map)();\n}\n//# sourceMappingURL=object-canon.js.map","import { __assign } from \"tslib\";\nimport { invariant, InvariantError } from '../../utilities/globals';\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, } from '../../utilities';\nimport { maybeDependOnExistenceOfEntity, supportsResultCaching } from './entityStore';\nimport { isArray, extractFragmentContext, getTypenameFromStoreObject, shouldCanonizeResults } from './helpers';\nimport { MissingFieldError } from '../core/types/common';\nimport { canonicalStringify, ObjectCanon } from './object-canon';\n;\nfunction execSelectionSetKeyArgs(options) {\n return [\n options.selectionSet,\n options.objectOrReference,\n options.context,\n options.context.canonizeResults,\n ];\n}\nvar StoreReader = (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 this.executeSelectionSet = wrap(function (options) {\n var _a;\n var canonizeResults = options.context.canonizeResults;\n var peekArgs = execSelectionSetKeyArgs(options);\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), { result: _this.canon.admit(other.result) });\n }\n return other;\n }\n maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);\n return _this.execSelectionSetImpl(options);\n }, {\n max: this.config.resultCacheMaxSize,\n keyArgs: execSelectionSetKeyArgs,\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 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 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 missing = [new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables)];\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, this.canon.isKnown(result));\n if (latest && result === latest.result) {\n return true;\n }\n }\n return false;\n };\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 objectsToMerge.push({ __typename: typename });\n }\n function handleMissing(result, resultName) {\n var _a;\n if (result.missing) {\n missing = missingMerger.merge(missing, (_a = {}, _a[resultName] = result.missing, _a));\n }\n return result.result;\n }\n var workSet = new Set(selectionSet.selections);\n workSet.forEach(function (selection) {\n var _a, _b;\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 fieldValue = handleMissing(_this.executeSubSelectedArray({\n field: selection,\n array: fieldValue,\n enclosingRef: enclosingRef,\n context: context,\n }), resultName);\n }\n else if (!selection.selectionSet) {\n if (context.canonizeResults) {\n fieldValue = _this.canon.pass(fieldValue);\n }\n }\n else if (fieldValue != 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 __DEV__ ? new InvariantError(\"No fragment named \".concat(selection.name.value)) : new InvariantError(5);\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 : maybeDeepFreeze(finalResult);\n if (frozen.result) {\n this.knownResults.set(frozen.result, selectionSet);\n }\n return frozen;\n };\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 if (item === null) {\n return null;\n }\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 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 (__DEV__) {\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 __DEV__ ? invariant(!isReference(value), \"Missing selection set for object of type \".concat(getTypenameFromStoreObject(store, value), \" returned for query field \").concat(field.name.value)) : invariant(!isReference(value), 6);\n Object.values(value).forEach(workSet_1.add, workSet_1);\n }\n });\n }\n}\n//# sourceMappingURL=readFromStore.js.map","import { dep } from \"optimism\";\nimport { Slot } from \"@wry/context\";\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}\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 getCacheInfo(cache).dep.dirty(rv);\n broadcast(cache);\n });\n var oldListeners = Array.from(listeners);\n listeners.clear();\n oldListeners.forEach(function (listener) { return listener(value); });\n }\n }\n else {\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 { invariant } from \"../../utilities/globals\";\nimport { argumentsObjectFromField, DeepMerger, isNonEmptyArray, isNonNullObject, } from \"../../utilities\";\nimport { hasOwn, isArray } from \"./helpers\";\nvar specifierInfoCache = Object.create(null);\nfunction lookupSpecifierInfo(spec) {\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) { return context.readField(key, from); };\n var keyObject = context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {\n var extracted = extractKeyPath(context.storeObject, schemaKeyPath, extract);\n if (extracted === void 0 &&\n object !== context.storeObject &&\n hasOwn.call(object, schemaKeyPath[0])) {\n extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n }\n __DEV__ ? invariant(extracted !== void 0, \"Missing field '\".concat(schemaKeyPath.join('.'), \"' while extracting keyFields from \").concat(JSON.stringify(object))) : invariant(extracted !== void 0, 2);\n return extracted;\n });\n return \"\".concat(context.typename, \":\").concat(JSON.stringify(keyObject));\n });\n}\nexport function keyArgsFnFromSpecifier(specifier) {\n var info = lookupSpecifierInfo(specifier);\n return info.keyArgsFn || (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 var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });\n var directiveArgs = d && argumentsObjectFromField(d, variables);\n return directiveArgs && extractKeyPath(directiveArgs, keyPath.slice(1));\n }\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 return;\n }\n if (args) {\n return extractKeyPath(args, keyPath);\n }\n });\n var suffix = JSON.stringify(collected);\n if (args || suffix !== \"{}\") {\n fieldName += \":\" + suffix;\n }\n return fieldName;\n });\n}\nexport function collectSpecifierPaths(specifier, extractor) {\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 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 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 if (isNonNullObject(value)) {\n if (isArray(value)) {\n return value.map(normalize);\n }\n return collectSpecifierPaths(Object.keys(value).sort(), function (path) { return extractKeyPath(value, path); });\n }\n return value;\n}\n//# sourceMappingURL=key-extractor.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant, InvariantError } from '../../utilities/globals';\nimport { storeKeyNameFromField, argumentsObjectFromField, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from '../../utilities';\nimport { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, isArray, } from './helpers';\nimport { cacheSlot } from './reactiveVars';\nimport { canonicalStringify } from './object-canon';\nimport { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier } from './key-extractor';\ngetStoreKeyName.setStringify(canonicalStringify);\nfunction argsFromFieldSpecifier(spec) {\n return spec.args !== void 0 ? spec.args :\n spec.field ? argumentsObjectFromField(spec.field, spec.variables) : null;\n}\nvar nullKeyFieldsFn = function () { return void 0; };\nvar simpleKeyArgsFn = function (_args, context) { return context.fieldName; };\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 = (function () {\n function Policies(config) {\n this.config = config;\n this.typePolicies = Object.create(null);\n this.toBeAdded = Object.create(null);\n this.supertypeMap = new Map();\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 && (partialContext.typename ||\n ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename)) || object.__typename;\n if (typename === this.rootTypenamesById.ROOT_QUERY) {\n return [\"ROOT_QUERY\"];\n }\n var storeObject = partialContext && partialContext.storeObject || object;\n var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: partialContext && partialContext.readField || 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(object, 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 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 merge === true ? mergeTrueFn :\n merge === false ? mergeFalseFn :\n existing.merge;\n }\n setMerge(existing, incoming.merge);\n existing.keyFn =\n keyFields === false ? nullKeyFieldsFn :\n isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields) :\n typeof keyFields === \"function\" ? keyFields :\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 keyArgs === false ? simpleKeyArgsFn :\n isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs) :\n typeof keyArgs === \"function\" ? keyArgs :\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 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 __DEV__ ? invariant(!old || old === which, \"Cannot change root \".concat(which, \" __typename more than once\")) : invariant(!old || old === which, 3);\n if (old)\n delete this.rootIdsByTypename[old];\n this.rootIdsByTypename[typename] = 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 _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 _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 var supertypes = this.supertypeMap.get(typename);\n if (supertypes && supertypes.size) {\n supertypes.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 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] || (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 (!typename)\n return false;\n var supertype = fragment.typeCondition.name.value;\n if (typename === supertype)\n return true;\n if (this.usingPossibleTypes &&\n 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 var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n var checkingFuzzySubtypes = false;\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 __DEV__ && invariant.warn(\"Inferring subtype \".concat(typename, \" of supertype \").concat(supertype));\n }\n typenameSupertypeSet.add(supertype);\n }\n return true;\n }\n supertypeSet.forEach(maybeEnqueue_1);\n if (needToCheckFuzzySubtypes &&\n i === workQueue_1.length - 1 &&\n selectionSetMatchesResult(fragment.selectionSet, result, variables)) {\n needToCheckFuzzySubtypes = false;\n checkingFuzzySubtypes = true;\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 storeFieldName = specifierOrString || fieldName;\n break;\n }\n }\n }\n if (storeFieldName === void 0) {\n storeFieldName = fieldSpec.field\n ? storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n }\n if (storeFieldName === false) {\n return fieldName;\n }\n return fieldName === fieldNameFromStoreName(storeFieldName)\n ? 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 return cacheSlot.withValue(this.cache, read, [existing, readOptions]);\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 return makeMergeObjectsFunction(context.store)(existing, incoming);\n }\n if (merge === mergeFalseFn) {\n return incoming;\n }\n if (context.overwrite) {\n existing = void 0;\n }\n return merge(existing, incoming, makeFieldFunctionOptions(this, void 0, { typename: typename, fieldName: field.name.value, field: field, variables: context.variables }, 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 from: argc > 1 ? from : objectOrReference,\n };\n }\n else {\n options = __assign({}, fieldNameOrOptions);\n if (!hasOwn.call(options, \"from\")) {\n options.from = objectOrReference;\n }\n }\n if (__DEV__ && options.from === void 0) {\n __DEV__ && invariant.warn(\"Undefined 'from' passed to readField with arguments \".concat(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 __DEV__ ? new InvariantError(\"Cannot automatically merge arrays\") : new InvariantError(4);\n }\n if (isNonNullObject(existing) &&\n 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) &&\n storeValueIsStoreObject(incoming)) {\n store.merge(existing.__ref, incoming);\n return existing;\n }\n if (storeValueIsStoreObject(existing) &&\n isReference(incoming)) {\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, InvariantError } from '../../utilities/globals';\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, } from '../../utilities';\nimport { isArray, makeProcessedFieldsMerger, fieldNameFromStoreName, storeValueIsStoreObject, extractFragmentContext } from './helpers';\nimport { canonicalStringify } from './object-canon';\nimport { normalizeReadFieldOptions } from './policies';\n;\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 = (context.clientOnly === clientOnly &&\n context.deferred === deferred) ? context : __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred }));\n }\n return flavored;\n}\nvar StoreWriter = (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 __DEV__ ? new InvariantError(\"Could not identify object \".concat(JSON.stringify(result))) : new InvariantError(7);\n }\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 return;\n }\n storeObject = applied;\n }\n if (__DEV__ && !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)] === 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 (hasSelectionSet_1(storeFieldName) &&\n !hasMergeFunction_1(storeFieldName)) {\n warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);\n }\n });\n }\n store.merge(dataId, storeObject);\n });\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, mergeTree = _a.mergeTree;\n var policies = this.cache.policies;\n var incoming = Object.create(null);\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 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, 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, field.selectionSet\n ? getContextFlavor(context, false, false)\n : context, childTree);\n var childTypename = void 0;\n if (field.selectionSet &&\n (isReference(incomingValue) ||\n 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 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 (__DEV__ &&\n !context.clientOnly &&\n !context.deferred &&\n !addTypenameToDocument.added(field) &&\n !policies.getReadFunction(typename, field.name.value)) {\n __DEV__ && invariant.error(\"Missing field '\".concat(resultKeyNameFromField(field), \"' while writing result \").concat(JSON.stringify(result, null, 2)).substring(0, 1000));\n }\n });\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 dataId = dataId || id;\n if (keyObject) {\n incoming = context.merge(incoming, keyObject);\n }\n }\n catch (e) {\n if (!dataId)\n throw e;\n }\n if (\"string\" === typeof dataId) {\n var dataRef = makeReference(dataId);\n var sets = context.written[dataId] || (context.written[dataId] = []);\n if (sets.indexOf(selectionSet) >= 0)\n return dataRef;\n sets.push(selectionSet);\n if (this.reader && 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 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 return __DEV__ ? 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 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);\n (function flatten(selectionSet, inheritedContext) {\n var visitedNode = limitingTrie.lookup(selectionSet, 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 (!(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 if (!args || args.if !== false) {\n deferred = true;\n }\n }\n });\n }\n if (isField(selection)) {\n var existing = fieldMap.get(selection);\n if (existing) {\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 __DEV__ ? new InvariantError(\"No fragment named \".concat(selection.name.value)) : new InvariantError(8);\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 = (!isArray(incoming) &&\n (isReference(existing) || storeValueIsStoreObject(existing))) ? existing : void 0;\n var i_1 = incoming;\n if (e_1 && !getStorageArgs) {\n getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];\n }\n var changedFields_1;\n var getValue_1 = function (from, name) {\n return isArray(from)\n ? (typeof name === \"number\" ? from[name] : 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 (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 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 : 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();\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 if (isReference(existing))\n return;\n if (equal(existing, incoming))\n return;\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 if (warnings.has(typeDotName))\n return;\n warnings.add(typeDotName);\n var childTypenames = [];\n if (!isArray(existing) &&\n !isArray(incoming)) {\n [existing, incoming].forEach(function (child) {\n var typename = store.getFieldValue(child, \"__typename\");\n if (typeof typename === \"string\" &&\n !childTypenames.includes(typename)) {\n childTypenames.push(typename);\n }\n });\n }\n __DEV__ && invariant.warn(\"Cache data may be lost when replacing the \".concat(fieldName, \" field of a \").concat(parentType, \" object.\\n\\nTo address this problem (which is not a bug in Apollo Client), \").concat(childTypenames.length\n ? \"either ensure all objects of type \" +\n childTypenames.join(\" and \") + \" have an ID or a custom merge function, or \"\n : \"\", \"define a custom merge function for the \").concat(typeDotName, \" field, so InMemoryCache can safely merge these objects:\\n\\n existing: \").concat(JSON.stringify(existing).slice(0, 1000), \"\\n incoming: \").concat(JSON.stringify(incoming).slice(0, 1000), \"\\n\\nFor more information about these options, please refer to the documentation:\\n\\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\\n\"));\n}\n//# sourceMappingURL=writeToStore.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from '../../utilities/globals';\nimport './fixPolyfills';\nimport { wrap } from 'optimism';\nimport { equal } from '@wry/equality';\nimport { ApolloCache } from '../core/cache';\nimport { MissingFieldError } from '../core/types/common';\nimport { addTypenameToDocument, isReference, } from '../../utilities';\nimport { StoreReader } from './readFromStore';\nimport { StoreWriter } from './writeToStore';\nimport { EntityStore, supportsResultCaching } from './entityStore';\nimport { makeVar, forgetCache, recallCache } from './reactiveVars';\nimport { Policies } from './policies';\nimport { hasOwn, normalizeConfig, shouldCanonizeResults } from './helpers';\nimport { canonicalStringify } from './object-canon';\nvar InMemoryCache = (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.typenameDocumentCache = new Map();\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 var rootStore = this.data = new EntityStore.Root({\n policies: this.policies,\n resultCaching: this.config.resultCaching,\n });\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 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\n ? void 0\n : 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 makeCacheKey: function (c) {\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, c.callback, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));\n }\n }\n });\n new Set([\n this.data.group,\n this.optimisticData.group,\n ]).forEach(function (group) { return group.resetCaching(); });\n };\n InMemoryCache.prototype.restore = function (data) {\n this.init();\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 _a = options.returnPartialData, 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 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 return false;\n }\n var store = options.optimistic\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 recallCache(this);\n }\n this.watches.add(watch);\n if (watch.immediate) {\n this.maybeBroadcastWatch(watch);\n }\n return function () {\n if (_this.watches.delete(watch) && !_this.watches.size) {\n forgetCache(_this);\n }\n _this.maybeBroadcastWatch.forget(watch);\n };\n };\n InMemoryCache.prototype.gc = function (options) {\n canonicalStringify.reset();\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 InMemoryCache.prototype.retain = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).retain(rootId);\n };\n InMemoryCache.prototype.release = function (rootId, optimistic) {\n return (optimistic ? this.optimisticData : this.data).release(rootId);\n };\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 __DEV__ && invariant.warn(e);\n }\n };\n InMemoryCache.prototype.evict = function (options) {\n if (!options.id) {\n if (hasOwn.call(options, \"id\")) {\n return false;\n }\n options = __assign(__assign({}, options), { id: \"ROOT_QUERY\" });\n }\n try {\n ++this.txCount;\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 this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });\n this.watches.clear();\n forgetCache(this);\n }\n else {\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 this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch) {\n alreadyDirty.add(watch);\n return false;\n } }));\n }\n if (typeof optimistic === 'string') {\n this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n }\n else if (optimistic === false) {\n perform(this.data);\n }\n else {\n perform();\n }\n if (typeof removeOptimistic === \"string\") {\n this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n }\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 alreadyDirty.delete(watch);\n }\n return result;\n } }));\n if (alreadyDirty.size) {\n alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });\n }\n }\n else {\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 if (this.addTypename) {\n var result = this.typenameDocumentCache.get(document);\n if (!result) {\n result = addTypenameToDocument(document);\n this.typenameDocumentCache.set(document, result);\n this.typenameDocumentCache.set(result, result);\n }\n return result;\n }\n return document;\n };\n InMemoryCache.prototype.transformForLink = function (document) {\n var fragments = this.config.fragments;\n return fragments\n ? fragments.transform(document)\n : 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.broadcastWatch = function (c, options) {\n var lastDiff = c.lastDiff;\n var diff = this.diff(c);\n if (options) {\n if (c.optimistic &&\n typeof options.optimistic === \"string\") {\n diff.fromOptimisticTransaction = true;\n }\n if (options.onWatchUpdated &&\n options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {\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 };\n//# sourceMappingURL=inMemoryCache.js.map","import { __extends } from \"tslib\";\nimport '../utilities/globals';\nimport { isNonEmptyArray } from '../utilities';\nexport function isApolloError(err) {\n return err.hasOwnProperty('graphQLErrors');\n}\nvar generateErrorMessage = function (err) {\n var message = '';\n if (isNonEmptyArray(err.graphQLErrors) || isNonEmptyArray(err.clientErrors)) {\n var errors = (err.graphQLErrors || [])\n .concat(err.clientErrors || []);\n errors.forEach(function (error) {\n var errorMessage = error\n ? error.message\n : 'Error message not found.';\n message += \"\".concat(errorMessage, \"\\n\");\n });\n }\n if (err.networkError) {\n message += \"\".concat(err.networkError.message, \"\\n\");\n }\n message = message.replace(/\\n$/, '');\n return message;\n};\nvar ApolloError = (function (_super) {\n __extends(ApolloError, _super);\n function ApolloError(_a) {\n var graphQLErrors = _a.graphQLErrors, clientErrors = _a.clientErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;\n var _this = _super.call(this, errorMessage) || this;\n _this.name = 'ApolloError';\n _this.graphQLErrors = graphQLErrors || [];\n _this.clientErrors = clientErrors || [];\n _this.networkError = networkError || null;\n _this.message = errorMessage || generateErrorMessage(_this);\n _this.extraInfo = extraInfo;\n _this.__proto__ = ApolloError.prototype;\n return _this;\n }\n return ApolloError;\n}(Error));\nexport { ApolloError };\n//# sourceMappingURL=index.js.map","export var NetworkStatus;\n(function (NetworkStatus) {\n NetworkStatus[NetworkStatus[\"loading\"] = 1] = \"loading\";\n NetworkStatus[NetworkStatus[\"setVariables\"] = 2] = \"setVariables\";\n NetworkStatus[NetworkStatus[\"fetchMore\"] = 3] = \"fetchMore\";\n NetworkStatus[NetworkStatus[\"refetch\"] = 4] = \"refetch\";\n NetworkStatus[NetworkStatus[\"poll\"] = 6] = \"poll\";\n NetworkStatus[NetworkStatus[\"ready\"] = 7] = \"ready\";\n NetworkStatus[NetworkStatus[\"error\"] = 8] = \"error\";\n})(NetworkStatus || (NetworkStatus = {}));\nexport function isNetworkRequestInFlight(networkStatus) {\n return networkStatus ? networkStatus < 7 : false;\n}\n//# sourceMappingURL=networkStatus.js.map","import { __assign, __extends } from \"tslib\";\nimport { invariant } from '../utilities/globals';\nimport { equal } from '@wry/equality';\nimport { NetworkStatus, isNetworkRequestInFlight } from './networkStatus';\nimport { cloneDeep, compact, getOperationDefinition, Observable, iterateObserversSafely, isNonEmptyArray, fixObservableSubclass, getQueryDefinition, } from '../utilities';\nvar assign = Object.assign, hasOwnProperty = Object.hasOwnProperty;\nvar ObservableQuery = (function (_super) {\n __extends(ObservableQuery, _super);\n function ObservableQuery(_a) {\n var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;\n var _this = _super.call(this, function (observer) {\n try {\n var subObserver = observer._subscription._observer;\n if (subObserver && !subObserver.error) {\n subObserver.error = defaultSubscriptionObserverErrorCallback;\n }\n }\n catch (_a) { }\n var first = !_this.observers.size;\n _this.observers.add(observer);\n var last = _this.last;\n if (last && last.error) {\n observer.error && observer.error(last.error);\n }\n else if (last && last.result) {\n observer.next && observer.next(last.result);\n }\n if (first) {\n _this.reobserve().catch(function () { });\n }\n return function () {\n if (_this.observers.delete(observer) && !_this.observers.size) {\n _this.tearDownQuery();\n }\n };\n }) || this;\n _this.observers = new Set();\n _this.subscriptions = new Set();\n _this.queryInfo = queryInfo;\n _this.queryManager = queryManager;\n _this.isTornDown = false;\n var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? \"cache-first\" : _d;\n var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e, _f = options.initialFetchPolicy, initialFetchPolicy = _f === void 0 ? (fetchPolicy === \"standby\" ? defaultFetchPolicy : fetchPolicy) : _f;\n _this.options = __assign(__assign({}, options), { initialFetchPolicy: initialFetchPolicy, fetchPolicy: fetchPolicy });\n _this.queryId = queryInfo.queryId || queryManager.generateQueryId();\n var opDef = getOperationDefinition(_this.query);\n _this.queryName = opDef && opDef.name && opDef.name.value;\n return _this;\n }\n Object.defineProperty(ObservableQuery.prototype, \"query\", {\n get: function () {\n return this.queryManager.transform(this.options.query).document;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(ObservableQuery.prototype, \"variables\", {\n get: function () {\n return this.options.variables;\n },\n enumerable: false,\n configurable: true\n });\n ObservableQuery.prototype.result = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n var observer = {\n next: function (result) {\n resolve(result);\n _this.observers.delete(observer);\n if (!_this.observers.size) {\n _this.queryManager.removeQuery(_this.queryId);\n }\n setTimeout(function () {\n subscription.unsubscribe();\n }, 0);\n },\n error: reject,\n };\n var subscription = _this.subscribe(observer);\n });\n };\n ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {\n if (saveAsLastResult === void 0) { saveAsLastResult = true; }\n var lastResult = this.getLastResult(true);\n var networkStatus = this.queryInfo.networkStatus ||\n (lastResult && lastResult.networkStatus) ||\n NetworkStatus.ready;\n var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });\n var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a;\n if (fetchPolicy === 'network-only' ||\n fetchPolicy === 'no-cache' ||\n fetchPolicy === 'standby' ||\n this.queryManager.transform(this.options.query).hasForcedResolvers) {\n }\n else {\n var diff = this.queryInfo.getDiff();\n if (diff.complete || this.options.returnPartialData) {\n result.data = diff.result;\n }\n if (equal(result.data, {})) {\n result.data = void 0;\n }\n if (diff.complete) {\n delete result.partial;\n if (diff.complete &&\n result.networkStatus === NetworkStatus.loading &&\n (fetchPolicy === 'cache-first' ||\n fetchPolicy === 'cache-only')) {\n result.networkStatus = NetworkStatus.ready;\n result.loading = false;\n }\n }\n else {\n result.partial = true;\n }\n if (__DEV__ &&\n !diff.complete &&\n !this.options.partialRefetch &&\n !result.loading &&\n !result.data &&\n !result.error) {\n logMissingFieldErrors(diff.missing);\n }\n }\n if (saveAsLastResult) {\n this.updateLastResult(result);\n }\n return result;\n };\n ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {\n return (!this.last ||\n !equal(this.last.result, newResult) ||\n (variables && !equal(this.last.variables, variables)));\n };\n ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {\n var last = this.last;\n if (last &&\n last[key] &&\n (!variablesMustMatch || equal(last.variables, this.variables))) {\n return last[key];\n }\n };\n ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {\n return this.getLast(\"result\", variablesMustMatch);\n };\n ObservableQuery.prototype.getLastError = function (variablesMustMatch) {\n return this.getLast(\"error\", variablesMustMatch);\n };\n ObservableQuery.prototype.resetLastResults = function () {\n delete this.last;\n this.isTornDown = false;\n };\n ObservableQuery.prototype.resetQueryStoreErrors = function () {\n this.queryManager.resetErrors(this.queryId);\n };\n ObservableQuery.prototype.refetch = function (variables) {\n var _a;\n var reobserveOptions = {\n pollInterval: 0,\n };\n var fetchPolicy = this.options.fetchPolicy;\n if (fetchPolicy === 'cache-and-network') {\n reobserveOptions.fetchPolicy = fetchPolicy;\n }\n else if (fetchPolicy === 'no-cache') {\n reobserveOptions.fetchPolicy = 'no-cache';\n }\n else {\n reobserveOptions.fetchPolicy = 'network-only';\n }\n if (__DEV__ && variables && hasOwnProperty.call(variables, \"variables\")) {\n var queryDef = getQueryDefinition(this.query);\n var vars = queryDef.variableDefinitions;\n if (!vars || !vars.some(function (v) { return v.variable.name.value === \"variables\"; })) {\n __DEV__ && invariant.warn(\"Called refetch(\".concat(JSON.stringify(variables), \") for query \").concat(((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || JSON.stringify(queryDef), \", which does not declare a $variables variable.\\nDid you mean to call refetch(variables) instead of refetch({ variables })?\"));\n }\n }\n if (variables && !equal(this.options.variables, variables)) {\n reobserveOptions.variables = this.options.variables = __assign(__assign({}, this.options.variables), variables);\n }\n this.queryInfo.resetLastWrite();\n return this.reobserve(reobserveOptions, NetworkStatus.refetch);\n };\n ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {\n var _this = this;\n var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : __assign(__assign(__assign(__assign({}, this.options), { query: this.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) }))), { fetchPolicy: \"no-cache\" });\n var qid = this.queryManager.generateQueryId();\n var queryInfo = this.queryInfo;\n var originalNetworkStatus = queryInfo.networkStatus;\n queryInfo.networkStatus = NetworkStatus.fetchMore;\n if (combinedOptions.notifyOnNetworkStatusChange) {\n this.observe();\n }\n var updatedQuerySet = new Set();\n return this.queryManager.fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore).then(function (fetchMoreResult) {\n _this.queryManager.removeQuery(qid);\n if (queryInfo.networkStatus === NetworkStatus.fetchMore) {\n queryInfo.networkStatus = originalNetworkStatus;\n }\n _this.queryManager.cache.batch({\n update: function (cache) {\n var updateQuery = fetchMoreOptions.updateQuery;\n if (updateQuery) {\n cache.updateQuery({\n query: _this.query,\n variables: _this.variables,\n returnPartialData: true,\n optimistic: false,\n }, function (previous) { return updateQuery(previous, {\n fetchMoreResult: fetchMoreResult.data,\n variables: combinedOptions.variables,\n }); });\n }\n else {\n cache.writeQuery({\n query: combinedOptions.query,\n variables: combinedOptions.variables,\n data: fetchMoreResult.data,\n });\n }\n },\n onWatchUpdated: function (watch) {\n updatedQuerySet.add(watch.query);\n },\n });\n return fetchMoreResult;\n }).finally(function () {\n if (!updatedQuerySet.has(_this.query)) {\n reobserveCacheFirst(_this);\n }\n });\n };\n ObservableQuery.prototype.subscribeToMore = function (options) {\n var _this = this;\n var subscription = this.queryManager\n .startGraphQLSubscription({\n query: options.document,\n variables: options.variables,\n context: options.context,\n })\n .subscribe({\n next: function (subscriptionData) {\n var updateQuery = options.updateQuery;\n if (updateQuery) {\n _this.updateQuery(function (previous, _a) {\n var variables = _a.variables;\n return updateQuery(previous, {\n subscriptionData: subscriptionData,\n variables: variables,\n });\n });\n }\n },\n error: function (err) {\n if (options.onError) {\n options.onError(err);\n return;\n }\n __DEV__ && invariant.error('Unhandled GraphQL subscription error', err);\n },\n });\n this.subscriptions.add(subscription);\n return function () {\n if (_this.subscriptions.delete(subscription)) {\n subscription.unsubscribe();\n }\n };\n };\n ObservableQuery.prototype.setOptions = function (newOptions) {\n return this.reobserve(newOptions);\n };\n ObservableQuery.prototype.setVariables = function (variables) {\n if (equal(this.variables, variables)) {\n return this.observers.size\n ? this.result()\n : Promise.resolve();\n }\n this.options.variables = variables;\n if (!this.observers.size) {\n return Promise.resolve();\n }\n return this.reobserve({\n fetchPolicy: this.options.initialFetchPolicy,\n variables: variables,\n }, NetworkStatus.setVariables);\n };\n ObservableQuery.prototype.updateQuery = function (mapFn) {\n var queryManager = this.queryManager;\n var result = queryManager.cache.diff({\n query: this.options.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n var newResult = mapFn(result, {\n variables: this.variables,\n });\n if (newResult) {\n queryManager.cache.writeQuery({\n query: this.options.query,\n data: newResult,\n variables: this.variables,\n });\n queryManager.broadcastQueries();\n }\n };\n ObservableQuery.prototype.startPolling = function (pollInterval) {\n this.options.pollInterval = pollInterval;\n this.updatePolling();\n };\n ObservableQuery.prototype.stopPolling = function () {\n this.options.pollInterval = 0;\n this.updatePolling();\n };\n ObservableQuery.prototype.applyNextFetchPolicy = function (reason, options) {\n if (options.nextFetchPolicy) {\n var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? \"cache-first\" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;\n if (fetchPolicy === \"standby\") {\n }\n else if (typeof options.nextFetchPolicy === \"function\") {\n options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {\n reason: reason,\n options: options,\n observable: this,\n initialFetchPolicy: initialFetchPolicy,\n });\n }\n else if (reason === \"variables-changed\") {\n options.fetchPolicy = initialFetchPolicy;\n }\n else {\n options.fetchPolicy = options.nextFetchPolicy;\n }\n }\n return options.fetchPolicy;\n };\n ObservableQuery.prototype.fetch = function (options, newNetworkStatus) {\n this.queryManager.setObservableQuery(this);\n return this.queryManager.fetchQueryObservable(this.queryId, options, newNetworkStatus);\n };\n ObservableQuery.prototype.updatePolling = function () {\n var _this = this;\n if (this.queryManager.ssrMode) {\n return;\n }\n var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;\n if (!pollInterval) {\n if (pollingInfo) {\n clearTimeout(pollingInfo.timeout);\n delete this.pollingInfo;\n }\n return;\n }\n if (pollingInfo &&\n pollingInfo.interval === pollInterval) {\n return;\n }\n __DEV__ ? invariant(pollInterval, 'Attempted to start a polling query without a polling interval.') : invariant(pollInterval, 13);\n var info = pollingInfo || (this.pollingInfo = {});\n info.interval = pollInterval;\n var maybeFetch = function () {\n if (_this.pollingInfo) {\n if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus)) {\n _this.reobserve({\n fetchPolicy: _this.options.initialFetchPolicy === 'no-cache' ? 'no-cache' : 'network-only',\n }, NetworkStatus.poll).then(poll, poll);\n }\n else {\n poll();\n }\n }\n ;\n };\n var poll = function () {\n var info = _this.pollingInfo;\n if (info) {\n clearTimeout(info.timeout);\n info.timeout = setTimeout(maybeFetch, info.interval);\n }\n };\n poll();\n };\n ObservableQuery.prototype.updateLastResult = function (newResult, variables) {\n if (variables === void 0) { variables = this.variables; }\n this.last = __assign(__assign({}, this.last), { result: this.queryManager.assumeImmutableResults\n ? newResult\n : cloneDeep(newResult), variables: variables });\n if (!isNonEmptyArray(newResult.errors)) {\n delete this.last.error;\n }\n return this.last;\n };\n ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {\n var _this = this;\n this.isTornDown = false;\n var useDisposableConcast = newNetworkStatus === NetworkStatus.refetch ||\n newNetworkStatus === NetworkStatus.fetchMore ||\n newNetworkStatus === NetworkStatus.poll;\n var oldVariables = this.options.variables;\n var oldFetchPolicy = this.options.fetchPolicy;\n var mergedOptions = compact(this.options, newOptions || {});\n var options = useDisposableConcast\n ? mergedOptions\n : assign(this.options, mergedOptions);\n if (!useDisposableConcast) {\n this.updatePolling();\n if (newOptions &&\n newOptions.variables &&\n !equal(newOptions.variables, oldVariables) &&\n options.fetchPolicy !== \"standby\" &&\n options.fetchPolicy === oldFetchPolicy) {\n this.applyNextFetchPolicy(\"variables-changed\", options);\n if (newNetworkStatus === void 0) {\n newNetworkStatus = NetworkStatus.setVariables;\n }\n }\n }\n var variables = options.variables && __assign({}, options.variables);\n var concast = this.fetch(options, newNetworkStatus);\n var observer = {\n next: function (result) {\n _this.reportResult(result, variables);\n },\n error: function (error) {\n _this.reportError(error, variables);\n },\n };\n if (!useDisposableConcast) {\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n }\n this.concast = concast;\n this.observer = observer;\n }\n concast.addObserver(observer);\n return concast.promise;\n };\n ObservableQuery.prototype.observe = function () {\n this.reportResult(this.getCurrentResult(false), this.variables);\n };\n ObservableQuery.prototype.reportResult = function (result, variables) {\n var lastError = this.getLastError();\n if (lastError || this.isDifferentFromLastResult(result, variables)) {\n if (lastError || !result.partial || this.options.returnPartialData) {\n this.updateLastResult(result, variables);\n }\n iterateObserversSafely(this.observers, 'next', result);\n }\n };\n ObservableQuery.prototype.reportError = function (error, variables) {\n var errorResult = __assign(__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });\n this.updateLastResult(errorResult, variables);\n iterateObserversSafely(this.observers, 'error', this.last.error = error);\n };\n ObservableQuery.prototype.hasObservers = function () {\n return this.observers.size > 0;\n };\n ObservableQuery.prototype.tearDownQuery = function () {\n if (this.isTornDown)\n return;\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n delete this.concast;\n delete this.observer;\n }\n this.stopPolling();\n this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });\n this.subscriptions.clear();\n this.queryManager.stopQuery(this.queryId);\n this.observers.clear();\n this.isTornDown = true;\n };\n return ObservableQuery;\n}(Observable));\nexport { ObservableQuery };\nfixObservableSubclass(ObservableQuery);\nexport function reobserveCacheFirst(obsQuery) {\n var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;\n if (fetchPolicy === \"cache-and-network\" ||\n fetchPolicy === \"network-only\") {\n return obsQuery.reobserve({\n fetchPolicy: \"cache-first\",\n nextFetchPolicy: function () {\n this.nextFetchPolicy = nextFetchPolicy;\n if (typeof nextFetchPolicy === \"function\") {\n return nextFetchPolicy.apply(this, arguments);\n }\n return fetchPolicy;\n },\n });\n }\n return obsQuery.reobserve();\n}\nfunction defaultSubscriptionObserverErrorCallback(error) {\n __DEV__ && invariant.error('Unhandled error', error.message, error.stack);\n}\nexport function logMissingFieldErrors(missing) {\n if (__DEV__ && missing) {\n __DEV__ && invariant.debug(\"Missing cache result fields: \".concat(JSON.stringify(missing)), missing);\n }\n}\n//# sourceMappingURL=ObservableQuery.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant } from '../utilities/globals';\nimport { visit, BREAK, isSelectionNode, } from 'graphql';\nimport { argumentsObjectFromField, buildQueryFromSelectionSet, createFragmentMap, getFragmentDefinitions, getMainDefinition, hasDirectives, isField, isInlineFragment, mergeDeep, mergeDeepArray, removeClientSetsFromDocument, resultKeyNameFromField, shouldInclude, } from '../utilities';\nimport { cacheSlot } from '../cache';\nvar LocalState = (function () {\n function LocalState(_a) {\n var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;\n this.selectionsToResolveCache = new WeakMap();\n this.cache = cache;\n if (client) {\n this.client = client;\n }\n if (resolvers) {\n this.addResolvers(resolvers);\n }\n if (fragmentMatcher) {\n this.setFragmentMatcher(fragmentMatcher);\n }\n }\n LocalState.prototype.addResolvers = function (resolvers) {\n var _this = this;\n this.resolvers = this.resolvers || {};\n if (Array.isArray(resolvers)) {\n resolvers.forEach(function (resolverGroup) {\n _this.resolvers = mergeDeep(_this.resolvers, resolverGroup);\n });\n }\n else {\n this.resolvers = mergeDeep(this.resolvers, resolvers);\n }\n };\n LocalState.prototype.setResolvers = function (resolvers) {\n this.resolvers = {};\n this.addResolvers(resolvers);\n };\n LocalState.prototype.getResolvers = function () {\n return this.resolvers || {};\n };\n LocalState.prototype.runResolvers = function (_a) {\n var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_c) {\n if (document) {\n return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];\n }\n return [2, remoteResult];\n });\n });\n };\n LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {\n this.fragmentMatcher = fragmentMatcher;\n };\n LocalState.prototype.getFragmentMatcher = function () {\n return this.fragmentMatcher;\n };\n LocalState.prototype.clientQuery = function (document) {\n if (hasDirectives(['client'], document)) {\n if (this.resolvers) {\n return document;\n }\n }\n return null;\n };\n LocalState.prototype.serverQuery = function (document) {\n return removeClientSetsFromDocument(document);\n };\n LocalState.prototype.prepareContext = function (context) {\n var cache = this.cache;\n return __assign(__assign({}, context), { cache: cache, getCacheKey: function (obj) {\n return cache.identify(obj);\n } });\n };\n LocalState.prototype.addExportedVariables = function (document, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (context === void 0) { context = {}; }\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (document) {\n return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];\n }\n return [2, __assign({}, variables)];\n });\n });\n };\n LocalState.prototype.shouldForceResolvers = function (document) {\n var forceResolvers = false;\n visit(document, {\n Directive: {\n enter: function (node) {\n if (node.name.value === 'client' && node.arguments) {\n forceResolvers = node.arguments.some(function (arg) {\n return arg.name.value === 'always' &&\n arg.value.kind === 'BooleanValue' &&\n arg.value.value === true;\n });\n if (forceResolvers) {\n return BREAK;\n }\n }\n },\n },\n });\n return forceResolvers;\n };\n LocalState.prototype.buildRootValueFromCache = function (document, variables) {\n return this.cache.diff({\n query: buildQueryFromSelectionSet(document),\n variables: variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n };\n LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {\n if (context === void 0) { context = {}; }\n if (variables === void 0) { variables = {}; }\n if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }\n if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }\n return __awaiter(this, void 0, void 0, function () {\n var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;\n return __generator(this, function (_b) {\n mainDefinition = getMainDefinition(document);\n fragments = getFragmentDefinitions(document);\n fragmentMap = createFragmentMap(fragments);\n selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);\n definitionOperation = mainDefinition.operation;\n defaultOperationType = definitionOperation\n ? definitionOperation.charAt(0).toUpperCase() +\n definitionOperation.slice(1)\n : 'Query';\n _a = this, cache = _a.cache, client = _a.client;\n execContext = {\n fragmentMap: fragmentMap,\n context: __assign(__assign({}, context), { cache: cache, client: client }),\n variables: variables,\n fragmentMatcher: fragmentMatcher,\n defaultOperationType: defaultOperationType,\n exportedVariables: {},\n selectionsToResolve: selectionsToResolve,\n onlyRunForcedResolvers: onlyRunForcedResolvers,\n };\n isClientFieldDescendant = false;\n return [2, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({\n result: result,\n exportedVariables: execContext.exportedVariables,\n }); })];\n });\n });\n };\n LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {\n return __awaiter(this, void 0, void 0, function () {\n var fragmentMap, context, variables, resultsToMerge, execute;\n var _this = this;\n return __generator(this, function (_a) {\n fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;\n resultsToMerge = [rootValue];\n execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {\n var fragment, typeCondition;\n return __generator(this, function (_a) {\n if (!isClientFieldDescendant && !execContext.selectionsToResolve.has(selection)) {\n return [2];\n }\n if (!shouldInclude(selection, variables)) {\n return [2];\n }\n if (isField(selection)) {\n return [2, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {\n var _a;\n if (typeof fieldResult !== 'undefined') {\n resultsToMerge.push((_a = {},\n _a[resultKeyNameFromField(selection)] = fieldResult,\n _a));\n }\n })];\n }\n if (isInlineFragment(selection)) {\n fragment = selection;\n }\n else {\n fragment = fragmentMap[selection.name.value];\n __DEV__ ? invariant(fragment, \"No fragment named \".concat(selection.name.value)) : invariant(fragment, 11);\n }\n if (fragment && fragment.typeCondition) {\n typeCondition = fragment.typeCondition.name.value;\n if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {\n return [2, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {\n resultsToMerge.push(fragmentResult);\n })];\n }\n }\n return [2];\n });\n }); };\n return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {\n return mergeDeepArray(resultsToMerge);\n })];\n });\n });\n };\n LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {\n return __awaiter(this, void 0, void 0, function () {\n var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;\n var _this = this;\n return __generator(this, function (_a) {\n if (!rootValue) {\n return [2, null];\n }\n variables = execContext.variables;\n fieldName = field.name.value;\n aliasedFieldName = resultKeyNameFromField(field);\n aliasUsed = fieldName !== aliasedFieldName;\n defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];\n resultPromise = Promise.resolve(defaultResult);\n if (!execContext.onlyRunForcedResolvers ||\n this.shouldForceResolvers(field)) {\n resolverType = rootValue.__typename || execContext.defaultOperationType;\n resolverMap = this.resolvers && this.resolvers[resolverType];\n if (resolverMap) {\n resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];\n if (resolve) {\n resultPromise = Promise.resolve(cacheSlot.withValue(this.cache, resolve, [\n rootValue,\n argumentsObjectFromField(field, variables),\n execContext.context,\n { field: field, fragmentMap: execContext.fragmentMap },\n ]));\n }\n }\n }\n return [2, resultPromise.then(function (result) {\n var _a, _b;\n if (result === void 0) { result = defaultResult; }\n if (field.directives) {\n field.directives.forEach(function (directive) {\n if (directive.name.value === 'export' && directive.arguments) {\n directive.arguments.forEach(function (arg) {\n if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {\n execContext.exportedVariables[arg.value.value] = result;\n }\n });\n }\n });\n }\n if (!field.selectionSet) {\n return result;\n }\n if (result == null) {\n return result;\n }\n var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === 'client'; })) !== null && _b !== void 0 ? _b : false;\n if (Array.isArray(result)) {\n return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);\n }\n if (field.selectionSet) {\n return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);\n }\n })];\n });\n });\n };\n LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {\n var _this = this;\n return Promise.all(result.map(function (item) {\n if (item === null) {\n return null;\n }\n if (Array.isArray(item)) {\n return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);\n }\n if (field.selectionSet) {\n return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);\n }\n }));\n };\n LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {\n var isSingleASTNode = function (node) { return !Array.isArray(node); };\n var selectionsToResolveCache = this.selectionsToResolveCache;\n function collectByDefinition(definitionNode) {\n if (!selectionsToResolveCache.has(definitionNode)) {\n var matches_1 = new Set();\n selectionsToResolveCache.set(definitionNode, matches_1);\n visit(definitionNode, {\n Directive: function (node, _, __, ___, ancestors) {\n if (node.name.value === 'client') {\n ancestors.forEach(function (node) {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches_1.add(node);\n }\n });\n }\n },\n FragmentSpread: function (spread, _, __, ___, ancestors) {\n var fragment = fragmentMap[spread.name.value];\n __DEV__ ? invariant(fragment, \"No fragment named \".concat(spread.name.value)) : invariant(fragment, 12);\n var fragmentSelections = collectByDefinition(fragment);\n if (fragmentSelections.size > 0) {\n ancestors.forEach(function (node) {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches_1.add(node);\n }\n });\n matches_1.add(spread);\n fragmentSelections.forEach(function (selection) {\n matches_1.add(selection);\n });\n }\n }\n });\n }\n return selectionsToResolveCache.get(definitionNode);\n }\n return collectByDefinition(mainDefinition);\n };\n return LocalState;\n}());\nexport { LocalState };\n//# sourceMappingURL=LocalState.js.map","import { __assign } from \"tslib\";\nimport { equal } from \"@wry/equality\";\nimport { DeepMerger } from \"../utilities\";\nimport { mergeIncrementalData } from '../utilities/common/incrementalResult';\nimport { reobserveCacheFirst } from './ObservableQuery';\nimport { isNonEmptyArray, graphQLResultHasError, canUseWeakMap, } from '../utilities';\nimport { NetworkStatus, isNetworkRequestInFlight, } from './networkStatus';\n;\nvar destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();\nfunction wrapDestructiveCacheMethod(cache, methodName) {\n var original = cache[methodName];\n if (typeof original === \"function\") {\n cache[methodName] = function () {\n destructiveMethodCounts.set(cache, (destructiveMethodCounts.get(cache) + 1) % 1e15);\n return original.apply(this, arguments);\n };\n }\n}\nfunction cancelNotifyTimeout(info) {\n if (info[\"notifyTimeout\"]) {\n clearTimeout(info[\"notifyTimeout\"]);\n info[\"notifyTimeout\"] = void 0;\n }\n}\nvar QueryInfo = (function () {\n function QueryInfo(queryManager, queryId) {\n if (queryId === void 0) { queryId = queryManager.generateQueryId(); }\n this.queryId = queryId;\n this.listeners = new Set();\n this.document = null;\n this.lastRequestId = 1;\n this.subscriptions = new Set();\n this.stopped = false;\n this.dirty = false;\n this.observableQuery = null;\n var cache = this.cache = queryManager.cache;\n if (!destructiveMethodCounts.has(cache)) {\n destructiveMethodCounts.set(cache, 0);\n wrapDestructiveCacheMethod(cache, \"evict\");\n wrapDestructiveCacheMethod(cache, \"modify\");\n wrapDestructiveCacheMethod(cache, \"reset\");\n }\n }\n QueryInfo.prototype.init = function (query) {\n var networkStatus = query.networkStatus || NetworkStatus.loading;\n if (this.variables &&\n this.networkStatus !== NetworkStatus.loading &&\n !equal(this.variables, query.variables)) {\n networkStatus = NetworkStatus.setVariables;\n }\n if (!equal(query.variables, this.variables)) {\n this.lastDiff = void 0;\n }\n Object.assign(this, {\n document: query.document,\n variables: query.variables,\n networkError: null,\n graphQLErrors: this.graphQLErrors || [],\n networkStatus: networkStatus,\n });\n if (query.observableQuery) {\n this.setObservableQuery(query.observableQuery);\n }\n if (query.lastRequestId) {\n this.lastRequestId = query.lastRequestId;\n }\n return this;\n };\n QueryInfo.prototype.reset = function () {\n cancelNotifyTimeout(this);\n this.dirty = false;\n };\n QueryInfo.prototype.getDiff = function (variables) {\n if (variables === void 0) { variables = this.variables; }\n var options = this.getDiffOptions(variables);\n if (this.lastDiff && equal(options, this.lastDiff.options)) {\n return this.lastDiff.diff;\n }\n this.updateWatch(this.variables = variables);\n var oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return { complete: false };\n }\n var diff = this.cache.diff(options);\n this.updateLastDiff(diff, options);\n return diff;\n };\n QueryInfo.prototype.updateLastDiff = function (diff, options) {\n this.lastDiff = diff ? {\n diff: diff,\n options: options || this.getDiffOptions(),\n } : void 0;\n };\n QueryInfo.prototype.getDiffOptions = function (variables) {\n var _a;\n if (variables === void 0) { variables = this.variables; }\n return {\n query: this.document,\n variables: variables,\n returnPartialData: true,\n optimistic: true,\n canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,\n };\n };\n QueryInfo.prototype.setDiff = function (diff) {\n var _this = this;\n var oldDiff = this.lastDiff && this.lastDiff.diff;\n this.updateLastDiff(diff);\n if (!this.dirty &&\n !equal(oldDiff && oldDiff.result, diff && diff.result)) {\n this.dirty = true;\n if (!this.notifyTimeout) {\n this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);\n }\n }\n };\n QueryInfo.prototype.setObservableQuery = function (oq) {\n var _this = this;\n if (oq === this.observableQuery)\n return;\n if (this.oqListener) {\n this.listeners.delete(this.oqListener);\n }\n this.observableQuery = oq;\n if (oq) {\n oq[\"queryInfo\"] = this;\n this.listeners.add(this.oqListener = function () {\n var diff = _this.getDiff();\n if (diff.fromOptimisticTransaction) {\n oq[\"observe\"]();\n }\n else {\n reobserveCacheFirst(oq);\n }\n });\n }\n else {\n delete this.oqListener;\n }\n };\n QueryInfo.prototype.notify = function () {\n var _this = this;\n cancelNotifyTimeout(this);\n if (this.shouldNotify()) {\n this.listeners.forEach(function (listener) { return listener(_this); });\n }\n this.dirty = false;\n };\n QueryInfo.prototype.shouldNotify = function () {\n if (!this.dirty || !this.listeners.size) {\n return false;\n }\n if (isNetworkRequestInFlight(this.networkStatus) &&\n this.observableQuery) {\n var fetchPolicy = this.observableQuery.options.fetchPolicy;\n if (fetchPolicy !== \"cache-only\" &&\n fetchPolicy !== \"cache-and-network\") {\n return false;\n }\n }\n return true;\n };\n QueryInfo.prototype.stop = function () {\n if (!this.stopped) {\n this.stopped = true;\n this.reset();\n this.cancel();\n this.cancel = QueryInfo.prototype.cancel;\n this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });\n var oq = this.observableQuery;\n if (oq)\n oq.stopPolling();\n }\n };\n QueryInfo.prototype.cancel = function () { };\n QueryInfo.prototype.updateWatch = function (variables) {\n var _this = this;\n if (variables === void 0) { variables = this.variables; }\n var oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return;\n }\n var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });\n if (!this.lastWatch ||\n !equal(watchOptions, this.lastWatch)) {\n this.cancel();\n this.cancel = this.cache.watch(this.lastWatch = watchOptions);\n }\n };\n QueryInfo.prototype.resetLastWrite = function () {\n this.lastWrite = void 0;\n };\n QueryInfo.prototype.shouldWrite = function (result, variables) {\n var lastWrite = this.lastWrite;\n return !(lastWrite &&\n lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&\n equal(variables, lastWrite.variables) &&\n equal(result.data, lastWrite.result.data));\n };\n QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {\n var _this = this;\n var merger = new DeepMerger();\n var graphQLErrors = isNonEmptyArray(result.errors)\n ? result.errors.slice(0)\n : [];\n this.reset();\n if ('incremental' in result && isNonEmptyArray(result.incremental)) {\n var mergedData = mergeIncrementalData(this.getDiff().result, result);\n result.data = mergedData;\n }\n else if ('hasNext' in result && result.hasNext) {\n var diff = this.getDiff();\n result.data = merger.merge(diff.result, result.data);\n }\n this.graphQLErrors = graphQLErrors;\n if (options.fetchPolicy === 'no-cache') {\n this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));\n }\n else if (cacheWriteBehavior !== 0) {\n if (shouldWriteResult(result, options.errorPolicy)) {\n this.cache.performTransaction(function (cache) {\n if (_this.shouldWrite(result, options.variables)) {\n cache.writeQuery({\n query: document,\n data: result.data,\n variables: options.variables,\n overwrite: cacheWriteBehavior === 1,\n });\n _this.lastWrite = {\n result: result,\n variables: options.variables,\n dmCount: destructiveMethodCounts.get(_this.cache),\n };\n }\n else {\n if (_this.lastDiff &&\n _this.lastDiff.diff.complete) {\n result.data = _this.lastDiff.diff.result;\n return;\n }\n }\n var diffOptions = _this.getDiffOptions(options.variables);\n var diff = cache.diff(diffOptions);\n if (!_this.stopped) {\n _this.updateWatch(options.variables);\n }\n _this.updateLastDiff(diff, diffOptions);\n if (diff.complete) {\n result.data = diff.result;\n }\n });\n }\n else {\n this.lastWrite = void 0;\n }\n }\n };\n QueryInfo.prototype.markReady = function () {\n this.networkError = null;\n return this.networkStatus = NetworkStatus.ready;\n };\n QueryInfo.prototype.markError = function (error) {\n this.networkStatus = NetworkStatus.error;\n this.lastWrite = void 0;\n this.reset();\n if (error.graphQLErrors) {\n this.graphQLErrors = error.graphQLErrors;\n }\n if (error.networkError) {\n this.networkError = error.networkError;\n }\n return error;\n };\n return QueryInfo;\n}());\nexport { QueryInfo };\nexport function shouldWriteResult(result, errorPolicy) {\n if (errorPolicy === void 0) { errorPolicy = \"none\"; }\n var ignoreErrors = errorPolicy === \"ignore\" ||\n errorPolicy === \"all\";\n var writeWithErrors = !graphQLResultHasError(result);\n if (!writeWithErrors && ignoreErrors && result.data) {\n writeWithErrors = true;\n }\n return writeWithErrors;\n}\n//# sourceMappingURL=QueryInfo.js.map","import { __assign, __awaiter, __generator } from \"tslib\";\nimport { invariant, InvariantError } from '../utilities/globals';\nimport { equal } from '@wry/equality';\nimport { execute } from '../link/core';\nimport { isExecutionPatchIncrementalResult, isExecutionPatchResult, } from '../utilities/common/incrementalResult';\nimport { canonicalStringify } from '../cache';\nimport { getDefaultValues, getOperationDefinition, getOperationName, hasClientExports, graphQLResultHasError, getGraphQLErrorsFromResult, removeConnectionDirectiveFromDocument, canUseWeakMap, Observable, asyncMap, isNonEmptyArray, Concast, makeUniqueId, isDocumentNode, isNonNullObject, } from '../utilities';\nimport { mergeIncrementalData } from '../utilities/common/incrementalResult';\nimport { ApolloError, isApolloError } from '../errors';\nimport { ObservableQuery, logMissingFieldErrors } from './ObservableQuery';\nimport { NetworkStatus, isNetworkRequestInFlight } from './networkStatus';\nimport { LocalState } from './LocalState';\nimport { QueryInfo, shouldWriteResult, } from './QueryInfo';\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar QueryManager = (function () {\n function QueryManager(_a) {\n var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;\n this.clientAwareness = {};\n this.queries = new Map();\n this.fetchCancelFns = new Map();\n this.transformCache = new (canUseWeakMap ? WeakMap : Map)();\n this.queryIdCounter = 1;\n this.requestIdCounter = 1;\n this.mutationIdCounter = 1;\n this.inFlightLinkObservables = new Map();\n this.cache = cache;\n this.link = link;\n this.defaultOptions = defaultOptions || Object.create(null);\n this.queryDeduplication = queryDeduplication;\n this.clientAwareness = clientAwareness;\n this.localState = localState || new LocalState({ cache: cache });\n this.ssrMode = ssrMode;\n this.assumeImmutableResults = !!assumeImmutableResults;\n if ((this.onBroadcast = onBroadcast)) {\n this.mutationStore = Object.create(null);\n }\n }\n QueryManager.prototype.stop = function () {\n var _this = this;\n this.queries.forEach(function (_info, queryId) {\n _this.stopQueryNoBroadcast(queryId);\n });\n this.cancelPendingFetches(__DEV__ ? new InvariantError('QueryManager stopped while query was in flight') : new InvariantError(14));\n };\n QueryManager.prototype.cancelPendingFetches = function (error) {\n this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });\n this.fetchCancelFns.clear();\n };\n QueryManager.prototype.mutate = function (_a) {\n var _b, _c;\n var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueries = _a.updateQueries, _d = _a.refetchQueries, refetchQueries = _d === void 0 ? [] : _d, _e = _a.awaitRefetchQueries, awaitRefetchQueries = _e === void 0 ? false : _e, updateWithProxyFn = _a.update, onQueryUpdated = _a.onQueryUpdated, _f = _a.fetchPolicy, fetchPolicy = _f === void 0 ? ((_b = this.defaultOptions.mutate) === null || _b === void 0 ? void 0 : _b.fetchPolicy) || \"network-only\" : _f, _g = _a.errorPolicy, errorPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.errorPolicy) || \"none\" : _g, keepRootFields = _a.keepRootFields, context = _a.context;\n return __awaiter(this, void 0, void 0, function () {\n var mutationId, _h, document, hasClientExports, mutationStoreValue, self;\n return __generator(this, function (_j) {\n switch (_j.label) {\n case 0:\n __DEV__ ? invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.') : invariant(mutation, 15);\n __DEV__ ? invariant(fetchPolicy === 'network-only' ||\n fetchPolicy === 'no-cache', \"Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write.\") : invariant(fetchPolicy === 'network-only' ||\n fetchPolicy === 'no-cache', 16);\n mutationId = this.generateMutationId();\n _h = this.transform(mutation), document = _h.document, hasClientExports = _h.hasClientExports;\n mutation = this.cache.transformForLink(document);\n variables = this.getVariables(mutation, variables);\n if (!hasClientExports) return [3, 2];\n return [4, this.localState.addExportedVariables(mutation, variables, context)];\n case 1:\n variables = (_j.sent());\n _j.label = 2;\n case 2:\n mutationStoreValue = this.mutationStore &&\n (this.mutationStore[mutationId] = {\n mutation: mutation,\n variables: variables,\n loading: true,\n error: null,\n });\n if (optimisticResponse) {\n this.markMutationOptimistic(optimisticResponse, {\n mutationId: mutationId,\n document: mutation,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n context: context,\n updateQueries: updateQueries,\n update: updateWithProxyFn,\n keepRootFields: keepRootFields,\n });\n }\n this.broadcastQueries();\n self = this;\n return [2, new Promise(function (resolve, reject) {\n return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false), function (result) {\n if (graphQLResultHasError(result) && errorPolicy === 'none') {\n throw new ApolloError({\n graphQLErrors: getGraphQLErrorsFromResult(result),\n });\n }\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = null;\n }\n var storeResult = __assign({}, result);\n if (typeof refetchQueries === \"function\") {\n refetchQueries = refetchQueries(storeResult);\n }\n if (errorPolicy === 'ignore' &&\n graphQLResultHasError(storeResult)) {\n delete storeResult.errors;\n }\n return self.markMutationResult({\n mutationId: mutationId,\n result: storeResult,\n document: mutation,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n context: context,\n update: updateWithProxyFn,\n updateQueries: updateQueries,\n awaitRefetchQueries: awaitRefetchQueries,\n refetchQueries: refetchQueries,\n removeOptimistic: optimisticResponse ? mutationId : void 0,\n onQueryUpdated: onQueryUpdated,\n keepRootFields: keepRootFields,\n });\n }).subscribe({\n next: function (storeResult) {\n self.broadcastQueries();\n if (!('hasNext' in storeResult) || storeResult.hasNext === false) {\n resolve(storeResult);\n }\n },\n error: function (err) {\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = err;\n }\n if (optimisticResponse) {\n self.cache.removeOptimistic(mutationId);\n }\n self.broadcastQueries();\n reject(err instanceof ApolloError ? err : new ApolloError({\n networkError: err,\n }));\n },\n });\n })];\n }\n });\n });\n };\n QueryManager.prototype.markMutationResult = function (mutation, cache) {\n var _this = this;\n if (cache === void 0) { cache = this.cache; }\n var result = mutation.result;\n var cacheWrites = [];\n var skipCache = mutation.fetchPolicy === \"no-cache\";\n if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {\n if (!isExecutionPatchIncrementalResult(result)) {\n cacheWrites.push({\n result: result.data,\n dataId: 'ROOT_MUTATION',\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n if (isExecutionPatchIncrementalResult(result) && isNonEmptyArray(result.incremental)) {\n var diff = cache.diff({\n id: \"ROOT_MUTATION\",\n query: this.transform(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n var mergedData = void 0;\n if (diff.result) {\n mergedData = mergeIncrementalData(diff.result, result);\n }\n if (typeof mergedData !== 'undefined') {\n result.data = mergedData;\n cacheWrites.push({\n result: mergedData,\n dataId: 'ROOT_MUTATION',\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n }\n var updateQueries_1 = mutation.updateQueries;\n if (updateQueries_1) {\n this.queries.forEach(function (_a, queryId) {\n var observableQuery = _a.observableQuery;\n var queryName = observableQuery && observableQuery.queryName;\n if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {\n return;\n }\n var updater = updateQueries_1[queryName];\n var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;\n var _c = cache.diff({\n query: document,\n variables: variables,\n returnPartialData: true,\n optimistic: false,\n }), currentQueryResult = _c.result, complete = _c.complete;\n if (complete && currentQueryResult) {\n var nextQueryResult = updater(currentQueryResult, {\n mutationResult: result,\n queryName: document && getOperationName(document) || void 0,\n queryVariables: variables,\n });\n if (nextQueryResult) {\n cacheWrites.push({\n result: nextQueryResult,\n dataId: 'ROOT_QUERY',\n query: document,\n variables: variables,\n });\n }\n }\n });\n }\n }\n if (cacheWrites.length > 0 ||\n mutation.refetchQueries ||\n mutation.update ||\n mutation.onQueryUpdated ||\n mutation.removeOptimistic) {\n var results_1 = [];\n this.refetchQueries({\n updateCache: function (cache) {\n if (!skipCache) {\n cacheWrites.forEach(function (write) { return cache.write(write); });\n }\n var update = mutation.update;\n var isFinalResult = !isExecutionPatchResult(result) ||\n (isExecutionPatchIncrementalResult(result) && !result.hasNext);\n if (update) {\n if (!skipCache) {\n var diff = cache.diff({\n id: \"ROOT_MUTATION\",\n query: _this.transform(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n if (diff.complete) {\n result = __assign(__assign({}, result), { data: diff.result });\n if ('incremental' in result) {\n delete result.incremental;\n }\n if ('hasNext' in result) {\n delete result.hasNext;\n }\n }\n }\n if (isFinalResult) {\n update(cache, result, {\n context: mutation.context,\n variables: mutation.variables,\n });\n }\n }\n if (!skipCache && !mutation.keepRootFields && isFinalResult) {\n cache.modify({\n id: 'ROOT_MUTATION',\n fields: function (value, _a) {\n var fieldName = _a.fieldName, DELETE = _a.DELETE;\n return fieldName === \"__typename\" ? value : DELETE;\n },\n });\n }\n },\n include: mutation.refetchQueries,\n optimistic: false,\n removeOptimistic: mutation.removeOptimistic,\n onQueryUpdated: mutation.onQueryUpdated || null,\n }).forEach(function (result) { return results_1.push(result); });\n if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {\n return Promise.all(results_1).then(function () { return result; });\n }\n }\n return Promise.resolve(result);\n };\n QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {\n var _this = this;\n var data = typeof optimisticResponse === \"function\"\n ? optimisticResponse(mutation.variables)\n : optimisticResponse;\n return this.cache.recordOptimisticTransaction(function (cache) {\n try {\n _this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);\n }\n catch (error) {\n __DEV__ && invariant.error(error);\n }\n }, mutation.mutationId);\n };\n QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {\n return this.fetchQueryObservable(queryId, options, networkStatus).promise;\n };\n QueryManager.prototype.getQueryStore = function () {\n var store = Object.create(null);\n this.queries.forEach(function (info, queryId) {\n store[queryId] = {\n variables: info.variables,\n networkStatus: info.networkStatus,\n networkError: info.networkError,\n graphQLErrors: info.graphQLErrors,\n };\n });\n return store;\n };\n QueryManager.prototype.resetErrors = function (queryId) {\n var queryInfo = this.queries.get(queryId);\n if (queryInfo) {\n queryInfo.networkError = undefined;\n queryInfo.graphQLErrors = [];\n }\n };\n QueryManager.prototype.transform = function (document) {\n var transformCache = this.transformCache;\n if (!transformCache.has(document)) {\n var transformed = this.cache.transformDocument(document);\n var noConnection = removeConnectionDirectiveFromDocument(transformed);\n var clientQuery = this.localState.clientQuery(transformed);\n var serverQuery = noConnection && this.localState.serverQuery(noConnection);\n var cacheEntry_1 = {\n document: transformed,\n hasClientExports: hasClientExports(transformed),\n hasForcedResolvers: this.localState.shouldForceResolvers(transformed),\n clientQuery: clientQuery,\n serverQuery: serverQuery,\n defaultVars: getDefaultValues(getOperationDefinition(transformed)),\n asQuery: __assign(__assign({}, transformed), { definitions: transformed.definitions.map(function (def) {\n if (def.kind === \"OperationDefinition\" &&\n def.operation !== \"query\") {\n return __assign(__assign({}, def), { operation: \"query\" });\n }\n return def;\n }) })\n };\n var add = function (doc) {\n if (doc && !transformCache.has(doc)) {\n transformCache.set(doc, cacheEntry_1);\n }\n };\n add(document);\n add(transformed);\n add(clientQuery);\n add(serverQuery);\n }\n return transformCache.get(document);\n };\n QueryManager.prototype.getVariables = function (document, variables) {\n return __assign(__assign({}, this.transform(document).defaultVars), variables);\n };\n QueryManager.prototype.watchQuery = function (options) {\n options = __assign(__assign({}, options), { variables: this.getVariables(options.query, options.variables) });\n if (typeof options.notifyOnNetworkStatusChange === 'undefined') {\n options.notifyOnNetworkStatusChange = false;\n }\n var queryInfo = new QueryInfo(this);\n var observable = new ObservableQuery({\n queryManager: this,\n queryInfo: queryInfo,\n options: options,\n });\n this.queries.set(observable.queryId, queryInfo);\n queryInfo.init({\n document: observable.query,\n observableQuery: observable,\n variables: observable.variables,\n });\n return observable;\n };\n QueryManager.prototype.query = function (options, queryId) {\n var _this = this;\n if (queryId === void 0) { queryId = this.generateQueryId(); }\n __DEV__ ? invariant(options.query, 'query option is required. You must specify your GraphQL document ' +\n 'in the query option.') : invariant(options.query, 17);\n __DEV__ ? invariant(options.query.kind === 'Document', 'You must wrap the query string in a \"gql\" tag.') : invariant(options.query.kind === 'Document', 18);\n __DEV__ ? invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.') : invariant(!options.returnPartialData, 19);\n __DEV__ ? invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.') : invariant(!options.pollInterval, 20);\n return this.fetchQuery(queryId, options).finally(function () { return _this.stopQuery(queryId); });\n };\n QueryManager.prototype.generateQueryId = function () {\n return String(this.queryIdCounter++);\n };\n QueryManager.prototype.generateRequestId = function () {\n return this.requestIdCounter++;\n };\n QueryManager.prototype.generateMutationId = function () {\n return String(this.mutationIdCounter++);\n };\n QueryManager.prototype.stopQueryInStore = function (queryId) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.broadcastQueries();\n };\n QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {\n var queryInfo = this.queries.get(queryId);\n if (queryInfo)\n queryInfo.stop();\n };\n QueryManager.prototype.clearStore = function (options) {\n if (options === void 0) { options = {\n discardWatches: true,\n }; }\n this.cancelPendingFetches(__DEV__ ? new InvariantError('Store reset while query was in flight (not completed in link chain)') : new InvariantError(21));\n this.queries.forEach(function (queryInfo) {\n if (queryInfo.observableQuery) {\n queryInfo.networkStatus = NetworkStatus.loading;\n }\n else {\n queryInfo.stop();\n }\n });\n if (this.mutationStore) {\n this.mutationStore = Object.create(null);\n }\n return this.cache.reset(options);\n };\n QueryManager.prototype.getObservableQueries = function (include) {\n var _this = this;\n if (include === void 0) { include = \"active\"; }\n var queries = new Map();\n var queryNamesAndDocs = new Map();\n var legacyQueryOptions = new Set();\n if (Array.isArray(include)) {\n include.forEach(function (desc) {\n if (typeof desc === \"string\") {\n queryNamesAndDocs.set(desc, false);\n }\n else if (isDocumentNode(desc)) {\n queryNamesAndDocs.set(_this.transform(desc).document, false);\n }\n else if (isNonNullObject(desc) && desc.query) {\n legacyQueryOptions.add(desc);\n }\n });\n }\n this.queries.forEach(function (_a, queryId) {\n var oq = _a.observableQuery, document = _a.document;\n if (oq) {\n if (include === \"all\") {\n queries.set(queryId, oq);\n return;\n }\n var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;\n if (fetchPolicy === \"standby\" ||\n (include === \"active\" && !oq.hasObservers())) {\n return;\n }\n if (include === \"active\" ||\n (queryName && queryNamesAndDocs.has(queryName)) ||\n (document && queryNamesAndDocs.has(document))) {\n queries.set(queryId, oq);\n if (queryName)\n queryNamesAndDocs.set(queryName, true);\n if (document)\n queryNamesAndDocs.set(document, true);\n }\n }\n });\n if (legacyQueryOptions.size) {\n legacyQueryOptions.forEach(function (options) {\n var queryId = makeUniqueId(\"legacyOneTimeQuery\");\n var queryInfo = _this.getQuery(queryId).init({\n document: options.query,\n variables: options.variables,\n });\n var oq = new ObservableQuery({\n queryManager: _this,\n queryInfo: queryInfo,\n options: __assign(__assign({}, options), { fetchPolicy: \"network-only\" }),\n });\n invariant(oq.queryId === queryId);\n queryInfo.setObservableQuery(oq);\n queries.set(queryId, oq);\n });\n }\n if (__DEV__ && queryNamesAndDocs.size) {\n queryNamesAndDocs.forEach(function (included, nameOrDoc) {\n if (!included) {\n __DEV__ && invariant.warn(\"Unknown query \".concat(typeof nameOrDoc === \"string\" ? \"named \" : \"\").concat(JSON.stringify(nameOrDoc, null, 2), \" requested in refetchQueries options.include array\"));\n }\n });\n }\n return queries;\n };\n QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {\n var _this = this;\n if (includeStandby === void 0) { includeStandby = false; }\n var observableQueryPromises = [];\n this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(function (observableQuery, queryId) {\n var fetchPolicy = observableQuery.options.fetchPolicy;\n observableQuery.resetLastResults();\n if (includeStandby ||\n (fetchPolicy !== \"standby\" &&\n fetchPolicy !== \"cache-only\")) {\n observableQueryPromises.push(observableQuery.refetch());\n }\n _this.getQuery(queryId).setDiff(null);\n });\n this.broadcastQueries();\n return Promise.all(observableQueryPromises);\n };\n QueryManager.prototype.setObservableQuery = function (observableQuery) {\n this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n };\n QueryManager.prototype.startGraphQLSubscription = function (_a) {\n var _this = this;\n var query = _a.query, fetchPolicy = _a.fetchPolicy, errorPolicy = _a.errorPolicy, variables = _a.variables, _b = _a.context, context = _b === void 0 ? {} : _b;\n query = this.transform(query).document;\n variables = this.getVariables(query, variables);\n var makeObservable = function (variables) {\n return _this.getObservableFromLink(query, context, variables).map(function (result) {\n if (fetchPolicy !== 'no-cache') {\n if (shouldWriteResult(result, errorPolicy)) {\n _this.cache.write({\n query: query,\n result: result.data,\n dataId: 'ROOT_SUBSCRIPTION',\n variables: variables,\n });\n }\n _this.broadcastQueries();\n }\n if (graphQLResultHasError(result)) {\n throw new ApolloError({\n graphQLErrors: result.errors,\n });\n }\n return result;\n });\n };\n if (this.transform(query).hasClientExports) {\n var observablePromise_1 = this.localState.addExportedVariables(query, variables, context).then(makeObservable);\n return new Observable(function (observer) {\n var sub = null;\n observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);\n return function () { return sub && sub.unsubscribe(); };\n });\n }\n return makeObservable(variables);\n };\n QueryManager.prototype.stopQuery = function (queryId) {\n this.stopQueryNoBroadcast(queryId);\n this.broadcastQueries();\n };\n QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.removeQuery(queryId);\n };\n QueryManager.prototype.removeQuery = function (queryId) {\n this.fetchCancelFns.delete(queryId);\n if (this.queries.has(queryId)) {\n this.getQuery(queryId).stop();\n this.queries.delete(queryId);\n }\n };\n QueryManager.prototype.broadcastQueries = function () {\n if (this.onBroadcast)\n this.onBroadcast();\n this.queries.forEach(function (info) { return info.notify(); });\n };\n QueryManager.prototype.getLocalState = function () {\n return this.localState;\n };\n QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {\n var _this = this;\n var _a;\n if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }\n var observable;\n var serverQuery = this.transform(query).serverQuery;\n if (serverQuery) {\n var _b = this, inFlightLinkObservables_1 = _b.inFlightLinkObservables, link = _b.link;\n var operation = {\n query: serverQuery,\n variables: variables,\n operationName: getOperationName(serverQuery) || void 0,\n context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),\n };\n context = operation.context;\n if (deduplication) {\n var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();\n inFlightLinkObservables_1.set(serverQuery, byVariables_1);\n var varJson_1 = canonicalStringify(variables);\n observable = byVariables_1.get(varJson_1);\n if (!observable) {\n var concast = new Concast([\n execute(link, operation)\n ]);\n byVariables_1.set(varJson_1, observable = concast);\n concast.beforeNext(function () {\n if (byVariables_1.delete(varJson_1) &&\n byVariables_1.size < 1) {\n inFlightLinkObservables_1.delete(serverQuery);\n }\n });\n }\n }\n else {\n observable = new Concast([\n execute(link, operation)\n ]);\n }\n }\n else {\n observable = new Concast([\n Observable.of({ data: {} })\n ]);\n context = this.prepareContext(context);\n }\n var clientQuery = this.transform(query).clientQuery;\n if (clientQuery) {\n observable = asyncMap(observable, function (result) {\n return _this.localState.runResolvers({\n document: clientQuery,\n remoteResult: result,\n context: context,\n variables: variables,\n });\n });\n }\n return observable;\n };\n QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {\n var requestId = queryInfo.lastRequestId = this.generateRequestId();\n var linkDocument = this.cache.transformForLink(this.transform(queryInfo.document).document);\n return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {\n var graphQLErrors = getGraphQLErrorsFromResult(result);\n var hasErrors = graphQLErrors.length > 0;\n if (requestId >= queryInfo.lastRequestId) {\n if (hasErrors && options.errorPolicy === \"none\") {\n throw queryInfo.markError(new ApolloError({\n graphQLErrors: graphQLErrors,\n }));\n }\n queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);\n queryInfo.markReady();\n }\n var aqr = {\n data: result.data,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n if (hasErrors && options.errorPolicy !== \"ignore\") {\n aqr.errors = graphQLErrors;\n aqr.networkStatus = NetworkStatus.error;\n }\n return aqr;\n }, function (networkError) {\n var error = isApolloError(networkError)\n ? networkError\n : new ApolloError({ networkError: networkError });\n if (requestId >= queryInfo.lastRequestId) {\n queryInfo.markError(error);\n }\n throw error;\n });\n };\n QueryManager.prototype.fetchQueryObservable = function (queryId, options, networkStatus) {\n var _this = this;\n if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }\n var query = this.transform(options.query).document;\n var variables = this.getVariables(query, options.variables);\n var queryInfo = this.getQuery(queryId);\n var defaults = this.defaultOptions.watchQuery;\n var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? defaults && defaults.fetchPolicy || \"cache-first\" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? defaults && defaults.errorPolicy || \"none\" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;\n var normalized = Object.assign({}, options, {\n query: query,\n variables: variables,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n returnPartialData: returnPartialData,\n notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,\n context: context,\n });\n var fromVariables = function (variables) {\n normalized.variables = variables;\n var concastSources = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);\n if (normalized.fetchPolicy !== \"standby\" &&\n concastSources.length > 0 &&\n queryInfo.observableQuery) {\n queryInfo.observableQuery[\"applyNextFetchPolicy\"](\"after-fetch\", options);\n }\n return concastSources;\n };\n var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };\n this.fetchCancelFns.set(queryId, function (reason) {\n cleanupCancelFn();\n setTimeout(function () { return concast.cancel(reason); });\n });\n var concast = new Concast(this.transform(normalized.query).hasClientExports\n ? this.localState.addExportedVariables(normalized.query, normalized.variables, normalized.context).then(fromVariables)\n : fromVariables(normalized.variables));\n concast.promise.then(cleanupCancelFn, cleanupCancelFn);\n return concast;\n };\n QueryManager.prototype.refetchQueries = function (_a) {\n var _this = this;\n var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId(\"refetchQueries\") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;\n var includedQueriesById = new Map();\n if (include) {\n this.getObservableQueries(include).forEach(function (oq, queryId) {\n includedQueriesById.set(queryId, {\n oq: oq,\n lastDiff: _this.getQuery(queryId).getDiff(),\n });\n });\n }\n var results = new Map;\n if (updateCache) {\n this.cache.batch({\n update: updateCache,\n optimistic: optimistic && removeOptimistic || false,\n removeOptimistic: removeOptimistic,\n onWatchUpdated: function (watch, diff, lastDiff) {\n var oq = watch.watcher instanceof QueryInfo &&\n watch.watcher.observableQuery;\n if (oq) {\n if (onQueryUpdated) {\n includedQueriesById.delete(oq.queryId);\n var result = onQueryUpdated(oq, diff, lastDiff);\n if (result === true) {\n result = oq.refetch();\n }\n if (result !== false) {\n results.set(oq, result);\n }\n return result;\n }\n if (onQueryUpdated !== null) {\n includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });\n }\n }\n },\n });\n }\n if (includedQueriesById.size) {\n includedQueriesById.forEach(function (_a, queryId) {\n var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;\n var result;\n if (onQueryUpdated) {\n if (!diff) {\n var info = oq[\"queryInfo\"];\n info.reset();\n diff = info.getDiff();\n }\n result = onQueryUpdated(oq, diff, lastDiff);\n }\n if (!onQueryUpdated || result === true) {\n result = oq.refetch();\n }\n if (result !== false) {\n results.set(oq, result);\n }\n if (queryId.indexOf(\"legacyOneTimeQuery\") >= 0) {\n _this.stopQueryNoBroadcast(queryId);\n }\n });\n }\n if (removeOptimistic) {\n this.cache.removeOptimistic(removeOptimistic);\n }\n return results;\n };\n QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, networkStatus) {\n var _this = this;\n var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;\n var oldNetworkStatus = queryInfo.networkStatus;\n queryInfo.init({\n document: this.transform(query).document,\n variables: variables,\n networkStatus: networkStatus,\n });\n var readCache = function () { return queryInfo.getDiff(variables); };\n var resultsFromCache = function (diff, networkStatus) {\n if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }\n var data = diff.result;\n if (__DEV__ &&\n !returnPartialData &&\n !equal(data, {})) {\n logMissingFieldErrors(diff.missing);\n }\n var fromData = function (data) { return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true }))); };\n if (data && _this.transform(query).hasForcedResolvers) {\n return _this.localState.runResolvers({\n document: query,\n remoteResult: { data: data },\n context: context,\n variables: variables,\n onlyRunForcedResolvers: true,\n }).then(function (resolved) { return fromData(resolved.data || void 0); });\n }\n if (errorPolicy === 'none' &&\n networkStatus === NetworkStatus.refetch &&\n Array.isArray(diff.missing)) {\n return fromData(void 0);\n }\n return fromData(data);\n };\n var cacheWriteBehavior = fetchPolicy === \"no-cache\" ? 0 :\n (networkStatus === NetworkStatus.refetch &&\n refetchWritePolicy !== \"merge\") ? 1\n : 2;\n var resultsFromLink = function () { return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {\n variables: variables,\n context: context,\n fetchPolicy: fetchPolicy,\n errorPolicy: errorPolicy,\n }); };\n var shouldNotify = notifyOnNetworkStatusChange &&\n typeof oldNetworkStatus === \"number\" &&\n oldNetworkStatus !== networkStatus &&\n isNetworkRequestInFlight(networkStatus);\n switch (fetchPolicy) {\n default:\n case \"cache-first\": {\n var diff = readCache();\n if (diff.complete) {\n return [\n resultsFromCache(diff, queryInfo.markReady()),\n ];\n }\n if (returnPartialData || shouldNotify) {\n return [\n resultsFromCache(diff),\n resultsFromLink(),\n ];\n }\n return [\n resultsFromLink(),\n ];\n }\n case \"cache-and-network\": {\n var diff = readCache();\n if (diff.complete || returnPartialData || shouldNotify) {\n return [\n resultsFromCache(diff),\n resultsFromLink(),\n ];\n }\n return [\n resultsFromLink(),\n ];\n }\n case \"cache-only\":\n return [\n resultsFromCache(readCache(), queryInfo.markReady()),\n ];\n case \"network-only\":\n if (shouldNotify) {\n return [\n resultsFromCache(readCache()),\n resultsFromLink(),\n ];\n }\n return [resultsFromLink()];\n case \"no-cache\":\n if (shouldNotify) {\n return [\n resultsFromCache(queryInfo.getDiff()),\n resultsFromLink(),\n ];\n }\n return [resultsFromLink()];\n case \"standby\":\n return [];\n }\n };\n QueryManager.prototype.getQuery = function (queryId) {\n if (queryId && !this.queries.has(queryId)) {\n this.queries.set(queryId, new QueryInfo(this, queryId));\n }\n return this.queries.get(queryId);\n };\n QueryManager.prototype.prepareContext = function (context) {\n if (context === void 0) { context = {}; }\n var newContext = this.localState.prepareContext(context);\n return __assign(__assign({}, newContext), { clientAwareness: this.clientAwareness });\n };\n return QueryManager;\n}());\nexport { QueryManager };\n//# sourceMappingURL=QueryManager.js.map","import { __assign } from \"tslib\";\nimport { invariant, InvariantError } from '../utilities/globals';\nimport { ApolloLink, execute } from '../link/core';\nimport { version } from '../version';\nimport { HttpLink } from '../link/http';\nimport { QueryManager } from './QueryManager';\nimport { LocalState, } from './LocalState';\nvar hasSuggestedDevtools = false;\nimport { mergeOptions } from \"../utilities\";\nexport { mergeOptions };\nvar ApolloClient = (function () {\n function ApolloClient(options) {\n var _this = this;\n this.resetStoreCallbacks = [];\n this.clearStoreCallbacks = [];\n var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, _c = options.connectToDevTools, connectToDevTools = _c === void 0 ? typeof window === 'object' &&\n !window.__APOLLO_CLIENT__ &&\n __DEV__ : _c, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d, defaultOptions = options.defaultOptions, _e = options.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? false : _e, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;\n var link = options.link;\n if (!link) {\n link = uri\n ? new HttpLink({ uri: uri, credentials: credentials, headers: headers })\n : ApolloLink.empty();\n }\n if (!cache) {\n throw __DEV__ ? new InvariantError(\"To initialize Apollo Client, you must specify a 'cache' property \" +\n \"in the options object. \\n\" +\n \"For more information, please visit: https://go.apollo.dev/c/docs\") : new InvariantError(9);\n }\n this.link = link;\n this.cache = cache;\n this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;\n this.queryDeduplication = queryDeduplication;\n this.defaultOptions = defaultOptions || Object.create(null);\n this.typeDefs = typeDefs;\n if (ssrForceFetchDelay) {\n setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);\n }\n this.watchQuery = this.watchQuery.bind(this);\n this.query = this.query.bind(this);\n this.mutate = this.mutate.bind(this);\n this.resetStore = this.resetStore.bind(this);\n this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);\n if (connectToDevTools && typeof window === 'object') {\n window.__APOLLO_CLIENT__ = this;\n }\n if (!hasSuggestedDevtools && connectToDevTools && __DEV__) {\n hasSuggestedDevtools = true;\n if (typeof window !== 'undefined' &&\n window.document &&\n window.top === window.self &&\n !window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {\n var nav = window.navigator;\n var ua = nav && nav.userAgent;\n var url = void 0;\n if (typeof ua === \"string\") {\n if (ua.indexOf(\"Chrome/\") > -1) {\n url = \"https://chrome.google.com/webstore/detail/\" +\n \"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm\";\n }\n else if (ua.indexOf(\"Firefox/\") > -1) {\n url = \"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/\";\n }\n }\n if (url) {\n __DEV__ && invariant.log(\"Download the Apollo DevTools for a better development \" +\n \"experience: \" + url);\n }\n }\n }\n this.version = version;\n this.localState = new LocalState({\n cache: cache,\n client: this,\n resolvers: resolvers,\n fragmentMatcher: fragmentMatcher,\n });\n this.queryManager = new QueryManager({\n cache: this.cache,\n link: this.link,\n defaultOptions: this.defaultOptions,\n queryDeduplication: queryDeduplication,\n ssrMode: ssrMode,\n clientAwareness: {\n name: clientAwarenessName,\n version: clientAwarenessVersion,\n },\n localState: this.localState,\n assumeImmutableResults: assumeImmutableResults,\n onBroadcast: connectToDevTools ? function () {\n if (_this.devToolsHookCb) {\n _this.devToolsHookCb({\n action: {},\n state: {\n queries: _this.queryManager.getQueryStore(),\n mutations: _this.queryManager.mutationStore || {},\n },\n dataWithOptimisticResults: _this.cache.extract(true),\n });\n }\n } : void 0,\n });\n }\n ApolloClient.prototype.stop = function () {\n this.queryManager.stop();\n };\n ApolloClient.prototype.watchQuery = function (options) {\n if (this.defaultOptions.watchQuery) {\n options = mergeOptions(this.defaultOptions.watchQuery, options);\n }\n if (this.disableNetworkFetches &&\n (options.fetchPolicy === 'network-only' ||\n options.fetchPolicy === 'cache-and-network')) {\n options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });\n }\n return this.queryManager.watchQuery(options);\n };\n ApolloClient.prototype.query = function (options) {\n if (this.defaultOptions.query) {\n options = mergeOptions(this.defaultOptions.query, options);\n }\n __DEV__ ? invariant(options.fetchPolicy !== 'cache-and-network', 'The cache-and-network fetchPolicy does not work with client.query, because ' +\n 'client.query can only return a single result. Please use client.watchQuery ' +\n 'to receive multiple results from the cache and the network, or consider ' +\n 'using a different fetchPolicy, such as cache-first or network-only.') : invariant(options.fetchPolicy !== 'cache-and-network', 10);\n if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {\n options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });\n }\n return this.queryManager.query(options);\n };\n ApolloClient.prototype.mutate = function (options) {\n if (this.defaultOptions.mutate) {\n options = mergeOptions(this.defaultOptions.mutate, options);\n }\n return this.queryManager.mutate(options);\n };\n ApolloClient.prototype.subscribe = function (options) {\n return this.queryManager.startGraphQLSubscription(options);\n };\n ApolloClient.prototype.readQuery = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return this.cache.readQuery(options, optimistic);\n };\n ApolloClient.prototype.readFragment = function (options, optimistic) {\n if (optimistic === void 0) { optimistic = false; }\n return this.cache.readFragment(options, optimistic);\n };\n ApolloClient.prototype.writeQuery = function (options) {\n var ref = this.cache.writeQuery(options);\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n return ref;\n };\n ApolloClient.prototype.writeFragment = function (options) {\n var ref = this.cache.writeFragment(options);\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n return ref;\n };\n ApolloClient.prototype.__actionHookForDevTools = function (cb) {\n this.devToolsHookCb = cb;\n };\n ApolloClient.prototype.__requestRaw = function (payload) {\n return execute(this.link, payload);\n };\n ApolloClient.prototype.resetStore = function () {\n var _this = this;\n return Promise.resolve()\n .then(function () { return _this.queryManager.clearStore({\n discardWatches: false,\n }); })\n .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })\n .then(function () { return _this.reFetchObservableQueries(); });\n };\n ApolloClient.prototype.clearStore = function () {\n var _this = this;\n return Promise.resolve()\n .then(function () { return _this.queryManager.clearStore({\n discardWatches: true,\n }); })\n .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });\n };\n ApolloClient.prototype.onResetStore = function (cb) {\n var _this = this;\n this.resetStoreCallbacks.push(cb);\n return function () {\n _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });\n };\n };\n ApolloClient.prototype.onClearStore = function (cb) {\n var _this = this;\n this.clearStoreCallbacks.push(cb);\n return function () {\n _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });\n };\n };\n ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {\n return this.queryManager.reFetchObservableQueries(includeStandby);\n };\n ApolloClient.prototype.refetchQueries = function (options) {\n var map = this.queryManager.refetchQueries(options);\n var queries = [];\n var results = [];\n map.forEach(function (result, obsQuery) {\n queries.push(obsQuery);\n results.push(result);\n });\n var result = Promise.all(results);\n result.queries = queries;\n result.results = results;\n result.catch(function (error) {\n __DEV__ && invariant.debug(\"In client.refetchQueries, Promise.all promise rejected with error \".concat(error));\n });\n return result;\n };\n ApolloClient.prototype.getObservableQueries = function (include) {\n if (include === void 0) { include = \"active\"; }\n return this.queryManager.getObservableQueries(include);\n };\n ApolloClient.prototype.extract = function (optimistic) {\n return this.cache.extract(optimistic);\n };\n ApolloClient.prototype.restore = function (serializedState) {\n return this.cache.restore(serializedState);\n };\n ApolloClient.prototype.addResolvers = function (resolvers) {\n this.localState.addResolvers(resolvers);\n };\n ApolloClient.prototype.setResolvers = function (resolvers) {\n this.localState.setResolvers(resolvers);\n };\n ApolloClient.prototype.getResolvers = function () {\n return this.localState.getResolvers();\n };\n ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {\n this.localState.setFragmentMatcher(fragmentMatcher);\n };\n ApolloClient.prototype.setLink = function (newLink) {\n this.link = this.queryManager.link = newLink;\n };\n return ApolloClient;\n}());\nexport { ApolloClient };\n//# sourceMappingURL=ApolloClient.js.map","import * as React from 'react';\nimport { canUseSymbol } from '../../utilities';\nvar contextKey = canUseSymbol\n ? Symbol.for('__APOLLO_CONTEXT__')\n : '__APOLLO_CONTEXT__';\nexport function getApolloContext() {\n var context = React.createContext[contextKey];\n if (!context) {\n Object.defineProperty(React.createContext, contextKey, {\n value: context = React.createContext({}),\n enumerable: false,\n writable: false,\n configurable: true,\n });\n context.displayName = 'ApolloContext';\n }\n return context;\n}\nexport { getApolloContext as resetApolloContext };\n//# sourceMappingURL=ApolloContext.js.map","import { invariant } from '../../utilities/globals';\nimport * as React from 'react';\nimport { getApolloContext } from './ApolloContext';\nexport var ApolloConsumer = function (props) {\n var ApolloContext = getApolloContext();\n return (React.createElement(ApolloContext.Consumer, null, function (context) {\n __DEV__ ? invariant(context && context.client, 'Could not find \"client\" in the context of ApolloConsumer. ' +\n 'Wrap the root component in an <ApolloProvider>.') : invariant(context && context.client, 28);\n return props.children(context.client);\n }));\n};\n//# sourceMappingURL=ApolloConsumer.js.map","import { invariant } from '../../utilities/globals';\nimport * as React from 'react';\nimport { getApolloContext } from './ApolloContext';\nexport var ApolloProvider = function (_a) {\n var client = _a.client, children = _a.children;\n var ApolloContext = getApolloContext();\n return (React.createElement(ApolloContext.Consumer, null, function (context) {\n if (context === void 0) { context = {}; }\n if (client && context.client !== client) {\n context = Object.assign({}, context, { client: client });\n }\n __DEV__ ? invariant(context.client, 'ApolloProvider was not passed a client instance. Make ' +\n 'sure you pass in your client via the \"client\" prop.') : invariant(context.client, 29);\n return (React.createElement(ApolloContext.Provider, { value: context }, children));\n }));\n};\n//# sourceMappingURL=ApolloProvider.js.map","import { invariant } from '../../utilities/globals';\nimport { useContext } from 'react';\nimport { getApolloContext } from '../context';\nexport function useApolloClient(override) {\n var context = useContext(getApolloContext());\n var client = override || context.client;\n __DEV__ ? invariant(!!client, 'Could not find \"client\" in the context or passed in as an option. ' +\n 'Wrap the root component in an <ApolloProvider>, or pass an ApolloClient ' +\n 'instance in via options.') : invariant(!!client, 32);\n return client;\n}\n//# sourceMappingURL=useApolloClient.js.map","import { invariant } from '../../utilities/globals';\nimport * as React from 'react';\nimport { canUseLayoutEffect } from '../../utilities';\nvar didWarnUncachedGetSnapshot = false;\nvar uSESKey = \"useSyncExternalStore\";\nvar realHook = React[uSESKey];\nexport var useSyncExternalStore = realHook || (function (subscribe, getSnapshot, getServerSnapshot) {\n var value = getSnapshot();\n if (__DEV__ &&\n !didWarnUncachedGetSnapshot &&\n value !== getSnapshot()) {\n didWarnUncachedGetSnapshot = true;\n __DEV__ && invariant.error('The result of getSnapshot should be cached to avoid an infinite loop');\n }\n var _a = React.useState({ inst: { value: value, getSnapshot: getSnapshot } }), inst = _a[0].inst, forceUpdate = _a[1];\n if (canUseLayoutEffect) {\n React.useLayoutEffect(function () {\n Object.assign(inst, { value: value, getSnapshot: getSnapshot });\n if (checkIfSnapshotChanged(inst)) {\n forceUpdate({ inst: inst });\n }\n }, [subscribe, value, getSnapshot]);\n }\n else {\n Object.assign(inst, { value: value, getSnapshot: getSnapshot });\n }\n React.useEffect(function () {\n if (checkIfSnapshotChanged(inst)) {\n forceUpdate({ inst: inst });\n }\n return subscribe(function handleStoreChange() {\n if (checkIfSnapshotChanged(inst)) {\n forceUpdate({ inst: inst });\n }\n });\n }, [subscribe]);\n return value;\n});\nfunction checkIfSnapshotChanged(_a) {\n var value = _a.value, getSnapshot = _a.getSnapshot;\n try {\n return value !== getSnapshot();\n }\n catch (_b) {\n return true;\n }\n}\n//# sourceMappingURL=useSyncExternalStore.js.map","import { invariant } from '../../utilities/globals';\nexport var DocumentType;\n(function (DocumentType) {\n DocumentType[DocumentType[\"Query\"] = 0] = \"Query\";\n DocumentType[DocumentType[\"Mutation\"] = 1] = \"Mutation\";\n DocumentType[DocumentType[\"Subscription\"] = 2] = \"Subscription\";\n})(DocumentType || (DocumentType = {}));\nvar cache = new Map();\nexport function operationName(type) {\n var name;\n switch (type) {\n case DocumentType.Query:\n name = 'Query';\n break;\n case DocumentType.Mutation:\n name = 'Mutation';\n break;\n case DocumentType.Subscription:\n name = 'Subscription';\n break;\n }\n return name;\n}\nexport function parser(document) {\n var cached = cache.get(document);\n if (cached)\n return cached;\n var variables, type, name;\n __DEV__ ? invariant(!!document && !!document.kind, \"Argument of \".concat(document, \" passed to parser was not a valid GraphQL \") +\n \"DocumentNode. You may need to use 'graphql-tag' or another method \" +\n \"to convert your operation into a document\") : invariant(!!document && !!document.kind, 33);\n var fragments = [];\n var queries = [];\n var mutations = [];\n var subscriptions = [];\n for (var _i = 0, _a = document.definitions; _i < _a.length; _i++) {\n var x = _a[_i];\n if (x.kind === 'FragmentDefinition') {\n fragments.push(x);\n continue;\n }\n if (x.kind === 'OperationDefinition') {\n switch (x.operation) {\n case 'query':\n queries.push(x);\n break;\n case 'mutation':\n mutations.push(x);\n break;\n case 'subscription':\n subscriptions.push(x);\n break;\n }\n }\n }\n __DEV__ ? invariant(!fragments.length ||\n (queries.length || mutations.length || subscriptions.length), \"Passing only a fragment to 'graphql' is not yet supported. \" +\n \"You must include a query, subscription or mutation as well\") : invariant(!fragments.length ||\n (queries.length || mutations.length || subscriptions.length), 34);\n __DEV__ ? invariant(queries.length + mutations.length + subscriptions.length <= 1, \"react-apollo only supports a query, subscription, or a mutation per HOC. \" +\n \"\".concat(document, \" had \").concat(queries.length, \" queries, \").concat(subscriptions.length, \" \") +\n \"subscriptions and \".concat(mutations.length, \" mutations. \") +\n \"You can use 'compose' to join multiple operation types to a component\") : invariant(queries.length + mutations.length + subscriptions.length <= 1, 35);\n type = queries.length ? DocumentType.Query : DocumentType.Mutation;\n if (!queries.length && !mutations.length)\n type = DocumentType.Subscription;\n var definitions = queries.length\n ? queries\n : mutations.length\n ? mutations\n : subscriptions;\n __DEV__ ? invariant(definitions.length === 1, \"react-apollo only supports one definition per HOC. \".concat(document, \" had \") +\n \"\".concat(definitions.length, \" definitions. \") +\n \"You can use 'compose' to join multiple operation types to a component\") : invariant(definitions.length === 1, 36);\n var definition = definitions[0];\n variables = definition.variableDefinitions || [];\n if (definition.name && definition.name.kind === 'Name') {\n name = definition.name.value;\n }\n else {\n name = 'data';\n }\n var payload = { name: name, type: type, variables: variables };\n cache.set(document, payload);\n return payload;\n}\nexport function verifyDocumentType(document, type) {\n var operation = parser(document);\n var requiredOperationName = operationName(type);\n var usedOperationName = operationName(operation.type);\n __DEV__ ? invariant(operation.type === type, \"Running a \".concat(requiredOperationName, \" requires a graphql \") +\n \"\".concat(requiredOperationName, \", but a \").concat(usedOperationName, \" was used instead.\")) : invariant(operation.type === type, 37);\n}\n//# sourceMappingURL=index.js.map","import { __assign, __rest } from \"tslib\";\nimport { invariant } from '../../utilities/globals';\nimport { useCallback, useContext, useMemo, useRef, useState, } from 'react';\nimport { useSyncExternalStore } from './useSyncExternalStore';\nimport { equal } from '@wry/equality';\nimport { mergeOptions } from '../../core';\nimport { getApolloContext } from '../context';\nimport { ApolloError } from '../../errors';\nimport { NetworkStatus, } from '../../core';\nimport { DocumentType, verifyDocumentType } from '../parser';\nimport { useApolloClient } from './useApolloClient';\nimport { canUseWeakMap, canUseWeakSet, compact, isNonEmptyArray, maybeDeepFreeze } from '../../utilities';\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function useQuery(query, options) {\n if (options === void 0) { options = Object.create(null); }\n return useInternalState(useApolloClient(options.client), query).useQuery(options);\n}\nexport function useInternalState(client, query) {\n var stateRef = useRef();\n if (!stateRef.current ||\n client !== stateRef.current.client ||\n query !== stateRef.current.query) {\n stateRef.current = new InternalState(client, query, stateRef.current);\n }\n var state = stateRef.current;\n var _a = useState(0), _tick = _a[0], setTick = _a[1];\n state.forceUpdate = function () {\n setTick(function (tick) { return tick + 1; });\n };\n return state;\n}\nvar InternalState = (function () {\n function InternalState(client, query, previous) {\n this.client = client;\n this.query = query;\n this.asyncResolveFns = new Set();\n this.optionsToIgnoreOnce = new (canUseWeakSet ? WeakSet : Set)();\n this.ssrDisabledResult = maybeDeepFreeze({\n loading: true,\n data: void 0,\n error: void 0,\n networkStatus: NetworkStatus.loading,\n });\n this.skipStandbyResult = maybeDeepFreeze({\n loading: false,\n data: void 0,\n error: void 0,\n networkStatus: NetworkStatus.ready,\n });\n this.toQueryResultCache = new (canUseWeakMap ? WeakMap : Map)();\n verifyDocumentType(query, DocumentType.Query);\n var previousResult = previous && previous.result;\n var previousData = previousResult && previousResult.data;\n if (previousData) {\n this.previousData = previousData;\n }\n }\n InternalState.prototype.forceUpdate = function () {\n __DEV__ && invariant.warn(\"Calling default no-op implementation of InternalState#forceUpdate\");\n };\n InternalState.prototype.asyncUpdate = function (signal) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n var watchQueryOptions = _this.watchQueryOptions;\n var handleAborted = function () {\n _this.asyncResolveFns.delete(resolve);\n _this.optionsToIgnoreOnce.delete(watchQueryOptions);\n signal.removeEventListener('abort', handleAborted);\n reject(signal.reason);\n };\n _this.asyncResolveFns.add(resolve);\n _this.optionsToIgnoreOnce.add(watchQueryOptions);\n signal.addEventListener('abort', handleAborted);\n _this.forceUpdate();\n });\n };\n InternalState.prototype.useQuery = function (options) {\n var _this = this;\n this.renderPromises = useContext(getApolloContext()).renderPromises;\n this.useOptions(options);\n var obsQuery = this.useObservableQuery();\n var result = useSyncExternalStore(useCallback(function () {\n if (_this.renderPromises) {\n return function () { };\n }\n var onNext = function () {\n var previousResult = _this.result;\n var result = obsQuery.getCurrentResult();\n if (previousResult &&\n previousResult.loading === result.loading &&\n previousResult.networkStatus === result.networkStatus &&\n equal(previousResult.data, result.data)) {\n return;\n }\n _this.setResult(result);\n };\n var onError = function (error) {\n var last = obsQuery[\"last\"];\n subscription.unsubscribe();\n try {\n obsQuery.resetLastResults();\n subscription = obsQuery.subscribe(onNext, onError);\n }\n finally {\n obsQuery[\"last\"] = last;\n }\n if (!hasOwnProperty.call(error, 'graphQLErrors')) {\n throw error;\n }\n var previousResult = _this.result;\n if (!previousResult ||\n (previousResult && previousResult.loading) ||\n !equal(error, previousResult.error)) {\n _this.setResult({\n data: (previousResult && previousResult.data),\n error: error,\n loading: false,\n networkStatus: NetworkStatus.error,\n });\n }\n };\n var subscription = obsQuery.subscribe(onNext, onError);\n return function () { return subscription.unsubscribe(); };\n }, [\n obsQuery,\n this.renderPromises,\n this.client.disableNetworkFetches,\n ]), function () { return _this.getCurrentResult(); }, function () { return _this.getCurrentResult(); });\n this.unsafeHandlePartialRefetch(result);\n var queryResult = this.toQueryResult(result);\n if (!queryResult.loading && this.asyncResolveFns.size) {\n this.asyncResolveFns.forEach(function (resolve) { return resolve(queryResult); });\n this.asyncResolveFns.clear();\n }\n return queryResult;\n };\n InternalState.prototype.useOptions = function (options) {\n var _a;\n var watchQueryOptions = this.createWatchQueryOptions(this.queryHookOptions = options);\n var currentWatchQueryOptions = this.watchQueryOptions;\n if (this.optionsToIgnoreOnce.has(currentWatchQueryOptions) ||\n !equal(watchQueryOptions, currentWatchQueryOptions)) {\n this.watchQueryOptions = watchQueryOptions;\n if (currentWatchQueryOptions && this.observable) {\n this.optionsToIgnoreOnce.delete(currentWatchQueryOptions);\n this.observable.reobserve(this.getObsQueryOptions());\n this.previousData = ((_a = this.result) === null || _a === void 0 ? void 0 : _a.data) || this.previousData;\n this.result = void 0;\n }\n }\n this.onCompleted = options.onCompleted || InternalState.prototype.onCompleted;\n this.onError = options.onError || InternalState.prototype.onError;\n if ((this.renderPromises || this.client.disableNetworkFetches) &&\n this.queryHookOptions.ssr === false &&\n !this.queryHookOptions.skip) {\n this.result = this.ssrDisabledResult;\n }\n else if (this.queryHookOptions.skip ||\n this.watchQueryOptions.fetchPolicy === 'standby') {\n this.result = this.skipStandbyResult;\n }\n else if (this.result === this.ssrDisabledResult ||\n this.result === this.skipStandbyResult) {\n this.result = void 0;\n }\n };\n InternalState.prototype.getObsQueryOptions = function () {\n var toMerge = [];\n var globalDefaults = this.client.defaultOptions.watchQuery;\n if (globalDefaults)\n toMerge.push(globalDefaults);\n if (this.queryHookOptions.defaultOptions) {\n toMerge.push(this.queryHookOptions.defaultOptions);\n }\n toMerge.push(compact(this.observable && this.observable.options, this.watchQueryOptions));\n return toMerge.reduce(mergeOptions);\n };\n InternalState.prototype.createWatchQueryOptions = function (_a) {\n var _b;\n if (_a === void 0) { _a = {}; }\n var skip = _a.skip, ssr = _a.ssr, onCompleted = _a.onCompleted, onError = _a.onError, defaultOptions = _a.defaultOptions, otherOptions = __rest(_a, [\"skip\", \"ssr\", \"onCompleted\", \"onError\", \"defaultOptions\"]);\n var watchQueryOptions = Object.assign(otherOptions, { query: this.query });\n if (this.renderPromises &&\n (watchQueryOptions.fetchPolicy === 'network-only' ||\n watchQueryOptions.fetchPolicy === 'cache-and-network')) {\n watchQueryOptions.fetchPolicy = 'cache-first';\n }\n if (!watchQueryOptions.variables) {\n watchQueryOptions.variables = {};\n }\n if (skip) {\n var _c = watchQueryOptions.fetchPolicy, fetchPolicy = _c === void 0 ? this.getDefaultFetchPolicy() : _c, _d = watchQueryOptions.initialFetchPolicy, initialFetchPolicy = _d === void 0 ? fetchPolicy : _d;\n Object.assign(watchQueryOptions, {\n initialFetchPolicy: initialFetchPolicy,\n fetchPolicy: 'standby',\n });\n }\n else if (!watchQueryOptions.fetchPolicy) {\n watchQueryOptions.fetchPolicy =\n ((_b = this.observable) === null || _b === void 0 ? void 0 : _b.options.initialFetchPolicy) ||\n this.getDefaultFetchPolicy();\n }\n return watchQueryOptions;\n };\n InternalState.prototype.getDefaultFetchPolicy = function () {\n var _a, _b;\n return (((_a = this.queryHookOptions.defaultOptions) === null || _a === void 0 ? void 0 : _a.fetchPolicy) ||\n ((_b = this.client.defaultOptions.watchQuery) === null || _b === void 0 ? void 0 : _b.fetchPolicy) ||\n \"cache-first\");\n };\n InternalState.prototype.onCompleted = function (data) { };\n InternalState.prototype.onError = function (error) { };\n InternalState.