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WAAjBA,EAAE4D,KAAKzH,KAAP,KAM/B,OAAO,oBACFsJ,GAAI,CACPkG,YAAY,oBAAIA,GAAY,GAAF,CAAE4uC,IAAc,IAhB5C,CAnBA,CAqCF,IAGN,GACA,CACEyC,MAAK,SAACpxC,GACJ,OAAOA,IAAU2uC,CACnB,IAsKJ,WAAkC,GAKhC,MAAsD,WAJxC,WAGuB,UAInC,GAIF,WACM,oBAAoB,CACxB,eAAqB,GACnB,OAAK,SAAC,QAAI,0B,KAWhB,c,OACA,QAAgB,GAGA,EAAU,CAEpB,CAEA,gDACE,QAAM,I,GAQb,cAGC,OADF,QAAgB,IACd,QAAa,EAAU,CAEvB,eAAa,SAAU,GACrB,MAEE,8CAAsD,wDAKtD,OAAC,8EAED,CAII,mBACE,KAAM,MAAK,SAAS,wB,0BC/tBzB,SAAS0C,EACdj7B,EACAc,EACAo6B,GAKA,IAAMC,EAAqC,GAC3Cn7B,EAAU5T,SAAQ,SAACiU,GAAQ,OAAAA,EAAIS,IAAWq6B,EAAoBzgD,KAAK2lB,EAAxC,IAC3B86B,EAAoB/uC,SAAQ,SAACiU,GAAQ,OAACA,EAAYS,GAAQo6B,EAArB,GACvC,C,4ECFO,SAASE,EAEdC,GACA,SAASntC,EAAIlM,GAIXhI,OAAOC,eAAeohD,EAAUr5C,EAAK,CAAE7H,MAAO,KAChD,CAQA,OAPI,MAAgBuM,OAAO40C,SACzBptC,EAAIxH,OAAO40C,SAKbptC,EAAI,aACGmtC,CACT,C,mCC5BO,IAAMjd,EAAU,Q","sources":["webpack:///../../node_modules/apollo-link-logger/es/formatMessage.js","webpack:///../../node_modules/apollo-link-logger/es/index.js","webpack:///../../node_modules/apollo-link-logger/es/logging.js","webpack:///../../node_modules/apollo-link/node_modules/tslib/tslib.es6.js","webpack:///../../node_modules/apollo-utilities/node_modules/@wry/equality/src/equality.ts","webpack:///../../node_modules/apollo-utilities/src/util/canUse.ts","webpack:///../../node_modules/apollo-utilities/src/util/cloneDeep.ts","webpack:///../../node_modules/apollo-utilities/src/util/mergeDeep.ts","webpack:///../../node_modules/apollo-utilities/src/util/warnOnce.ts","webpack:///../../node_modules/apollo-link/src/linkUtils.ts","webpack:///../../node_modules/apollo-link/src/link.ts","webpack:///../../node_modules/apollo-utilities/src/getFromAST.ts","webpack:///../../node_modules/apollo-link/node_modules/zen-observable-ts/src/zenObservable.ts","webpack:///../../node_modules/asap/browser-asap.js","webpack:///../../node_modules/asap/browser-raw.js","webpack:///../../node_modules/@apollo/src/cache/core/cache.ts","webpack:///../../node_modules/@apollo/src/cache/core/types/common.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/helpers.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/entityStore.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/object-canon.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/readFromStore.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/key-extractor.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/policies.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/writeToStore.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/inMemoryCache.ts","webpack:///../../node_modules/@apollo/src/cache/inmemory/reactiveVars.ts","webpack:///../../node_modules/@apollo/src/utilities/observables/asyncMap.ts","webpack:///../../node_modules/@apollo/src/utilities/common/errorHandling.ts","webpack:///../../node_modules/@apollo/src/utilities/observables/Concast.ts","webpack:///../../node_modules/@apollo/src/core/QueryInfo.ts","webpack:///../../node_modules/@apollo/src/core/QueryManager.ts","webpack:///../../node_modules/@apollo/src/masking/maskOperation.ts","webpack:///../../node_modules/@apollo/src/core/LocalState.ts","webpack:///../../node_modules/@apollo/src/core/ApolloClient.ts","webpack:///../../node_modules/@apollo/src/core/ObservableQuery.ts","webpack:///../../node_modules/@apollo/src/utilities/promises/preventUnhandledRejection.ts","webpack:///../../node_modules/@apollo/src/core/equalByQuery.ts","webpack:///../../node_modules/@apollo/src/core/networkStatus.ts","webpack:///../../node_modules/@apollo/src/errors/index.ts","webpack:///../../node_modules/@apollo/src/cache/core/types/Cache.ts","webpack:///../../node_modules/@apollo/src/link/core/empty.ts","webpack:///../../node_modules/@apollo/src/link/core/from.ts","webpack:///../../node_modules/@apollo/src/link/core/split.ts","webpack:///../../node_modules/@apollo/src/link/core/concat.ts","webpack:///../../node_modules/@apollo/src/link/http/createSignalIfSupported.ts","webpack:///../../node_modules/@apollo/src/link/utils/toPromise.ts","webpack:///../../node_modules/@apollo/src/link/utils/fromPromise.ts","webpack:///../../node_modules/@apollo/src/core/index.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useLazyQuery.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useReactiveVar.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useFragment.ts","webpack:///../../node_modules/@apollo/src/utilities/promises/decoration.ts","webpack:///../../node_modules/@apollo/src/react/hooks/internal/__use.ts","webpack:///../../node_modules/@apollo/src/react/internal/cache/QueryReference.ts","webpack:///../../node_modules/@apollo/src/react/internal/cache/FragmentReference.ts","webpack:///../../node_modules/@apollo/src/react/internal/cache/SuspenseCache.ts","webpack:///../../node_modules/@apollo/src/react/internal/cache/getSuspenseCache.ts","webpack:///../../node_modules/@apollo/src/react/hooks/constants.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useSuspenseQuery.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useBackgroundQuery.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useSuspenseFragment.ts","webpack:///../../node_modules/@apollo/src/react/hooks/internal/useRenderGuard.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useLoadableQuery.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useQueryRefHandlers.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useReadQuery.ts","webpack:///../../node_modules/@apollo/src/react/query-preloader/createQueryPreloader.ts","webpack:///../../node_modules/@apollo/src/link/batch/batching.ts","webpack:///../../node_modules/@apollo/src/link/batch/batchLink.ts","webpack:///../../node_modules/@apollo/src/link/batch-http/batchHttpLink.ts","webpack:///../../node_modules/@apollo/src/link/core/ApolloLink.ts","webpack:///../../node_modules/@apollo/src/link/utils/createOperation.ts","webpack:///../../node_modules/@apollo/src/link/utils/transformOperation.ts","webpack:///../../node_modules/@apollo/src/link/utils/validateOperation.ts","webpack:///../../node_modules/@apollo/src/link/core/execute.ts","webpack:///../../node_modules/@apollo/src/link/error/index.ts","webpack:///../../node_modules/@apollo/src/link/http/HttpLink.ts","webpack:///../../node_modules/@apollo/src/link/http/checkFetcher.ts","webpack:///../../node_modules/@apollo/src/link/http/createHttpLink.ts","webpack:///../../node_modules/@apollo/src/link/http/iterators/nodeStream.ts","webpack:///../../node_modules/@apollo/src/link/http/iterators/reader.ts","webpack:///../../node_modules/@apollo/src/link/http/responseIterator.ts","webpack:///../../node_modules/@apollo/src/link/http/iterators/async.ts","webpack:///../../node_modules/@apollo/src/link/http/iterators/promise.ts","webpack:///../../node_modules/@apollo/src/link/http/parseAndCheckHttpResponse.ts","webpack:///../../node_modules/@apollo/src/link/http/rewriteURIForGET.ts","webpack:///../../node_modules/@apollo/src/link/http/selectHttpOptionsAndBody.ts","webpack:///../../node_modules/@apollo/src/link/http/selectURI.ts","webpack:///../../node_modules/@apollo/src/link/http/serializeFetchParameter.ts","webpack:///../../node_modules/@apollo/src/link/retry/retryLink.ts","webpack:///../../node_modules/@apollo/src/link/retry/delayFunction.ts","webpack:///../../node_modules/@apollo/src/link/retry/retryFunction.ts","webpack:///../../node_modules/@apollo/src/link/utils/filterOperationVariables.ts","webpack:///../../node_modules/@apollo/src/link/utils/fromError.ts","webpack:///../../node_modules/@apollo/src/link/utils/throwServerError.ts","webpack:///../../node_modules/@apollo/src/masking/maskDefinition.ts","webpack:///../../node_modules/@apollo/src/masking/maskFragment.ts","webpack:///../../node_modules/@apollo/src/masking/utils.ts","webpack:///../../node_modules/@apollo/client/node_modules/@wry/trie/src/index.ts","webpack:///../../node_modules/@apollo/client/node_modules/ts-invariant/src/invariant.ts","webpack:///../../node_modules/@apollo/src/react/context/ApolloConsumer.tsx","webpack:///../../node_modules/@apollo/src/react/context/ApolloContext.ts","webpack:///../../node_modules/@apollo/src/react/context/ApolloProvider.tsx","webpack:///../../node_modules/@apollo/src/react/hooks/internal/useDeepMemo.ts","webpack:///../../node_modules/@apollo/src/react/hooks/internal/useIsomorphicLayoutEffect.ts","webpack:///../../node_modules/@apollo/src/react/hooks/internal/wrapHook.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useApolloClient.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useMutation.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useQuery.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useSubscription.ts","webpack:///../../node_modules/@apollo/src/react/hooks/useSyncExternalStore.ts","webpack:///../../node_modules/@apollo/src/react/parser/index.ts","webpack:///../../node_modules/@apollo/src/utilities/caching/caches.ts","webpack:///../../node_modules/@apollo/src/utilities/caching/getMemoryInternals.ts","webpack:///../../node_modules/@apollo/src/utilities/caching/sizes.ts","webpack:///../../node_modules/@apollo/src/utilities/common/arrays.ts","webpack:///../../node_modules/@apollo/src/utilities/common/canUse.ts","webpack:///../../node_modules/@apollo/src/utilities/common/canonicalStringify.ts","webpack:///../../node_modules/@apollo/src/utilities/common/cloneDeep.ts","webpack:///../../node_modules/@apollo/src/utilities/common/compact.ts","webpack:///../../node_modules/@apollo/src/utilities/common/incrementalResult.ts","webpack:///../../node_modules/@apollo/src/utilities/common/makeUniqueId.ts","webpack:///../../node_modules/@apollo/src/utilities/common/maybeDeepFreeze.ts","webpack:///../../node_modules/@apollo/src/utilities/common/mergeDeep.ts","webpack:///../../node_modules/@apollo/src/utilities/common/mergeOptions.ts","webpack:///../../node_modules/@apollo/src/utilities/common/objects.ts","webpack:///../../node_modules/@apollo/src/utilities/common/stringifyForDisplay.ts","webpack:///../../node_modules/@apollo/src/utilities/globals/global.ts","webpack:///../../node_modules/@apollo/src/utilities/globals/index.ts","webpack:///../../node_modules/@apollo/src/utilities/globals/invariantWrappers.ts","webpack:///../../node_modules/@apollo/src/utilities/globals/maybe.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/DocumentTransform.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/directives.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/fragments.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/getFromAST.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/print.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/storeUtils.ts","webpack:///../../node_modules/@apollo/src/utilities/graphql/transform.ts","webpack:///../../node_modules/@apollo/src/utilities/observables/iteration.ts","webpack:///../../node_modules/@apollo/src/utilities/observables/subclassing.ts","webpack:///../../node_modules/@apollo/src/version.ts"],"sourcesContent":["'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar formatMessage = function formatMessage(operationType, operation, ellapsed) {\n var headerCss = ['color: gray; font-weight: lighter', // title\n 'color: ' + (operationType === 'query' ? '#03A9F4' : 'red') + ';', // operationType\n 'color: inherit;'];\n\n var parts = ['%c apollo', '%c' + operationType, '%c' + operation.operationName];\n\n if (operationType !== 'subscription') {\n parts.push('%c(in ' + ellapsed + ' ms)');\n headerCss.push('color: gray; font-weight: lighter;'); // time\n }\n\n return [parts.join(' ')].concat(headerCss);\n};\n\nexports.default = formatMessage;","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _client = require('@apollo/client');\n\nvar _formatMessage = require('./formatMessage');\n\nvar _formatMessage2 = _interopRequireDefault(_formatMessage);\n\nvar _logging = require('./logging');\n\nvar _logging2 = _interopRequireDefault(_logging);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /* eslint-disable import/no-unresolved,import/extensions */\n\n\nvar loggerLink = new _client.ApolloLink(function (operation, forward) {\n var startTime = new Date().getTime();\n\n return forward(operation).map(function (result) {\n var operationType = operation.query.definitions[0].operation;\n var ellapsed = new Date().getTime() - startTime;\n\n var group = (0, _formatMessage2.default)(operationType, operation, ellapsed);\n\n _logging2.default.groupCollapsed.apply(_logging2.default, _toConsumableArray(group));\n\n _logging2.default.log('INIT', operation);\n _logging2.default.log('RESULT', result);\n\n _logging2.default.groupEnd.apply(_logging2.default, _toConsumableArray(group));\n return result;\n });\n});\n\nexports.default = loggerLink;","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n/* eslint-disable no-console */\nvar bindToConsole = function bindToConsole(consoleMethod, polyfill) {\n return consoleMethod ? consoleMethod.bind(console) : polyfill;\n};\n\nvar logging = function () {\n var prefix = '';\n\n var consoleLog = function consoleLog() {\n var _console;\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n (_console = console).log.apply(_console, [prefix].concat(args));\n };\n\n var consoleError = function consoleError() {\n var _console2;\n\n for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n (_console2 = console).error.apply(_console2, [prefix].concat(args));\n };\n\n var consoleGroup = function consoleGroup() {\n consoleLog.apply(undefined, arguments);\n prefix += '> ';\n };\n\n var consoleGroupEnd = function consoleGroupEnd() {\n prefix = prefix.slice(0, -2);\n };\n\n return {\n log: consoleLog,\n error: consoleError,\n group: bindToConsole(console.group, consoleGroup),\n groupCollapsed: bindToConsole(console.groupCollapsed, consoleGroup),\n groupEnd: bindToConsole(console.groupEnd, consoleGroupEnd)\n };\n}();\n\nexports.default = logging;","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","const { toString, hasOwnProperty } = Object.prototype;\nconst previousComparisons = new Map>();\n\n/**\n * Performs a deep equality check on two JavaScript values, tolerating cycles.\n */\nexport function equal(a: any, b: any): boolean {\n try {\n return check(a, b);\n } finally {\n previousComparisons.clear();\n }\n}\n\n// Allow default imports as well.\nexport default equal;\n\nfunction check(a: any, b: any): boolean {\n // If the two values are strictly equal, our job is easy.\n if (a === b) {\n return true;\n }\n\n // Object.prototype.toString returns a representation of the runtime type of\n // the given value that is considerably more precise than typeof.\n const aTag = toString.call(a);\n const bTag = toString.call(b);\n\n // If the runtime types of a and b are different, they could maybe be equal\n // under some interpretation of equality, but for simplicity and performance\n // we just return false instead.\n if (aTag !== bTag) {\n return false;\n }\n\n switch (aTag) {\n case '[object Array]':\n // Arrays are a lot like other objects, but we can cheaply compare their\n // lengths as a short-cut before comparing their elements.\n if (a.length !== b.length) return false;\n // Fall through to object case...\n case '[object Object]': {\n if (previouslyCompared(a, b)) return true;\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n\n // If `a` and `b` have a different number of enumerable keys, they\n // must be different.\n const keyCount = aKeys.length;\n if (keyCount !== bKeys.length) return false;\n\n // Now make sure they have the same keys.\n for (let k = 0; k < keyCount; ++k) {\n if (!hasOwnProperty.call(b, aKeys[k])) {\n return false;\n }\n }\n\n // Finally, check deep equality of all child properties.\n for (let k = 0; k < keyCount; ++k) {\n const key = aKeys[k];\n if (!check(a[key], b[key])) {\n return false;\n }\n }\n\n return true;\n }\n\n case '[object Error]':\n return a.name === b.name && a.message === b.message;\n\n case '[object Number]':\n // Handle NaN, which is !== itself.\n if (a !== a) return b !== b;\n // Fall through to shared +a === +b case...\n case '[object Boolean]':\n case '[object Date]':\n return +a === +b;\n\n case '[object RegExp]':\n case '[object String]':\n return a == `${b}`;\n\n case '[object Map]':\n case '[object Set]': {\n if (a.size !== b.size) return false;\n if (previouslyCompared(a, b)) return true;\n\n const aIterator = a.entries();\n const isMap = aTag === '[object Map]';\n\n while (true) {\n const info = aIterator.next();\n if (info.done) break;\n\n // If a instanceof Set, aValue === aKey.\n const [aKey, aValue] = info.value;\n\n // So this works the same way for both Set and Map.\n if (!b.has(aKey)) {\n return false;\n }\n\n // However, we care about deep equality of values only when dealing\n // with Map structures.\n if (isMap && !check(aValue, b.get(aKey))) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n // Otherwise the values are not equal.\n return false;\n}\n\nfunction previouslyCompared(a: object, b: object): boolean {\n // Though cyclic references can make an object graph appear infinite from the\n // perspective of a depth-first traversal, the graph still contains a finite\n // number of distinct object references. We use the previousComparisons cache\n // to avoid comparing the same pair of object references more than once, which\n // guarantees termination (even if we end up comparing every object in one\n // graph to every object in the other graph, which is extremely unlikely),\n // while still allowing weird isomorphic structures (like rings with different\n // lengths) a chance to pass the equality test.\n let bSet = previousComparisons.get(a);\n if (bSet) {\n // Return true here because we can be sure false will be returned somewhere\n // else if the objects are not equivalent.\n if (bSet.has(b)) return true;\n } else {\n previousComparisons.set(a, bSet = new Set);\n }\n bSet.add(b);\n return false;\n}\n","export const canUseWeakMap = typeof WeakMap === 'function' && !(\n typeof navigator === 'object' &&\n navigator.product === 'ReactNative'\n);\n","const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep(value: T): T {\n return cloneDeepHelper(value, new Map());\n}\n\nfunction cloneDeepHelper(val: T, seen: Map): T {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n if (seen.has(val)) return seen.get(val);\n const copy: T & any[] = (val as any).slice(0);\n seen.set(val, copy);\n copy.forEach(function (child, i) {\n copy[i] = cloneDeepHelper(child, seen);\n });\n return copy;\n }\n\n case \"[object Object]\": {\n if (seen.has(val)) return seen.get(val);\n // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n // possible in all JS environments, so we will assume they exist/work.\n const copy = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy);\n Object.keys(val).forEach(key => {\n copy[key] = cloneDeepHelper((val as any)[key], seen);\n });\n return copy;\n }\n\n default:\n return val;\n }\n}\n","const { hasOwnProperty } = Object.prototype;\n\n// These mergeDeep and mergeDeepArray utilities merge any number of objects\n// together, sharing as much memory as possible with the source objects, while\n// remaining careful to avoid modifying any source objects.\n\n// Logically, the return type of mergeDeep should be the intersection of\n// all the argument types. The binary call signature is by far the most\n// common, but we support 0- through 5-ary as well. After that, the\n// resulting type is just the inferred array element type. Note to nerds:\n// there is a more clever way of doing this that converts the tuple type\n// first to a union type (easy enough: T[number]) and then converts the\n// union to an intersection type using distributive conditional type\n// inference, but that approach has several fatal flaws (boolean becomes\n// true & false, and the inferred type ends up as unknown in many cases),\n// in addition to being nearly impossible to explain/understand.\nexport type TupleToIntersection =\n T extends [infer A] ? A :\n T extends [infer A, infer B] ? A & B :\n T extends [infer A, infer B, infer C] ? A & B & C :\n T extends [infer A, infer B, infer C, infer D] ? A & B & C & D :\n T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E :\n T extends (infer U)[] ? U : any;\n\nexport function mergeDeep(\n ...sources: T\n): TupleToIntersection {\n return mergeDeepArray(sources);\n}\n\n// In almost any situation where you could succeed in getting the\n// TypeScript compiler to infer a tuple type for the sources array, you\n// could just use mergeDeep instead of mergeDeepArray, so instead of\n// trying to convert T[] to an intersection type we just infer the array\n// element type, which works perfectly when the sources array has a\n// consistent element type.\nexport function mergeDeepArray(sources: T[]): T {\n let target = sources[0] || {} as T;\n const count = sources.length;\n if (count > 1) {\n const pastCopies: any[] = [];\n target = shallowCopyForMerge(target, pastCopies);\n for (let i = 1; i < count; ++i) {\n target = mergeHelper(target, sources[i], pastCopies);\n }\n }\n return target;\n}\n\nfunction isObject(obj: any): obj is Record {\n return obj !== null && typeof obj === 'object';\n}\n\nfunction mergeHelper(\n target: any,\n source: any,\n pastCopies: any[],\n) {\n if (isObject(source) && isObject(target)) {\n // In case the target has been frozen, make an extensible copy so that\n // we can merge properties into the copy.\n if (Object.isExtensible && !Object.isExtensible(target)) {\n target = shallowCopyForMerge(target, pastCopies);\n }\n\n Object.keys(source).forEach(sourceKey => {\n const sourceValue = source[sourceKey];\n if (hasOwnProperty.call(target, sourceKey)) {\n const targetValue = target[sourceKey];\n if (sourceValue !== targetValue) {\n // When there is a key collision, we need to make a shallow copy of\n // target[sourceKey] so the merge does not modify any source objects.\n // To avoid making unnecessary copies, we use a simple array to track\n // past copies, since it's safe to modify copies created earlier in\n // the merge. We use an array for pastCopies instead of a Map or Set,\n // since the number of copies should be relatively small, and some\n // Map/Set polyfills modify their keys.\n target[sourceKey] = mergeHelper(\n shallowCopyForMerge(targetValue, pastCopies),\n sourceValue,\n pastCopies,\n );\n }\n } else {\n // If there is no collision, the target can safely share memory with\n // the source, and the recursion can terminate here.\n target[sourceKey] = sourceValue;\n }\n });\n\n return target;\n }\n\n // If source (or target) is not an object, let source replace target.\n return source;\n}\n\nfunction shallowCopyForMerge(value: T, pastCopies: any[]): T {\n if (\n value !== null &&\n typeof value === 'object' &&\n pastCopies.indexOf(value) < 0\n ) {\n if (Array.isArray(value)) {\n value = (value as any).slice(0);\n } else {\n value = {\n __proto__: Object.getPrototypeOf(value),\n ...value,\n };\n }\n pastCopies.push(value);\n }\n return value;\n}\n","import { isProduction, isTest } from './environment';\n\nconst haveWarned = Object.create({});\n\n/**\n * Print a warning only once in development.\n * In production no warnings are printed.\n * In test all warnings are printed.\n *\n * @param msg The warning message\n * @param type warn or error (will call console.warn or console.error)\n */\nexport function warnOnceInDevelopment(msg: string, type = 'warn') {\n if (!isProduction() && !haveWarned[msg]) {\n if (!isTest()) {\n haveWarned[msg] = true;\n }\n if (type === 'error') {\n console.error(msg);\n } else {\n console.warn(msg);\n }\n }\n}\n","import Observable from 'zen-observable-ts';\n\nimport { GraphQLRequest, Operation } from './types';\nimport { ApolloLink } from './link';\n\nimport { getOperationName } from 'apollo-utilities';\nimport { invariant, InvariantError } from 'ts-invariant';\nexport { getOperationName };\n\nexport function validateOperation(operation: GraphQLRequest): GraphQLRequest {\n const OPERATION_FIELDS = [\n 'query',\n 'operationName',\n 'variables',\n 'extensions',\n 'context',\n ];\n for (let key of Object.keys(operation)) {\n if (OPERATION_FIELDS.indexOf(key) < 0) {\n throw new InvariantError(`illegal argument: ${key}`);\n }\n }\n\n return operation;\n}\n\nexport class LinkError extends Error {\n public link: ApolloLink;\n constructor(message?: string, link?: ApolloLink) {\n super(message);\n this.link = link;\n }\n}\n\nexport function isTerminating(link: ApolloLink): boolean {\n return link.request.length <= 1;\n}\n\nexport function toPromise(observable: Observable): Promise {\n let completed = false;\n return new Promise((resolve, reject) => {\n observable.subscribe({\n next: data => {\n if (completed) {\n invariant.warn(\n `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\n// backwards compat\nexport const makePromise = toPromise;\n\nexport function fromPromise(promise: Promise): Observable {\n return new Observable(observer => {\n promise\n .then((value: T) => {\n observer.next(value);\n observer.complete();\n })\n .catch(observer.error.bind(observer));\n });\n}\n\nexport function fromError(errorValue: any): Observable {\n return new Observable(observer => {\n observer.error(errorValue);\n });\n}\n\nexport function transformOperation(operation: GraphQLRequest): GraphQLRequest {\n const transformedOperation: GraphQLRequest = {\n variables: operation.variables || {},\n extensions: operation.extensions || {},\n operationName: operation.operationName,\n query: operation.query,\n };\n\n // best guess at an operation name\n if (!transformedOperation.operationName) {\n transformedOperation.operationName =\n typeof transformedOperation.query !== 'string'\n ? getOperationName(transformedOperation.query)\n : '';\n }\n\n return transformedOperation as Operation;\n}\n\nexport function createOperation(\n starting: any,\n operation: GraphQLRequest,\n): Operation {\n let context = { ...starting };\n const setContext = next => {\n if (typeof next === 'function') {\n context = { ...context, ...next(context) };\n } else {\n context = { ...context, ...next };\n }\n };\n const getContext = () => ({ ...context });\n\n Object.defineProperty(operation, 'setContext', {\n enumerable: false,\n value: setContext,\n });\n\n Object.defineProperty(operation, 'getContext', {\n enumerable: false,\n value: getContext,\n });\n\n Object.defineProperty(operation, 'toKey', {\n enumerable: false,\n value: () => getKey(operation),\n });\n\n return operation as Operation;\n}\n\nexport function getKey(operation: GraphQLRequest) {\n // XXX We're assuming here that query and variables will be serialized in\n // the same order, which might not always be true.\n const { query, variables, operationName } = operation;\n return JSON.stringify([operationName, query, variables]);\n}\n","import Observable from 'zen-observable-ts';\nimport { invariant, InvariantError } from 'ts-invariant';\n\nimport {\n GraphQLRequest,\n NextLink,\n Operation,\n RequestHandler,\n FetchResult,\n} from './types';\n\nimport {\n validateOperation,\n isTerminating,\n LinkError,\n transformOperation,\n createOperation,\n} from './linkUtils';\n\nfunction passthrough(op, forward) {\n return forward ? forward(op) : Observable.of();\n}\n\nfunction toLink(handler: RequestHandler | ApolloLink) {\n return typeof handler === 'function' ? new ApolloLink(handler) : handler;\n}\n\nexport function empty(): ApolloLink {\n return new ApolloLink(() => Observable.of());\n}\n\nexport function from(links: ApolloLink[]): ApolloLink {\n if (links.length === 0) return empty();\n return links.map(toLink).reduce((x, y) => x.concat(y));\n}\n\nexport function split(\n test: (op: Operation) => boolean,\n left: ApolloLink | RequestHandler,\n right?: ApolloLink | RequestHandler,\n): ApolloLink {\n const leftLink = toLink(left);\n const rightLink = toLink(right || new ApolloLink(passthrough));\n\n if (isTerminating(leftLink) && isTerminating(rightLink)) {\n return new ApolloLink(operation => {\n return test(operation)\n ? leftLink.request(operation) || Observable.of()\n : rightLink.request(operation) || Observable.of();\n });\n } else {\n return new ApolloLink((operation, forward) => {\n return test(operation)\n ? leftLink.request(operation, forward) || Observable.of()\n : rightLink.request(operation, forward) || Observable.of();\n });\n }\n}\n\n// join two Links together\nexport const concat = (\n first: ApolloLink | RequestHandler,\n second: ApolloLink | RequestHandler,\n) => {\n const firstLink = toLink(first);\n if (isTerminating(firstLink)) {\n invariant.warn(\n new LinkError(\n `You are calling concat on a terminating link, which will have no effect`,\n firstLink,\n ),\n );\n return firstLink;\n }\n const nextLink = toLink(second);\n\n if (isTerminating(nextLink)) {\n return new ApolloLink(\n operation =>\n firstLink.request(\n operation,\n op => nextLink.request(op) || Observable.of(),\n ) || Observable.of(),\n );\n } else {\n return new ApolloLink((operation, forward) => {\n return (\n firstLink.request(operation, op => {\n return nextLink.request(op, forward) || Observable.of();\n }) || Observable.of()\n );\n });\n }\n};\n\nexport class ApolloLink {\n public static empty = empty;\n public static from = from;\n public static split = split;\n public static execute = execute;\n\n constructor(request?: RequestHandler) {\n if (request) this.request = request;\n }\n\n public split(\n test: (op: Operation) => boolean,\n left: ApolloLink | RequestHandler,\n right?: ApolloLink | RequestHandler,\n ): ApolloLink {\n return this.concat(split(test, left, right || new ApolloLink(passthrough)));\n }\n\n public concat(next: ApolloLink | RequestHandler): ApolloLink {\n return concat(this, next);\n }\n\n public request(\n operation: Operation,\n forward?: NextLink,\n ): Observable | null {\n throw new InvariantError('request is not implemented');\n }\n}\n\nexport function execute(\n link: ApolloLink,\n operation: GraphQLRequest,\n): Observable {\n return (\n link.request(\n createOperation(\n operation.context,\n transformOperation(validateOperation(operation)),\n ),\n ) || Observable.of()\n );\n}\n","import {\n DocumentNode,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n ValueNode,\n} from 'graphql';\n\nimport { invariant, InvariantError } from 'ts-invariant';\n\nimport { assign } from './util/assign';\n\nimport { valueToObjectRepresentation, JsonValue } from './storeUtils';\n\nexport function getMutationDefinition(\n doc: DocumentNode,\n): OperationDefinitionNode {\n checkDocument(doc);\n\n let mutationDef: OperationDefinitionNode | null = doc.definitions.filter(\n definition =>\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'mutation',\n )[0] as OperationDefinitionNode;\n\n invariant(mutationDef, 'Must contain a mutation definition.');\n\n return mutationDef;\n}\n\n// Checks the document for errors and throws an exception if there is an error.\nexport function checkDocument(doc: DocumentNode) {\n invariant(\n doc && doc.kind === 'Document',\n `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`,\n );\n\n const operations = doc.definitions\n .filter(d => d.kind !== 'FragmentDefinition')\n .map(definition => {\n if (definition.kind !== 'OperationDefinition') {\n throw new InvariantError(\n `Schema type definitions not allowed in queries. Found: \"${\n definition.kind\n }\"`,\n );\n }\n return definition;\n });\n\n invariant(\n operations.length <= 1,\n `Ambiguous GraphQL document: contains ${operations.length} operations`,\n );\n\n return doc;\n}\n\nexport function getOperationDefinition(\n doc: DocumentNode,\n): OperationDefinitionNode | undefined {\n checkDocument(doc);\n return doc.definitions.filter(\n definition => definition.kind === 'OperationDefinition',\n )[0] as OperationDefinitionNode;\n}\n\nexport function getOperationDefinitionOrDie(\n document: DocumentNode,\n): OperationDefinitionNode {\n const def = getOperationDefinition(document);\n invariant(def, `GraphQL document is missing an operation`);\n return def;\n}\n\nexport function getOperationName(doc: DocumentNode): string | null {\n return (\n doc.definitions\n .filter(\n definition =>\n definition.kind === 'OperationDefinition' && definition.name,\n )\n .map((x: OperationDefinitionNode) => x.name.value)[0] || null\n );\n}\n\n// Returns the FragmentDefinitions from a particular document as an array\nexport function getFragmentDefinitions(\n doc: DocumentNode,\n): FragmentDefinitionNode[] {\n return doc.definitions.filter(\n definition => definition.kind === 'FragmentDefinition',\n ) as FragmentDefinitionNode[];\n}\n\nexport function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode {\n const queryDef = getOperationDefinition(doc) as OperationDefinitionNode;\n\n invariant(\n queryDef && queryDef.operation === 'query',\n 'Must contain a query definition.',\n );\n\n return queryDef;\n}\n\nexport function getFragmentDefinition(\n doc: DocumentNode,\n): FragmentDefinitionNode {\n invariant(\n doc.kind === 'Document',\n `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`,\n );\n\n invariant(\n doc.definitions.length <= 1,\n 'Fragment must have exactly one definition.',\n );\n\n const fragmentDef = doc.definitions[0] as FragmentDefinitionNode;\n\n invariant(\n fragmentDef.kind === 'FragmentDefinition',\n 'Must be a fragment definition.',\n );\n\n return fragmentDef as FragmentDefinitionNode;\n}\n\n/**\n * Returns the first operation definition found in this document.\n * If no operation definition is found, the first fragment definition will be returned.\n * If no definitions are found, an error will be thrown.\n */\nexport function getMainDefinition(\n queryDoc: DocumentNode,\n): OperationDefinitionNode | FragmentDefinitionNode {\n checkDocument(queryDoc);\n\n let fragmentDefinition;\n\n for (let definition of queryDoc.definitions) {\n if (definition.kind === 'OperationDefinition') {\n const operation = (definition as OperationDefinitionNode).operation;\n if (\n operation === 'query' ||\n operation === 'mutation' ||\n operation === 'subscription'\n ) {\n return definition as OperationDefinitionNode;\n }\n }\n if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {\n // we do this because we want to allow multiple fragment definitions\n // to precede an operation definition.\n fragmentDefinition = definition as FragmentDefinitionNode;\n }\n }\n\n if (fragmentDefinition) {\n return fragmentDefinition;\n }\n\n throw new InvariantError(\n 'Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.',\n );\n}\n\n/**\n * This is an interface that describes a map from fragment names to fragment definitions.\n */\nexport interface FragmentMap {\n [fragmentName: string]: FragmentDefinitionNode;\n}\n\n// Utility function that takes a list of fragment definitions and makes a hash out of them\n// that maps the name of the fragment to the fragment definition.\nexport function createFragmentMap(\n fragments: FragmentDefinitionNode[] = [],\n): FragmentMap {\n const symTable: FragmentMap = {};\n fragments.forEach(fragment => {\n symTable[fragment.name.value] = fragment;\n });\n\n return symTable;\n}\n\nexport function getDefaultValues(\n definition: OperationDefinitionNode | undefined,\n): { [key: string]: JsonValue } {\n if (\n definition &&\n definition.variableDefinitions &&\n definition.variableDefinitions.length\n ) {\n const defaultValues = definition.variableDefinitions\n .filter(({ defaultValue }) => defaultValue)\n .map(\n ({ variable, defaultValue }): { [key: string]: JsonValue } => {\n const defaultValueObj: { [key: string]: JsonValue } = {};\n valueToObjectRepresentation(\n defaultValueObj,\n variable.name,\n defaultValue as ValueNode,\n );\n\n return defaultValueObj;\n },\n );\n\n return assign({}, ...defaultValues);\n }\n\n return {};\n}\n\n/**\n * Returns the names of all variables declared by the operation.\n */\nexport function variablesInOperation(\n operation: OperationDefinitionNode,\n): Set {\n const names = new Set();\n if (operation.variableDefinitions) {\n for (const definition of operation.variableDefinitions) {\n names.add(definition.variable.name.value);\n }\n }\n\n return names;\n}\n","/* tslint:disable */\n\nimport zenObservable from 'zen-observable';\n\nnamespace Observable {\n\n}\n\nimport { ZenObservable } from './types';\n\nexport { ZenObservable };\n\nexport type Observer = ZenObservable.Observer;\nexport type Subscriber = ZenObservable.Subscriber;\nexport type ObservableLike = ZenObservable.ObservableLike;\n\nexport const Observable: {\n new (subscriber: Subscriber): Observable;\n from(\n observable: Observable | ZenObservable.ObservableLike | ArrayLike,\n ): Observable;\n of(...args: Array): Observable;\n} = zenObservable;\n\nexport interface Observable {\n subscribe(\n observerOrNext: ((value: T) => void) | ZenObservable.Observer,\n error?: (error: any) => void,\n complete?: () => void,\n ): ZenObservable.Subscription;\n\n forEach(fn: (value: T) => void): Promise;\n\n map(fn: (value: T) => R): Observable;\n\n filter(fn: (value: T) => boolean): Observable;\n\n reduce(\n fn: (previousValue: R | T, currentValue: T) => R | T,\n initialValue?: R | T,\n ): Observable;\n\n flatMap(fn: (value: T) => ZenObservable.ObservableLike): Observable;\n\n from(\n observable: Observable | ZenObservable.ObservableLike | ArrayLike,\n ): Observable;\n of(...args: Array): Observable;\n}\n","\"use strict\";\n\n// rawAsap provides everything we need except exception management.\nvar rawAsap = require(\"./raw\");\n// RawTasks are recycled to reduce GC churn.\nvar freeTasks = [];\n// We queue errors to ensure they are thrown in right order (FIFO).\n// Array-as-queue is good enough here, since we are just dealing with exceptions.\nvar pendingErrors = [];\nvar requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);\n\nfunction throwFirstError() {\n if (pendingErrors.length) {\n throw pendingErrors.shift();\n }\n}\n\n/**\n * Calls a task as soon as possible after returning, in its own event, with priority\n * over other events like animation, reflow, and repaint. An error thrown from an\n * event will not interrupt, nor even substantially slow down the processing of\n * other events, but will be rather postponed to a lower priority event.\n * @param {{call}} task A callable object, typically a function that takes no\n * arguments.\n */\nmodule.exports = asap;\nfunction asap(task) {\n var rawTask;\n if (freeTasks.length) {\n rawTask = freeTasks.pop();\n } else {\n rawTask = new RawTask();\n }\n rawTask.task = task;\n rawAsap(rawTask);\n}\n\n// We wrap tasks with recyclable task objects. A task object implements\n// `call`, just like a function.\nfunction RawTask() {\n this.task = null;\n}\n\n// The sole purpose of wrapping the task is to catch the exception and recycle\n// the task object after its single use.\nRawTask.prototype.call = function () {\n try {\n this.task.call();\n } catch (error) {\n if (asap.onerror) {\n // This hook exists purely for testing purposes.\n // Its name will be periodically randomized to break any code that\n // depends on its existence.\n asap.onerror(error);\n } else {\n // In a web browser, exceptions are not fatal. However, to avoid\n // slowing down the queue of pending tasks, we rethrow the error in a\n // lower priority turn.\n pendingErrors.push(error);\n requestErrorThrow();\n }\n } finally {\n this.task = null;\n freeTasks[freeTasks.length] = this;\n }\n};\n","\"use strict\";\n\n// Use the fastest means possible to execute a task in its own turn, with\n// priority over other events including IO, animation, reflow, and redraw\n// events in browsers.\n//\n// An exception thrown by a task will permanently interrupt the processing of\n// subsequent tasks. The higher level `asap` function ensures that if an\n// exception is thrown by a task, that the task queue will continue flushing as\n// soon as possible, but if you use `rawAsap` directly, you are responsible to\n// either ensure that no exceptions are thrown from your task, or to manually\n// call `rawAsap.requestFlush` if an exception is thrown.\nmodule.exports = rawAsap;\nfunction rawAsap(task) {\n if (!queue.length) {\n requestFlush();\n flushing = true;\n }\n // Equivalent to push, but avoids a function call.\n queue[queue.length] = task;\n}\n\nvar queue = [];\n// Once a flush has been requested, no further calls to `requestFlush` are\n// necessary until the next `flush` completes.\nvar flushing = false;\n// `requestFlush` is an implementation-specific method that attempts to kick\n// off a `flush` event as quickly as possible. `flush` will attempt to exhaust\n// the event queue before yielding to the browser's own event loop.\nvar requestFlush;\n// The position of the next task to execute in the task queue. This is\n// preserved between calls to `flush` so that it can be resumed if\n// a task throws an exception.\nvar index = 0;\n// If a task schedules additional tasks recursively, the task queue can grow\n// unbounded. To prevent memory exhaustion, the task queue will periodically\n// truncate already-completed tasks.\nvar capacity = 1024;\n\n// The flush function processes all tasks that have been scheduled with\n// `rawAsap` unless and until one of those tasks throws an exception.\n// If a task throws an exception, `flush` ensures that its state will remain\n// consistent and will resume where it left off when called again.\n// However, `flush` does not make any arrangements to be called again if an\n// exception is thrown.\nfunction flush() {\n while (index < queue.length) {\n var currentIndex = index;\n // Advance the index before calling the task. This ensures that we will\n // begin flushing on the next task the task throws an error.\n index = index + 1;\n queue[currentIndex].call();\n // Prevent leaking memory for long chains of recursive calls to `asap`.\n // If we call `asap` within tasks scheduled by `asap`, the queue will\n // grow, but to avoid an O(n) walk for every task we execute, we don't\n // shift tasks off the queue after they have been executed.\n // Instead, we periodically shift 1024 tasks off the queue.\n if (index > capacity) {\n // Manually shift all values starting at the index back to the\n // beginning of the queue.\n for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {\n queue[scan] = queue[scan + index];\n }\n queue.length -= index;\n index = 0;\n }\n }\n queue.length = 0;\n index = 0;\n flushing = false;\n}\n\n// `requestFlush` is implemented using a strategy based on data collected from\n// every available SauceLabs Selenium web driver worker at time of writing.\n// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593\n\n// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that\n// have WebKitMutationObserver but not un-prefixed MutationObserver.\n// Must use `global` or `self` instead of `window` to work in both frames and web\n// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.\n\n/* globals self */\nvar scope = typeof global !== \"undefined\" ? global : self;\nvar BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver;\n\n// MutationObservers are desirable because they have high priority and work\n// reliably everywhere they are implemented.\n// They are implemented in all modern browsers.\n//\n// - Android 4-4.3\n// - Chrome 26-34\n// - Firefox 14-29\n// - Internet Explorer 11\n// - iPad Safari 6-7.1\n// - iPhone Safari 7-7.1\n// - Safari 6-7\nif (typeof BrowserMutationObserver === \"function\") {\n requestFlush = makeRequestCallFromMutationObserver(flush);\n\n// MessageChannels are desirable because they give direct access to the HTML\n// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera\n// 11-12, and in web workers in many engines.\n// Although message channels yield to any queued rendering and IO tasks, they\n// would be better than imposing the 4ms delay of timers.\n// However, they do not work reliably in Internet Explorer or Safari.\n\n// Internet Explorer 10 is the only browser that has setImmediate but does\n// not have MutationObservers.\n// Although setImmediate yields to the browser's renderer, it would be\n// preferrable to falling back to setTimeout since it does not have\n// the minimum 4ms penalty.\n// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and\n// Desktop to a lesser extent) that renders both setImmediate and\n// MessageChannel useless for the purposes of ASAP.\n// https://github.com/kriskowal/q/issues/396\n\n// Timers are implemented universally.\n// We fall back to timers in workers in most engines, and in foreground\n// contexts in the following browsers.\n// However, note that even this simple case requires nuances to operate in a\n// broad spectrum of browsers.\n//\n// - Firefox 3-13\n// - Internet Explorer 6-9\n// - iPad Safari 4.3\n// - Lynx 2.8.7\n} else {\n requestFlush = makeRequestCallFromTimer(flush);\n}\n\n// `requestFlush` requests that the high priority event queue be flushed as\n// soon as possible.\n// This is useful to prevent an error thrown in a task from stalling the event\n// queue if the exception handled by Node.js’s\n// `process.on(\"uncaughtException\")` or by a domain.\nrawAsap.requestFlush = requestFlush;\n\n// To request a high priority event, we induce a mutation observer by toggling\n// the text of a text node between \"1\" and \"-1\".\nfunction makeRequestCallFromMutationObserver(callback) {\n var toggle = 1;\n var observer = new BrowserMutationObserver(callback);\n var node = document.createTextNode(\"\");\n observer.observe(node, {characterData: true});\n return function requestCall() {\n toggle = -toggle;\n node.data = toggle;\n };\n}\n\n// The message channel technique was discovered by Malte Ubl and was the\n// original foundation for this library.\n// http://www.nonblocking.io/2011/06/windownexttick.html\n\n// Safari 6.0.5 (at least) intermittently fails to create message ports on a\n// page's first load. Thankfully, this version of Safari supports\n// MutationObservers, so we don't need to fall back in that case.\n\n// function makeRequestCallFromMessageChannel(callback) {\n// var channel = new MessageChannel();\n// channel.port1.onmessage = callback;\n// return function requestCall() {\n// channel.port2.postMessage(0);\n// };\n// }\n\n// For reasons explained above, we are also unable to use `setImmediate`\n// under any circumstances.\n// Even if we were, there is another bug in Internet Explorer 10.\n// It is not sufficient to assign `setImmediate` to `requestFlush` because\n// `setImmediate` must be called *by name* and therefore must be wrapped in a\n// closure.\n// Never forget.\n\n// function makeRequestCallFromSetImmediate(callback) {\n// return function requestCall() {\n// setImmediate(callback);\n// };\n// }\n\n// Safari 6.0 has a problem where timers will get lost while the user is\n// scrolling. This problem does not impact ASAP because Safari 6.0 supports\n// mutation observers, so that implementation is used instead.\n// However, if we ever elect to use timers in Safari, the prevalent work-around\n// is to add a scroll event listener that calls for a flush.\n\n// `setTimeout` does not call the passed callback if the delay is less than\n// approximately 7 in web workers in Firefox 8 through 18, and sometimes not\n// even then.\n\nfunction makeRequestCallFromTimer(callback) {\n return function requestCall() {\n // We dispatch a timeout with a specified delay of 0 for engines that\n // can reliably accommodate that request. This will usually be snapped\n // to a 4 milisecond delay, but once we're flushing, there's no delay\n // between events.\n var timeoutHandle = setTimeout(handleTimer, 0);\n // However, since this timer gets frequently dropped in Firefox\n // workers, we enlist an interval handle that will try to fire\n // an event 20 times per second until it succeeds.\n var intervalHandle = setInterval(handleTimer, 50);\n\n function handleTimer() {\n // Whichever timer succeeds will cancel both timers and\n // execute the callback.\n clearTimeout(timeoutHandle);\n clearInterval(intervalHandle);\n callback();\n }\n };\n}\n\n// This is for `asap.js` only.\n// Its name will be periodically randomized to break any code that depends on\n// its existence.\nrawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;\n\n// ASAP was originally a nextTick shim included in Q. This was factored out\n// into this ASAP package. It was later adapted to RSVP which made further\n// amendments. These decisions, particularly to marginalize MessageChannel and\n// to capture the MutationObserver implementation in a closure, were integrated\n// back into ASAP proper.\n// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js\n","import type {\n DocumentNode,\n FragmentDefinitionNode,\n InlineFragmentNode,\n} from \"graphql\";\nimport { wrap } from \"optimism\";\n\nimport type {\n StoreObject,\n Reference,\n DeepPartial,\n NoInfer,\n} from \"../../utilities/index.js\";\nimport {\n Observable,\n cacheSizes,\n defaultCacheSizes,\n getFragmentDefinition,\n getFragmentQueryDocument,\n mergeDeepArray,\n} from \"../../utilities/index.js\";\nimport type { DataProxy } from \"./types/DataProxy.js\";\nimport type { Cache } from \"./types/Cache.js\";\nimport { WeakCache } from \"@wry/caches\";\nimport { getApolloCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\nimport type {\n OperationVariables,\n TypedDocumentNode,\n} from \"../../core/types.js\";\nimport type { MissingTree } from \"./types/common.js\";\nimport { equalByQuery } from \"../../core/equalByQuery.js\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport { maskFragment } from \"../../masking/index.js\";\nimport type {\n FragmentType,\n MaybeMasked,\n Unmasked,\n} from \"../../masking/index.js\";\n\nexport type Transaction = (c: ApolloCache) => void;\n\n/**\n * Watched fragment options.\n */\nexport interface WatchFragmentOptions {\n /**\n * A GraphQL fragment document parsed into an AST with the `gql`\n * template literal.\n *\n * @docGroup 1. Required options\n */\n fragment: DocumentNode | TypedDocumentNode;\n /**\n * An object containing a `__typename` and primary key fields\n * (such as `id`) identifying the entity object from which the fragment will\n * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n * (uncommon).\n *\n * @docGroup 1. Required options\n */\n from: StoreObject | Reference | FragmentType> | string;\n /**\n * Any variables that the GraphQL fragment may depend on.\n *\n * @docGroup 2. Cache options\n */\n variables?: TVars;\n /**\n * The name of the fragment defined in the fragment document.\n *\n * Required if the fragment document includes more than one fragment,\n * optional otherwise.\n *\n * @docGroup 2. Cache options\n */\n fragmentName?: string;\n /**\n * If `true`, `watchFragment` returns optimistic results.\n *\n * The default value is `true`.\n *\n * @docGroup 2. Cache options\n */\n optimistic?: boolean;\n}\n\n/**\n * Watched fragment results.\n */\nexport type WatchFragmentResult =\n | {\n data: MaybeMasked;\n complete: true;\n missing?: never;\n }\n | {\n data: DeepPartial>;\n complete: false;\n missing: MissingTree;\n };\n\nexport abstract class ApolloCache implements DataProxy {\n public readonly assumeImmutableResults: boolean = false;\n\n // required to implement\n // core API\n public abstract read(\n query: Cache.ReadOptions\n ): Unmasked | null;\n public abstract write(\n write: Cache.WriteOptions\n ): Reference | undefined;\n public abstract diff(query: Cache.DiffOptions): Cache.DiffResult;\n public abstract watch(\n watch: Cache.WatchOptions\n ): () => void;\n\n // Empty the cache and restart all current watches (unless\n // options.discardWatches is true).\n public abstract reset(options?: Cache.ResetOptions): Promise;\n\n // Remove whole objects from the cache by passing just options.id, or\n // specific fields by passing options.field and/or options.args. If no\n // options.args are provided, all fields matching options.field (even\n // those with arguments) will be removed. Returns true iff any data was\n // removed from the cache.\n public abstract evict(options: Cache.EvictOptions): boolean;\n\n // initializer / offline / ssr API\n /**\n * Replaces existing state in the cache (if any) with the values expressed by\n * `serializedState`.\n *\n * Called when hydrating a cache (server side rendering, or offline storage),\n * and also (potentially) during hot reloads.\n */\n public abstract restore(\n serializedState: TSerialized\n ): ApolloCache;\n\n /**\n * Exposes the cache's complete state, in a serializable format for later restoration.\n */\n public abstract extract(optimistic?: boolean): TSerialized;\n\n // Optimistic API\n\n public abstract removeOptimistic(id: string): void;\n\n // Data masking API\n\n // Used by data masking to determine if an inline fragment with a type\n // condition matches a given typename.\n //\n // If not implemented by a cache subclass, data masking will effectively be\n // disabled since we will not be able to accurately determine if a given type\n // condition for a union or interface matches a particular type.\n public fragmentMatches?(\n fragment: InlineFragmentNode,\n typename: string\n ): boolean;\n\n // Function used to lookup a fragment when a fragment definition is not part\n // of the GraphQL document. This is useful for caches, such as InMemoryCache,\n // that register fragments ahead of time so they can be referenced by name.\n public lookupFragment(fragmentName: string): FragmentDefinitionNode | null {\n return null;\n }\n\n // Transactional API\n\n // The batch method is intended to replace/subsume both performTransaction\n // and recordOptimisticTransaction, but performTransaction came first, so we\n // provide a default batch implementation that's just another way of calling\n // performTransaction. Subclasses of ApolloCache (such as InMemoryCache) can\n // override the batch method to do more interesting things with its options.\n public batch(options: Cache.BatchOptions): U {\n const optimisticId =\n typeof options.optimistic === \"string\" ? options.optimistic\n : options.optimistic === false ? null\n : void 0;\n let updateResult: U;\n this.performTransaction(\n () => (updateResult = options.update(this)),\n optimisticId\n );\n return updateResult!;\n }\n\n public abstract performTransaction(\n transaction: Transaction,\n // Although subclasses may implement recordOptimisticTransaction\n // however they choose, the default implementation simply calls\n // performTransaction with a string as the second argument, allowing\n // performTransaction to handle both optimistic and non-optimistic\n // (broadcast-batching) transactions. Passing null for optimisticId is\n // also allowed, and indicates that performTransaction should apply\n // the transaction non-optimistically (ignoring optimistic data).\n optimisticId?: string | null\n ): void;\n\n public recordOptimisticTransaction(\n transaction: Transaction,\n optimisticId: string\n ) {\n this.performTransaction(transaction, optimisticId);\n }\n\n // Optional API\n\n // Called once per input document, allowing the cache to make static changes\n // to the query, such as adding __typename fields.\n public transformDocument(document: DocumentNode): DocumentNode {\n return document;\n }\n\n // Called before each ApolloLink request, allowing the cache to make dynamic\n // changes to the query, such as filling in missing fragment definitions.\n public transformForLink(document: DocumentNode): DocumentNode {\n return document;\n }\n\n public identify(object: StoreObject | Reference): string | undefined {\n return;\n }\n\n public gc(): string[] {\n return [];\n }\n\n public modify = Record>(\n options: Cache.ModifyOptions\n ): boolean {\n return false;\n }\n\n // DataProxy API\n public readQuery(\n options: Cache.ReadQueryOptions,\n optimistic = !!options.optimistic\n ): Unmasked | null {\n return this.read({\n ...options,\n rootId: options.id || \"ROOT_QUERY\",\n optimistic,\n });\n }\n\n /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n public watchFragment(\n options: WatchFragmentOptions\n ): Observable> {\n const {\n fragment,\n fragmentName,\n from,\n optimistic = true,\n ...otherOptions\n } = options;\n const query = this.getFragmentDoc(fragment, fragmentName);\n // While our TypeScript types do not allow for `undefined` as a valid\n // `from`, its possible `useFragment` gives us an `undefined` since it\n // calls` cache.identify` and provides that value to `from`. We are\n // adding this fix here however to ensure those using plain JavaScript\n // and using `cache.identify` themselves will avoid seeing the obscure\n // warning.\n const id =\n typeof from === \"undefined\" || typeof from === \"string\" ?\n from\n : this.identify(from);\n const dataMasking = !!(options as any)[Symbol.for(\"apollo.dataMasking\")];\n\n if (__DEV__) {\n const actualFragmentName =\n fragmentName || getFragmentDefinition(fragment).name.value;\n\n if (!id) {\n invariant.warn(\n \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n actualFragmentName\n );\n }\n }\n\n const diffOptions: Cache.DiffOptions = {\n ...otherOptions,\n returnPartialData: true,\n id,\n query,\n optimistic,\n };\n\n let latestDiff: DataProxy.DiffResult | undefined;\n\n return new Observable((observer) => {\n return this.watch({\n ...diffOptions,\n immediate: true,\n callback: (diff) => {\n const data =\n dataMasking ?\n maskFragment(diff.result, fragment, this, fragmentName)\n : diff.result;\n\n if (\n // Always ensure we deliver the first result\n latestDiff &&\n equalByQuery(\n query,\n { data: latestDiff.result },\n { data },\n // TODO: Fix the type on WatchFragmentOptions so that TVars\n // extends OperationVariables\n options.variables as OperationVariables\n )\n ) {\n return;\n }\n\n const result = {\n data,\n complete: !!diff.complete,\n } as WatchFragmentResult;\n\n if (diff.missing) {\n result.missing = mergeDeepArray(\n diff.missing.map((error) => error.missing)\n );\n }\n\n latestDiff = { ...diff, result: data };\n observer.next(result);\n },\n });\n });\n }\n\n // Make sure we compute the same (===) fragment query document every\n // time we receive the same fragment in readFragment.\n private getFragmentDoc = wrap(getFragmentQueryDocument, {\n max:\n cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n cache: WeakCache,\n });\n\n public readFragment(\n options: Cache.ReadFragmentOptions,\n optimistic = !!options.optimistic\n ): Unmasked | null {\n return this.read({\n ...options,\n query: this.getFragmentDoc(options.fragment, options.fragmentName),\n rootId: options.id,\n optimistic,\n });\n }\n\n public writeQuery({\n id,\n data,\n ...options\n }: Cache.WriteQueryOptions): Reference | undefined {\n return this.write(\n Object.assign(options, {\n dataId: id || \"ROOT_QUERY\",\n result: data,\n })\n );\n }\n\n public writeFragment({\n id,\n data,\n fragment,\n fragmentName,\n ...options\n }: Cache.WriteFragmentOptions): Reference | undefined {\n return this.write(\n Object.assign(options, {\n query: this.getFragmentDoc(fragment, fragmentName),\n dataId: id,\n result: data,\n })\n );\n }\n\n public updateQuery(\n options: Cache.UpdateQueryOptions,\n update: (data: Unmasked | null) => Unmasked | null | void\n ): Unmasked | null {\n return this.batch({\n update(cache) {\n const value = cache.readQuery(options);\n const data = update(value);\n if (data === void 0 || data === null) return value;\n cache.writeQuery({ ...options, data });\n return data;\n },\n });\n }\n\n public updateFragment(\n options: Cache.UpdateFragmentOptions,\n update: (data: Unmasked | null) => Unmasked | null | void\n ): Unmasked | null {\n return this.batch({\n update(cache) {\n const value = cache.readFragment(options);\n const data = update(value);\n if (data === void 0 || data === null) return value;\n cache.writeFragment({ ...options, data });\n return data;\n },\n });\n }\n\n /**\n * @experimental\n * @internal\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n */\n public getMemoryInternals?: typeof getApolloCacheMemoryInternals;\n}\n\nif (__DEV__) {\n ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n","import type { DocumentNode, FieldNode } from \"graphql\";\n\nimport type {\n Reference,\n StoreObject,\n StoreValue,\n isReference,\n AsStoreObject,\n DeepPartial,\n} from \"../../../utilities/index.js\";\n\nimport type { StorageType } from \"../../inmemory/policies.js\";\n\n// The Readonly type only really works for object types, since it marks\n// all of the object's properties as readonly, but there are many cases when\n// a generic type parameter like TExisting might be a string or some other\n// primitive type, in which case we need to avoid wrapping it with Readonly.\n// SafeReadonly collapses to just string, which makes string\n// assignable to SafeReadonly, whereas string is not assignable to\n// Readonly, somewhat surprisingly.\nexport type SafeReadonly = T extends object ? Readonly : T;\n\nexport type MissingTree =\n | string\n | {\n readonly [key: string]: MissingTree;\n };\n\nexport class MissingFieldError extends Error {\n constructor(\n public readonly message: string,\n public readonly path: MissingTree | Array,\n public readonly query: DocumentNode,\n public readonly variables?: Record\n ) {\n // 'Error' breaks prototype chain here\n super(message);\n\n if (Array.isArray(this.path)) {\n this.missing = this.message;\n for (let i = this.path.length - 1; i >= 0; --i) {\n this.missing = { [this.path[i]]: this.missing };\n }\n } else {\n this.missing = this.path;\n }\n\n // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n // on Android (see issue #3236).\n (this as any).__proto__ = MissingFieldError.prototype;\n }\n\n public readonly missing: MissingTree;\n}\n\nexport interface FieldSpecifier {\n typename?: string;\n fieldName: string;\n field?: FieldNode;\n args?: Record;\n variables?: Record;\n}\n\nexport interface ReadFieldOptions extends FieldSpecifier {\n from?: StoreObject | Reference;\n}\n\nexport interface ReadFieldFunction {\n (options: ReadFieldOptions): SafeReadonly | undefined;\n (\n fieldName: string,\n from?: StoreObject | Reference\n ): SafeReadonly | undefined;\n}\n\nexport type ToReferenceFunction = (\n objOrIdOrRef: StoreObject | string | Reference,\n mergeIntoStore?: boolean\n) => Reference | undefined;\n\nexport type CanReadFunction = (value: StoreValue) => boolean;\n\ndeclare const _deleteModifier: unique symbol;\nexport interface DeleteModifier {\n [_deleteModifier]: true;\n}\ndeclare const _invalidateModifier: unique symbol;\nexport interface InvalidateModifier {\n [_invalidateModifier]: true;\n}\ndeclare const _ignoreModifier: unique symbol;\nexport interface IgnoreModifier {\n [_ignoreModifier]: true;\n}\n\nexport type ModifierDetails = {\n DELETE: DeleteModifier;\n INVALIDATE: InvalidateModifier;\n fieldName: string;\n storeFieldName: string;\n readField: ReadFieldFunction;\n canRead: CanReadFunction;\n isReference: typeof isReference;\n toReference: ToReferenceFunction;\n storage: StorageType;\n};\n\nexport type Modifier = (\n value: T,\n details: ModifierDetails\n) => DeepPartial | DeleteModifier | InvalidateModifier | undefined;\n\ntype StoreObjectValueMaybeReference =\n StoreVal extends Array> ?\n StoreVal extends Array ?\n [Item] extends [Record] ?\n ReadonlyArray | Reference>\n : never\n : never\n : StoreVal extends Record ? AsStoreObject | Reference\n : StoreVal;\n\nexport type AllFieldsModifier> = Modifier<\n Entity[keyof Entity] extends infer Value ?\n StoreObjectValueMaybeReference>\n : never\n>;\n\nexport type Modifiers = Record> =\n Partial<{\n [FieldName in keyof T]: Modifier<\n StoreObjectValueMaybeReference>\n >;\n }>;\n","import type {\n DocumentNode,\n FragmentDefinitionNode,\n SelectionSetNode,\n} from \"graphql\";\n\nimport type { NormalizedCache, InMemoryCacheConfig } from \"./types.js\";\n\nimport type { KeyFieldsContext } from \"./policies.js\";\nimport type { FragmentRegistryAPI } from \"./fragmentRegistry.js\";\n\nimport type {\n Reference,\n StoreValue,\n StoreObject,\n FragmentMap,\n FragmentMapFunction,\n} from \"../../utilities/index.js\";\nimport {\n isReference,\n isField,\n DeepMerger,\n resultKeyNameFromField,\n shouldInclude,\n isNonNullObject,\n compact,\n createFragmentMap,\n getFragmentDefinitions,\n isArray,\n} from \"../../utilities/index.js\";\n\nexport const { hasOwnProperty: hasOwn } = Object.prototype;\n\nexport function isNullish(value: any): value is null | undefined {\n return value === null || value === void 0;\n}\n\nexport { isArray };\n\nexport function defaultDataIdFromObject(\n { __typename, id, _id }: Readonly,\n context?: KeyFieldsContext\n): string | undefined {\n if (typeof __typename === \"string\") {\n if (context) {\n context.keyObject =\n !isNullish(id) ? { id }\n : !isNullish(_id) ? { _id }\n : void 0;\n }\n\n // If there is no object.id, fall back to object._id.\n if (isNullish(id) && !isNullish(_id)) {\n id = _id;\n }\n\n if (!isNullish(id)) {\n return `${__typename}:${\n typeof id === \"number\" || typeof id === \"string\" ?\n id\n : JSON.stringify(id)\n }`;\n }\n }\n}\n\nconst defaultConfig = {\n dataIdFromObject: defaultDataIdFromObject,\n addTypename: true,\n resultCaching: true,\n // Thanks to the shouldCanonizeResults helper, this should be the only line\n // you have to change to reenable canonization by default in the future.\n canonizeResults: false,\n};\n\nexport function normalizeConfig(config: InMemoryCacheConfig) {\n return compact(defaultConfig, config);\n}\n\nexport function shouldCanonizeResults(\n config: Pick\n): boolean {\n const value = config.canonizeResults;\n return value === void 0 ? defaultConfig.canonizeResults : value;\n}\n\nexport function getTypenameFromStoreObject(\n store: NormalizedCache,\n objectOrReference: StoreObject | Reference\n): string | undefined {\n return isReference(objectOrReference) ?\n (store.get(objectOrReference.__ref, \"__typename\") as string)\n : objectOrReference && objectOrReference.__typename;\n}\n\nexport const TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\n\nexport function fieldNameFromStoreName(storeFieldName: string): string {\n const match = storeFieldName.match(TypeOrFieldNameRegExp);\n return match ? match[0] : storeFieldName;\n}\n\nexport function selectionSetMatchesResult(\n selectionSet: SelectionSetNode,\n result: Record,\n variables?: Record\n): boolean {\n if (isNonNullObject(result)) {\n return isArray(result) ?\n result.every((item) =>\n selectionSetMatchesResult(selectionSet, item, variables)\n )\n : selectionSet.selections.every((field) => {\n if (isField(field) && shouldInclude(field, variables)) {\n const key = resultKeyNameFromField(field);\n return (\n hasOwn.call(result, key) &&\n (!field.selectionSet ||\n selectionSetMatchesResult(\n field.selectionSet,\n result[key],\n variables\n ))\n );\n }\n // If the selection has been skipped with @skip(true) or\n // @include(false), it should not count against the matching. If\n // the selection is not a field, it must be a fragment (inline or\n // named). We will determine if selectionSetMatchesResult for that\n // fragment when we get to it, so for now we return true.\n return true;\n });\n }\n return false;\n}\n\nexport function storeValueIsStoreObject(\n value: StoreValue\n): value is StoreObject {\n return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\n\nexport function makeProcessedFieldsMerger() {\n return new DeepMerger();\n}\n\nexport function extractFragmentContext(\n document: DocumentNode,\n fragments?: FragmentRegistryAPI\n): {\n fragmentMap: FragmentMap;\n lookupFragment: FragmentMapFunction;\n} {\n // FragmentMap consisting only of fragments defined directly in document, not\n // including other fragments registered in the FragmentRegistry.\n const fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n return {\n fragmentMap,\n lookupFragment(name) {\n let def: FragmentDefinitionNode | null = fragmentMap[name];\n if (!def && fragments) {\n def = fragments.lookup(name);\n }\n return def || null;\n },\n };\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep } from \"optimism\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\n\nimport type {\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n isReference,\n makeReference,\n DeepMerger,\n maybeDeepFreeze,\n canUseWeakMap,\n isNonNullObject,\n} from \"../../utilities/index.js\";\nimport type { NormalizedCache, NormalizedCacheObject } from \"./types.js\";\nimport { hasOwn, fieldNameFromStoreName } from \"./helpers.js\";\nimport type { Policies, StorageType } from \"./policies.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type {\n SafeReadonly,\n Modifier,\n Modifiers,\n ReadFieldOptions,\n ToReferenceFunction,\n CanReadFunction,\n InvalidateModifier,\n DeleteModifier,\n ModifierDetails,\n} from \"../core/types/common.js\";\nimport type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\n\nconst DELETE: DeleteModifier = Object.create(null);\nconst delModifier: Modifier = () => DELETE;\nconst INVALIDATE: InvalidateModifier = Object.create(null);\n\nexport abstract class EntityStore implements NormalizedCache {\n protected data: NormalizedCacheObject = Object.create(null);\n\n constructor(\n public readonly policies: Policies,\n public readonly group: CacheGroup\n ) {}\n\n public abstract addLayer(\n layerId: string,\n replay: (layer: EntityStore) => any\n ): Layer;\n\n public abstract removeLayer(layerId: string): EntityStore;\n\n // Although the EntityStore class is abstract, it contains concrete\n // implementations of the various NormalizedCache interface methods that\n // are inherited by the Root and Layer subclasses.\n\n public toObject(): NormalizedCacheObject {\n return { ...this.data };\n }\n\n public has(dataId: string): boolean {\n return this.lookup(dataId, true) !== void 0;\n }\n\n public get(dataId: string, fieldName: string): StoreValue {\n this.group.depend(dataId, fieldName);\n if (hasOwn.call(this.data, dataId)) {\n const storeObject = this.data[dataId];\n if (storeObject && hasOwn.call(storeObject, fieldName)) {\n return storeObject[fieldName];\n }\n }\n if (\n fieldName === \"__typename\" &&\n hasOwn.call(this.policies.rootTypenamesById, dataId)\n ) {\n return this.policies.rootTypenamesById[dataId];\n }\n if (this instanceof Layer) {\n return this.parent.get(dataId, fieldName);\n }\n }\n\n protected lookup(\n dataId: string,\n dependOnExistence?: boolean\n ): StoreObject | undefined {\n // The has method (above) calls lookup with dependOnExistence = true, so\n // that it can later be invalidated when we add or remove a StoreObject for\n // this dataId. Any consumer who cares about the contents of the StoreObject\n // should not rely on this dependency, since the contents could change\n // without the object being added or removed.\n if (dependOnExistence) this.group.depend(dataId, \"__exists\");\n\n if (hasOwn.call(this.data, dataId)) {\n return this.data[dataId];\n }\n\n if (this instanceof Layer) {\n return this.parent.lookup(dataId, dependOnExistence);\n }\n\n if (this.policies.rootTypenamesById[dataId]) {\n return Object.create(null);\n }\n }\n\n public merge(older: string | StoreObject, newer: StoreObject | string): void {\n let dataId: string | undefined;\n\n // Convert unexpected references to ID strings.\n if (isReference(older)) older = older.__ref;\n if (isReference(newer)) newer = newer.__ref;\n\n const existing: StoreObject | undefined =\n typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n\n const incoming: StoreObject | undefined =\n typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\n\n // If newer was a string ID, but that ID was not defined in this store,\n // then there are no fields to be merged, so we're done.\n if (!incoming) return;\n\n invariant(typeof dataId === \"string\", \"store.merge expects a string ID\");\n\n const merged: StoreObject = new DeepMerger(storeObjectReconciler).merge(\n existing,\n incoming\n );\n\n // Even if merged === existing, existing may have come from a lower\n // layer, so we always need to set this.data[dataId] on this level.\n this.data[dataId] = merged;\n\n if (merged !== existing) {\n delete this.refs[dataId];\n if (this.group.caching) {\n const fieldsToDirty: Record = Object.create(null);\n\n // If we added a new StoreObject where there was previously none, dirty\n // anything that depended on the existence of this dataId, such as the\n // EntityStore#has method.\n if (!existing) fieldsToDirty.__exists = 1;\n\n // Now invalidate dependents who called getFieldValue for any fields\n // that are changing as a result of this merge.\n Object.keys(incoming).forEach((storeFieldName) => {\n if (\n !existing ||\n existing[storeFieldName] !== merged[storeFieldName]\n ) {\n // Always dirty the full storeFieldName, which may include\n // serialized arguments following the fieldName prefix.\n fieldsToDirty[storeFieldName] = 1;\n\n // Also dirty fieldNameFromStoreName(storeFieldName) if it's\n // different from storeFieldName and this field does not have\n // keyArgs configured, because that means the cache can't make\n // any assumptions about how field values with the same field\n // name but different arguments might be interrelated, so it\n // must err on the side of invalidating all field values that\n // share the same short fieldName, regardless of arguments.\n const fieldName = fieldNameFromStoreName(storeFieldName);\n if (\n fieldName !== storeFieldName &&\n !this.policies.hasKeyArgs(merged.__typename, fieldName)\n ) {\n fieldsToDirty[fieldName] = 1;\n }\n\n // If merged[storeFieldName] has become undefined, and this is the\n // Root layer, actually delete the property from the merged object,\n // which is guaranteed to have been created fresh in this method.\n if (merged[storeFieldName] === void 0 && !(this instanceof Layer)) {\n delete merged[storeFieldName];\n }\n }\n });\n\n if (\n fieldsToDirty.__typename &&\n !(existing && existing.__typename) &&\n // Since we return default root __typename strings\n // automatically from store.get, we don't need to dirty the\n // ROOT_QUERY.__typename field if merged.__typename is equal\n // to the default string (usually \"Query\").\n this.policies.rootTypenamesById[dataId] === merged.__typename\n ) {\n delete fieldsToDirty.__typename;\n }\n\n Object.keys(fieldsToDirty).forEach((fieldName) =>\n this.group.dirty(dataId as string, fieldName)\n );\n }\n }\n }\n\n public modify(\n dataId: string,\n fields: Modifier | Modifiers>\n ): boolean {\n const storeObject = this.lookup(dataId);\n\n if (storeObject) {\n const changedFields: Record = Object.create(null);\n let needToMerge = false;\n let allDeleted = true;\n\n const sharedDetails = {\n DELETE,\n INVALIDATE,\n isReference,\n toReference: this.toReference,\n canRead: this.canRead,\n readField: (\n fieldNameOrOptions: string | ReadFieldOptions,\n from?: StoreObject | Reference\n ) =>\n this.policies.readField(\n typeof fieldNameOrOptions === \"string\" ?\n {\n fieldName: fieldNameOrOptions,\n from: from || makeReference(dataId),\n }\n : fieldNameOrOptions,\n { store: this }\n ),\n } satisfies Partial;\n\n Object.keys(storeObject).forEach((storeFieldName) => {\n const fieldName = fieldNameFromStoreName(storeFieldName);\n let fieldValue = storeObject[storeFieldName];\n if (fieldValue === void 0) return;\n const modify: Modifier | undefined =\n typeof fields === \"function\" ? fields : (\n fields[storeFieldName] || fields[fieldName]\n );\n if (modify) {\n let newValue =\n modify === delModifier ? DELETE : (\n modify(maybeDeepFreeze(fieldValue), {\n ...sharedDetails,\n fieldName,\n storeFieldName,\n storage: this.getStorage(dataId, storeFieldName),\n })\n );\n if (newValue === INVALIDATE) {\n this.group.dirty(dataId, storeFieldName);\n } else {\n if (newValue === DELETE) newValue = void 0;\n if (newValue !== fieldValue) {\n changedFields[storeFieldName] = newValue;\n needToMerge = true;\n fieldValue = newValue as StoreValue;\n\n if (__DEV__) {\n const checkReference = (ref: Reference) => {\n if (this.lookup(ref.__ref) === undefined) {\n invariant.warn(\n \"cache.modify: You are trying to write a Reference that is not part of the store: %o\\n\" +\n \"Please make sure to set the `mergeIntoStore` parameter to `true` when creating a Reference that is not part of the store yet:\\n\" +\n \"`toReference(object, true)`\",\n ref\n );\n return true;\n }\n };\n if (isReference(newValue)) {\n checkReference(newValue);\n } else if (Array.isArray(newValue)) {\n // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n let seenReference: boolean = false;\n let someNonReference: unknown;\n for (const value of newValue) {\n if (isReference(value)) {\n seenReference = true;\n if (checkReference(value)) break;\n } else {\n // Do not warn on primitive values, since those could never be represented\n // by a reference. This is a valid (albeit uncommon) use case.\n if (typeof value === \"object\" && !!value) {\n const [id] = this.policies.identify(value);\n // check if object could even be referenced, otherwise we are not interested in it for this warning\n if (id) {\n someNonReference = value;\n }\n }\n }\n if (seenReference && someNonReference !== undefined) {\n invariant.warn(\n \"cache.modify: Writing an array with a mix of both References and Objects will not result in the Objects being normalized correctly.\\n\" +\n \"Please convert the object instance %o to a Reference before writing it to the cache by calling `toReference(object, true)`.\",\n someNonReference\n );\n break;\n }\n }\n }\n }\n }\n }\n }\n if (fieldValue !== void 0) {\n allDeleted = false;\n }\n });\n\n if (needToMerge) {\n this.merge(dataId, changedFields);\n\n if (allDeleted) {\n if (this instanceof Layer) {\n this.data[dataId] = void 0;\n } else {\n delete this.data[dataId];\n }\n this.group.dirty(dataId, \"__exists\");\n }\n\n return true;\n }\n }\n\n return false;\n }\n\n // If called with only one argument, removes the entire entity\n // identified by dataId. If called with a fieldName as well, removes all\n // fields of that entity whose names match fieldName according to the\n // fieldNameFromStoreName helper function. If called with a fieldName\n // and variables, removes all fields of that entity whose names match fieldName\n // and whose arguments when cached exactly match the variables passed.\n public delete(\n dataId: string,\n fieldName?: string,\n args?: Record\n ) {\n const storeObject = this.lookup(dataId);\n if (storeObject) {\n const typename = this.getFieldValue(storeObject, \"__typename\");\n const storeFieldName =\n fieldName && args ?\n this.policies.getStoreFieldName({ typename, fieldName, args })\n : fieldName;\n return this.modify(\n dataId,\n storeFieldName ?\n {\n [storeFieldName]: delModifier,\n }\n : delModifier\n );\n }\n return false;\n }\n\n public evict(options: Cache.EvictOptions, limit: EntityStore): boolean {\n let evicted = false;\n if (options.id) {\n if (hasOwn.call(this.data, options.id)) {\n evicted = this.delete(options.id, options.fieldName, options.args);\n }\n if (this instanceof Layer && this !== limit) {\n evicted = this.parent.evict(options, limit) || evicted;\n }\n // Always invalidate the field to trigger rereading of watched\n // queries, even if no cache data was modified by the eviction,\n // because queries may depend on computed fields with custom read\n // functions, whose values are not stored in the EntityStore.\n if (options.fieldName || evicted) {\n this.group.dirty(options.id, options.fieldName || \"__exists\");\n }\n }\n return evicted;\n }\n\n public clear(): void {\n this.replace(null);\n }\n\n public extract(): NormalizedCacheObject {\n const obj = this.toObject();\n const extraRootIds: string[] = [];\n this.getRootIdSet().forEach((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\n public replace(newData: NormalizedCacheObject | null): void {\n Object.keys(this.data).forEach((dataId) => {\n if (!(newData && hasOwn.call(newData, dataId))) {\n this.delete(dataId);\n }\n });\n if (newData) {\n const { __META, ...rest } = newData;\n Object.keys(rest).forEach((dataId) => {\n this.merge(dataId, rest[dataId] as StoreObject);\n });\n if (__META) {\n __META.extraRootIds.forEach(this.retain, this);\n }\n }\n }\n\n public abstract getStorage(\n idOrObj: string | StoreObject,\n ...storeFieldNames: (string | number)[]\n ): StorageType;\n\n // Maps root entity IDs to the number of times they have been retained, minus\n // the number of times they have been released. Retained entities keep other\n // entities they reference (even indirectly) from being garbage collected.\n private rootIds: {\n [rootId: string]: number;\n } = Object.create(null);\n\n public retain(rootId: string): number {\n return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n }\n\n public release(rootId: string): number {\n if (this.rootIds[rootId] > 0) {\n const count = --this.rootIds[rootId];\n if (!count) delete this.rootIds[rootId];\n return count;\n }\n return 0;\n }\n\n // Return a Set of all the ID strings that have been retained by\n // this layer/root *and* any layers/roots beneath it.\n public getRootIdSet(ids = new Set()) {\n Object.keys(this.rootIds).forEach(ids.add, ids);\n if (this instanceof Layer) {\n this.parent.getRootIdSet(ids);\n } else {\n // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n // always considered roots for garbage collection, regardless of\n // their retainment counts in this.rootIds.\n Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n }\n return ids;\n }\n\n // The goal of garbage collection is to remove IDs from the Root layer of the\n // store that are no longer reachable starting from any IDs that have been\n // explicitly retained (see retain and release, above). Returns an array of\n // dataId strings that were removed from the store.\n public gc() {\n const ids = this.getRootIdSet();\n const snapshot = this.toObject();\n ids.forEach((id) => {\n if (hasOwn.call(snapshot, id)) {\n // Because we are iterating over an ECMAScript Set, the IDs we add here\n // will be visited in later iterations of the forEach loop only if they\n // were not previously contained by the Set.\n Object.keys(this.findChildRefIds(id)).forEach(ids.add, ids);\n // By removing IDs from the snapshot object here, we protect them from\n // getting removed from the root store layer below.\n delete snapshot[id];\n }\n });\n const idsToRemove = Object.keys(snapshot);\n if (idsToRemove.length) {\n let root: EntityStore = this;\n while (root instanceof Layer) root = root.parent;\n idsToRemove.forEach((id) => root.delete(id));\n }\n return idsToRemove;\n }\n\n // Lazily tracks { __ref: } strings contained by this.data[dataId].\n private refs: {\n [dataId: string]: Record;\n } = Object.create(null);\n\n public findChildRefIds(dataId: string): Record {\n if (!hasOwn.call(this.refs, dataId)) {\n const found = (this.refs[dataId] = Object.create(null));\n const root = this.data[dataId];\n if (!root) return found;\n\n const workSet = new Set>([root]);\n // Within the store, only arrays and objects can contain child entity\n // references, so we can prune the traversal using this predicate:\n workSet.forEach((obj) => {\n if (isReference(obj)) {\n found[obj.__ref] = true;\n // In rare cases, a { __ref } Reference object may have other fields.\n // This often indicates a mismerging of References with StoreObjects,\n // but garbage collection should not be fooled by a stray __ref\n // property in a StoreObject (ignoring all the other fields just\n // because the StoreObject looks like a Reference). To avoid this\n // premature termination of findChildRefIds recursion, we fall through\n // to the code below, which will handle any other properties of obj.\n }\n if (isNonNullObject(obj)) {\n Object.keys(obj).forEach((key) => {\n const child = obj[key];\n // No need to add primitive values to the workSet, since they cannot\n // contain reference objects.\n if (isNonNullObject(child)) {\n workSet.add(child);\n }\n });\n }\n });\n }\n return this.refs[dataId];\n }\n\n // Used to compute cache keys specific to this.group.\n /** overload for `InMemoryCache.maybeBroadcastWatch` */\n public makeCacheKey(\n document: DocumentNode,\n callback: Cache.WatchCallback,\n details: string\n ): object;\n /** overload for `StoreReader.executeSelectionSet` */\n public makeCacheKey(\n selectionSet: SelectionSetNode,\n parent: string /* = ( Reference.__ref ) */ | StoreObject,\n varString: string | undefined,\n canonizeResults: boolean\n ): object;\n /** overload for `StoreReader.executeSubSelectedArray` */\n public makeCacheKey(\n field: FieldNode,\n array: readonly any[],\n varString: string | undefined\n ): object;\n /** @deprecated This is only meant for internal usage,\n * in your own code please use a `Trie` instance instead. */\n public makeCacheKey(...args: any[]): object;\n public makeCacheKey() {\n return this.group.keyMaker.lookupArray(arguments);\n }\n\n // Bound function that can be passed around to provide easy access to fields\n // of Reference objects as well as ordinary objects.\n public getFieldValue = (\n objectOrReference: StoreObject | Reference | undefined,\n storeFieldName: string\n ) =>\n maybeDeepFreeze(\n isReference(objectOrReference) ?\n this.get(objectOrReference.__ref, storeFieldName)\n : objectOrReference && objectOrReference[storeFieldName]\n ) as SafeReadonly;\n\n // Returns true for non-normalized StoreObjects and non-dangling\n // References, indicating that readField(name, objOrRef) has a chance of\n // working. Useful for filtering out dangling references from lists.\n public canRead: CanReadFunction = (objOrRef) => {\n return isReference(objOrRef) ?\n this.has(objOrRef.__ref)\n : typeof objOrRef === \"object\";\n };\n\n // Bound function that converts an id or an object with a __typename and\n // primary key fields to a Reference object. If called with a Reference object,\n // that same Reference object is returned. Pass true for mergeIntoStore to persist\n // an object into the store.\n public toReference: ToReferenceFunction = (objOrIdOrRef, mergeIntoStore) => {\n if (typeof objOrIdOrRef === \"string\") {\n return makeReference(objOrIdOrRef);\n }\n\n if (isReference(objOrIdOrRef)) {\n return objOrIdOrRef;\n }\n\n const [id] = this.policies.identify(objOrIdOrRef);\n\n if (id) {\n const ref = makeReference(id);\n if (mergeIntoStore) {\n this.merge(id, objOrIdOrRef);\n }\n return ref;\n }\n };\n}\n\nexport type FieldValueGetter = EntityStore[\"getFieldValue\"];\n\n// A single CacheGroup represents a set of one or more EntityStore objects,\n// typically the Root store in a CacheGroup by itself, and all active Layer\n// stores in a group together. A single EntityStore object belongs to only\n// one CacheGroup, store.group. The CacheGroup is responsible for tracking\n// dependencies, so store.group is helpful for generating unique keys for\n// cached results that need to be invalidated when/if those dependencies\n// change. If we used the EntityStore objects themselves as cache keys (that\n// is, store rather than store.group), the cache would become unnecessarily\n// fragmented by all the different Layer objects. Instead, the CacheGroup\n// approach allows all optimistic Layer objects in the same linked list to\n// belong to one CacheGroup, with the non-optimistic Root object belonging\n// to another CacheGroup, allowing resultCaching dependencies to be tracked\n// separately for optimistic and non-optimistic entity data.\nclass CacheGroup {\n private d: OptimisticDependencyFunction | null = null;\n\n // Used by the EntityStore#makeCacheKey method to compute cache keys\n // specific to this CacheGroup.\n public keyMaker!: Trie;\n\n constructor(\n public readonly caching: boolean,\n private parent: CacheGroup | null = null\n ) {\n this.resetCaching();\n }\n\n public resetCaching() {\n this.d = this.caching ? dep() : null;\n this.keyMaker = new Trie(canUseWeakMap);\n }\n\n public depend(dataId: string, storeFieldName: string) {\n if (this.d) {\n this.d(makeDepKey(dataId, storeFieldName));\n const fieldName = fieldNameFromStoreName(storeFieldName);\n if (fieldName !== storeFieldName) {\n // Fields with arguments that contribute extra identifying\n // information to the fieldName (thus forming the storeFieldName)\n // depend not only on the full storeFieldName but also on the\n // short fieldName, so the field can be invalidated using either\n // level of specificity.\n this.d(makeDepKey(dataId, fieldName));\n }\n if (this.parent) {\n this.parent.depend(dataId, storeFieldName);\n }\n }\n }\n\n public dirty(dataId: string, storeFieldName: string) {\n if (this.d) {\n this.d.dirty(\n makeDepKey(dataId, storeFieldName),\n // When storeFieldName === \"__exists\", that means the entity identified\n // by dataId has either disappeared from the cache or was newly added,\n // so the result caching system would do well to \"forget everything it\n // knows\" about that object. To achieve that kind of invalidation, we\n // not only dirty the associated result cache entry, but also remove it\n // completely from the dependency graph. For the optimism implementation\n // details, see https://github.com/benjamn/optimism/pull/195.\n storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\"\n );\n }\n }\n}\n\nfunction makeDepKey(dataId: string, storeFieldName: string) {\n // Since field names cannot have '#' characters in them, this method\n // of joining the field name and the ID should be unambiguous, and much\n // cheaper than JSON.stringify([dataId, fieldName]).\n return storeFieldName + \"#\" + dataId;\n}\n\nexport function maybeDependOnExistenceOfEntity(\n store: NormalizedCache,\n entityId: string\n) {\n if (supportsResultCaching(store)) {\n // We use this pseudo-field __exists elsewhere in the EntityStore code to\n // represent changes in the existence of the entity object identified by\n // entityId. This dependency gets reliably dirtied whenever an object with\n // this ID is deleted (or newly created) within this group, so any result\n // cache entries (for example, StoreReader#executeSelectionSet results) that\n // depend on __exists for this entityId will get dirtied as well, leading to\n // the eventual recomputation (instead of reuse) of those result objects the\n // next time someone reads them from the cache.\n store.group.depend(entityId, \"__exists\");\n }\n}\n\nexport namespace EntityStore {\n // Refer to this class as EntityStore.Root outside this namespace.\n export class Root extends EntityStore {\n constructor({\n policies,\n resultCaching = true,\n seed,\n }: {\n policies: Policies;\n resultCaching?: boolean;\n seed?: NormalizedCacheObject;\n }) {\n super(policies, new CacheGroup(resultCaching));\n if (seed) this.replace(seed);\n }\n\n public readonly stump = new Stump(this);\n\n public addLayer(\n layerId: string,\n replay: (layer: EntityStore) => any\n ): Layer {\n // Adding an optimistic Layer on top of the Root actually adds the Layer\n // on top of the Stump, so the Stump always comes between the Root and\n // any Layer objects that we've added.\n return this.stump.addLayer(layerId, replay);\n }\n\n public removeLayer(): Root {\n // Never remove the root layer.\n return this;\n }\n\n public readonly storageTrie = new Trie(canUseWeakMap);\n public getStorage(): StorageType {\n return this.storageTrie.lookupArray(arguments);\n }\n }\n}\n\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nclass Layer extends EntityStore {\n constructor(\n public readonly id: string,\n public readonly parent: EntityStore,\n public readonly replay: (layer: EntityStore) => any,\n public readonly group: CacheGroup\n ) {\n super(parent.policies, group);\n replay(this);\n }\n\n public addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer {\n return new Layer(layerId, this, replay, this.group);\n }\n\n public removeLayer(layerId: string): EntityStore {\n // Remove all instances of the given id, not just the first one.\n const parent = this.parent.removeLayer(layerId);\n\n if (layerId === this.id) {\n if (this.group.caching) {\n // Dirty every ID we're removing. Technically we might be able to avoid\n // dirtying fields that have values in higher layers, but we don't have\n // easy access to higher layers here, and we're about to recreate those\n // layers anyway (see parent.addLayer below).\n Object.keys(this.data).forEach((dataId) => {\n const ownStoreObject = this.data[dataId];\n const parentStoreObject = parent[\"lookup\"](dataId);\n if (!parentStoreObject) {\n // The StoreObject identified by dataId was defined in this layer\n // but will be undefined in the parent layer, so we can delete the\n // whole entity using this.delete(dataId). Since we're about to\n // throw this layer away, the only goal of this deletion is to dirty\n // the removed fields.\n this.delete(dataId);\n } else if (!ownStoreObject) {\n // This layer had an entry for dataId but it was undefined, which\n // means the entity was deleted in this layer, and it's about to\n // become undeleted when we remove this layer, so we need to dirty\n // all fields that are about to be reexposed.\n this.group.dirty(dataId, \"__exists\");\n Object.keys(parentStoreObject).forEach((storeFieldName) => {\n this.group.dirty(dataId, storeFieldName);\n });\n } else if (ownStoreObject !== parentStoreObject) {\n // If ownStoreObject is not exactly the same as parentStoreObject,\n // dirty any fields whose values will change as a result of this\n // removal.\n Object.keys(ownStoreObject).forEach((storeFieldName) => {\n if (\n !equal(\n ownStoreObject[storeFieldName],\n parentStoreObject[storeFieldName]\n )\n ) {\n this.group.dirty(dataId, storeFieldName);\n }\n });\n }\n });\n }\n\n return parent;\n }\n\n // No changes are necessary if the parent chain remains identical.\n if (parent === this.parent) return this;\n\n // Recreate this layer on top of the new parent.\n return parent.addLayer(this.id, this.replay);\n }\n\n public toObject(): NormalizedCacheObject {\n return {\n ...this.parent.toObject(),\n ...this.data,\n };\n }\n\n public findChildRefIds(dataId: string): Record {\n const fromParent = this.parent.findChildRefIds(dataId);\n return hasOwn.call(this.data, dataId) ?\n {\n ...fromParent,\n ...super.findChildRefIds(dataId),\n }\n : fromParent;\n }\n\n public getStorage(): StorageType {\n let p: EntityStore = this.parent;\n while ((p as Layer).parent) p = (p as Layer).parent;\n return p.getStorage.apply(\n p,\n // @ts-expect-error\n arguments\n );\n }\n}\n\n// Represents a Layer permanently installed just above the Root, which allows\n// reading optimistically (and registering optimistic dependencies) even when\n// no optimistic layers are currently active. The stump.group CacheGroup object\n// is shared by any/all Layer objects added on top of the Stump.\nclass Stump extends Layer {\n constructor(root: EntityStore.Root) {\n super(\n \"EntityStore.Stump\",\n root,\n () => {},\n new CacheGroup(root.group.caching, root.group)\n );\n }\n\n public removeLayer() {\n // Never remove the Stump layer.\n return this;\n }\n\n public merge(older: string | StoreObject, newer: string | StoreObject) {\n // We never want to write any data into the Stump, so we forward any merge\n // calls to the Root instead. Another option here would be to throw an\n // exception, but the toReference(object, true) function can sometimes\n // trigger Stump writes (which used to be Root writes, before the Stump\n // concept was introduced).\n return this.parent.merge(older, newer);\n }\n}\n\nfunction storeObjectReconciler(\n existingObject: StoreObject,\n incomingObject: StoreObject,\n property: string | number\n): StoreValue {\n const existingValue = existingObject[property];\n const incomingValue = incomingObject[property];\n // Wherever there is a key collision, prefer the incoming value, unless\n // it is deeply equal to the existing value. It's worth checking deep\n // equality here (even though blindly returning incoming would be\n // logically correct) because preserving the referential identity of\n // existing data can prevent needless rereading and rerendering.\n return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\n\nexport function supportsResultCaching(store: any): store is EntityStore {\n // When result caching is disabled, store.depend will be null.\n return !!(store instanceof EntityStore && store.group.caching);\n}\n","import { Trie } from \"@wry/trie\";\nimport {\n canUseWeakMap,\n canUseWeakSet,\n isNonNullObject as isObjectOrArray,\n} from \"../../utilities/index.js\";\nimport { isArray } from \"./helpers.js\";\n\nfunction shallowCopy(value: T): T {\n if (isObjectOrArray(value)) {\n return isArray(value) ?\n (value.slice(0) as any as T)\n : { __proto__: Object.getPrototypeOf(value), ...value };\n }\n return value;\n}\n\n// When programmers talk about the \"canonical form\" of an object, they\n// usually have the following meaning in mind, which I've copied from\n// https://en.wiktionary.org/wiki/canonical_form:\n//\n// 1. A standard or normal presentation of a mathematical entity [or\n// object]. A canonical form is an element of a set of representatives\n// of equivalence classes of forms such that there is a function or\n// procedure which projects every element of each equivalence class\n// onto that one element, the canonical form of that equivalence\n// class. The canonical form is expected to be simpler than the rest of\n// the forms in some way.\n//\n// That's a long-winded way of saying any two objects that have the same\n// canonical form may be considered equivalent, even if they are !==,\n// which usually means the objects are structurally equivalent (deeply\n// equal), but don't necessarily use the same memory.\n//\n// Like a literary or musical canon, this ObjectCanon class represents a\n// collection of unique canonical items (JavaScript objects), with the\n// important property that canon.admit(a) === canon.admit(b) if a and b\n// are deeply equal to each other. In terms of the definition above, the\n// canon.admit method is the \"function or procedure which projects every\"\n// object \"onto that one element, the canonical form.\"\n//\n// In the worst case, the canonicalization process may involve looking at\n// every property in the provided object tree, so it takes the same order\n// of time as deep equality checking. Fortunately, already-canonicalized\n// objects are returned immediately from canon.admit, so the presence of\n// canonical subtrees tends to speed up canonicalization.\n//\n// Since consumers of canonical objects can check for deep equality in\n// constant time, canonicalizing cache results can massively improve the\n// performance of application code that skips re-rendering unchanged\n// results, such as \"pure\" UI components in a framework like React.\n//\n// Of course, since canonical objects may be shared widely between\n// unrelated consumers, it's important to think of them as immutable, even\n// though they are not actually frozen with Object.freeze in production,\n// due to the extra performance overhead that comes with frozen objects.\n//\n// Custom scalar objects whose internal class name is neither Array nor\n// Object can be included safely in the admitted tree, but they will not\n// be replaced with a canonical version (to put it another way, they are\n// assumed to be canonical already).\n//\n// If we ignore custom objects, no detection of cycles or repeated object\n// references is currently required by the StoreReader class, since\n// GraphQL result objects are JSON-serializable trees (and thus contain\n// neither cycles nor repeated subtrees), so we can avoid the complexity\n// of keeping track of objects we've already seen during the recursion of\n// the admit method.\n//\n// In the future, we may consider adding additional cases to the switch\n// statement to handle other common object types, such as \"[object Date]\"\n// objects, as needed.\nexport class ObjectCanon {\n // Set of all canonical objects this ObjectCanon has admitted, allowing\n // canon.admit to return previously-canonicalized objects immediately.\n private known = new (canUseWeakSet ? WeakSet : Set)();\n\n // Efficient storage/lookup structure for canonical objects.\n private pool = new Trie<{\n array?: any[];\n object?: Record;\n keys?: SortedKeysInfo;\n }>(canUseWeakMap);\n\n public isKnown(value: any): boolean {\n return isObjectOrArray(value) && this.known.has(value);\n }\n\n // Make the ObjectCanon assume this value has already been\n // canonicalized.\n private passes = new WeakMap();\n public pass(value: T): T;\n public pass(value: any) {\n if (isObjectOrArray(value)) {\n const copy = shallowCopy(value);\n this.passes.set(copy, value);\n return copy;\n }\n return value;\n }\n\n // Returns the canonical version of value.\n public admit(value: T): T;\n public admit(value: any) {\n if (isObjectOrArray(value)) {\n const original = this.passes.get(value);\n if (original) return original;\n\n const proto = Object.getPrototypeOf(value);\n switch (proto) {\n case Array.prototype: {\n if (this.known.has(value)) return value;\n const array: any[] = (value as any[]).map(this.admit, this);\n // Arrays are looked up in the Trie using their recursively\n // canonicalized elements, and the known version of the array is\n // preserved as node.array.\n const node = this.pool.lookupArray(array);\n if (!node.array) {\n this.known.add((node.array = array));\n // Since canonical arrays may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (__DEV__) {\n Object.freeze(array);\n }\n }\n return node.array;\n }\n\n case null:\n case Object.prototype: {\n if (this.known.has(value)) return value;\n const proto = Object.getPrototypeOf(value);\n const array = [proto];\n const keys = this.sortedKeys(value);\n array.push(keys.json);\n const firstValueIndex = array.length;\n keys.sorted.forEach((key) => {\n array.push(this.admit((value as any)[key]));\n });\n // Objects are looked up in the Trie by their prototype (which\n // is *not* recursively canonicalized), followed by a JSON\n // representation of their (sorted) keys, followed by the\n // sequence of recursively canonicalized values corresponding to\n // those keys. To keep the final results unambiguous with other\n // sequences (such as arrays that just happen to contain [proto,\n // keys.json, value1, value2, ...]), the known version of the\n // object is stored as node.object.\n const node = this.pool.lookupArray(array);\n if (!node.object) {\n const obj = (node.object = Object.create(proto));\n this.known.add(obj);\n keys.sorted.forEach((key, i) => {\n obj[key] = array[firstValueIndex + i];\n });\n // Since canonical objects may be shared widely between\n // unrelated consumers, it's important to regard them as\n // immutable, even if they are not frozen in production.\n if (__DEV__) {\n Object.freeze(obj);\n }\n }\n return node.object;\n }\n }\n }\n return value;\n }\n\n // It's worthwhile to cache the sorting of arrays of strings, since the\n // same initial unsorted arrays tend to be encountered many times.\n // Fortunately, we can reuse the Trie machinery to look up the sorted\n // arrays in linear time (which is faster than sorting large arrays).\n private sortedKeys(obj: object) {\n const keys = Object.keys(obj);\n const node = this.pool.lookupArray(keys);\n if (!node.keys) {\n keys.sort();\n const json = JSON.stringify(keys);\n if (!(node.keys = this.keysByJSON.get(json))) {\n this.keysByJSON.set(json, (node.keys = { sorted: keys, json }));\n }\n }\n return node.keys;\n }\n // Arrays that contain the same elements in a different order can share\n // the same SortedKeysInfo object, to save memory.\n private keysByJSON = new Map();\n\n // This has to come last because it depends on keysByJSON.\n public readonly empty = this.admit({});\n}\n\ntype SortedKeysInfo = {\n sorted: string[];\n json: string;\n};\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\n\nimport type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\nimport { Kind } from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\n\nimport type {\n Reference,\n StoreObject,\n FragmentMap,\n FragmentMapFunction,\n} from \"../../utilities/index.js\";\nimport {\n isField,\n resultKeyNameFromField,\n isReference,\n makeReference,\n shouldInclude,\n addTypenameToDocument,\n getDefaultValues,\n getMainDefinition,\n getQueryDefinition,\n getFragmentFromSelection,\n maybeDeepFreeze,\n mergeDeepArray,\n DeepMerger,\n isNonNullObject,\n canUseWeakMap,\n compact,\n canonicalStringify,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type {\n DiffQueryAgainstStoreOptions,\n InMemoryCacheConfig,\n NormalizedCache,\n ReadMergeModifyContext,\n} from \"./types.js\";\nimport {\n maybeDependOnExistenceOfEntity,\n supportsResultCaching,\n} from \"./entityStore.js\";\nimport {\n isArray,\n extractFragmentContext,\n getTypenameFromStoreObject,\n shouldCanonizeResults,\n} from \"./helpers.js\";\nimport type { Policies } from \"./policies.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { MissingTree } from \"../core/types/common.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport { ObjectCanon } from \"./object-canon.js\";\n\nexport type VariableMap = { [name: string]: any };\n\ninterface ReadContext extends ReadMergeModifyContext {\n query: DocumentNode;\n policies: Policies;\n canonizeResults: boolean;\n fragmentMap: FragmentMap;\n lookupFragment: FragmentMapFunction;\n}\n\nexport type ExecResult = {\n result: R;\n missing?: MissingTree;\n};\n\ntype ExecSelectionSetOptions = {\n selectionSet: SelectionSetNode;\n objectOrReference: StoreObject | Reference;\n enclosingRef: Reference;\n context: ReadContext;\n};\n\ntype ExecSubSelectedArrayOptions = {\n field: FieldNode;\n array: readonly any[];\n enclosingRef: Reference;\n context: ReadContext;\n};\n\nexport interface StoreReaderConfig {\n cache: InMemoryCache;\n addTypename?: boolean;\n resultCacheMaxSize?: number;\n canonizeResults?: boolean;\n canon?: ObjectCanon;\n fragments?: InMemoryCacheConfig[\"fragments\"];\n}\n\n// Arguments type after keyArgs translation.\ntype ExecSelectionSetKeyArgs = [\n SelectionSetNode,\n StoreObject | Reference,\n ReadMergeModifyContext,\n boolean,\n];\n\nfunction execSelectionSetKeyArgs(\n options: ExecSelectionSetOptions\n): ExecSelectionSetKeyArgs {\n return [\n options.selectionSet,\n options.objectOrReference,\n options.context,\n // We split out this property so we can pass different values\n // independently without modifying options.context itself.\n options.context.canonizeResults,\n ];\n}\n\nexport class StoreReader {\n // cached version of executeSelectionSet\n private executeSelectionSet: OptimisticWrapperFunction<\n [ExecSelectionSetOptions], // Actual arguments tuple type.\n ExecResult, // Actual return type.\n ExecSelectionSetKeyArgs\n >;\n\n // cached version of executeSubSelectedArray\n private executeSubSelectedArray: OptimisticWrapperFunction<\n [ExecSubSelectedArrayOptions],\n ExecResult,\n [ExecSubSelectedArrayOptions]\n >;\n\n private config: {\n cache: InMemoryCache;\n addTypename: boolean;\n resultCacheMaxSize?: number;\n canonizeResults: boolean;\n fragments?: InMemoryCacheConfig[\"fragments\"];\n };\n\n private knownResults = new (canUseWeakMap ? WeakMap : Map)<\n Record,\n SelectionSetNode\n >();\n\n public canon: ObjectCanon;\n public resetCanon() {\n this.canon = new ObjectCanon();\n }\n\n constructor(config: StoreReaderConfig) {\n this.config = compact(config, {\n addTypename: config.addTypename !== false,\n canonizeResults: shouldCanonizeResults(config),\n });\n\n this.canon = config.canon || new ObjectCanon();\n\n // memoized functions in this class will be \"garbage-collected\"\n // by recreating the whole `StoreReader` in\n // `InMemoryCache.resetResultsCache`\n // (triggered from `InMemoryCache.gc` with `resetResultCache: true`)\n this.executeSelectionSet = wrap(\n (options) => {\n const { canonizeResults } = options.context;\n\n const peekArgs = execSelectionSetKeyArgs(options);\n\n // Negate this boolean option so we can find out if we've already read\n // this result using the other boolean value.\n peekArgs[3] = !canonizeResults;\n\n const other = this.executeSelectionSet.peek(...peekArgs);\n\n if (other) {\n if (canonizeResults) {\n return {\n ...other,\n // If we previously read this result without canonizing it, we can\n // reuse that result simply by canonizing it now.\n result: this.canon.admit(other.result),\n };\n }\n // If we previously read this result with canonization enabled, we can\n // return that canonized result as-is.\n return other;\n }\n\n maybeDependOnExistenceOfEntity(\n options.context.store,\n options.enclosingRef.__ref\n );\n\n // Finally, if we didn't find any useful previous results, run the real\n // execSelectionSetImpl method with the given options.\n return this.execSelectionSetImpl(options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n keyArgs: execSelectionSetKeyArgs,\n // Note that the parameters of makeCacheKey are determined by the\n // array returned by keyArgs.\n makeCacheKey(selectionSet, parent, context, canonizeResults) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(\n selectionSet,\n isReference(parent) ? parent.__ref : parent,\n context.varString,\n canonizeResults\n );\n }\n },\n }\n );\n\n this.executeSubSelectedArray = wrap(\n (options: ExecSubSelectedArrayOptions) => {\n maybeDependOnExistenceOfEntity(\n options.context.store,\n options.enclosingRef.__ref\n );\n return this.execSubSelectedArrayImpl(options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n makeCacheKey({ field, array, context }) {\n if (supportsResultCaching(context.store)) {\n return context.store.makeCacheKey(field, array, context.varString);\n }\n },\n }\n );\n }\n\n /**\n * Given a store and a query, return as much of the result as possible and\n * identify if any data was missing from the store.\n */\n public diffQueryAgainstStore({\n store,\n query,\n rootId = \"ROOT_QUERY\",\n variables,\n returnPartialData = true,\n canonizeResults = this.config.canonizeResults,\n }: DiffQueryAgainstStoreOptions): Cache.DiffResult {\n const policies = this.config.cache.policies;\n\n variables = {\n ...getDefaultValues(getQueryDefinition(query)),\n ...variables!,\n };\n\n const rootRef = makeReference(rootId);\n const execResult = this.executeSelectionSet({\n selectionSet: getMainDefinition(query).selectionSet,\n objectOrReference: rootRef,\n enclosingRef: rootRef,\n context: {\n store,\n query,\n policies,\n variables,\n varString: canonicalStringify(variables),\n canonizeResults,\n ...extractFragmentContext(query, this.config.fragments),\n },\n });\n\n let missing: MissingFieldError[] | undefined;\n if (execResult.missing) {\n // For backwards compatibility we still report an array of\n // MissingFieldError objects, even though there will only ever be at most\n // one of them, now that all missing field error messages are grouped\n // together in the execResult.missing tree.\n missing = [\n new MissingFieldError(\n firstMissing(execResult.missing)!,\n execResult.missing,\n query,\n variables\n ),\n ];\n if (!returnPartialData) {\n throw missing[0];\n }\n }\n\n return {\n result: execResult.result,\n complete: !missing,\n missing,\n };\n }\n\n public isFresh(\n result: Record,\n parent: StoreObject | Reference,\n selectionSet: SelectionSetNode,\n context: ReadMergeModifyContext\n ): boolean {\n if (\n supportsResultCaching(context.store) &&\n this.knownResults.get(result) === selectionSet\n ) {\n const latest = this.executeSelectionSet.peek(\n selectionSet,\n parent,\n context,\n // If result is canonical, then it could only have been previously\n // cached by the canonizing version of executeSelectionSet, so we can\n // avoid checking both possibilities here.\n this.canon.isKnown(result)\n );\n if (latest && result === latest.result) {\n return true;\n }\n }\n return false;\n }\n\n // Uncached version of executeSelectionSet.\n private execSelectionSetImpl({\n selectionSet,\n objectOrReference,\n enclosingRef,\n context,\n }: ExecSelectionSetOptions): ExecResult {\n if (\n isReference(objectOrReference) &&\n !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n !context.store.has(objectOrReference.__ref)\n ) {\n return {\n result: this.canon.empty,\n missing: `Dangling reference to missing ${objectOrReference.__ref} object`,\n };\n }\n\n const { variables, policies, store } = context;\n const typename = store.getFieldValue(\n objectOrReference,\n \"__typename\"\n );\n\n const objectsToMerge: Record[] = [];\n let missing: MissingTree | undefined;\n const missingMerger = new DeepMerger();\n\n if (\n this.config.addTypename &&\n typeof typename === \"string\" &&\n !policies.rootIdsByTypename[typename]\n ) {\n // Ensure we always include a default value for the __typename\n // field, if we have one, and this.config.addTypename is true. Note\n // that this field can be overridden by other merged objects.\n objectsToMerge.push({ __typename: typename });\n }\n\n function handleMissing(result: ExecResult, resultName: string): T {\n if (result.missing) {\n missing = missingMerger.merge(missing, {\n [resultName]: result.missing,\n });\n }\n return result.result;\n }\n\n const workSet = new Set(selectionSet.selections);\n\n workSet.forEach((selection) => {\n // Omit fields with directives @skip(if: ) or\n // @include(if: ).\n if (!shouldInclude(selection, variables)) return;\n\n if (isField(selection)) {\n let fieldValue = policies.readField(\n {\n fieldName: selection.name.value,\n field: selection,\n variables: context.variables,\n from: objectOrReference,\n },\n context\n );\n\n const resultName = resultKeyNameFromField(selection);\n\n if (fieldValue === void 0) {\n if (!addTypenameToDocument.added(selection)) {\n missing = missingMerger.merge(missing, {\n [resultName]: `Can't find field '${selection.name.value}' on ${\n isReference(objectOrReference) ?\n objectOrReference.__ref + \" object\"\n : \"object \" + JSON.stringify(objectOrReference, null, 2)\n }`,\n });\n }\n } else if (isArray(fieldValue)) {\n if (fieldValue.length > 0) {\n fieldValue = handleMissing(\n this.executeSubSelectedArray({\n field: selection,\n array: fieldValue,\n enclosingRef,\n context,\n }),\n resultName\n );\n }\n } else if (!selection.selectionSet) {\n // If the field does not have a selection set, then we handle it\n // as a scalar value. To keep this.canon from canonicalizing\n // this value, we use this.canon.pass to wrap fieldValue in a\n // Pass object that this.canon.admit will later unwrap as-is.\n if (context.canonizeResults) {\n fieldValue = this.canon.pass(fieldValue);\n }\n } else if (fieldValue != null) {\n // In this case, because we know the field has a selection set,\n // it must be trying to query a GraphQLObjectType, which is why\n // fieldValue must be != null.\n fieldValue = handleMissing(\n this.executeSelectionSet({\n selectionSet: selection.selectionSet,\n objectOrReference: fieldValue as StoreObject | Reference,\n enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n context,\n }),\n resultName\n );\n }\n\n if (fieldValue !== void 0) {\n objectsToMerge.push({ [resultName]: fieldValue });\n }\n } else {\n const fragment = getFragmentFromSelection(\n selection,\n context.lookupFragment\n );\n\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(`No fragment named %s`, selection.name.value);\n }\n\n if (fragment && policies.fragmentMatches(fragment, typename)) {\n fragment.selectionSet.selections.forEach(workSet.add, workSet);\n }\n }\n });\n\n const result = mergeDeepArray(objectsToMerge);\n const finalResult: ExecResult = { result, missing };\n const frozen =\n context.canonizeResults ?\n this.canon.admit(finalResult)\n // Since this.canon is normally responsible for freezing results (only in\n // development), freeze them manually if canonization is disabled.\n : maybeDeepFreeze(finalResult);\n\n // Store this result with its selection set so that we can quickly\n // recognize it again in the StoreReader#isFresh method.\n if (frozen.result) {\n this.knownResults.set(frozen.result, selectionSet);\n }\n\n return frozen;\n }\n\n // Uncached version of executeSubSelectedArray.\n private execSubSelectedArrayImpl({\n field,\n array,\n enclosingRef,\n context,\n }: ExecSubSelectedArrayOptions): ExecResult {\n let missing: MissingTree | undefined;\n let missingMerger = new DeepMerger();\n\n function handleMissing(childResult: ExecResult, i: number): T {\n if (childResult.missing) {\n missing = missingMerger.merge(missing, { [i]: childResult.missing });\n }\n return childResult.result;\n }\n\n if (field.selectionSet) {\n array = array.filter(context.store.canRead);\n }\n\n array = array.map((item, i) => {\n // null value in array\n if (item === null) {\n return null;\n }\n\n // This is a nested array, recurse\n if (isArray(item)) {\n return handleMissing(\n this.executeSubSelectedArray({\n field,\n array: item,\n enclosingRef,\n context,\n }),\n i\n );\n }\n\n // This is an object, run the selection set on it\n if (field.selectionSet) {\n return handleMissing(\n this.executeSelectionSet({\n selectionSet: field.selectionSet,\n objectOrReference: item,\n enclosingRef: isReference(item) ? item : enclosingRef,\n context,\n }),\n i\n );\n }\n\n if (__DEV__) {\n assertSelectionSetForIdValue(context.store, field, item);\n }\n\n return item;\n });\n\n return {\n result: context.canonizeResults ? this.canon.admit(array) : array,\n missing,\n };\n }\n}\n\nfunction firstMissing(tree: MissingTree): string | undefined {\n try {\n JSON.stringify(tree, (_, value) => {\n if (typeof value === \"string\") throw value;\n return value;\n });\n } catch (result) {\n return result as string;\n }\n}\n\nfunction assertSelectionSetForIdValue(\n store: NormalizedCache,\n field: FieldNode,\n fieldValue: any\n) {\n if (!field.selectionSet) {\n const workSet = new Set([fieldValue]);\n workSet.forEach((value) => {\n if (isNonNullObject(value)) {\n invariant(\n !isReference(value),\n `Missing selection set for object of type %s returned for query field %s`,\n getTypenameFromStoreObject(store, value),\n field.name.value\n );\n Object.values(value).forEach(workSet.add, workSet);\n }\n });\n }\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport {\n argumentsObjectFromField,\n DeepMerger,\n isNonEmptyArray,\n isNonNullObject,\n} from \"../../utilities/index.js\";\n\nimport { hasOwn, isArray } from \"./helpers.js\";\nimport type {\n KeySpecifier,\n KeyFieldsFunction,\n KeyArgsFunction,\n} from \"./policies.js\";\n\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nconst specifierInfoCache: Record<\n string,\n {\n paths?: string[][];\n keyFieldsFn?: KeyFieldsFunction;\n keyArgsFn?: KeyArgsFunction;\n }\n> = Object.create(null);\n\nfunction lookupSpecifierInfo(spec: KeySpecifier) {\n // It's safe to encode KeySpecifier arrays with JSON.stringify, since they're\n // just arrays of strings or nested KeySpecifier arrays, and the order of the\n // array elements is important (and suitably preserved by JSON.stringify).\n const cacheKey = JSON.stringify(spec);\n return (\n specifierInfoCache[cacheKey] ||\n (specifierInfoCache[cacheKey] = Object.create(null))\n );\n}\n\nexport function keyFieldsFnFromSpecifier(\n specifier: KeySpecifier\n): KeyFieldsFunction {\n const info = lookupSpecifierInfo(specifier);\n\n return (\n info.keyFieldsFn ||\n (info.keyFieldsFn = (object, context) => {\n const extract: typeof extractKey = (from, key) =>\n context.readField(key, from);\n\n const keyObject = (context.keyObject = collectSpecifierPaths(\n specifier,\n (schemaKeyPath) => {\n let extracted = extractKeyPath(\n context.storeObject,\n schemaKeyPath,\n // Using context.readField to extract paths from context.storeObject\n // allows the extraction to see through Reference objects and respect\n // custom read functions.\n extract\n );\n\n if (\n extracted === void 0 &&\n object !== context.storeObject &&\n hasOwn.call(object, schemaKeyPath[0])\n ) {\n // If context.storeObject fails to provide a value for the requested\n // path, fall back to the raw result object, if it has a top-level key\n // matching the first key in the path (schemaKeyPath[0]). This allows\n // key fields included in the written data to be saved in the cache\n // even if they are not selected explicitly in context.selectionSet.\n // Not being mentioned by context.selectionSet is convenient here,\n // since it means these extra fields cannot be affected by field\n // aliasing, which is why we can use extractKey instead of\n // context.readField for this extraction.\n extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n }\n\n invariant(\n extracted !== void 0,\n `Missing field '%s' while extracting keyFields from %s`,\n schemaKeyPath.join(\".\"),\n object\n );\n\n return extracted;\n }\n ));\n\n return `${context.typename}:${JSON.stringify(keyObject)}`;\n })\n );\n}\n\n// The keyArgs extraction process is roughly analogous to keyFields extraction,\n// but there are no aliases involved, missing fields are tolerated (by merely\n// omitting them from the key), and drawing from field.directives or variables\n// is allowed (in addition to drawing from the field's arguments object).\n// Concretely, these differences mean passing a different key path extractor\n// function to collectSpecifierPaths, reusing the shared extractKeyPath helper\n// wherever possible.\nexport function keyArgsFnFromSpecifier(\n specifier: KeySpecifier\n): KeyArgsFunction {\n const info = lookupSpecifierInfo(specifier);\n\n return (\n info.keyArgsFn ||\n (info.keyArgsFn = (args, { field, variables, fieldName }) => {\n const collected = collectSpecifierPaths(specifier, (keyPath) => {\n const firstKey = keyPath[0];\n const firstChar = firstKey.charAt(0);\n\n if (firstChar === \"@\") {\n if (field && isNonEmptyArray(field.directives)) {\n const directiveName = firstKey.slice(1);\n // If the directive appears multiple times, only the first\n // occurrence's arguments will be used. TODO Allow repetition?\n // TODO Cache this work somehow, a la aliasMap?\n const d = field.directives.find(\n (d) => d.name.value === directiveName\n );\n // Fortunately argumentsObjectFromField works for DirectiveNode!\n const directiveArgs = d && argumentsObjectFromField(d, variables);\n // For directives without arguments (d defined, but directiveArgs ===\n // null), the presence or absence of the directive still counts as\n // part of the field key, so we return null in those cases. If no\n // directive with this name was found for this field (d undefined and\n // thus directiveArgs undefined), we return undefined, which causes\n // this value to be omitted from the key object returned by\n // collectSpecifierPaths.\n return (\n directiveArgs &&\n extractKeyPath(\n directiveArgs,\n // If keyPath.length === 1, this code calls extractKeyPath with an\n // empty path, which works because it uses directiveArgs as the\n // extracted value.\n keyPath.slice(1)\n )\n );\n }\n // If the key started with @ but there was no corresponding directive,\n // we want to omit this value from the key object, not fall through to\n // treating @whatever as a normal argument name.\n return;\n }\n\n if (firstChar === \"$\") {\n const variableName = firstKey.slice(1);\n if (variables && hasOwn.call(variables, variableName)) {\n const varKeyPath = keyPath.slice(0);\n varKeyPath[0] = variableName;\n return extractKeyPath(variables, varKeyPath);\n }\n // If the key started with $ but there was no corresponding variable, we\n // want to omit this value from the key object, not fall through to\n // treating $whatever as a normal argument name.\n return;\n }\n\n if (args) {\n return extractKeyPath(args, keyPath);\n }\n });\n\n const suffix = JSON.stringify(collected);\n\n // If no arguments were passed to this field, and it didn't have any other\n // field key contributions from directives or variables, hide the empty\n // :{} suffix from the field key. However, a field passed no arguments can\n // still end up with a non-empty :{...} suffix if its key configuration\n // refers to directives or variables.\n if (args || suffix !== \"{}\") {\n fieldName += \":\" + suffix;\n }\n\n return fieldName;\n })\n );\n}\n\nexport function collectSpecifierPaths(\n specifier: KeySpecifier,\n extractor: (path: string[]) => any\n): Record {\n // For each path specified by specifier, invoke the extractor, and repeatedly\n // merge the results together, with appropriate ancestor context.\n const merger = new DeepMerger();\n return getSpecifierPaths(specifier).reduce((collected, path) => {\n let toMerge = extractor(path);\n if (toMerge !== void 0) {\n // This path is not expected to contain array indexes, so the toMerge\n // reconstruction will not contain arrays. TODO Fix this?\n for (let i = path.length - 1; i >= 0; --i) {\n toMerge = { [path[i]]: toMerge };\n }\n collected = merger.merge(collected, toMerge);\n }\n return collected;\n }, Object.create(null));\n}\n\nexport function getSpecifierPaths(spec: KeySpecifier): string[][] {\n const info = lookupSpecifierInfo(spec);\n\n if (!info.paths) {\n const paths: string[][] = (info.paths = []);\n const currentPath: string[] = [];\n\n spec.forEach((s, i) => {\n if (isArray(s)) {\n getSpecifierPaths(s).forEach((p) => paths.push(currentPath.concat(p)));\n currentPath.length = 0;\n } else {\n currentPath.push(s);\n if (!isArray(spec[i + 1])) {\n paths.push(currentPath.slice(0));\n currentPath.length = 0;\n }\n }\n });\n }\n\n return info.paths!;\n}\n\nfunction extractKey, TKey extends string>(\n object: TObj,\n key: TKey\n): TObj[TKey] | undefined {\n return object[key];\n}\n\nexport function extractKeyPath(\n object: Record,\n path: string[],\n extract?: typeof extractKey\n): any {\n // For each key in path, extract the corresponding child property from obj,\n // flattening arrays if encountered (uncommon for keyFields and keyArgs, but\n // possible). The final result of path.reduce is normalized so unexpected leaf\n // objects have their keys safely sorted. That final result is difficult to\n // type as anything other than any. You're welcome to try to improve the\n // return type, but keep in mind extractKeyPath is not a public function\n // (exported only for testing), so the effort may not be worthwhile unless the\n // limited set of actual callers (see above) pass arguments that TypeScript\n // can statically type. If we know only that path is some array of strings\n // (and not, say, a specific tuple of statically known strings), any (or\n // possibly unknown) is the honest answer.\n extract = extract || extractKey;\n return normalize(\n path.reduce(function reducer(obj, key): any {\n return isArray(obj) ?\n obj.map((child) => reducer(child, key))\n : obj && extract!(obj, key);\n }, object)\n );\n}\n\nfunction normalize(value: T): T {\n // Usually the extracted value will be a scalar value, since most primary\n // key fields are scalar, but just in case we get an object or an array, we\n // need to do some normalization of the order of (nested) keys.\n if (isNonNullObject(value)) {\n if (isArray(value)) {\n return value.map(normalize) as any;\n }\n return collectSpecifierPaths(Object.keys(value).sort(), (path) =>\n extractKeyPath(value, path)\n ) as T;\n }\n return value;\n}\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\n\nimport type {\n InlineFragmentNode,\n FragmentDefinitionNode,\n SelectionSetNode,\n FieldNode,\n} from \"graphql\";\n\nimport type {\n FragmentMap,\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n storeKeyNameFromField,\n argumentsObjectFromField,\n isReference,\n getStoreKeyName,\n isNonNullObject,\n stringifyForDisplay,\n} from \"../../utilities/index.js\";\nimport type {\n IdGetter,\n MergeInfo,\n NormalizedCache,\n ReadMergeModifyContext,\n} from \"./types.js\";\nimport {\n hasOwn,\n fieldNameFromStoreName,\n storeValueIsStoreObject,\n selectionSetMatchesResult,\n TypeOrFieldNameRegExp,\n defaultDataIdFromObject,\n isArray,\n} from \"./helpers.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type {\n SafeReadonly,\n FieldSpecifier,\n ToReferenceFunction,\n ReadFieldFunction,\n ReadFieldOptions,\n CanReadFunction,\n} from \"../core/types/common.js\";\nimport type { WriteContext } from \"./writeToStore.js\";\n\nimport {\n keyArgsFnFromSpecifier,\n keyFieldsFnFromSpecifier,\n} from \"./key-extractor.js\";\nimport { disableWarningsSlot } from \"../../masking/index.js\";\n\nexport type TypePolicies = {\n [__typename: string]: TypePolicy;\n};\n\n// TypeScript 3.7 will allow recursive type aliases, so this should work:\n// type KeySpecifier = (string | KeySpecifier)[]\nexport type KeySpecifier = ReadonlyArray;\n\nexport type KeyFieldsContext = {\n // The __typename of the incoming object, even if the __typename field was\n // aliased to another name in the raw result object. May be undefined when\n // dataIdFromObject is called for objects without __typename fields.\n typename: string | undefined;\n\n // The object to be identified, after processing to remove aliases and\n // normalize identifiable child objects with references.\n storeObject: StoreObject;\n\n // Handy tool for reading additional fields from context.storeObject, either\n // readField(\"fieldName\") to read storeObject[fieldName], or readField(\"name\",\n // objectOrReference) to read from another object or Reference. If you read a\n // field with a read function, that function will be invoked.\n readField: ReadFieldFunction;\n\n // If you are writing a custom keyFields function, and you plan to use the raw\n // result object passed as the first argument, you may also need access to the\n // selection set and available fragments for this object, just in case any\n // fields have aliases. Since this logic is tricky to get right, and these\n // context properties are not even always provided (for example, they are\n // omitted when calling cache.identify(object), where object is assumed to be\n // a StoreObject), we recommend you use context.storeObject (which has already\n // been de-aliased) and context.readField (which can read from references as\n // well as objects) instead of the raw result object in your keyFields\n // functions, or just rely on the internal implementation of keyFields:[...]\n // syntax to get these details right for you.\n selectionSet?: SelectionSetNode;\n fragmentMap?: FragmentMap;\n\n // Internal. May be set by the KeyFieldsFunction to report fields that were\n // involved in computing the ID. Never passed in by the caller.\n keyObject?: Record;\n};\n\nexport type KeyFieldsFunction = (\n object: Readonly,\n context: KeyFieldsContext\n) => KeySpecifier | false | ReturnType;\n\ntype KeyFieldsResult = Exclude, KeySpecifier>;\n\n// TODO Should TypePolicy be a generic type, with a TObject or TEntity\n// type parameter?\nexport type TypePolicy = {\n // Allows defining the primary key fields for this type, either using an\n // array of field names or a function that returns an arbitrary string.\n keyFields?: KeySpecifier | KeyFieldsFunction | false;\n\n // Allows defining a merge function (or merge:true/false shorthand) to\n // be used for merging objects of this type wherever they appear, unless\n // the parent field also defines a merge function/boolean (that is,\n // parent field merge functions take precedence over type policy merge\n // functions). In many cases, defining merge:true for a given type\n // policy can save you from specifying merge:true for all the field\n // policies where that type might be encountered.\n merge?: FieldMergeFunction | boolean;\n\n // In the rare event that your schema happens to use a different\n // __typename for the root Query, Mutation, and/or Schema types, you can\n // express your deviant preferences by enabling one of these options.\n queryType?: true;\n mutationType?: true;\n subscriptionType?: true;\n\n fields?: {\n [fieldName: string]: FieldPolicy | FieldReadFunction;\n };\n};\n\nexport type KeyArgsFunction = (\n args: Record | null,\n context: {\n typename: string;\n fieldName: string;\n field: FieldNode | null;\n variables?: Record;\n }\n) => KeySpecifier | false | ReturnType;\n\nexport type FieldPolicy<\n // The internal representation used to store the field's data in the\n // cache. Must be JSON-serializable if you plan to serialize the result\n // of cache.extract() using JSON.\n TExisting = any,\n // The type of the incoming parameter passed to the merge function,\n // typically matching the GraphQL response format, but with Reference\n // objects substituted for any identifiable child objects. Often the\n // same as TExisting, but not necessarily.\n TIncoming = TExisting,\n // The type that the read function actually returns, using TExisting\n // data and options.args as input. Usually the same as TIncoming.\n TReadResult = TIncoming,\n // Allows FieldFunctionOptions definition to be overwritten by the\n // developer\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = {\n keyArgs?: KeySpecifier | KeyArgsFunction | false;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction | boolean;\n};\n\nexport type StorageType = Record;\n\nfunction argsFromFieldSpecifier(spec: FieldSpecifier) {\n return (\n spec.args !== void 0 ? spec.args\n : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n : null\n );\n}\n\nexport interface FieldFunctionOptions<\n TArgs = Record,\n TVars = Record,\n> {\n args: TArgs | null;\n\n // The name of the field, equal to options.field.name.value when\n // options.field is available. Useful if you reuse the same function for\n // multiple fields, and you need to know which field you're currently\n // processing. Always a string, even when options.field is null.\n fieldName: string;\n\n // The full field key used internally, including serialized key arguments.\n storeFieldName: string;\n\n // The FieldNode object used to read this field. Useful if you need to\n // know about other attributes of the field, such as its directives. This\n // option will be null when a string was passed to options.readField.\n field: FieldNode | null;\n\n variables?: TVars;\n\n // Utilities for dealing with { __ref } objects.\n isReference: typeof isReference;\n toReference: ToReferenceFunction;\n\n // A handy place to put field-specific data that you want to survive\n // across multiple read function calls. Useful for field-level caching,\n // if your read function does any expensive work.\n storage: StorageType;\n\n cache: InMemoryCache;\n\n // Helper function for reading other fields within the current object.\n // If a foreign object or reference is provided, the field will be read\n // from that object instead of the current object, so this function can\n // be used (together with isReference) to examine the cache outside the\n // current object. If a FieldNode is passed instead of a string, and\n // that FieldNode has arguments, the same options.variables will be used\n // to compute the argument values. Note that this function will invoke\n // custom read functions for other fields, if defined. Always returns\n // immutable data (enforced with Object.freeze in development).\n readField: ReadFieldFunction;\n\n // Returns true for non-normalized StoreObjects and non-dangling\n // References, indicating that readField(name, objOrRef) has a chance of\n // working. Useful for filtering out dangling references from lists.\n canRead: CanReadFunction;\n\n // Instead of just merging objects with { ...existing, ...incoming }, this\n // helper function can be used to merge objects in a way that respects any\n // custom merge functions defined for their fields.\n mergeObjects: MergeObjectsFunction;\n}\n\ntype MergeObjectsFunction = (\n existing: T,\n incoming: T\n) => T;\n\nexport type FieldReadFunction<\n TExisting = any,\n TReadResult = TExisting,\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = (\n // When reading a field, one often needs to know about any existing\n // value stored for that field. If the field is read before any value\n // has been written to the cache, this existing parameter will be\n // undefined, which makes it easy to use a default parameter expression\n // to supply the initial value. This parameter is positional (rather\n // than one of the named options) because that makes it possible for the\n // developer to annotate it with a type, without also having to provide\n // a whole new type for the options object.\n existing: SafeReadonly | undefined,\n options: TOptions\n) => TReadResult | undefined;\n\nexport type FieldMergeFunction<\n TExisting = any,\n TIncoming = TExisting,\n // Passing the whole FieldFunctionOptions makes the current definition\n // independent from its implementation\n TOptions extends FieldFunctionOptions = FieldFunctionOptions,\n> = (\n existing: SafeReadonly | undefined,\n // The incoming parameter needs to be positional as well, for the same\n // reasons discussed in FieldReadFunction above.\n incoming: SafeReadonly,\n options: TOptions\n) => SafeReadonly;\n\nconst nullKeyFieldsFn: KeyFieldsFunction = () => void 0;\nconst simpleKeyArgsFn: KeyArgsFunction = (_args, context) => context.fieldName;\n\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nconst mergeTrueFn: FieldMergeFunction = (\n existing,\n incoming,\n { mergeObjects }\n) => mergeObjects(existing, incoming);\nconst mergeFalseFn: FieldMergeFunction = (_, incoming) => incoming;\n\nexport type PossibleTypesMap = {\n [supertype: string]: string[];\n};\n\nexport class Policies {\n private typePolicies: {\n [__typename: string]: {\n keyFn?: KeyFieldsFunction;\n merge?: FieldMergeFunction;\n fields: {\n [fieldName: string]: {\n keyFn?: KeyArgsFunction;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction;\n };\n };\n };\n } = Object.create(null);\n\n private toBeAdded: {\n [__typename: string]: TypePolicy[];\n } = Object.create(null);\n\n // Map from subtype names to sets of supertype names. Note that this\n // representation inverts the structure of possibleTypes (whose keys are\n // supertypes and whose values are arrays of subtypes) because it tends\n // to be much more efficient to search upwards than downwards.\n private supertypeMap = new Map>();\n\n // Any fuzzy subtypes specified by possibleTypes will be converted to\n // RegExp objects and recorded here. Every key of this map can also be\n // found in supertypeMap. In many cases this Map will be empty, which\n // means no fuzzy subtype checking will happen in fragmentMatches.\n private fuzzySubtypes = new Map();\n\n public readonly cache: InMemoryCache;\n\n public readonly rootIdsByTypename: Record =\n Object.create(null);\n public readonly rootTypenamesById: Record =\n Object.create(null);\n\n public readonly usingPossibleTypes = false;\n\n constructor(\n private config: {\n cache: InMemoryCache;\n dataIdFromObject?: KeyFieldsFunction;\n possibleTypes?: PossibleTypesMap;\n typePolicies?: TypePolicies;\n }\n ) {\n this.config = {\n dataIdFromObject: defaultDataIdFromObject,\n ...config,\n };\n\n this.cache = this.config.cache;\n\n this.setRootTypename(\"Query\");\n this.setRootTypename(\"Mutation\");\n this.setRootTypename(\"Subscription\");\n\n if (config.possibleTypes) {\n this.addPossibleTypes(config.possibleTypes);\n }\n\n if (config.typePolicies) {\n this.addTypePolicies(config.typePolicies);\n }\n }\n\n public identify(\n object: StoreObject,\n partialContext?: Partial\n ): [string?, StoreObject?] {\n const policies = this;\n\n const typename =\n (partialContext &&\n (partialContext.typename || partialContext.storeObject?.__typename)) ||\n object.__typename;\n\n // It should be possible to write root Query fields with writeFragment,\n // using { __typename: \"Query\", ... } as the data, but it does not make\n // sense to allow the same identification behavior for the Mutation and\n // Subscription types, since application code should never be writing\n // directly to (or reading directly from) those root objects.\n if (typename === this.rootTypenamesById.ROOT_QUERY) {\n return [\"ROOT_QUERY\"];\n }\n\n // Default context.storeObject to object if not otherwise provided.\n const storeObject =\n (partialContext && partialContext.storeObject) || object;\n\n const context: KeyFieldsContext = {\n ...partialContext,\n typename,\n storeObject,\n readField:\n (partialContext && partialContext.readField) ||\n function () {\n const options = normalizeReadFieldOptions(arguments, storeObject);\n return policies.readField(options, {\n store: policies.cache[\"data\"],\n variables: options.variables,\n });\n },\n };\n\n let id: KeyFieldsResult;\n\n const policy = typename && this.getTypePolicy(typename);\n let keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n\n disableWarningsSlot.withValue(true, () => {\n while (keyFn) {\n const specifierOrId = keyFn({ ...object, ...storeObject }, context);\n if (isArray(specifierOrId)) {\n keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n } else {\n id = specifierOrId;\n break;\n }\n }\n });\n\n id = id ? String(id) : void 0;\n return context.keyObject ? [id, context.keyObject] : [id];\n }\n\n public addTypePolicies(typePolicies: TypePolicies) {\n Object.keys(typePolicies).forEach((typename) => {\n const { queryType, mutationType, subscriptionType, ...incoming } =\n typePolicies[typename];\n\n // Though {query,mutation,subscription}Type configurations are rare,\n // it's important to call setRootTypename as early as possible,\n // since these configurations should apply consistently for the\n // entire lifetime of the cache. Also, since only one __typename can\n // qualify as one of these root types, these three properties cannot\n // be inherited, unlike the rest of the incoming properties. That\n // restriction is convenient, because the purpose of this.toBeAdded\n // is to delay the processing of type/field policies until the first\n // time they're used, allowing policies to be added in any order as\n // long as all relevant policies (including policies for supertypes)\n // have been added by the time a given policy is used for the first\n // time. In other words, since inheritance doesn't matter for these\n // properties, there's also no need to delay their processing using\n // the this.toBeAdded queue.\n if (queryType) this.setRootTypename(\"Query\", typename);\n if (mutationType) this.setRootTypename(\"Mutation\", typename);\n if (subscriptionType) this.setRootTypename(\"Subscription\", typename);\n\n if (hasOwn.call(this.toBeAdded, typename)) {\n this.toBeAdded[typename].push(incoming);\n } else {\n this.toBeAdded[typename] = [incoming];\n }\n });\n }\n\n private updateTypePolicy(typename: string, incoming: TypePolicy) {\n const existing = this.getTypePolicy(typename);\n const { keyFields, fields } = incoming;\n\n function setMerge(\n existing: { merge?: FieldMergeFunction | boolean },\n merge?: FieldMergeFunction | boolean\n ) {\n existing.merge =\n typeof merge === \"function\" ? merge\n // Pass merge:true as a shorthand for a merge implementation\n // that returns options.mergeObjects(existing, incoming).\n : merge === true ? mergeTrueFn\n // Pass merge:false to make incoming always replace existing\n // without any warnings about data clobbering.\n : merge === false ? mergeFalseFn\n : existing.merge;\n }\n\n // Type policies can define merge functions, as an alternative to\n // using field policies to merge child objects.\n setMerge(existing, incoming.merge);\n\n existing.keyFn =\n // Pass false to disable normalization for this typename.\n keyFields === false ? nullKeyFieldsFn\n // Pass an array of strings to use those fields to compute a\n // composite ID for objects of this typename.\n : isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)\n // Pass a function to take full control over identification.\n : typeof keyFields === \"function\" ? keyFields\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n\n if (fields) {\n Object.keys(fields).forEach((fieldName) => {\n const existing = this.getFieldPolicy(typename, fieldName, true)!;\n const incoming = fields[fieldName];\n\n if (typeof incoming === \"function\") {\n existing.read = incoming;\n } else {\n const { keyArgs, read, merge } = incoming;\n\n existing.keyFn =\n // Pass false to disable argument-based differentiation of\n // field identities.\n keyArgs === false ? simpleKeyArgsFn\n // Pass an array of strings to use named arguments to\n // compute a composite identity for the field.\n : isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)\n // Pass a function to take full control over field identity.\n : typeof keyArgs === \"function\" ? keyArgs\n // Leave existing.keyFn unchanged if above cases fail.\n : existing.keyFn;\n\n if (typeof read === \"function\") {\n existing.read = read;\n }\n\n setMerge(existing, merge);\n }\n\n if (existing.read && existing.merge) {\n // If we have both a read and a merge function, assume\n // keyArgs:false, because read and merge together can take\n // responsibility for interpreting arguments in and out. This\n // default assumption can always be overridden by specifying\n // keyArgs explicitly in the FieldPolicy.\n existing.keyFn = existing.keyFn || simpleKeyArgsFn;\n }\n });\n }\n }\n\n private setRootTypename(\n which: \"Query\" | \"Mutation\" | \"Subscription\",\n typename: string = which\n ) {\n const rootId = \"ROOT_\" + which.toUpperCase();\n const old = this.rootTypenamesById[rootId];\n if (typename !== old) {\n invariant(\n !old || old === which,\n `Cannot change root %s __typename more than once`,\n which\n );\n // First, delete any old __typename associated with this rootId from\n // rootIdsByTypename.\n if (old) delete this.rootIdsByTypename[old];\n // Now make this the only __typename that maps to this rootId.\n this.rootIdsByTypename[typename] = rootId;\n // Finally, update the __typename associated with this rootId.\n this.rootTypenamesById[rootId] = typename;\n }\n }\n\n public addPossibleTypes(possibleTypes: PossibleTypesMap) {\n (this.usingPossibleTypes as boolean) = true;\n Object.keys(possibleTypes).forEach((supertype) => {\n // Make sure all types have an entry in this.supertypeMap, even if\n // their supertype set is empty, so we can return false immediately\n // from policies.fragmentMatches for unknown supertypes.\n this.getSupertypeSet(supertype, true);\n\n possibleTypes[supertype].forEach((subtype) => {\n this.getSupertypeSet(subtype, true)!.add(supertype);\n const match = subtype.match(TypeOrFieldNameRegExp);\n if (!match || match[0] !== subtype) {\n // TODO Don't interpret just any invalid typename as a RegExp.\n this.fuzzySubtypes.set(subtype, new RegExp(subtype));\n }\n });\n });\n }\n\n private getTypePolicy(typename: string): Policies[\"typePolicies\"][string] {\n if (!hasOwn.call(this.typePolicies, typename)) {\n const policy: Policies[\"typePolicies\"][string] = (this.typePolicies[\n typename\n ] = Object.create(null));\n policy.fields = Object.create(null);\n\n // When the TypePolicy for typename is first accessed, instead of\n // starting with an empty policy object, inherit any properties or\n // fields from the type policies of the supertypes of typename.\n //\n // Any properties or fields defined explicitly within the TypePolicy\n // for typename will take precedence, and if there are multiple\n // supertypes, the properties of policies whose types were added\n // later via addPossibleTypes will take precedence over those of\n // earlier supertypes. TODO Perhaps we should warn about these\n // conflicts in development, and recommend defining the property\n // explicitly in the subtype policy?\n //\n // Field policy inheritance is atomic/shallow: you can't inherit a\n // field policy and then override just its read function, since read\n // and merge functions often need to cooperate, so changing only one\n // of them would be a recipe for inconsistency.\n //\n // Once the TypePolicy for typename has been accessed, its properties can\n // still be updated directly using addTypePolicies, but future changes to\n // inherited supertype policies will not be reflected in this subtype\n // policy, because this code runs at most once per typename.\n let supertypes = this.supertypeMap.get(typename);\n if (!supertypes && this.fuzzySubtypes.size) {\n // To make the inheritance logic work for unknown typename strings that\n // may have fuzzy supertypes, we give this typename an empty supertype\n // set and then populate it with any fuzzy supertypes that match.\n supertypes = this.getSupertypeSet(typename, true)!;\n // This only works for typenames that are directly matched by a fuzzy\n // supertype. What if there is an intermediate chain of supertypes?\n // While possible, that situation can only be solved effectively by\n // specifying the intermediate relationships via possibleTypes, manually\n // and in a non-fuzzy way.\n this.fuzzySubtypes.forEach((regExp, fuzzy) => {\n if (regExp.test(typename)) {\n // The fuzzy parameter is just the original string version of regExp\n // (not a valid __typename string), but we can look up the\n // associated supertype(s) in this.supertypeMap.\n const fuzzySupertypes = this.supertypeMap.get(fuzzy);\n if (fuzzySupertypes) {\n fuzzySupertypes.forEach((supertype) =>\n supertypes!.add(supertype)\n );\n }\n }\n });\n }\n if (supertypes && supertypes.size) {\n supertypes.forEach((supertype) => {\n const { fields, ...rest } = this.getTypePolicy(supertype);\n Object.assign(policy, rest);\n Object.assign(policy.fields, fields);\n });\n }\n }\n\n const inbox = this.toBeAdded[typename];\n if (inbox && inbox.length) {\n // Merge the pending policies into this.typePolicies, in the order they\n // were originally passed to addTypePolicy.\n inbox.splice(0).forEach((policy) => {\n this.updateTypePolicy(typename, policy);\n });\n }\n\n return this.typePolicies[typename];\n }\n\n private getFieldPolicy(\n typename: string | undefined,\n fieldName: string,\n createIfMissing: boolean\n ):\n | {\n keyFn?: KeyArgsFunction;\n read?: FieldReadFunction;\n merge?: FieldMergeFunction;\n }\n | undefined {\n if (typename) {\n const fieldPolicies = this.getTypePolicy(typename).fields;\n return (\n fieldPolicies[fieldName] ||\n (createIfMissing && (fieldPolicies[fieldName] = Object.create(null)))\n );\n }\n }\n\n private getSupertypeSet(\n subtype: string,\n createIfMissing: boolean\n ): Set | undefined {\n let supertypeSet = this.supertypeMap.get(subtype);\n if (!supertypeSet && createIfMissing) {\n this.supertypeMap.set(subtype, (supertypeSet = new Set()));\n }\n return supertypeSet;\n }\n\n public fragmentMatches(\n fragment: InlineFragmentNode | FragmentDefinitionNode,\n typename: string | undefined,\n result?: Record,\n variables?: Record\n ): boolean {\n if (!fragment.typeCondition) return true;\n\n // If the fragment has a type condition but the object we're matching\n // against does not have a __typename, the fragment cannot match.\n if (!typename) return false;\n\n const supertype = fragment.typeCondition.name.value;\n // Common case: fragment type condition and __typename are the same.\n if (typename === supertype) return true;\n\n if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n const typenameSupertypeSet = this.getSupertypeSet(typename, true)!;\n const workQueue = [typenameSupertypeSet];\n const maybeEnqueue = (subtype: string) => {\n const supertypeSet = this.getSupertypeSet(subtype, false);\n if (\n supertypeSet &&\n supertypeSet.size &&\n workQueue.indexOf(supertypeSet) < 0\n ) {\n workQueue.push(supertypeSet);\n }\n };\n\n // We need to check fuzzy subtypes only if we encountered fuzzy\n // subtype strings in addPossibleTypes, and only while writing to\n // the cache, since that's when selectionSetMatchesResult gives a\n // strong signal of fragment matching. The StoreReader class calls\n // policies.fragmentMatches without passing a result object, so\n // needToCheckFuzzySubtypes is always false while reading.\n let needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n let checkingFuzzySubtypes = false;\n\n // It's important to keep evaluating workQueue.length each time through\n // the loop, because the queue can grow while we're iterating over it.\n for (let i = 0; i < workQueue.length; ++i) {\n const supertypeSet = workQueue[i];\n\n if (supertypeSet.has(supertype)) {\n if (!typenameSupertypeSet.has(supertype)) {\n if (checkingFuzzySubtypes) {\n invariant.warn(\n `Inferring subtype %s of supertype %s`,\n typename,\n supertype\n );\n }\n // Record positive results for faster future lookup.\n // Unfortunately, we cannot safely cache negative results,\n // because new possibleTypes data could always be added to the\n // Policies class.\n typenameSupertypeSet.add(supertype);\n }\n return true;\n }\n\n supertypeSet.forEach(maybeEnqueue);\n\n if (\n needToCheckFuzzySubtypes &&\n // Start checking fuzzy subtypes only after exhausting all\n // non-fuzzy subtypes (after the final iteration of the loop).\n i === workQueue.length - 1 &&\n // We could wait to compare fragment.selectionSet to result\n // after we verify the supertype, but this check is often less\n // expensive than that search, and we will have to do the\n // comparison anyway whenever we find a potential match.\n selectionSetMatchesResult(fragment.selectionSet, result!, variables)\n ) {\n // We don't always need to check fuzzy subtypes (if no result\n // was provided, or !this.fuzzySubtypes.size), but, when we do,\n // we only want to check them once.\n needToCheckFuzzySubtypes = false;\n checkingFuzzySubtypes = true;\n\n // If we find any fuzzy subtypes that match typename, extend the\n // workQueue to search through the supertypes of those fuzzy\n // subtypes. Otherwise the for-loop will terminate and we'll\n // return false below.\n this.fuzzySubtypes.forEach((regExp, fuzzyString) => {\n const match = typename.match(regExp);\n if (match && match[0] === typename) {\n maybeEnqueue(fuzzyString);\n }\n });\n }\n }\n }\n\n return false;\n }\n\n public hasKeyArgs(typename: string | undefined, fieldName: string) {\n const policy = this.getFieldPolicy(typename, fieldName, false);\n return !!(policy && policy.keyFn);\n }\n\n public getStoreFieldName(fieldSpec: FieldSpecifier): string {\n const { typename, fieldName } = fieldSpec;\n const policy = this.getFieldPolicy(typename, fieldName, false);\n let storeFieldName: Exclude, KeySpecifier>;\n\n let keyFn = policy && policy.keyFn;\n if (keyFn && typename) {\n const context: Parameters[1] = {\n typename,\n fieldName,\n field: fieldSpec.field || null,\n variables: fieldSpec.variables,\n };\n const args = argsFromFieldSpecifier(fieldSpec);\n while (keyFn) {\n const specifierOrString = keyFn(args, context);\n if (isArray(specifierOrString)) {\n keyFn = keyArgsFnFromSpecifier(specifierOrString);\n } else {\n // If the custom keyFn returns a falsy value, fall back to\n // fieldName instead.\n storeFieldName = specifierOrString || fieldName;\n break;\n }\n }\n }\n\n if (storeFieldName === void 0) {\n storeFieldName =\n fieldSpec.field ?\n storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n }\n\n // Returning false from a keyArgs function is like configuring\n // keyArgs: false, but more dynamic.\n if (storeFieldName === false) {\n return fieldName;\n }\n\n // Make sure custom field names start with the actual field.name.value\n // of the field, so we can always figure out which properties of a\n // StoreObject correspond to which original field names.\n return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName\n : fieldName + \":\" + storeFieldName;\n }\n\n public readField(\n options: ReadFieldOptions,\n context: ReadMergeModifyContext\n ): SafeReadonly | undefined {\n const objectOrReference = options.from;\n if (!objectOrReference) return;\n\n const nameOrField = options.field || options.fieldName;\n if (!nameOrField) return;\n\n if (options.typename === void 0) {\n const typename = context.store.getFieldValue(\n objectOrReference,\n \"__typename\"\n );\n if (typename) options.typename = typename;\n }\n\n const storeFieldName = this.getStoreFieldName(options);\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const existing = context.store.getFieldValue(\n objectOrReference,\n storeFieldName\n );\n const policy = this.getFieldPolicy(options.typename, fieldName, false);\n const read = policy && policy.read;\n\n if (read) {\n const readOptions = makeFieldFunctionOptions(\n this,\n objectOrReference,\n options,\n context,\n context.store.getStorage(\n isReference(objectOrReference) ?\n objectOrReference.__ref\n : objectOrReference,\n storeFieldName\n )\n );\n\n // Call read(existing, readOptions) with cacheSlot holding this.cache.\n return cacheSlot.withValue(this.cache, read, [\n existing,\n readOptions,\n ]) as SafeReadonly;\n }\n\n return existing;\n }\n\n public getReadFunction(\n typename: string | undefined,\n fieldName: string\n ): FieldReadFunction | undefined {\n const policy = this.getFieldPolicy(typename, fieldName, false);\n return policy && policy.read;\n }\n\n public getMergeFunction(\n parentTypename: string | undefined,\n fieldName: string,\n childTypename: string | undefined\n ): FieldMergeFunction | undefined {\n let policy:\n | Policies[\"typePolicies\"][string]\n | Policies[\"typePolicies\"][string][\"fields\"][string]\n | undefined = this.getFieldPolicy(parentTypename, fieldName, false);\n let merge = policy && policy.merge;\n if (!merge && childTypename) {\n policy = this.getTypePolicy(childTypename);\n merge = policy && policy.merge;\n }\n return merge;\n }\n\n public runMergeFunction(\n existing: StoreValue,\n incoming: StoreValue,\n { field, typename, merge }: MergeInfo,\n context: WriteContext,\n storage?: StorageType\n ) {\n if (merge === mergeTrueFn) {\n // Instead of going to the trouble of creating a full\n // FieldFunctionOptions object and calling mergeTrueFn, we can\n // simply call mergeObjects, as mergeTrueFn would.\n return makeMergeObjectsFunction(context.store)(\n existing as StoreObject,\n incoming as StoreObject\n );\n }\n\n if (merge === mergeFalseFn) {\n // Likewise for mergeFalseFn, whose implementation is even simpler.\n return incoming;\n }\n\n // If cache.writeQuery or cache.writeFragment was called with\n // options.overwrite set to true, we still call merge functions, but\n // the existing data is always undefined, so the merge function will\n // not attempt to combine the incoming data with the existing data.\n if (context.overwrite) {\n existing = void 0;\n }\n\n return merge(\n existing,\n incoming,\n makeFieldFunctionOptions(\n this,\n // Unlike options.readField for read functions, we do not fall\n // back to the current object if no foreignObjOrRef is provided,\n // because it's not clear what the current object should be for\n // merge functions: the (possibly undefined) existing object, or\n // the incoming object? If you think your merge function needs\n // to read sibling fields in order to produce a new value for\n // the current field, you might want to rethink your strategy,\n // because that's a recipe for making merge behavior sensitive\n // to the order in which fields are written into the cache.\n // However, readField(name, ref) is useful for merge functions\n // that need to deduplicate child objects and references.\n void 0,\n {\n typename,\n fieldName: field.name.value,\n field,\n variables: context.variables,\n },\n context,\n storage || Object.create(null)\n )\n );\n }\n}\n\nfunction makeFieldFunctionOptions(\n policies: Policies,\n objectOrReference: StoreObject | Reference | undefined,\n fieldSpec: FieldSpecifier,\n context: ReadMergeModifyContext,\n storage: StorageType\n): FieldFunctionOptions {\n const storeFieldName = policies.getStoreFieldName(fieldSpec);\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const variables = fieldSpec.variables || context.variables;\n const { toReference, canRead } = context.store;\n\n return {\n args: argsFromFieldSpecifier(fieldSpec),\n field: fieldSpec.field || null,\n fieldName,\n storeFieldName,\n variables,\n isReference,\n toReference,\n storage,\n cache: policies.cache,\n canRead,\n readField() {\n return policies.readField(\n normalizeReadFieldOptions(arguments, objectOrReference, variables),\n context\n );\n },\n mergeObjects: makeMergeObjectsFunction(context.store),\n };\n}\n\nexport function normalizeReadFieldOptions(\n readFieldArgs: IArguments,\n objectOrReference: StoreObject | Reference | undefined,\n variables?: ReadMergeModifyContext[\"variables\"]\n): ReadFieldOptions {\n const { 0: fieldNameOrOptions, 1: from, length: argc } = readFieldArgs;\n\n let options: ReadFieldOptions;\n\n if (typeof fieldNameOrOptions === \"string\") {\n options = {\n fieldName: fieldNameOrOptions,\n // Default to objectOrReference only when no second argument was\n // passed for the from parameter, not when undefined is explicitly\n // passed as the second argument.\n from: argc > 1 ? from : objectOrReference,\n };\n } else {\n options = { ...fieldNameOrOptions };\n // Default to objectOrReference only when fieldNameOrOptions.from is\n // actually omitted, rather than just undefined.\n if (!hasOwn.call(options, \"from\")) {\n options.from = objectOrReference;\n }\n }\n\n if (__DEV__ && options.from === void 0) {\n invariant.warn(\n `Undefined 'from' passed to readField with arguments %s`,\n stringifyForDisplay(Array.from(readFieldArgs))\n );\n }\n\n if (void 0 === options.variables) {\n options.variables = variables;\n }\n\n return options;\n}\n\nfunction makeMergeObjectsFunction(\n store: NormalizedCache\n): MergeObjectsFunction {\n return function mergeObjects(existing, incoming) {\n if (isArray(existing) || isArray(incoming)) {\n throw newInvariantError(\"Cannot automatically merge arrays\");\n }\n\n // These dynamic checks are necessary because the parameters of a\n // custom merge function can easily have the any type, so the type\n // system cannot always enforce the StoreObject | Reference parameter\n // types of options.mergeObjects.\n if (isNonNullObject(existing) && isNonNullObject(incoming)) {\n const eType = store.getFieldValue(existing, \"__typename\");\n const iType = store.getFieldValue(incoming, \"__typename\");\n const typesDiffer = eType && iType && eType !== iType;\n\n if (typesDiffer) {\n return incoming;\n }\n\n if (isReference(existing) && storeValueIsStoreObject(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // existing.__ref, preferring/overwriting any fields contributed by the\n // newer incoming StoreObject.\n store.merge(existing.__ref, incoming);\n return existing;\n }\n\n if (storeValueIsStoreObject(existing) && isReference(incoming)) {\n // Update the normalized EntityStore for the entity identified by\n // incoming.__ref, taking fields from the older existing object only if\n // those fields are not already present in the newer StoreObject\n // identified by incoming.__ref.\n store.merge(existing, incoming.__ref);\n return incoming;\n }\n\n if (\n storeValueIsStoreObject(existing) &&\n storeValueIsStoreObject(incoming)\n ) {\n return { ...existing, ...incoming };\n }\n }\n\n return incoming;\n };\n}\n","import { invariant, newInvariantError } from \"../../utilities/globals/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport type { SelectionSetNode, FieldNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport type {\n FragmentMap,\n FragmentMapFunction,\n StoreValue,\n StoreObject,\n Reference,\n} from \"../../utilities/index.js\";\nimport {\n getFragmentFromSelection,\n getDefaultValues,\n getOperationDefinition,\n getTypenameFromResult,\n makeReference,\n isField,\n resultKeyNameFromField,\n isReference,\n shouldInclude,\n cloneDeep,\n addTypenameToDocument,\n isNonEmptyArray,\n argumentsObjectFromField,\n canonicalStringify,\n} from \"../../utilities/index.js\";\n\nimport type {\n NormalizedCache,\n ReadMergeModifyContext,\n MergeTree,\n InMemoryCacheConfig,\n} from \"./types.js\";\nimport {\n isArray,\n makeProcessedFieldsMerger,\n fieldNameFromStoreName,\n storeValueIsStoreObject,\n extractFragmentContext,\n} from \"./helpers.js\";\nimport type { StoreReader } from \"./readFromStore.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { EntityStore } from \"./entityStore.js\";\nimport type { Cache } from \"../../core/index.js\";\nimport { normalizeReadFieldOptions } from \"./policies.js\";\nimport type { ReadFieldFunction } from \"../core/types/common.js\";\n\nexport interface WriteContext extends ReadMergeModifyContext {\n readonly written: {\n [dataId: string]: SelectionSetNode[];\n };\n readonly fragmentMap: FragmentMap;\n lookupFragment: FragmentMapFunction;\n // General-purpose deep-merge function for use during writes.\n merge(existing: T, incoming: T): T;\n // If true, merge functions will be called with undefined existing data.\n overwrite: boolean;\n incomingById: Map<\n string,\n {\n storeObject: StoreObject;\n mergeTree?: MergeTree;\n fieldNodeSet: Set;\n }\n >;\n // Directive metadata for @client and @defer. We could use a bitfield for this\n // information to save some space, and use that bitfield number as the keys in\n // the context.flavors Map.\n clientOnly: boolean;\n deferred: boolean;\n flavors: Map;\n}\n\ntype FlavorableWriteContext = Pick<\n WriteContext,\n \"clientOnly\" | \"deferred\" | \"flavors\"\n>;\n\n// Since there are only four possible combinations of context.clientOnly and\n// context.deferred values, we should need at most four \"flavors\" of any given\n// WriteContext. To avoid creating multiple copies of the same context, we cache\n// the contexts in the context.flavors Map (shared by all flavors) according to\n// their clientOnly and deferred values (always in that order).\nfunction getContextFlavor(\n context: TContext,\n clientOnly: TContext[\"clientOnly\"],\n deferred: TContext[\"deferred\"]\n): TContext {\n const key = `${clientOnly}${deferred}`;\n let flavored = context.flavors.get(key);\n if (!flavored) {\n context.flavors.set(\n key,\n (flavored =\n context.clientOnly === clientOnly && context.deferred === deferred ?\n context\n : {\n ...context,\n clientOnly,\n deferred,\n })\n );\n }\n return flavored as TContext;\n}\n\ninterface ProcessSelectionSetOptions {\n dataId?: string;\n result: Record;\n selectionSet: SelectionSetNode;\n context: WriteContext;\n mergeTree: MergeTree;\n}\n\nexport class StoreWriter {\n constructor(\n public readonly cache: InMemoryCache,\n private reader?: StoreReader,\n private fragments?: InMemoryCacheConfig[\"fragments\"]\n ) {}\n\n public writeToStore(\n store: NormalizedCache,\n { query, result, dataId, variables, overwrite }: Cache.WriteOptions\n ): Reference | undefined {\n const operationDefinition = getOperationDefinition(query)!;\n const merger = makeProcessedFieldsMerger();\n\n variables = {\n ...getDefaultValues(operationDefinition),\n ...variables!,\n };\n\n const context: WriteContext = {\n store,\n written: Object.create(null),\n merge(existing: T, incoming: T) {\n return merger.merge(existing, incoming) as T;\n },\n variables,\n varString: canonicalStringify(variables),\n ...extractFragmentContext(query, this.fragments),\n overwrite: !!overwrite,\n incomingById: new Map(),\n clientOnly: false,\n deferred: false,\n flavors: new Map(),\n };\n\n const ref = this.processSelectionSet({\n result: result || Object.create(null),\n dataId,\n selectionSet: operationDefinition.selectionSet,\n mergeTree: { map: new Map() },\n context,\n });\n\n if (!isReference(ref)) {\n throw newInvariantError(`Could not identify object %s`, result);\n }\n\n // So far, the store has not been modified, so now it's time to process\n // context.incomingById and merge those incoming fields into context.store.\n context.incomingById.forEach(\n ({ storeObject, mergeTree, fieldNodeSet }, dataId) => {\n const entityRef = makeReference(dataId);\n\n if (mergeTree && mergeTree.map.size) {\n const applied = this.applyMerges(\n mergeTree,\n entityRef,\n storeObject,\n context\n );\n if (isReference(applied)) {\n // Assume References returned by applyMerges have already been merged\n // into the store. See makeMergeObjectsFunction in policies.ts for an\n // example of how this can happen.\n return;\n }\n // Otherwise, applyMerges returned a StoreObject, whose fields we should\n // merge into the store (see store.merge statement below).\n storeObject = applied;\n }\n\n if (__DEV__ && !context.overwrite) {\n const fieldsWithSelectionSets: Record =\n Object.create(null);\n fieldNodeSet.forEach((field) => {\n if (field.selectionSet) {\n fieldsWithSelectionSets[field.name.value] = true;\n }\n });\n\n const hasSelectionSet = (storeFieldName: string) =>\n fieldsWithSelectionSets[fieldNameFromStoreName(storeFieldName)] ===\n true;\n\n const hasMergeFunction = (storeFieldName: string) => {\n const childTree = mergeTree && mergeTree.map.get(storeFieldName);\n return Boolean(childTree && childTree.info && childTree.info.merge);\n };\n\n Object.keys(storeObject).forEach((storeFieldName) => {\n // If a merge function was defined for this field, trust that it\n // did the right thing about (not) clobbering data. If the field\n // has no selection set, it's a scalar field, so it doesn't need\n // a merge function (even if it's an object, like JSON data).\n if (\n hasSelectionSet(storeFieldName) &&\n !hasMergeFunction(storeFieldName)\n ) {\n warnAboutDataLoss(\n entityRef,\n storeObject,\n storeFieldName,\n context.store\n );\n }\n });\n }\n\n store.merge(dataId, storeObject);\n }\n );\n\n // Any IDs written explicitly to the cache will be retained as\n // reachable root IDs for garbage collection purposes. Although this\n // logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their\n // retainment counts are effectively ignored because cache.gc() always\n // includes them in its root ID set.\n store.retain(ref.__ref);\n\n return ref;\n }\n\n private processSelectionSet({\n dataId,\n result,\n selectionSet,\n context,\n // This object allows processSelectionSet to report useful information\n // to its callers without explicitly returning that information.\n mergeTree,\n }: ProcessSelectionSetOptions): StoreObject | Reference {\n const { policies } = this.cache;\n\n // This variable will be repeatedly updated using context.merge to\n // accumulate all fields that need to be written into the store.\n let incoming: StoreObject = Object.create(null);\n\n // If typename was not passed in, infer it. Note that typename is\n // always passed in for tricky-to-infer cases such as \"Query\" for\n // ROOT_QUERY.\n const typename: string | undefined =\n (dataId && policies.rootTypenamesById[dataId]) ||\n getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n (dataId && (context.store.get(dataId, \"__typename\") as string));\n\n if (\"string\" === typeof typename) {\n incoming.__typename = typename;\n }\n\n // This readField function will be passed as context.readField in the\n // KeyFieldsContext object created within policies.identify (called below).\n // In addition to reading from the existing context.store (thanks to the\n // policies.readField(options, context) line at the very bottom), this\n // version of readField can read from Reference objects that are currently\n // pending in context.incomingById, which is important whenever keyFields\n // need to be extracted from a child object that processSelectionSet has\n // turned into a Reference.\n const readField: ReadFieldFunction = function (this: void) {\n const options = normalizeReadFieldOptions(\n arguments,\n incoming,\n context.variables\n );\n\n if (isReference(options.from)) {\n const info = context.incomingById.get(options.from.__ref);\n if (info) {\n const result = policies.readField(\n {\n ...options,\n from: info.storeObject,\n },\n context\n );\n\n if (result !== void 0) {\n return result;\n }\n }\n }\n\n return policies.readField(options, context);\n };\n\n const fieldNodeSet = new Set();\n\n this.flattenFields(\n selectionSet,\n result,\n // This WriteContext will be the default context value for fields returned\n // by the flattenFields method, but some fields may be assigned a modified\n // context, depending on the presence of @client and other directives.\n context,\n typename\n ).forEach((context, field) => {\n const resultFieldKey = resultKeyNameFromField(field);\n const value = result[resultFieldKey];\n\n fieldNodeSet.add(field);\n\n if (value !== void 0) {\n const storeFieldName = policies.getStoreFieldName({\n typename,\n fieldName: field.name.value,\n field,\n variables: context.variables,\n });\n\n const childTree = getChildMergeTree(mergeTree, storeFieldName);\n\n let incomingValue = this.processFieldValue(\n value,\n field,\n // Reset context.clientOnly and context.deferred to their default\n // values before processing nested selection sets.\n field.selectionSet ?\n getContextFlavor(context, false, false)\n : context,\n childTree\n );\n\n // To determine if this field holds a child object with a merge function\n // defined in its type policy (see PR #7070), we need to figure out the\n // child object's __typename.\n let childTypename: string | undefined;\n\n // The field's value can be an object that has a __typename only if the\n // field has a selection set. Otherwise incomingValue is scalar.\n if (\n field.selectionSet &&\n (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))\n ) {\n childTypename = readField(\"__typename\", incomingValue);\n }\n\n const merge = policies.getMergeFunction(\n typename,\n field.name.value,\n childTypename\n );\n\n if (merge) {\n childTree.info = {\n // TODO Check compatibility against any existing childTree.field?\n field,\n typename,\n merge,\n };\n } else {\n maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n }\n\n incoming = context.merge(incoming, {\n [storeFieldName]: incomingValue,\n });\n } else if (\n __DEV__ &&\n !context.clientOnly &&\n !context.deferred &&\n !addTypenameToDocument.added(field) &&\n // If the field has a read function, it may be a synthetic field or\n // provide a default value, so its absence from the written data should\n // not be cause for alarm.\n !policies.getReadFunction(typename, field.name.value)\n ) {\n invariant.error(\n `Missing field '%s' while writing result %o`,\n resultKeyNameFromField(field),\n result\n );\n }\n });\n\n // Identify the result object, even if dataId was already provided,\n // since we always need keyObject below.\n try {\n const [id, keyObject] = policies.identify(result, {\n typename,\n selectionSet,\n fragmentMap: context.fragmentMap,\n storeObject: incoming,\n readField,\n });\n\n // If dataId was not provided, fall back to the id just generated by\n // policies.identify.\n dataId = dataId || id;\n\n // Write any key fields that were used during identification, even if\n // they were not mentioned in the original query.\n if (keyObject) {\n // TODO Reverse the order of the arguments?\n incoming = context.merge(incoming, keyObject);\n }\n } catch (e) {\n // If dataId was provided, tolerate failure of policies.identify.\n if (!dataId) throw e;\n }\n\n if (\"string\" === typeof dataId) {\n const dataRef = makeReference(dataId);\n\n // Avoid processing the same entity object using the same selection\n // set more than once. We use an array instead of a Set since most\n // entity IDs will be written using only one selection set, so the\n // size of this array is likely to be very small, meaning indexOf is\n // likely to be faster than Set.prototype.has.\n const sets = context.written[dataId] || (context.written[dataId] = []);\n if (sets.indexOf(selectionSet) >= 0) return dataRef;\n sets.push(selectionSet);\n\n // If we're about to write a result object into the store, but we\n // happen to know that the exact same (===) result object would be\n // returned if we were to reread the result with the same inputs,\n // then we can skip the rest of the processSelectionSet work for\n // this object, and immediately return a Reference to it.\n if (\n this.reader &&\n this.reader.isFresh(result, dataRef, selectionSet, context)\n ) {\n return dataRef;\n }\n\n const previous = context.incomingById.get(dataId);\n if (previous) {\n previous.storeObject = context.merge(previous.storeObject, incoming);\n previous.mergeTree = mergeMergeTrees(previous.mergeTree, mergeTree);\n fieldNodeSet.forEach((field) => previous.fieldNodeSet.add(field));\n } else {\n context.incomingById.set(dataId, {\n storeObject: incoming,\n // Save a reference to mergeTree only if it is not empty, because\n // empty MergeTrees may be recycled by maybeRecycleChildMergeTree and\n // reused for entirely different parts of the result tree.\n mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,\n fieldNodeSet,\n });\n }\n\n return dataRef;\n }\n\n return incoming;\n }\n\n private processFieldValue(\n value: any,\n field: FieldNode,\n context: WriteContext,\n mergeTree: MergeTree\n ): StoreValue {\n if (!field.selectionSet || value === null) {\n // In development, we need to clone scalar values so that they can be\n // safely frozen with maybeDeepFreeze in readFromStore.ts. In production,\n // it's cheaper to store the scalar values directly in the cache.\n return __DEV__ ? cloneDeep(value) : value;\n }\n\n if (isArray(value)) {\n return value.map((item, i) => {\n const value = this.processFieldValue(\n item,\n field,\n context,\n getChildMergeTree(mergeTree, i)\n );\n maybeRecycleChildMergeTree(mergeTree, i);\n return value;\n });\n }\n\n return this.processSelectionSet({\n result: value,\n selectionSet: field.selectionSet,\n context,\n mergeTree,\n });\n }\n\n // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n // some additions for tracking @client and @defer directives.\n private flattenFields<\n TContext extends Pick<\n WriteContext,\n | \"clientOnly\"\n | \"deferred\"\n | \"flavors\"\n | \"fragmentMap\"\n | \"lookupFragment\"\n | \"variables\"\n >,\n >(\n selectionSet: SelectionSetNode,\n result: Record,\n context: TContext,\n typename = getTypenameFromResult(result, selectionSet, context.fragmentMap)\n ): Map {\n const fieldMap = new Map();\n const { policies } = this.cache;\n\n const limitingTrie = new Trie<{\n // Tracks whether (selectionSet, clientOnly, deferred) has been flattened\n // before. The GraphQL specification only uses the fragment name for\n // skipping previously visited fragments, but the top-level fragment\n // selection set corresponds 1:1 with the fagment name (and is slightly\n // easier too work with), and we need to consider clientOnly and deferred\n // values as well, potentially revisiting selection sets that were\n // previously visited with different inherited configurations of those\n // directives.\n visited?: boolean;\n }>(false); // No need for WeakMap, since limitingTrie does not escape.\n\n (function flatten(\n this: void,\n selectionSet: SelectionSetNode,\n inheritedContext: TContext\n ) {\n const visitedNode = limitingTrie.lookup(\n selectionSet,\n // Because we take inheritedClientOnly and inheritedDeferred into\n // consideration here (in addition to selectionSet), it's possible for\n // the same selection set to be flattened more than once, if it appears\n // in the query with different @client and/or @directive configurations.\n inheritedContext.clientOnly,\n inheritedContext.deferred\n );\n if (visitedNode.visited) return;\n visitedNode.visited = true;\n\n selectionSet.selections.forEach((selection) => {\n if (!shouldInclude(selection, context.variables)) return;\n\n let { clientOnly, deferred } = inheritedContext;\n if (\n // Since the presence of @client or @defer on this field can only\n // cause clientOnly or deferred to become true, we can skip the\n // forEach loop if both clientOnly and deferred are already true.\n !(clientOnly && deferred) &&\n isNonEmptyArray(selection.directives)\n ) {\n selection.directives.forEach((dir) => {\n const name = dir.name.value;\n if (name === \"client\") clientOnly = true;\n if (name === \"defer\") {\n const args = argumentsObjectFromField(dir, context.variables);\n // The @defer directive takes an optional args.if boolean\n // argument, similar to @include(if: boolean). Note that\n // @defer(if: false) does not make context.deferred false, but\n // instead behaves as if there was no @defer directive.\n if (!args || (args as { if?: boolean }).if !== false) {\n deferred = true;\n }\n // TODO In the future, we may want to record args.label using\n // context.deferred, if a label is specified.\n }\n });\n }\n\n if (isField(selection)) {\n const existing = fieldMap.get(selection);\n if (existing) {\n // If this field has been visited along another recursive path\n // before, the final context should have clientOnly or deferred set\n // to true only if *all* paths have the directive (hence the &&).\n clientOnly = clientOnly && existing.clientOnly;\n deferred = deferred && existing.deferred;\n }\n\n fieldMap.set(\n selection,\n getContextFlavor(context, clientOnly, deferred)\n );\n } else {\n const fragment = getFragmentFromSelection(\n selection,\n context.lookupFragment\n );\n\n if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n throw newInvariantError(\n `No fragment named %s`,\n selection.name.value\n );\n }\n\n if (\n fragment &&\n policies.fragmentMatches(\n fragment,\n typename,\n result,\n context.variables\n )\n ) {\n flatten(\n fragment.selectionSet,\n getContextFlavor(context, clientOnly, deferred)\n );\n }\n }\n });\n })(selectionSet, context);\n\n return fieldMap;\n }\n\n private applyMerges(\n mergeTree: MergeTree,\n existing: StoreValue,\n incoming: T,\n context: WriteContext,\n getStorageArgs?: Parameters\n ): T | Reference {\n if (mergeTree.map.size && !isReference(incoming)) {\n const e: StoreObject | Reference | undefined =\n // Items in the same position in different arrays are not\n // necessarily related to each other, so when incoming is an array\n // we process its elements as if there was no existing data.\n (\n !isArray(incoming) &&\n // Likewise, existing must be either a Reference or a StoreObject\n // in order for its fields to be safe to merge with the fields of\n // the incoming object.\n (isReference(existing) || storeValueIsStoreObject(existing))\n ) ?\n existing\n : void 0;\n\n // This narrowing is implied by mergeTree.map.size > 0 and\n // !isReference(incoming), though TypeScript understandably cannot\n // hope to infer this type.\n const i = incoming as StoreObject | StoreValue[];\n\n // The options.storage objects provided to read and merge functions\n // are derived from the identity of the parent object plus a\n // sequence of storeFieldName strings/numbers identifying the nested\n // field name path of each field value to be merged.\n if (e && !getStorageArgs) {\n getStorageArgs = [isReference(e) ? e.__ref : e];\n }\n\n // It's possible that applying merge functions to this subtree will\n // not change the incoming data, so this variable tracks the fields\n // that did change, so we can create a new incoming object when (and\n // only when) at least one incoming field has changed. We use a Map\n // to preserve the type of numeric keys.\n let changedFields: Map | undefined;\n\n const getValue = (\n from: typeof e | typeof i,\n name: string | number\n ): StoreValue => {\n return (\n isArray(from) ?\n typeof name === \"number\" ?\n from[name]\n : void 0\n : context.store.getFieldValue(from, String(name))\n );\n };\n\n mergeTree.map.forEach((childTree, storeFieldName) => {\n const eVal = getValue(e, storeFieldName);\n const iVal = getValue(i, storeFieldName);\n // If we have no incoming data, leave any existing data untouched.\n if (void 0 === iVal) return;\n if (getStorageArgs) {\n getStorageArgs.push(storeFieldName);\n }\n const aVal = this.applyMerges(\n childTree,\n eVal,\n iVal,\n context,\n getStorageArgs\n );\n if (aVal !== iVal) {\n changedFields = changedFields || new Map();\n changedFields.set(storeFieldName, aVal);\n }\n if (getStorageArgs) {\n invariant(getStorageArgs.pop() === storeFieldName);\n }\n });\n\n if (changedFields) {\n // Shallow clone i so we can add changed fields to it.\n incoming = (isArray(i) ? i.slice(0) : { ...i }) as T;\n changedFields.forEach((value, name) => {\n (incoming as any)[name] = value;\n });\n }\n }\n\n if (mergeTree.info) {\n return this.cache.policies.runMergeFunction(\n existing,\n incoming,\n mergeTree.info,\n context,\n getStorageArgs && context.store.getStorage(...getStorageArgs)\n );\n }\n\n return incoming;\n }\n}\n\nconst emptyMergeTreePool: MergeTree[] = [];\n\nfunction getChildMergeTree(\n { map }: MergeTree,\n name: string | number\n): MergeTree {\n if (!map.has(name)) {\n map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n }\n return map.get(name)!;\n}\n\nfunction mergeMergeTrees(\n left: MergeTree | undefined,\n right: MergeTree | undefined\n): MergeTree {\n if (left === right || !right || mergeTreeIsEmpty(right)) return left!;\n if (!left || mergeTreeIsEmpty(left)) return right;\n\n const info =\n left.info && right.info ?\n {\n ...left.info,\n ...right.info,\n }\n : left.info || right.info;\n\n const needToMergeMaps = left.map.size && right.map.size;\n const map =\n needToMergeMaps ? new Map()\n : left.map.size ? left.map\n : right.map;\n\n const merged = { info, map };\n\n if (needToMergeMaps) {\n const remainingRightKeys = new Set(right.map.keys());\n\n left.map.forEach((leftTree, key) => {\n merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n remainingRightKeys.delete(key);\n });\n\n remainingRightKeys.forEach((key) => {\n merged.map.set(\n key,\n mergeMergeTrees(right.map.get(key), left.map.get(key))\n );\n });\n }\n\n return merged;\n}\n\nfunction mergeTreeIsEmpty(tree: MergeTree | undefined): boolean {\n return !tree || !(tree.info || tree.map.size);\n}\n\nfunction maybeRecycleChildMergeTree({ map }: MergeTree, name: string | number) {\n const childTree = map.get(name);\n if (childTree && mergeTreeIsEmpty(childTree)) {\n emptyMergeTreePool.push(childTree);\n map.delete(name);\n }\n}\n\nconst warnings = new Set();\n\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(\n existingRef: Reference,\n incomingObj: StoreObject,\n storeFieldName: string,\n store: NormalizedCache\n) {\n const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {\n const child = store.getFieldValue(objOrRef, storeFieldName);\n return typeof child === \"object\" && child;\n };\n\n const existing = getChild(existingRef);\n if (!existing) return;\n\n const incoming = getChild(incomingObj);\n if (!incoming) return;\n\n // It's always safe to replace a reference, since it refers to data\n // safely stored elsewhere.\n if (isReference(existing)) return;\n\n // If the values are structurally equivalent, we do not need to worry\n // about incoming replacing existing.\n if (equal(existing, incoming)) return;\n\n // If we're replacing every key of the existing object, then the\n // existing data would be overwritten even if the objects were\n // normalized, so warning would not be helpful here.\n if (\n Object.keys(existing).every(\n (key) => store.getFieldValue(incoming, key) !== void 0\n )\n ) {\n return;\n }\n\n const parentType =\n store.getFieldValue(existingRef, \"__typename\") ||\n store.getFieldValue(incomingObj, \"__typename\");\n const fieldName = fieldNameFromStoreName(storeFieldName);\n const typeDotName = `${parentType}.${fieldName}`;\n // Avoid warning more than once for the same type and field name.\n if (warnings.has(typeDotName)) return;\n warnings.add(typeDotName);\n\n const childTypenames: string[] = [];\n // Arrays do not have __typename fields, and always need a custom merge\n // function, even if their elements are normalized entities.\n if (!isArray(existing) && !isArray(incoming)) {\n [existing, incoming].forEach((child) => {\n const typename = store.getFieldValue(child, \"__typename\");\n if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n childTypenames.push(typename);\n }\n });\n }\n\n invariant.warn(\n `Cache data may be lost when replacing the %s field of a %s object.\n\nThis could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.\n\nTo address this problem (which is not a bug in Apollo Client), %sdefine a custom merge function for the %s field, so InMemoryCache can safely merge these objects:\n\n existing: %o\n incoming: %o\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 fieldName,\n parentType,\n childTypenames.length ?\n \"either ensure all objects of type \" +\n childTypenames.join(\" and \") +\n \" have an ID or a custom merge function, or \"\n : \"\",\n typeDotName,\n { ...existing },\n { ...incoming }\n );\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\n// Make builtins like Map and Set safe to use with non-extensible objects.\nimport \"./fixPolyfills.js\";\n\nimport type {\n DocumentNode,\n FragmentDefinitionNode,\n InlineFragmentNode,\n} from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\nimport { equal } from \"@wry/equality\";\n\nimport { ApolloCache } from \"../core/cache.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\nimport type { StoreObject, Reference } from \"../../utilities/index.js\";\nimport {\n addTypenameToDocument,\n isReference,\n DocumentTransform,\n canonicalStringify,\n print,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport type { InMemoryCacheConfig, NormalizedCacheObject } from \"./types.js\";\nimport { StoreReader } from \"./readFromStore.js\";\nimport { StoreWriter } from \"./writeToStore.js\";\nimport { EntityStore, supportsResultCaching } from \"./entityStore.js\";\nimport { makeVar, forgetCache, recallCache } from \"./reactiveVars.js\";\nimport { Policies } from \"./policies.js\";\nimport { hasOwn, normalizeConfig, shouldCanonizeResults } from \"./helpers.js\";\nimport type { OperationVariables } from \"../../core/index.js\";\nimport { getInMemoryCacheMemoryInternals } from \"../../utilities/caching/getMemoryInternals.js\";\n\ntype BroadcastOptions = Pick<\n Cache.BatchOptions,\n \"optimistic\" | \"onWatchUpdated\"\n>;\n\nexport class InMemoryCache extends ApolloCache {\n private data!: EntityStore;\n private optimisticData!: EntityStore;\n\n protected config: InMemoryCacheConfig;\n private watches = new Set();\n private addTypename: boolean;\n\n private storeReader!: StoreReader;\n private storeWriter!: StoreWriter;\n private addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n\n private maybeBroadcastWatch!: OptimisticWrapperFunction<\n [Cache.WatchOptions, BroadcastOptions?],\n any,\n [Cache.WatchOptions]\n >;\n\n // Override the default value, since InMemoryCache result objects are frozen\n // in development and expected to remain logically immutable in production.\n public readonly assumeImmutableResults = true;\n\n // Dynamically imported code can augment existing typePolicies or\n // possibleTypes by calling cache.policies.addTypePolicies or\n // cache.policies.addPossibletypes.\n public readonly policies: Policies;\n\n public readonly makeVar = makeVar;\n\n constructor(config: InMemoryCacheConfig = {}) {\n super();\n this.config = normalizeConfig(config);\n this.addTypename = !!this.config.addTypename;\n\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\n this.init();\n }\n\n private init() {\n // Passing { resultCaching: false } in the InMemoryCache constructor options\n // will completely disable dependency tracking, which will improve memory\n // usage but worsen the performance of repeated reads.\n const rootStore = (this.data = new EntityStore.Root({\n policies: this.policies,\n resultCaching: this.config.resultCaching,\n }));\n\n // When no optimistic writes are currently active, cache.optimisticData ===\n // cache.data, so there are no additional layers on top of the actual data.\n // When an optimistic update happens, this.optimisticData will become a\n // linked list of EntityStore Layer objects that terminates with the\n // original this.data cache object.\n this.optimisticData = rootStore.stump;\n\n this.resetResultCache();\n }\n\n private resetResultCache(resetResultIdentities?: boolean) {\n const previousReader = this.storeReader;\n const { fragments } = this.config;\n\n // The StoreWriter is mostly stateless and so doesn't really need to be\n // reset, but it does need to have its writer.storeReader reference updated,\n // so it's simpler to update this.storeWriter as well.\n this.storeWriter = new StoreWriter(\n this,\n (this.storeReader = new StoreReader({\n cache: this,\n addTypename: this.addTypename,\n resultCacheMaxSize: this.config.resultCacheMaxSize,\n canonizeResults: shouldCanonizeResults(this.config),\n canon:\n resetResultIdentities ? void 0 : (\n previousReader && previousReader.canon\n ),\n fragments,\n })),\n fragments\n );\n\n this.maybeBroadcastWatch = wrap(\n (c: Cache.WatchOptions, options?: BroadcastOptions) => {\n return this.broadcastWatch(c, options);\n },\n {\n max:\n this.config.resultCacheMaxSize ||\n cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n makeCacheKey: (c: Cache.WatchOptions) => {\n // Return a cache key (thus enabling result caching) only if we're\n // currently using a data store that can track cache dependencies.\n const store = c.optimistic ? this.optimisticData : this.data;\n if (supportsResultCaching(store)) {\n const { optimistic, id, variables } = c;\n return store.makeCacheKey(\n c.query,\n // Different watches can have the same query, optimistic\n // status, rootId, and variables, but if their callbacks are\n // different, the (identical) result needs to be delivered to\n // each distinct callback. The easiest way to achieve that\n // separation is to include c.callback in the cache key for\n // maybeBroadcastWatch calls. See issue #5733.\n c.callback,\n canonicalStringify({ optimistic, id, variables })\n );\n }\n },\n }\n );\n\n // Since we have thrown away all the cached functions that depend on the\n // CacheGroup dependencies maintained by EntityStore, we should also reset\n // all CacheGroup dependency information.\n new Set([this.data.group, this.optimisticData.group]).forEach((group) =>\n group.resetCaching()\n );\n }\n\n public restore(data: NormalizedCacheObject): this {\n this.init();\n // Since calling this.init() discards/replaces the entire StoreReader, along\n // with the result caches it maintains, this.data.replace(data) won't have\n // to bother deleting the old data.\n if (data) this.data.replace(data);\n return this;\n }\n\n public extract(optimistic: boolean = false): NormalizedCacheObject {\n return (optimistic ? this.optimisticData : this.data).extract();\n }\n\n public read(options: Cache.ReadOptions): T | null {\n const {\n // Since read returns data or null, without any additional metadata\n // about whether/where there might have been missing fields, the\n // default behavior cannot be returnPartialData = true (like it is\n // for the diff method), since defaulting to true would violate the\n // integrity of the T in the return type. However, partial data may\n // be useful in some cases, so returnPartialData:true may be\n // specified explicitly.\n returnPartialData = false,\n } = options;\n try {\n return (\n this.storeReader.diffQueryAgainstStore({\n ...options,\n store: options.optimistic ? this.optimisticData : this.data,\n config: this.config,\n returnPartialData,\n }).result || null\n );\n } catch (e) {\n if (e instanceof MissingFieldError) {\n // Swallow MissingFieldError and return null, so callers do not need to\n // worry about catching \"normal\" exceptions resulting from incomplete\n // cache data. Unexpected errors will be re-thrown. If you need more\n // information about which fields were missing, use cache.diff instead,\n // and examine diffResult.missing.\n return null;\n }\n throw e;\n }\n }\n\n public write(options: Cache.WriteOptions): Reference | undefined {\n try {\n ++this.txCount;\n return this.storeWriter.writeToStore(this.data, options);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public modify = Record>(\n options: Cache.ModifyOptions\n ): boolean {\n if (hasOwn.call(options, \"id\") && !options.id) {\n // To my knowledge, TypeScript does not currently provide a way to\n // enforce that an optional property?:type must *not* be undefined\n // when present. That ability would be useful here, because we want\n // options.id to default to ROOT_QUERY only when no options.id was\n // provided. If the caller attempts to pass options.id with a\n // falsy/undefined value (perhaps because cache.identify failed), we\n // should not assume the goal was to modify the ROOT_QUERY object.\n // We could throw, but it seems natural to return false to indicate\n // that nothing was modified.\n return false;\n }\n const store =\n (\n options.optimistic // Defaults to false.\n ) ?\n this.optimisticData\n : this.data;\n try {\n ++this.txCount;\n return store.modify(options.id || \"ROOT_QUERY\", options.fields);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public diff(\n options: Cache.DiffOptions\n ): Cache.DiffResult {\n return this.storeReader.diffQueryAgainstStore({\n ...options,\n store: options.optimistic ? this.optimisticData : this.data,\n rootId: options.id || \"ROOT_QUERY\",\n config: this.config,\n });\n }\n\n public watch(\n watch: Cache.WatchOptions\n ): () => void {\n if (!this.watches.size) {\n // In case we previously called forgetCache(this) because\n // this.watches became empty (see below), reattach this cache to any\n // reactive variables on which it previously depended. It might seem\n // paradoxical that we're able to recall something we supposedly\n // forgot, but the point of calling forgetCache(this) is to silence\n // useless broadcasts while this.watches is empty, and to allow the\n // cache to be garbage collected. If, however, we manage to call\n // recallCache(this) here, this cache object must not have been\n // garbage collected yet, and should resume receiving updates from\n // reactive variables, now that it has a watcher to notify.\n recallCache(this);\n }\n this.watches.add(watch);\n if (watch.immediate) {\n this.maybeBroadcastWatch(watch);\n }\n return () => {\n // Once we remove the last watch from this.watches, cache.broadcastWatches\n // no longer does anything, so we preemptively tell the reactive variable\n // system to exclude this cache from future broadcasts.\n if (this.watches.delete(watch) && !this.watches.size) {\n forgetCache(this);\n }\n // Remove this watch from the LRU cache managed by the\n // maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory\n // leaks involving the closure of watch.callback.\n this.maybeBroadcastWatch.forget(watch);\n };\n }\n\n public gc(options?: {\n // If true, also free non-essential result cache memory by bulk-releasing\n // this.{store{Reader,Writer},maybeBroadcastWatch}. Defaults to false.\n resetResultCache?: boolean;\n // If resetResultCache is true, this.storeReader.canon will be preserved by\n // default, but can also be discarded by passing resetResultIdentities:true.\n // Defaults to false.\n resetResultIdentities?: boolean;\n }) {\n canonicalStringify.reset();\n print.reset();\n this.addTypenameTransform.resetCache();\n this.config.fragments?.resetCaches();\n const ids = this.optimisticData.gc();\n if (options && !this.txCount) {\n if (options.resetResultCache) {\n this.resetResultCache(options.resetResultIdentities);\n } else if (options.resetResultIdentities) {\n this.storeReader.resetCanon();\n }\n }\n return ids;\n }\n\n // Call this method to ensure the given root ID remains in the cache after\n // garbage collection, along with its transitive child entities. Note that\n // the cache automatically retains all directly written entities. By default,\n // the retainment persists after optimistic updates are removed. Pass true\n // for the optimistic argument if you would prefer for the retainment to be\n // discarded when the top-most optimistic layer is removed. Returns the\n // resulting (non-negative) retainment count.\n public retain(rootId: string, optimistic?: boolean): number {\n return (optimistic ? this.optimisticData : this.data).retain(rootId);\n }\n\n // Call this method to undo the effect of the retain method, above. Once the\n // retainment count falls to zero, the given ID will no longer be preserved\n // during garbage collection, though it may still be preserved by other safe\n // entities that refer to it. Returns the resulting (non-negative) retainment\n // count, in case that's useful.\n public release(rootId: string, optimistic?: boolean): number {\n return (optimistic ? this.optimisticData : this.data).release(rootId);\n }\n\n // Returns the canonical ID for a given StoreObject, obeying typePolicies\n // and keyFields (and dataIdFromObject, if you still use that). At minimum,\n // the object must contain a __typename and any primary key fields required\n // to identify entities of that type. If you pass a query result object, be\n // sure that none of the primary key fields have been renamed by aliasing.\n // If you pass a Reference object, its __ref ID string will be returned.\n public identify(object: StoreObject | Reference): string | undefined {\n if (isReference(object)) return object.__ref;\n try {\n return this.policies.identify(object)[0];\n } catch (e) {\n invariant.warn(e);\n }\n }\n\n public evict(options: Cache.EvictOptions): boolean {\n if (!options.id) {\n if (hasOwn.call(options, \"id\")) {\n // See comment in modify method about why we return false when\n // options.id exists but is falsy/undefined.\n return false;\n }\n options = { ...options, id: \"ROOT_QUERY\" };\n }\n try {\n // It's unlikely that the eviction will end up invoking any other\n // cache update operations while it's running, but {in,de}crementing\n // this.txCount still seems like a good idea, for uniformity with\n // the other update methods.\n ++this.txCount;\n // Pass this.data as a limit on the depth of the eviction, so evictions\n // during optimistic updates (when this.data is temporarily set equal to\n // this.optimisticData) do not escape their optimistic Layer.\n return this.optimisticData.evict(options, this.data);\n } finally {\n if (!--this.txCount && options.broadcast !== false) {\n this.broadcastWatches();\n }\n }\n }\n\n public reset(options?: Cache.ResetOptions): Promise {\n this.init();\n\n canonicalStringify.reset();\n\n if (options && options.discardWatches) {\n // Similar to what happens in the unsubscribe function returned by\n // cache.watch, applied to all current watches.\n this.watches.forEach((watch) => this.maybeBroadcastWatch.forget(watch));\n this.watches.clear();\n forgetCache(this);\n } else {\n // Calling this.init() above unblocks all maybeBroadcastWatch caching, so\n // this.broadcastWatches() triggers a broadcast to every current watcher\n // (letting them know their data is now missing). This default behavior is\n // convenient because it means the watches do not have to be manually\n // reestablished after resetting the cache. To prevent this broadcast and\n // cancel all watches, pass true for options.discardWatches.\n this.broadcastWatches();\n }\n\n return Promise.resolve();\n }\n\n public removeOptimistic(idToRemove: string) {\n const newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n if (newOptimisticData !== this.optimisticData) {\n this.optimisticData = newOptimisticData;\n this.broadcastWatches();\n }\n }\n\n private txCount = 0;\n\n public batch(\n options: Cache.BatchOptions\n ): TUpdateResult {\n const {\n update,\n optimistic = true,\n removeOptimistic,\n onWatchUpdated,\n } = options;\n\n let updateResult: TUpdateResult;\n const perform = (layer?: EntityStore): TUpdateResult => {\n const { data, optimisticData } = this;\n ++this.txCount;\n if (layer) {\n this.data = this.optimisticData = layer;\n }\n try {\n return (updateResult = update(this));\n } finally {\n --this.txCount;\n this.data = data;\n this.optimisticData = optimisticData;\n }\n };\n\n const alreadyDirty = new Set();\n\n if (onWatchUpdated && !this.txCount) {\n // If an options.onWatchUpdated callback is provided, we want to call it\n // with only the Cache.WatchOptions objects affected by options.update,\n // but there might be dirty watchers already waiting to be broadcast that\n // have nothing to do with the update. To prevent including those watchers\n // in the post-update broadcast, we perform this initial broadcast to\n // collect the dirty watchers, so we can re-dirty them later, after the\n // post-update broadcast, allowing them to receive their pending\n // broadcasts the next time broadcastWatches is called, just as they would\n // if we never called cache.batch.\n this.broadcastWatches({\n ...options,\n onWatchUpdated(watch) {\n alreadyDirty.add(watch);\n return false;\n },\n });\n }\n\n if (typeof optimistic === \"string\") {\n // Note that there can be multiple layers with the same optimistic ID.\n // When removeOptimistic(id) is called for that id, all matching layers\n // will be removed, and the remaining layers will be reapplied.\n this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n } else if (optimistic === false) {\n // Ensure both this.data and this.optimisticData refer to the root\n // (non-optimistic) layer of the cache during the update. Note that\n // this.data could be a Layer if we are currently executing an optimistic\n // update function, but otherwise will always be an EntityStore.Root\n // instance.\n perform(this.data);\n } else {\n // Otherwise, leave this.data and this.optimisticData unchanged and run\n // the update with broadcast batching.\n perform();\n }\n\n if (typeof removeOptimistic === \"string\") {\n this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n }\n\n // Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code\n // takes the else branch and calls this.broadcastWatches(options), which\n // does nothing when this.txCount > 0.\n if (onWatchUpdated && alreadyDirty.size) {\n this.broadcastWatches({\n ...options,\n onWatchUpdated(watch, diff) {\n const result = onWatchUpdated.call(this, watch, diff);\n if (result !== false) {\n // Since onWatchUpdated did not return false, this diff is\n // about to be broadcast to watch.callback, so we don't need\n // to re-dirty it with the other alreadyDirty watches below.\n alreadyDirty.delete(watch);\n }\n return result;\n },\n });\n // Silently re-dirty any watches that were already dirty before the update\n // was performed, and were not broadcast just now.\n if (alreadyDirty.size) {\n alreadyDirty.forEach((watch) => this.maybeBroadcastWatch.dirty(watch));\n }\n } else {\n // If alreadyDirty is empty or we don't have an onWatchUpdated\n // function, we don't need to go to the trouble of wrapping\n // options.onWatchUpdated.\n this.broadcastWatches(options);\n }\n\n return updateResult!;\n }\n\n public performTransaction(\n update: (cache: InMemoryCache) => any,\n optimisticId?: string | null\n ) {\n return this.batch({\n update,\n optimistic: optimisticId || optimisticId !== null,\n });\n }\n\n public transformDocument(document: DocumentNode): DocumentNode {\n return this.addTypenameToDocument(this.addFragmentsToDocument(document));\n }\n\n public fragmentMatches(\n fragment: InlineFragmentNode,\n typename: string\n ): boolean {\n return this.policies.fragmentMatches(fragment, typename);\n }\n\n public lookupFragment(fragmentName: string): FragmentDefinitionNode | null {\n return this.config.fragments?.lookup(fragmentName) || null;\n }\n\n protected broadcastWatches(options?: BroadcastOptions) {\n if (!this.txCount) {\n this.watches.forEach((c) => this.maybeBroadcastWatch(c, options));\n }\n }\n\n private addFragmentsToDocument(document: DocumentNode) {\n const { fragments } = this.config;\n return fragments ? fragments.transform(document) : document;\n }\n\n private addTypenameToDocument(document: DocumentNode) {\n if (this.addTypename) {\n return this.addTypenameTransform.transformDocument(document);\n }\n return document;\n }\n\n // This method is wrapped by maybeBroadcastWatch, which is called by\n // broadcastWatches, so that we compute and broadcast results only when\n // the data that would be broadcast might have changed. It would be\n // simpler to check for changes after recomputing a result but before\n // broadcasting it, but this wrapping approach allows us to skip both\n // the recomputation and the broadcast, in most cases.\n private broadcastWatch(c: Cache.WatchOptions, options?: BroadcastOptions) {\n const { lastDiff } = c;\n\n // Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions\n // currently requires no additional properties, so we can use c (a\n // WatchOptions object) as DiffOptions, without having to allocate a new\n // object, and without having to enumerate the relevant properties (query,\n // variables, etc.) explicitly. There will be some additional properties\n // (lastDiff, callback, etc.), but cache.diff ignores them.\n const diff = this.diff(c);\n\n if (options) {\n if (c.optimistic && typeof options.optimistic === \"string\") {\n diff.fromOptimisticTransaction = true;\n }\n\n if (\n options.onWatchUpdated &&\n options.onWatchUpdated.call(this, c, diff, lastDiff) === false\n ) {\n // Returning false from the onWatchUpdated callback will prevent\n // calling c.callback(diff) for this watcher.\n return;\n }\n }\n\n if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n c.callback((c.lastDiff = diff), lastDiff);\n }\n }\n\n /**\n * @experimental\n * @internal\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n */\n public getMemoryInternals?: typeof getInMemoryCacheMemoryInternals;\n}\n\nif (__DEV__) {\n InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n","import type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep, Slot } from \"optimism\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { ApolloCache } from \"../../core/index.js\";\n\nexport interface ReactiveVar {\n (newValue?: T): T;\n onNextChange(listener: ReactiveListener): () => void;\n attachCache(cache: ApolloCache): this;\n forgetCache(cache: ApolloCache): boolean;\n}\n\nexport type ReactiveListener = (value: T) => any;\n\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport const cacheSlot = new Slot>();\n\nconst cacheInfoMap = new WeakMap<\n ApolloCache,\n {\n vars: Set>;\n dep: OptimisticDependencyFunction>;\n }\n>();\n\nfunction getCacheInfo(cache: ApolloCache) {\n let info = cacheInfoMap.get(cache)!;\n if (!info) {\n cacheInfoMap.set(\n cache,\n (info = {\n vars: new Set(),\n dep: dep(),\n })\n );\n }\n return info;\n}\n\nexport function forgetCache(cache: ApolloCache) {\n getCacheInfo(cache).vars.forEach((rv) => rv.forgetCache(cache));\n}\n\n// Calling forgetCache(cache) serves to silence broadcasts and allows the\n// cache to be garbage collected. However, the varsByCache WeakMap\n// preserves the set of reactive variables that were previously associated\n// with this cache, which makes it possible to \"recall\" the cache at a\n// later time, by reattaching it to those variables. If the cache has been\n// garbage collected in the meantime, because it is no longer reachable,\n// you won't be able to call recallCache(cache), and the cache will\n// automatically disappear from the varsByCache WeakMap.\nexport function recallCache(cache: ApolloCache) {\n getCacheInfo(cache).vars.forEach((rv) => rv.attachCache(cache));\n}\n\nexport function makeVar(value: T): ReactiveVar {\n const caches = new Set>();\n const listeners = new Set>();\n\n const rv: ReactiveVar = function (newValue) {\n if (arguments.length > 0) {\n if (value !== newValue) {\n value = newValue!;\n caches.forEach((cache) => {\n // Invalidate any fields with custom read functions that\n // consumed this variable, so query results involving those\n // fields will be recomputed the next time we read them.\n getCacheInfo(cache).dep.dirty(rv);\n // Broadcast changes to any caches that have previously read\n // from this variable.\n broadcast(cache);\n });\n // Finally, notify any listeners added via rv.onNextChange.\n const oldListeners = Array.from(listeners);\n listeners.clear();\n oldListeners.forEach((listener) => listener(value));\n }\n } else {\n // When reading from the variable, obtain the current cache from\n // context via cacheSlot. This isn't entirely foolproof, but it's\n // the same system that powers varDep.\n const cache = cacheSlot.getValue();\n if (cache) {\n attach(cache);\n getCacheInfo(cache).dep(rv);\n }\n }\n\n return value;\n };\n\n rv.onNextChange = (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const attach = (rv.attachCache = (cache) => {\n caches.add(cache);\n getCacheInfo(cache).vars.add(rv);\n return rv;\n });\n\n rv.forgetCache = (cache) => caches.delete(cache);\n\n return rv;\n}\n\ntype Broadcastable = ApolloCache & {\n // This method is protected in InMemoryCache, which we are ignoring, but\n // we still want some semblance of type safety when we call it.\n broadcastWatches?: InMemoryCache[\"broadcastWatches\"];\n};\n\nfunction broadcast(cache: Broadcastable) {\n if (cache.broadcastWatches) {\n cache.broadcastWatches();\n }\n}\n","import type { Observer } from \"./Observable.js\";\nimport { Observable } from \"./Observable.js\";\n\n// Like Observable.prototype.map, except that the mapping function can\n// optionally return a Promise (or be async).\nexport function asyncMap(\n observable: Observable,\n mapFn: (value: V) => R | PromiseLike,\n catchFn?: (error: any) => R | PromiseLike\n): Observable {\n return new Observable((observer) => {\n let promiseQueue = {\n // Normally we would initialize promiseQueue to Promise.resolve(), but\n // in this case, for backwards compatibility, we need to be careful to\n // invoke the first callback synchronously.\n then(callback: () => any) {\n return new Promise((resolve) => resolve(callback()));\n },\n } as Promise;\n\n function makeCallback(\n examiner: typeof mapFn | typeof catchFn,\n key: \"next\" | \"error\"\n ): (arg: any) => void {\n return (arg) => {\n if (examiner) {\n const both = () =>\n // If the observer is closed, we don't want to continue calling the\n // mapping function - it's result will be swallowed anyways.\n observer.closed ?\n /* will be swallowed */ (0 as any)\n : examiner(arg);\n\n promiseQueue = promiseQueue.then(both, both).then(\n (result) => observer.next(result),\n (error) => observer.error(error)\n );\n } else {\n observer[key](arg);\n }\n };\n }\n\n const handler: Observer = {\n next: makeCallback(mapFn, \"next\"),\n error: makeCallback(catchFn, \"error\"),\n complete() {\n // no need to reassign `promiseQueue`, after `observer.complete`,\n // the observer will be closed and short-circuit everything anyways\n /*promiseQueue = */ promiseQueue.then(() => observer.complete());\n },\n };\n\n const sub = observable.subscribe(handler);\n return () => sub.unsubscribe();\n });\n}\n","import type { FetchResult } from \"../../link/core/index.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\n\nexport function graphQLResultHasError(result: FetchResult): boolean {\n const errors = getGraphQLErrorsFromResult(result);\n return isNonEmptyArray(errors);\n}\n\nexport function getGraphQLErrorsFromResult(result: FetchResult) {\n const graphQLErrors =\n isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach((incrementalResult) => {\n if (incrementalResult.errors) {\n graphQLErrors.push(...incrementalResult.errors);\n }\n });\n }\n return graphQLErrors;\n}\n","import type {\n Observer,\n ObservableSubscription,\n Subscriber,\n} from \"./Observable.js\";\nimport { Observable } from \"./Observable.js\";\nimport { iterateObserversSafely } from \"./iteration.js\";\nimport { fixObservableSubclass } from \"./subclassing.js\";\n\ntype MaybeAsync = T | PromiseLike;\n\nfunction isPromiseLike(value: MaybeAsync): value is PromiseLike {\n return value && typeof (value as any).then === \"function\";\n}\n\n// Any individual Source can be an Observable or a promise for one.\ntype Source = MaybeAsync>;\n\nexport type ConcastSourcesIterable = Iterable>;\nexport type ConcastSourcesArray = Array>;\n\n// A Concast observable concatenates the given sources into a single\n// non-overlapping sequence of Ts, automatically unwrapping any promises,\n// and broadcasts the T elements of that sequence to any number of\n// subscribers, all without creating a bunch of intermediary Observable\n// wrapper objects.\n//\n// Even though any number of observers can subscribe to the Concast, each\n// source observable is guaranteed to receive at most one subscribe call,\n// and the results are multicast to all observers.\n//\n// In addition to broadcasting every next/error message to this.observers,\n// the Concast stores the most recent message using this.latest, so any\n// new observers can immediately receive the latest message, even if it\n// was originally delivered in the past. This behavior means we can assume\n// every active observer in this.observers has received the same most\n// recent message.\n//\n// With the exception of this.latest replay, a Concast is a \"hot\"\n// observable in the sense that it does not replay past results from the\n// beginning of time for each new observer.\n//\n// Could we have used some existing RxJS class instead? Concast is\n// similar to a BehaviorSubject, because it is multicast and redelivers\n// the latest next/error message to new subscribers. Unlike Subject,\n// Concast does not expose an Observer interface (this.handlers is\n// intentionally private), since Concast gets its inputs from the\n// concatenated sources. If we ever switch to RxJS, there may be some\n// value in reusing their code, but for now we use zen-observable, which\n// does not contain any Subject implementations.\nexport class Concast extends Observable {\n // Active observers receiving broadcast messages. Thanks to this.latest,\n // we can assume all observers in this Set have received the same most\n // recent message, though possibly at different times in the past.\n private observers = new Set>();\n\n // This property starts off undefined to indicate the initial\n // subscription has not yet begun, then points to each source\n // subscription in turn, and finally becomes null after the sources have\n // been exhausted. After that, it stays null.\n private sub?: ObservableSubscription | null;\n\n // Not only can the individual elements of the iterable be promises, but\n // also the iterable itself can be wrapped in a promise.\n constructor(sources: MaybeAsync> | Subscriber) {\n super((observer) => {\n this.addObserver(observer);\n return () => this.removeObserver(observer);\n });\n\n // Suppress rejection warnings for this.promise, since it's perfectly\n // acceptable to pay no attention to this.promise if you're consuming\n // the results through the normal observable API.\n this.promise.catch((_) => {});\n\n // If someone accidentally tries to create a Concast using a subscriber\n // function, recover by creating an Observable from that subscriber and\n // using it as the source.\n if (typeof sources === \"function\") {\n sources = [new Observable(sources)];\n }\n\n if (isPromiseLike(sources)) {\n sources.then((iterable) => this.start(iterable), this.handlers.error);\n } else {\n this.start(sources);\n }\n }\n\n // A consumable array of source observables, incrementally consumed each time\n // this.handlers.complete is called. This private field is not initialized\n // until the concast.start method is called, which can happen asynchronously\n // if a Promise is passed to the Concast constructor, so undefined is a\n // possible value for this.sources before concast.start is called.\n private sources: Source[] | undefined;\n\n private start(sources: ConcastSourcesIterable) {\n if (this.sub !== void 0) return;\n\n // In practice, sources is most often simply an Array of observables.\n // TODO Consider using sources[Symbol.iterator]() to take advantage\n // of the laziness of non-Array iterables.\n this.sources = Array.from(sources);\n\n // Calling this.handlers.complete() kicks off consumption of the first\n // source observable. It's tempting to do this step lazily in\n // addObserver, but this.promise can be accessed without calling\n // addObserver, so consumption needs to begin eagerly.\n this.handlers.complete();\n }\n\n private deliverLastMessage(observer: Observer) {\n if (this.latest) {\n const nextOrError = this.latest[0];\n const method = observer[nextOrError];\n if (method) {\n method.call(observer, this.latest[1]);\n }\n // If the subscription is already closed, and the last message was\n // a 'next' message, simulate delivery of the final 'complete'\n // message again.\n if (this.sub === null && nextOrError === \"next\" && observer.complete) {\n observer.complete();\n }\n }\n }\n\n public addObserver(observer: Observer) {\n if (!this.observers.has(observer)) {\n // Immediately deliver the most recent message, so we can always\n // be sure all observers have the latest information.\n this.deliverLastMessage(observer);\n this.observers.add(observer);\n }\n }\n\n public removeObserver(observer: Observer) {\n if (this.observers.delete(observer) && this.observers.size < 1) {\n // In case there are still any listeners in this.nextResultListeners, and\n // no error or completion has been broadcast yet, make sure those\n // observers have a chance to run and then remove themselves from\n // this.observers.\n this.handlers.complete();\n }\n }\n\n // Any Concast object can be trivially converted to a Promise, without\n // having to create a new wrapper Observable. This promise provides an\n // easy way to observe the final state of the Concast.\n private resolve!: (result?: T | PromiseLike) => void;\n private reject!: (reason: any) => void;\n public readonly promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n\n // Name and argument of the most recently invoked observer method, used\n // to deliver latest results immediately to new observers.\n private latest?: [\"next\", T] | [\"error\", any];\n\n // Bound handler functions that can be reused for every internal\n // subscription.\n private handlers = {\n next: (result: T) => {\n if (this.sub !== null) {\n this.latest = [\"next\", result];\n this.notify(\"next\", result);\n iterateObserversSafely(this.observers, \"next\", result);\n }\n },\n\n error: (error: any) => {\n const { sub } = this;\n if (sub !== null) {\n // Delay unsubscribing from the underlying subscription slightly,\n // so that immediately subscribing another observer can keep the\n // subscription active.\n if (sub) setTimeout(() => 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\n complete: () => {\n const { sub, sources = [] } = this;\n if (sub !== null) {\n // If complete is called before concast.start, this.sources may be\n // undefined, so we use a default value of [] for sources. That works\n // here because it falls into the if (!value) {...} block, which\n // appropriately terminates the Concast, even if this.sources might\n // eventually have been initialized to a non-empty array.\n const value = sources.shift();\n if (!value) {\n if (sub) setTimeout(() => sub.unsubscribe());\n this.sub = null;\n if (this.latest && this.latest[0] === \"next\") {\n this.resolve(this.latest[1]);\n } else {\n this.resolve();\n }\n this.notify(\"complete\");\n // We do not store this.latest = [\"complete\"], because doing so\n // discards useful information about the previous next (or\n // error) message. Instead, if new observers subscribe after\n // this Concast has completed, they will receive the final\n // 'next' message (unless there was an error) immediately\n // followed by a 'complete' message (see addObserver).\n iterateObserversSafely(this.observers, \"complete\");\n } else if (isPromiseLike(value)) {\n value.then(\n (obs) => (this.sub = obs.subscribe(this.handlers)),\n this.handlers.error\n );\n } else {\n this.sub = value.subscribe(this.handlers);\n }\n }\n },\n };\n\n private nextResultListeners = new Set();\n\n private notify(\n method: Parameters[0],\n arg?: Parameters[1]\n ) {\n const { nextResultListeners } = this;\n if (nextResultListeners.size) {\n // Replacing this.nextResultListeners first ensures it does not grow while\n // we are iterating over it, potentially leading to infinite loops.\n this.nextResultListeners = new Set();\n nextResultListeners.forEach((listener) => listener(method, arg));\n }\n }\n\n // We need a way to run callbacks just *before* the next result (or error or\n // completion) is delivered by this Concast, so we can be sure any code that\n // runs as a result of delivering that result/error observes the effects of\n // running the callback(s). It was tempting to reuse the Observer type instead\n // of introducing NextResultListener, but that messes with the sizing and\n // maintenance of this.observers, and ends up being more code overall.\n beforeNext(callback: NextResultListener) {\n let called = false;\n this.nextResultListeners.add((method, arg) => {\n if (!called) {\n called = true;\n callback(method, arg);\n }\n });\n }\n\n // A public way to abort observation and broadcast.\n public cancel = (reason: any) => {\n this.reject(reason);\n this.sources = [];\n this.handlers.error(reason);\n };\n}\n\ntype NextResultListener = (\n method: \"next\" | \"error\" | \"complete\",\n arg?: any\n) => any;\n\n// Necessary because the Concast constructor has a different signature\n// than the Observable constructor.\nfixObservableSubclass(Concast);\n","import type { DocumentNode, GraphQLFormattedError } from \"graphql\";\nimport { equal } from \"@wry/equality\";\n\nimport type { Cache, ApolloCache } from \"../cache/index.js\";\nimport { DeepMerger } from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/index.js\";\nimport type { WatchQueryOptions, ErrorPolicy } from \"./watchQueryOptions.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport { reobserveCacheFirst } from \"./ObservableQuery.js\";\nimport type { QueryListener } from \"./types.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\nimport {\n isNonEmptyArray,\n graphQLResultHasError,\n canUseWeakMap,\n} from \"../utilities/index.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type { ApolloError } from \"../errors/index.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type { Unmasked } from \"../masking/index.js\";\n\nexport type QueryStoreValue = Pick<\n QueryInfo,\n \"variables\" | \"networkStatus\" | \"networkError\" | \"graphQLErrors\"\n>;\n\nexport const enum CacheWriteBehavior {\n FORBID,\n OVERWRITE,\n MERGE,\n}\n\nconst destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)<\n ApolloCache,\n number\n>();\n\nfunction wrapDestructiveCacheMethod(\n cache: ApolloCache,\n methodName: \"evict\" | \"modify\" | \"reset\"\n) {\n const original = cache[methodName];\n if (typeof original === \"function\") {\n // @ts-expect-error this is just too generic to be typed correctly\n cache[methodName] = function () {\n destructiveMethodCounts.set(\n cache,\n // The %1e15 allows the count to wrap around to 0 safely every\n // quadrillion evictions, so there's no risk of overflow. To be\n // clear, this is more of a pedantic principle than something\n // that matters in any conceivable practical scenario.\n (destructiveMethodCounts.get(cache)! + 1) % 1e15\n );\n // @ts-expect-error this is just too generic to be typed correctly\n return original.apply(this, arguments);\n };\n }\n}\n\nfunction cancelNotifyTimeout(info: QueryInfo) {\n if (info[\"notifyTimeout\"]) {\n clearTimeout(info[\"notifyTimeout\"]);\n info[\"notifyTimeout\"] = void 0;\n }\n}\n\n// A QueryInfo object represents a single query managed by the\n// QueryManager, which tracks all QueryInfo objects by queryId in its\n// this.queries Map. QueryInfo objects store the latest results and errors\n// for the given query, and are responsible for reporting those results to\n// the corresponding ObservableQuery, via the QueryInfo.notify method.\n// Results are reported asynchronously whenever setDiff marks the\n// QueryInfo object as dirty, though a call to the QueryManager's\n// broadcastQueries method may trigger the notification before it happens\n// automatically. This class used to be a simple interface type without\n// any field privacy or meaningful methods, which is why it still has so\n// many public fields. The effort to lock down and simplify the QueryInfo\n// interface is ongoing, and further improvements are welcome.\nexport class QueryInfo {\n listeners = new Set();\n document: DocumentNode | null = null;\n lastRequestId = 1;\n variables?: Record;\n networkStatus?: NetworkStatus;\n networkError?: Error | null;\n graphQLErrors?: ReadonlyArray;\n stopped = false;\n\n private cache: ApolloCache;\n\n constructor(\n queryManager: QueryManager,\n public readonly queryId = queryManager.generateQueryId()\n ) {\n const cache = (this.cache = queryManager.cache);\n\n // Track how often cache.evict is called, since we want eviction to\n // override the feud-stopping logic in the markResult method, by\n // causing shouldWrite to return true. Wrapping the cache.evict method\n // is a bit of a hack, but it saves us from having to make eviction\n // counting an official part of the ApolloCache API.\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\n public init(query: {\n document: DocumentNode;\n variables: Record | undefined;\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus?: NetworkStatus;\n observableQuery?: ObservableQuery;\n lastRequestId?: number;\n }): this {\n let networkStatus = query.networkStatus || NetworkStatus.loading;\n if (\n this.variables &&\n this.networkStatus !== NetworkStatus.loading &&\n !equal(this.variables, query.variables)\n ) {\n networkStatus = NetworkStatus.setVariables;\n }\n\n if (!equal(query.variables, this.variables)) {\n this.lastDiff = void 0;\n }\n\n Object.assign(this, {\n document: query.document,\n variables: query.variables,\n networkError: null,\n graphQLErrors: this.graphQLErrors || [],\n networkStatus,\n });\n\n if (query.observableQuery) {\n this.setObservableQuery(query.observableQuery);\n }\n\n if (query.lastRequestId) {\n this.lastRequestId = query.lastRequestId;\n }\n\n return this;\n }\n\n private dirty: boolean = false;\n\n private notifyTimeout?: ReturnType;\n\n reset() {\n cancelNotifyTimeout(this);\n this.dirty = false;\n }\n\n resetDiff() {\n this.lastDiff = void 0;\n }\n\n getDiff(): Cache.DiffResult {\n const options = this.getDiffOptions();\n\n if (this.lastDiff && equal(options, this.lastDiff.options)) {\n return this.lastDiff.diff;\n }\n\n this.updateWatch(this.variables);\n\n const oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return { complete: false };\n }\n\n const diff = this.cache.diff(options);\n this.updateLastDiff(diff, options);\n return diff;\n }\n\n private lastDiff?: {\n diff: Cache.DiffResult;\n options: Cache.DiffOptions;\n };\n\n private updateLastDiff(\n diff: Cache.DiffResult | null,\n options?: Cache.DiffOptions\n ) {\n this.lastDiff =\n diff ?\n {\n diff,\n options: options || this.getDiffOptions(),\n }\n : void 0;\n }\n\n private getDiffOptions(variables = this.variables): Cache.DiffOptions {\n return {\n query: this.document!,\n variables,\n returnPartialData: true,\n optimistic: true,\n canonizeResults: this.observableQuery?.options.canonizeResults,\n };\n }\n\n setDiff(diff: Cache.DiffResult | null) {\n const oldDiff = this.lastDiff && this.lastDiff.diff;\n\n // If we are trying to deliver an incomplete cache result, we avoid\n // reporting it if the query has errored, otherwise we let the broadcast try\n // and repair the partial result by refetching the query. This check avoids\n // a situation where a query that errors and another succeeds with\n // overlapping data does not report the partial data result to the errored\n // query.\n //\n // See https://github.com/apollographql/apollo-client/issues/11400 for more\n // information on this issue.\n if (diff && !diff.complete && this.observableQuery?.getLastError()) {\n return;\n }\n\n this.updateLastDiff(diff);\n\n if (!this.dirty && !equal(oldDiff && oldDiff.result, diff && diff.result)) {\n this.dirty = true;\n if (!this.notifyTimeout) {\n this.notifyTimeout = setTimeout(() => this.notify(), 0);\n }\n }\n }\n\n public readonly observableQuery: ObservableQuery | null = null;\n private oqListener?: QueryListener;\n\n setObservableQuery(oq: ObservableQuery | null) {\n if (oq === this.observableQuery) return;\n\n if (this.oqListener) {\n this.listeners.delete(this.oqListener);\n }\n\n (this as any).observableQuery = oq;\n\n if (oq) {\n oq[\"queryInfo\"] = this;\n this.listeners.add(\n (this.oqListener = () => {\n const diff = this.getDiff();\n if (diff.fromOptimisticTransaction) {\n // If this diff came from an optimistic transaction, deliver the\n // current cache data to the ObservableQuery, but don't perform a\n // reobservation, since oq.reobserveCacheFirst might make a network\n // request, and we never want to trigger network requests in the\n // middle of optimistic updates.\n oq[\"observe\"]();\n } else {\n // Otherwise, make the ObservableQuery \"reobserve\" the latest data\n // using a temporary fetch policy of \"cache-first\", so complete cache\n // results have a chance to be delivered without triggering additional\n // network requests, even when options.fetchPolicy is \"network-only\"\n // or \"cache-and-network\". All other fetch policies are preserved by\n // this method, and are handled by calling oq.reobserve(). If this\n // reobservation is spurious, isDifferentFromLastResult still has a\n // chance to catch it before delivery to ObservableQuery subscribers.\n reobserveCacheFirst(oq);\n }\n })\n );\n } else {\n delete this.oqListener;\n }\n }\n\n notify() {\n cancelNotifyTimeout(this);\n\n if (this.shouldNotify()) {\n this.listeners.forEach((listener) => listener(this));\n }\n\n this.dirty = false;\n }\n\n private shouldNotify() {\n if (!this.dirty || !this.listeners.size) {\n return false;\n }\n\n if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {\n const { fetchPolicy } = this.observableQuery.options;\n if (fetchPolicy !== \"cache-only\" && fetchPolicy !== \"cache-and-network\") {\n return false;\n }\n }\n\n return true;\n }\n\n public stop() {\n if (!this.stopped) {\n this.stopped = true;\n\n // Cancel the pending notify timeout\n this.reset();\n\n this.cancel();\n // Revert back to the no-op version of cancel inherited from\n // QueryInfo.prototype.\n this.cancel = QueryInfo.prototype.cancel;\n\n const oq = this.observableQuery;\n if (oq) oq.stopPolling();\n }\n }\n\n // This method is a no-op by default, until/unless overridden by the\n // updateWatch method.\n private cancel() {}\n\n private lastWatch?: Cache.WatchOptions;\n\n private updateWatch(variables = this.variables) {\n const oq = this.observableQuery;\n if (oq && oq.options.fetchPolicy === \"no-cache\") {\n return;\n }\n\n const watchOptions: Cache.WatchOptions = {\n // Although this.getDiffOptions returns Cache.DiffOptions instead of\n // Cache.WatchOptions, all the overlapping options should be the same, so\n // we can reuse getDiffOptions here, for consistency.\n ...this.getDiffOptions(variables),\n watcher: this,\n callback: (diff) => this.setDiff(diff),\n };\n\n if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {\n this.cancel();\n this.cancel = this.cache.watch((this.lastWatch = watchOptions));\n }\n }\n\n private lastWrite?: {\n result: FetchResult;\n variables: WatchQueryOptions[\"variables\"];\n dmCount: number | undefined;\n };\n\n public resetLastWrite() {\n this.lastWrite = void 0;\n }\n\n private shouldWrite(\n result: FetchResult,\n variables: WatchQueryOptions[\"variables\"]\n ) {\n const { lastWrite } = this;\n return !(\n lastWrite &&\n // If cache.evict has been called since the last time we wrote this\n // data into the cache, there's a chance writing this result into\n // the cache will repair what was evicted.\n lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&\n equal(variables, lastWrite.variables) &&\n equal(result.data, lastWrite.result.data)\n );\n }\n\n public markResult(\n result: FetchResult,\n document: DocumentNode,\n options: Pick<\n WatchQueryOptions,\n \"variables\" | \"fetchPolicy\" | \"errorPolicy\"\n >,\n cacheWriteBehavior: CacheWriteBehavior\n ) {\n const merger = new DeepMerger();\n const graphQLErrors =\n isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n\n // Cancel the pending notify timeout (if it exists) to prevent extraneous network\n // requests. To allow future notify timeouts, diff and dirty are reset as well.\n this.reset();\n\n if (\"incremental\" in result && isNonEmptyArray(result.incremental)) {\n const mergedData = mergeIncrementalData(this.getDiff().result, result);\n result.data = mergedData;\n\n // Detect the first chunk of a deferred query and merge it with existing\n // cache data. This ensures a `cache-first` fetch policy that returns\n // partial cache data or a `cache-and-network` fetch policy that already\n // has full data in the cache does not complain when trying to merge the\n // initial deferred server data with existing cache data.\n } else if (\"hasNext\" in result && result.hasNext) {\n const diff = this.getDiff();\n result.data = merger.merge(diff.result, result.data);\n }\n\n this.graphQLErrors = graphQLErrors;\n\n if (options.fetchPolicy === \"no-cache\") {\n this.updateLastDiff(\n { result: result.data, complete: true },\n this.getDiffOptions(options.variables)\n );\n } else if (cacheWriteBehavior !== CacheWriteBehavior.FORBID) {\n if (shouldWriteResult(result, options.errorPolicy)) {\n // Using a transaction here so we have a chance to read the result\n // back from the cache before the watch callback fires as a result\n // of writeQuery, so we can store the new diff quietly and ignore\n // it when we receive it redundantly from the watch callback.\n this.cache.performTransaction((cache) => {\n if (this.shouldWrite(result, options.variables)) {\n cache.writeQuery({\n query: document,\n data: result.data as Unmasked,\n variables: options.variables,\n overwrite: cacheWriteBehavior === CacheWriteBehavior.OVERWRITE,\n });\n\n this.lastWrite = {\n result,\n variables: options.variables,\n dmCount: destructiveMethodCounts.get(this.cache),\n };\n } else {\n // If result is the same as the last result we received from\n // the network (and the variables match too), avoid writing\n // result into the cache again. The wisdom of skipping this\n // cache write is far from obvious, since any cache write\n // could be the one that puts the cache back into a desired\n // state, fixing corruption or missing data. However, if we\n // always write every network result into the cache, we enable\n // feuds between queries competing to update the same data in\n // incompatible ways, which can lead to an endless cycle of\n // cache broadcasts and useless network requests. As with any\n // feud, eventually one side must step back from the brink,\n // letting the other side(s) have the last word(s). There may\n // be other points where we could break this cycle, such as\n // silencing the broadcast for cache.writeQuery (not a good\n // idea, since it just delays the feud a bit) or somehow\n // avoiding the network request that just happened (also bad,\n // because the server could return useful new data). All\n // options considered, skipping this cache write seems to be\n // the least damaging place to break the cycle, because it\n // reflects the intuition that we recently wrote this exact\n // result into the cache, so the cache *should* already/still\n // contain this data. If some other query has clobbered that\n // data in the meantime, that's too bad, but there will be no\n // winners if every query blindly reverts to its own version\n // of the data. This approach also gives the network a chance\n // to return new data, which will be written into the cache as\n // usual, notifying only those queries that are directly\n // affected by the cache updates, as usual. In the future, an\n // even more sophisticated cache could perhaps prevent or\n // mitigate the clobbering somehow, but that would make this\n // particular cache write even less important, and thus\n // skipping it would be even safer than it is today.\n if (this.lastDiff && this.lastDiff.diff.complete) {\n // Reuse data from the last good (complete) diff that we\n // received, when possible.\n result.data = this.lastDiff.diff.result;\n return;\n }\n // If the previous this.diff was incomplete, fall through to\n // re-reading the latest data with cache.diff, below.\n }\n\n const diffOptions = this.getDiffOptions(options.variables);\n const diff = cache.diff(diffOptions);\n\n // In case the QueryManager stops this QueryInfo before its\n // results are delivered, it's important to avoid restarting the\n // cache watch when markResult is called. We also avoid updating\n // the watch if we are writing a result that doesn't match the current\n // variables to avoid race conditions from broadcasting the wrong\n // result.\n if (!this.stopped && equal(this.variables, options.variables)) {\n // Any time we're about to update this.diff, we need to make\n // sure we've started watching the cache.\n this.updateWatch(options.variables);\n }\n\n // If we're allowed to write to the cache, and we can read a\n // complete result from the cache, update result.data to be the\n // result from the cache, rather than the raw network result.\n // Set without setDiff to avoid triggering a notify call, since\n // we have other ways of notifying for this result.\n this.updateLastDiff(diff, diffOptions);\n if (diff.complete) {\n result.data = diff.result;\n }\n });\n } else {\n this.lastWrite = void 0;\n }\n }\n }\n\n public markReady() {\n this.networkError = null;\n return (this.networkStatus = NetworkStatus.ready);\n }\n\n public markError(error: ApolloError) {\n this.networkStatus = NetworkStatus.error;\n this.lastWrite = void 0;\n\n this.reset();\n\n if (error.graphQLErrors) {\n this.graphQLErrors = error.graphQLErrors;\n }\n\n if (error.networkError) {\n this.networkError = error.networkError;\n }\n\n return error;\n }\n}\n\nexport function shouldWriteResult(\n result: FetchResult,\n errorPolicy: ErrorPolicy = \"none\"\n) {\n const ignoreErrors = errorPolicy === \"ignore\" || errorPolicy === \"all\";\n let writeWithErrors = !graphQLResultHasError(result);\n if (!writeWithErrors && ignoreErrors && result.data) {\n writeWithErrors = true;\n }\n return writeWithErrors;\n}\n","import { invariant, newInvariantError } from \"../utilities/globals/index.js\";\n\nimport type { DocumentNode } from \"graphql\";\n// TODO(brian): A hack until this issue is resolved (https://github.com/graphql/graphql-js/issues/3356)\ntype OperationTypeNode = any;\nimport { equal } from \"@wry/equality\";\n\nimport type { ApolloLink, FetchResult } from \"../link/core/index.js\";\nimport { execute } from \"../link/core/index.js\";\nimport {\n addNonReactiveToNamedFragments,\n defaultCacheSizes,\n hasDirectives,\n isExecutionPatchIncrementalResult,\n isExecutionPatchResult,\n isFullyUnmaskedOperation,\n removeDirectivesFromDocument,\n} from \"../utilities/index.js\";\nimport type { Cache, ApolloCache } from \"../cache/index.js\";\nimport { canonicalStringify } from \"../cache/index.js\";\n\nimport type {\n ObservableSubscription,\n ConcastSourcesArray,\n} from \"../utilities/index.js\";\nimport {\n getDefaultValues,\n getOperationDefinition,\n getOperationName,\n hasClientExports,\n graphQLResultHasError,\n getGraphQLErrorsFromResult,\n Observable,\n asyncMap,\n isNonEmptyArray,\n Concast,\n makeUniqueId,\n isDocumentNode,\n isNonNullObject,\n DocumentTransform,\n} from \"../utilities/index.js\";\nimport { mergeIncrementalData } from \"../utilities/common/incrementalResult.js\";\nimport {\n ApolloError,\n isApolloError,\n graphQLResultHasProtocolErrors,\n} from \"../errors/index.js\";\nimport type {\n QueryOptions,\n WatchQueryOptions,\n SubscriptionOptions,\n MutationOptions,\n ErrorPolicy,\n MutationFetchPolicy,\n WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\nimport { ObservableQuery, logMissingFieldErrors } from \"./ObservableQuery.js\";\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type {\n ApolloQueryResult,\n OperationVariables,\n MutationUpdaterFunction,\n OnQueryUpdated,\n InternalRefetchQueriesInclude,\n InternalRefetchQueriesOptions,\n InternalRefetchQueriesResult,\n InternalRefetchQueriesMap,\n DefaultContext,\n} from \"./types.js\";\nimport type { LocalState } from \"./LocalState.js\";\n\nimport type { QueryStoreValue } from \"./QueryInfo.js\";\nimport {\n QueryInfo,\n shouldWriteResult,\n CacheWriteBehavior,\n} from \"./QueryInfo.js\";\nimport type { ApolloErrorOptions } from \"../errors/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../errors/index.js\";\nimport { print } from \"../utilities/index.js\";\nimport type { IgnoreModifier } from \"../cache/core/types/common.js\";\nimport type { TODO } from \"../utilities/types/TODO.js\";\n\nconst { hasOwnProperty } = Object.prototype;\n\nconst IGNORE: IgnoreModifier = Object.create(null);\n\ninterface MutationStoreValue {\n mutation: DocumentNode;\n variables: Record;\n loading: boolean;\n error: Error | null;\n}\n\ntype UpdateQueries = MutationOptions[\"updateQueries\"];\n\ninterface TransformCacheEntry {\n hasClientExports: boolean;\n hasForcedResolvers: boolean;\n hasNonreactiveDirective: boolean;\n nonReactiveQuery: DocumentNode;\n clientQuery: DocumentNode | null;\n serverQuery: DocumentNode | null;\n defaultVars: OperationVariables;\n asQuery: DocumentNode;\n}\n\nimport type { DefaultOptions } from \"./ApolloClient.js\";\nimport { Trie } from \"@wry/trie\";\nimport { AutoCleanedWeakCache, cacheSizes } from \"../utilities/index.js\";\nimport { maskFragment, maskOperation } from \"../masking/index.js\";\nimport type { MaybeMasked, Unmasked } from \"../masking/index.js\";\n\ninterface MaskFragmentOptions {\n fragment: DocumentNode;\n data: TData;\n fragmentName?: string;\n}\n\ninterface MaskOperationOptions {\n document: DocumentNode;\n data: TData;\n id: string;\n fetchPolicy?: WatchQueryFetchPolicy;\n}\n\nexport interface QueryManagerOptions {\n cache: ApolloCache;\n link: ApolloLink;\n defaultOptions: DefaultOptions;\n documentTransform: DocumentTransform | null | undefined;\n queryDeduplication: boolean;\n onBroadcast: undefined | (() => void);\n ssrMode: boolean;\n clientAwareness: Record;\n localState: LocalState;\n assumeImmutableResults: boolean;\n defaultContext: Partial | undefined;\n dataMasking: boolean;\n}\n\nexport class QueryManager {\n public cache: ApolloCache;\n public link: ApolloLink;\n public defaultOptions: DefaultOptions;\n\n public readonly assumeImmutableResults: boolean;\n public readonly documentTransform: DocumentTransform;\n public readonly ssrMode: boolean;\n public readonly defaultContext: Partial;\n public readonly dataMasking: boolean;\n\n private queryDeduplication: boolean;\n private clientAwareness: Record = {};\n private localState: LocalState;\n\n private onBroadcast?: () => void;\n public mutationStore?: {\n [mutationId: string]: MutationStoreValue;\n };\n\n // All the queries that the QueryManager is currently managing (not\n // including mutations and subscriptions).\n private queries = new Map();\n\n // Maps from queryId strings to Promise rejection functions for\n // currently active queries and fetches.\n // Use protected instead of private field so\n // @apollo/experimental-nextjs-app-support can access type info.\n protected fetchCancelFns = new Map any>();\n\n constructor(options: QueryManagerOptions) {\n const defaultDocumentTransform = new DocumentTransform(\n (document) => this.cache.transformDocument(document),\n // Allow the apollo cache to manage its own transform caches\n { cache: false }\n );\n\n this.cache = options.cache;\n this.link = options.link;\n this.defaultOptions = options.defaultOptions;\n this.queryDeduplication = options.queryDeduplication;\n this.clientAwareness = options.clientAwareness;\n this.localState = options.localState;\n this.ssrMode = options.ssrMode;\n this.assumeImmutableResults = options.assumeImmutableResults;\n this.dataMasking = options.dataMasking;\n const documentTransform = options.documentTransform;\n this.documentTransform =\n documentTransform ?\n defaultDocumentTransform\n .concat(documentTransform)\n // The custom document transform may add new fragment spreads or new\n // field selections, so we want to give the cache a chance to run\n // again. For example, the InMemoryCache adds __typename to field\n // selections and fragments from the fragment registry.\n .concat(defaultDocumentTransform)\n : defaultDocumentTransform;\n this.defaultContext = options.defaultContext || Object.create(null);\n\n if ((this.onBroadcast = options.onBroadcast)) {\n this.mutationStore = Object.create(null);\n }\n }\n\n /**\n * Call this method to terminate any active query processes, making it safe\n * to dispose of this QueryManager instance.\n */\n public stop() {\n this.queries.forEach((_info, queryId) => {\n this.stopQueryNoBroadcast(queryId);\n });\n\n this.cancelPendingFetches(\n newInvariantError(\"QueryManager stopped while query was in flight\")\n );\n }\n\n private cancelPendingFetches(error: Error) {\n this.fetchCancelFns.forEach((cancel) => cancel(error));\n this.fetchCancelFns.clear();\n }\n\n public async mutate<\n TData,\n TVariables extends OperationVariables,\n TContext extends Record,\n TCache extends ApolloCache,\n >({\n mutation,\n variables,\n optimisticResponse,\n updateQueries,\n refetchQueries = [],\n awaitRefetchQueries = false,\n update: updateWithProxyFn,\n onQueryUpdated,\n fetchPolicy = this.defaultOptions.mutate?.fetchPolicy || \"network-only\",\n errorPolicy = this.defaultOptions.mutate?.errorPolicy || \"none\",\n keepRootFields,\n context,\n }: MutationOptions): Promise<\n FetchResult>\n > {\n invariant(\n mutation,\n \"mutation option is required. You must specify your GraphQL document in the mutation option.\"\n );\n\n invariant(\n fetchPolicy === \"network-only\" || fetchPolicy === \"no-cache\",\n \"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.\"\n );\n\n const mutationId = this.generateMutationId();\n\n mutation = this.cache.transformForLink(this.transform(mutation));\n const { hasClientExports } = this.getDocumentInfo(mutation);\n\n variables = this.getVariables(mutation, variables) as TVariables;\n if (hasClientExports) {\n variables = (await this.localState.addExportedVariables(\n mutation,\n variables,\n context\n )) as TVariables;\n }\n\n const mutationStoreValue =\n this.mutationStore &&\n (this.mutationStore[mutationId] = {\n mutation,\n variables,\n loading: true,\n error: null,\n } as MutationStoreValue);\n\n const isOptimistic =\n optimisticResponse &&\n this.markMutationOptimistic(\n optimisticResponse,\n {\n mutationId,\n document: mutation,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n updateQueries,\n update: updateWithProxyFn,\n keepRootFields,\n }\n );\n\n this.broadcastQueries();\n\n const self = this;\n\n return new Promise((resolve, reject) => {\n return asyncMap(\n self.getObservableFromLink(\n mutation,\n {\n ...context,\n optimisticResponse: isOptimistic ? optimisticResponse : void 0,\n },\n variables,\n {},\n false\n ),\n\n (result: FetchResult) => {\n if (graphQLResultHasError(result) && errorPolicy === \"none\") {\n throw new ApolloError({\n graphQLErrors: getGraphQLErrorsFromResult(result),\n });\n }\n\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = null;\n }\n\n const storeResult: typeof result = { ...result };\n\n if (typeof refetchQueries === \"function\") {\n refetchQueries = refetchQueries(\n storeResult as FetchResult>\n );\n }\n\n if (errorPolicy === \"ignore\" && graphQLResultHasError(storeResult)) {\n delete storeResult.errors;\n }\n\n return self.markMutationResult({\n mutationId,\n result: storeResult,\n document: mutation,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n update: updateWithProxyFn,\n updateQueries,\n awaitRefetchQueries,\n refetchQueries,\n removeOptimistic: isOptimistic ? mutationId : void 0,\n onQueryUpdated,\n keepRootFields,\n });\n }\n ).subscribe({\n next(storeResult) {\n self.broadcastQueries();\n\n // Since mutations might receive multiple payloads from the\n // ApolloLink chain (e.g. when used with @defer),\n // we resolve with a SingleExecutionResult or after the final\n // ExecutionPatchResult has arrived and we have assembled the\n // multipart response into a single result.\n if (!(\"hasNext\" in storeResult) || storeResult.hasNext === false) {\n resolve({\n ...storeResult,\n data: self.maskOperation({\n document: mutation,\n data: storeResult.data,\n fetchPolicy,\n id: mutationId,\n }) as any,\n });\n }\n },\n\n error(err: Error) {\n if (mutationStoreValue) {\n mutationStoreValue.loading = false;\n mutationStoreValue.error = err;\n }\n\n if (isOptimistic) {\n self.cache.removeOptimistic(mutationId);\n }\n\n self.broadcastQueries();\n\n reject(\n err instanceof ApolloError ? err : (\n new ApolloError({\n networkError: err,\n })\n )\n );\n },\n });\n });\n }\n\n public markMutationResult<\n TData,\n TVariables,\n TContext,\n TCache extends ApolloCache,\n >(\n mutation: {\n mutationId: string;\n result: FetchResult;\n document: DocumentNode;\n variables?: TVariables;\n fetchPolicy?: MutationFetchPolicy;\n errorPolicy: ErrorPolicy;\n context?: TContext;\n updateQueries: UpdateQueries;\n update?: MutationUpdaterFunction;\n awaitRefetchQueries?: boolean;\n refetchQueries?: InternalRefetchQueriesInclude;\n removeOptimistic?: string;\n onQueryUpdated?: OnQueryUpdated;\n keepRootFields?: boolean;\n },\n cache = this.cache\n ): Promise> {\n let { result } = mutation;\n const cacheWrites: Cache.WriteOptions[] = [];\n const skipCache = mutation.fetchPolicy === \"no-cache\";\n\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 (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n const diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n let mergedData;\n if (diff.result) {\n mergedData = mergeIncrementalData(diff.result, result);\n }\n if (typeof mergedData !== \"undefined\") {\n // cast the ExecutionPatchResult to FetchResult here since\n // ExecutionPatchResult never has `data` when returned from the server\n (result as FetchResult).data = mergedData;\n cacheWrites.push({\n result: mergedData,\n dataId: \"ROOT_MUTATION\",\n query: mutation.document,\n variables: mutation.variables,\n });\n }\n }\n\n const { updateQueries } = mutation;\n if (updateQueries) {\n this.queries.forEach(({ observableQuery }, queryId) => {\n const queryName = observableQuery && observableQuery.queryName;\n if (!queryName || !hasOwnProperty.call(updateQueries, queryName)) {\n return;\n }\n const updater = updateQueries[queryName];\n const { document, variables } = this.queries.get(queryId)!;\n\n // Read the current query result from the store.\n const { result: currentQueryResult, complete } = cache.diff({\n query: document!,\n variables,\n returnPartialData: true,\n optimistic: false,\n });\n\n if (complete && currentQueryResult) {\n // Run our reducer using the current query result and the mutation result.\n const nextQueryResult = updater(currentQueryResult, {\n mutationResult: result as FetchResult>,\n queryName: (document && getOperationName(document)) || void 0,\n queryVariables: variables!,\n });\n\n // Write the modified result back into the store if we got a new result.\n if (nextQueryResult) {\n cacheWrites.push({\n result: nextQueryResult,\n dataId: \"ROOT_QUERY\",\n query: document!,\n variables,\n });\n }\n }\n });\n }\n }\n\n if (\n cacheWrites.length > 0 ||\n (mutation.refetchQueries || \"\").length > 0 ||\n mutation.update ||\n mutation.onQueryUpdated ||\n mutation.removeOptimistic\n ) {\n const results: any[] = [];\n\n this.refetchQueries({\n updateCache: (cache) => {\n if (!skipCache) {\n cacheWrites.forEach((write) => cache.write(write));\n }\n\n // If the mutation has some writes associated with it then we need to\n // apply those writes to the store by running this reducer again with\n // a write action.\n const { update } = mutation;\n // Determine whether result is a SingleExecutionResult,\n // or the final ExecutionPatchResult.\n const isFinalResult =\n !isExecutionPatchResult(result) ||\n (isExecutionPatchIncrementalResult(result) && !result.hasNext);\n\n if (update) {\n if (!skipCache) {\n // Re-read the ROOT_MUTATION data we just wrote into the cache\n // (the first cache.write call in the cacheWrites.forEach loop\n // above), so field read functions have a chance to run for\n // fields within mutation result objects.\n const diff = cache.diff({\n id: \"ROOT_MUTATION\",\n // The cache complains if passed a mutation where it expects a\n // query, so we transform mutations and subscriptions to queries\n // (only once, thanks to this.transformCache).\n query: this.getDocumentInfo(mutation.document).asQuery,\n variables: mutation.variables,\n optimistic: false,\n returnPartialData: true,\n });\n\n if (diff.complete) {\n result = { ...(result as FetchResult), 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\n // If we've received the whole response,\n // either a SingleExecutionResult or the final ExecutionPatchResult,\n // call the update function.\n if (isFinalResult) {\n update(cache as TCache, result as FetchResult>, {\n context: mutation.context,\n variables: mutation.variables,\n });\n }\n }\n\n // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it\n // shallow to allow rolling back optimistic evictions.\n if (!skipCache && !mutation.keepRootFields && isFinalResult) {\n cache.modify({\n id: \"ROOT_MUTATION\",\n fields(value, { fieldName, DELETE }) {\n return fieldName === \"__typename\" ? value : DELETE;\n },\n });\n }\n },\n\n include: mutation.refetchQueries,\n\n // Write the final mutation.result to the root layer of the cache.\n optimistic: false,\n\n // Remove the corresponding optimistic layer at the same time as we\n // write the final non-optimistic result.\n removeOptimistic: mutation.removeOptimistic,\n\n // Let the caller of client.mutate optionally determine the refetching\n // behavior for watched queries after the mutation.update function runs.\n // If no onQueryUpdated function was provided for this mutation, pass\n // null instead of undefined to disable the default refetching behavior.\n onQueryUpdated: mutation.onQueryUpdated || null,\n }).forEach((result) => results.push(result));\n\n if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {\n // Returning a promise here makes the mutation await that promise, so we\n // include results in that promise's work if awaitRefetchQueries or an\n // onQueryUpdated function was specified.\n return Promise.all(results).then(() => result);\n }\n }\n\n return Promise.resolve(result);\n }\n\n public markMutationOptimistic<\n TData,\n TVariables,\n TContext,\n TCache extends ApolloCache,\n >(\n optimisticResponse: any,\n mutation: {\n mutationId: string;\n document: DocumentNode;\n variables?: TVariables;\n fetchPolicy?: MutationFetchPolicy;\n errorPolicy: ErrorPolicy;\n context?: TContext;\n updateQueries: UpdateQueries;\n update?: MutationUpdaterFunction;\n keepRootFields?: boolean;\n }\n ) {\n const data =\n typeof optimisticResponse === \"function\" ?\n optimisticResponse(mutation.variables, { IGNORE })\n : optimisticResponse;\n\n if (data === IGNORE) {\n return false;\n }\n\n this.cache.recordOptimisticTransaction((cache) => {\n try {\n this.markMutationResult(\n {\n ...mutation,\n result: { data },\n },\n cache\n );\n } catch (error) {\n invariant.error(error);\n }\n }, mutation.mutationId);\n\n return true;\n }\n\n public fetchQuery(\n queryId: string,\n options: WatchQueryOptions,\n networkStatus?: NetworkStatus\n ): Promise> {\n return this.fetchConcastWithInfo(queryId, options, networkStatus).concast\n .promise as TODO;\n }\n\n public getQueryStore() {\n const store: Record = Object.create(null);\n this.queries.forEach((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\n public resetErrors(queryId: string) {\n const queryInfo = this.queries.get(queryId);\n if (queryInfo) {\n queryInfo.networkError = undefined;\n queryInfo.graphQLErrors = [];\n }\n }\n\n public transform(document: DocumentNode) {\n return this.documentTransform.transformDocument(document);\n }\n\n private transformCache = new AutoCleanedWeakCache<\n DocumentNode,\n TransformCacheEntry\n >(\n cacheSizes[\"queryManager.getDocumentInfo\"] ||\n defaultCacheSizes[\"queryManager.getDocumentInfo\"]\n );\n\n public getDocumentInfo(document: DocumentNode) {\n const { transformCache } = this;\n\n if (!transformCache.has(document)) {\n const cacheEntry: TransformCacheEntry = {\n // TODO These three calls (hasClientExports, shouldForceResolvers, and\n // usesNonreactiveDirective) are performing independent full traversals\n // of the transformed document. We should consider merging these\n // traversals into a single pass in the future, though the work is\n // cached after the first time.\n hasClientExports: hasClientExports(document),\n hasForcedResolvers: this.localState.shouldForceResolvers(document),\n hasNonreactiveDirective: hasDirectives([\"nonreactive\"], document),\n nonReactiveQuery: addNonReactiveToNamedFragments(document),\n clientQuery: this.localState.clientQuery(document),\n serverQuery: removeDirectivesFromDocument(\n [\n { name: \"client\", remove: true },\n { name: \"connection\" },\n { name: \"nonreactive\" },\n { name: \"unmask\" },\n ],\n document\n ),\n defaultVars: getDefaultValues(\n getOperationDefinition(document)\n ) as OperationVariables,\n // Transform any mutation or subscription operations to query operations\n // so we can read/write them from/to the cache.\n asQuery: {\n ...document,\n definitions: document.definitions.map((def) => {\n if (\n def.kind === \"OperationDefinition\" &&\n def.operation !== \"query\"\n ) {\n return { ...def, operation: \"query\" as OperationTypeNode };\n }\n return def;\n }),\n },\n };\n\n transformCache.set(document, cacheEntry);\n }\n\n return transformCache.get(document)!;\n }\n\n private getVariables(\n document: DocumentNode,\n variables?: TVariables\n ): OperationVariables {\n return {\n ...this.getDocumentInfo(document).defaultVars,\n ...variables,\n };\n }\n\n public watchQuery<\n T,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions): ObservableQuery {\n const query = this.transform(options.query);\n\n // assign variable default values if supplied\n // NOTE: We don't modify options.query here with the transformed query to\n // ensure observable.options.query is set to the raw untransformed query.\n options = {\n ...options,\n variables: this.getVariables(query, options.variables) as TVariables,\n };\n\n if (typeof options.notifyOnNetworkStatusChange === \"undefined\") {\n options.notifyOnNetworkStatusChange = false;\n }\n\n const queryInfo = new QueryInfo(this);\n const observable = new ObservableQuery({\n queryManager: this,\n queryInfo,\n options,\n });\n observable[\"lastQuery\"] = query;\n\n this.queries.set(observable.queryId, queryInfo);\n\n // We give queryInfo the transformed query to ensure the first cache diff\n // uses the transformed query instead of the raw query\n queryInfo.init({\n document: query,\n observableQuery: observable,\n variables: observable.variables,\n });\n\n return observable;\n }\n\n public query(\n options: QueryOptions,\n queryId = this.generateQueryId()\n ): Promise>> {\n invariant(\n options.query,\n \"query option is required. You must specify your GraphQL document \" +\n \"in the query option.\"\n );\n\n invariant(\n options.query.kind === \"Document\",\n 'You must wrap the query string in a \"gql\" tag.'\n );\n\n invariant(\n !(options as any).returnPartialData,\n \"returnPartialData option only supported on watchQuery.\"\n );\n\n invariant(\n !(options as any).pollInterval,\n \"pollInterval option only supported on watchQuery.\"\n );\n\n const query = this.transform(options.query);\n\n return this.fetchQuery(queryId, { ...options, query })\n .then(\n (result) =>\n result && {\n ...result,\n data: this.maskOperation({\n document: query,\n data: result.data,\n fetchPolicy: options.fetchPolicy,\n id: queryId,\n }),\n }\n )\n .finally(() => this.stopQuery(queryId));\n }\n\n private queryIdCounter = 1;\n public generateQueryId() {\n return String(this.queryIdCounter++);\n }\n\n private requestIdCounter = 1;\n public generateRequestId() {\n return this.requestIdCounter++;\n }\n\n private mutationIdCounter = 1;\n public generateMutationId() {\n return String(this.mutationIdCounter++);\n }\n\n public stopQueryInStore(queryId: string) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.broadcastQueries();\n }\n\n private stopQueryInStoreNoBroadcast(queryId: string) {\n const queryInfo = this.queries.get(queryId);\n if (queryInfo) queryInfo.stop();\n }\n\n public clearStore(\n options: Cache.ResetOptions = {\n discardWatches: true,\n }\n ): Promise {\n // Before we have sent the reset action to the store, we can no longer\n // rely on the results returned by in-flight requests since these may\n // depend on values that previously existed in the data portion of the\n // store. So, we cancel the promises and observers that we have issued\n // so far and not yet resolved (in the case of queries).\n this.cancelPendingFetches(\n newInvariantError(\n \"Store reset while query was in flight (not completed in link chain)\"\n )\n );\n\n this.queries.forEach((queryInfo) => {\n if (queryInfo.observableQuery) {\n // Set loading to true so listeners don't trigger unless they want\n // results with partial data.\n queryInfo.networkStatus = NetworkStatus.loading;\n } else {\n queryInfo.stop();\n }\n });\n\n if (this.mutationStore) {\n this.mutationStore = Object.create(null);\n }\n\n // begin removing data from the store\n return this.cache.reset(options);\n }\n\n public getObservableQueries(\n include: InternalRefetchQueriesInclude = \"active\"\n ) {\n const queries = new Map>();\n const queryNames = new Map();\n const queryNamesAndQueryStrings = new Map();\n const legacyQueryOptions = new Set();\n\n if (Array.isArray(include)) {\n include.forEach((desc) => {\n if (typeof desc === \"string\") {\n queryNames.set(desc, desc);\n queryNamesAndQueryStrings.set(desc, false);\n } else if (isDocumentNode(desc)) {\n const queryString = print(this.transform(desc));\n queryNames.set(queryString, getOperationName(desc));\n queryNamesAndQueryStrings.set(queryString, false);\n } else if (isNonNullObject(desc) && desc.query) {\n legacyQueryOptions.add(desc);\n }\n });\n }\n\n this.queries.forEach(({ observableQuery: oq, document }, queryId) => {\n if (oq) {\n if (include === \"all\") {\n queries.set(queryId, oq);\n return;\n }\n\n const {\n queryName,\n options: { fetchPolicy },\n } = oq;\n\n if (\n fetchPolicy === \"standby\" ||\n (include === \"active\" && !oq.hasObservers())\n ) {\n return;\n }\n\n if (\n include === \"active\" ||\n (queryName && queryNamesAndQueryStrings.has(queryName)) ||\n (document && queryNamesAndQueryStrings.has(print(document)))\n ) {\n queries.set(queryId, oq);\n if (queryName) queryNamesAndQueryStrings.set(queryName, true);\n if (document) queryNamesAndQueryStrings.set(print(document), true);\n }\n }\n });\n\n if (legacyQueryOptions.size) {\n legacyQueryOptions.forEach((options: QueryOptions) => {\n // We will be issuing a fresh network request for this query, so we\n // pre-allocate a new query ID here, using a special prefix to enable\n // cleaning up these temporary queries later, after fetching.\n const queryId = makeUniqueId(\"legacyOneTimeQuery\");\n const queryInfo = this.getQuery(queryId).init({\n document: options.query,\n variables: options.variables,\n });\n const oq = new ObservableQuery({\n queryManager: this,\n queryInfo,\n options: {\n ...options,\n fetchPolicy: \"network-only\",\n },\n });\n invariant(oq.queryId === queryId);\n queryInfo.setObservableQuery(oq);\n queries.set(queryId, oq);\n });\n }\n\n if (__DEV__ && queryNamesAndQueryStrings.size) {\n queryNamesAndQueryStrings.forEach((included, nameOrQueryString) => {\n if (!included) {\n const queryName = queryNames.get(nameOrQueryString);\n\n if (queryName) {\n invariant.warn(\n `Unknown query named \"%s\" requested in refetchQueries options.include array`,\n queryName\n );\n } else {\n invariant.warn(\n `Unknown anonymous query requested in refetchQueries options.include array`\n );\n }\n }\n });\n }\n\n return queries;\n }\n\n public reFetchObservableQueries(\n includeStandby: boolean = false\n ): Promise[]> {\n const observableQueryPromises: Promise>[] = [];\n\n this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(\n (observableQuery, queryId) => {\n const { fetchPolicy } = observableQuery.options;\n observableQuery.resetLastResults();\n if (\n includeStandby ||\n (fetchPolicy !== \"standby\" && fetchPolicy !== \"cache-only\")\n ) {\n observableQueryPromises.push(observableQuery.refetch());\n }\n this.getQuery(queryId).setDiff(null);\n }\n );\n\n this.broadcastQueries();\n\n return Promise.all(observableQueryPromises);\n }\n\n public setObservableQuery(observableQuery: ObservableQuery) {\n this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);\n }\n\n public startGraphQLSubscription(\n options: SubscriptionOptions\n ): Observable> {\n let { query, variables } = options;\n const {\n fetchPolicy,\n errorPolicy = \"none\",\n context = {},\n extensions = {},\n } = options;\n\n query = this.transform(query);\n variables = this.getVariables(query, variables);\n\n const makeObservable = (variables: OperationVariables) =>\n this.getObservableFromLink(query, context, variables, extensions).map(\n (result) => {\n if (fetchPolicy !== \"no-cache\") {\n // the subscription interface should handle not sending us results we no longer subscribe to.\n // XXX I don't think we ever send in an object with errors, but we might in the future...\n if (shouldWriteResult(result, errorPolicy)) {\n this.cache.write({\n query,\n result: result.data,\n dataId: \"ROOT_SUBSCRIPTION\",\n variables: variables,\n });\n }\n\n this.broadcastQueries();\n }\n\n const hasErrors = graphQLResultHasError(result);\n const hasProtocolErrors = graphQLResultHasProtocolErrors(result);\n if (hasErrors || hasProtocolErrors) {\n const errors: ApolloErrorOptions = {};\n if (hasErrors) {\n errors.graphQLErrors = result.errors;\n }\n if (hasProtocolErrors) {\n errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];\n }\n\n // `errorPolicy` is a mechanism for handling GraphQL errors, according\n // to our documentation, so we throw protocol errors regardless of the\n // set error policy.\n if (errorPolicy === \"none\" || hasProtocolErrors) {\n throw new ApolloError(errors);\n }\n }\n\n if (errorPolicy === \"ignore\") {\n delete result.errors;\n }\n\n return result;\n }\n );\n\n if (this.getDocumentInfo(query).hasClientExports) {\n const observablePromise = this.localState\n .addExportedVariables(query, variables, context)\n .then(makeObservable);\n\n return new Observable>((observer) => {\n let sub: ObservableSubscription | null = null;\n observablePromise.then(\n (observable) => (sub = observable.subscribe(observer)),\n observer.error\n );\n return () => sub && sub.unsubscribe();\n });\n }\n\n return makeObservable(variables);\n }\n\n public stopQuery(queryId: string) {\n this.stopQueryNoBroadcast(queryId);\n this.broadcastQueries();\n }\n\n private stopQueryNoBroadcast(queryId: string) {\n this.stopQueryInStoreNoBroadcast(queryId);\n this.removeQuery(queryId);\n }\n\n public removeQuery(queryId: string) {\n // teardown all links\n // Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises\n // that each add their reject functions to fetchCancelFns.\n // A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.\n // The same queryId could have two rejection fns for two promises\n this.fetchCancelFns.delete(queryId);\n if (this.queries.has(queryId)) {\n this.getQuery(queryId).stop();\n this.queries.delete(queryId);\n }\n }\n\n public broadcastQueries() {\n if (this.onBroadcast) this.onBroadcast();\n this.queries.forEach((info) => info.notify());\n }\n\n public getLocalState(): LocalState {\n return this.localState;\n }\n\n // Use protected instead of private field so\n // @apollo/experimental-nextjs-app-support can access type info.\n protected inFlightLinkObservables = new Trie<{\n observable?: Observable>;\n }>(false);\n\n private getObservableFromLink(\n query: DocumentNode,\n context: any,\n variables?: OperationVariables,\n extensions?: Record,\n // Prefer context.queryDeduplication if specified.\n deduplication: boolean = context?.queryDeduplication ??\n this.queryDeduplication\n ): Observable> {\n let observable: Observable> | undefined;\n\n const { serverQuery, clientQuery } = this.getDocumentInfo(query);\n if (serverQuery) {\n const { inFlightLinkObservables, link } = this;\n\n const operation = {\n query: serverQuery,\n variables,\n operationName: getOperationName(serverQuery) || void 0,\n context: this.prepareContext({\n ...context,\n forceFetch: !deduplication,\n }),\n extensions,\n };\n\n context = operation.context;\n\n if (deduplication) {\n const printedServerQuery = print(serverQuery);\n const varJson = canonicalStringify(variables);\n\n const entry = inFlightLinkObservables.lookup(\n printedServerQuery,\n varJson\n );\n\n observable = entry.observable;\n if (!observable) {\n const concast = new Concast([\n execute(link, operation) as Observable>,\n ]);\n observable = entry.observable = concast;\n\n concast.beforeNext(function cb(method, arg: FetchResult) {\n if (method === \"next\" && \"hasNext\" in arg && arg.hasNext) {\n concast.beforeNext(cb);\n } else {\n inFlightLinkObservables.remove(printedServerQuery, varJson);\n }\n });\n }\n } else {\n observable = new Concast([\n execute(link, operation) as Observable>,\n ]);\n }\n } else {\n observable = new Concast([Observable.of({ data: {} } as FetchResult)]);\n context = this.prepareContext(context);\n }\n\n if (clientQuery) {\n observable = asyncMap(observable, (result) => {\n return this.localState.runResolvers({\n document: clientQuery,\n remoteResult: result,\n context,\n variables,\n });\n });\n }\n\n return observable;\n }\n\n private getResultsFromLink(\n queryInfo: QueryInfo,\n cacheWriteBehavior: CacheWriteBehavior,\n options: Pick<\n WatchQueryOptions,\n \"query\" | \"variables\" | \"context\" | \"fetchPolicy\" | \"errorPolicy\"\n >\n ): Observable> {\n const requestId = (queryInfo.lastRequestId = this.generateRequestId());\n\n // Performing transformForLink here gives this.cache a chance to fill in\n // missing fragment definitions (for example) before sending this document\n // through the link chain.\n const linkDocument = this.cache.transformForLink(options.query);\n\n return asyncMap(\n this.getObservableFromLink(\n linkDocument,\n options.context,\n options.variables\n ),\n\n (result) => {\n const graphQLErrors = getGraphQLErrorsFromResult(result);\n const hasErrors = graphQLErrors.length > 0;\n const { errorPolicy } = options;\n\n // If we interrupted this request by calling getResultsFromLink again\n // with the same QueryInfo object, we ignore the old results.\n if (requestId >= queryInfo.lastRequestId) {\n if (hasErrors && errorPolicy === \"none\") {\n // Throwing here effectively calls observer.error.\n throw queryInfo.markError(\n new ApolloError({\n graphQLErrors,\n })\n );\n }\n // Use linkDocument rather than queryInfo.document so the\n // operation/fragments used to write the result are the same as the\n // ones used to obtain it from the link.\n queryInfo.markResult(\n result,\n linkDocument,\n options,\n cacheWriteBehavior\n );\n queryInfo.markReady();\n }\n\n const aqr: ApolloQueryResult = {\n data: result.data,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n\n // In the case we start multiple network requests simulatenously, we\n // want to ensure we properly set `data` if we're reporting on an old\n // result which will not be caught by the conditional above that ends up\n // throwing the markError result.\n if (hasErrors && errorPolicy === \"none\") {\n aqr.data = void 0 as TData;\n }\n\n if (hasErrors && errorPolicy !== \"ignore\") {\n aqr.errors = graphQLErrors;\n aqr.networkStatus = NetworkStatus.error;\n }\n\n return aqr;\n },\n\n (networkError) => {\n const error =\n isApolloError(networkError) ? networkError : (\n new ApolloError({ networkError })\n );\n\n // Avoid storing errors from older interrupted queries.\n if (requestId >= queryInfo.lastRequestId) {\n queryInfo.markError(error);\n }\n\n throw error;\n }\n );\n }\n\n private fetchConcastWithInfo(\n queryId: string,\n options: WatchQueryOptions,\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus = NetworkStatus.loading,\n query = options.query\n ): ConcastAndInfo {\n const variables = this.getVariables(query, options.variables) as TVars;\n const queryInfo = this.getQuery(queryId);\n\n const defaults = this.defaultOptions.watchQuery;\n let {\n fetchPolicy = (defaults && defaults.fetchPolicy) || \"cache-first\",\n errorPolicy = (defaults && defaults.errorPolicy) || \"none\",\n returnPartialData = false,\n notifyOnNetworkStatusChange = false,\n context = {},\n } = options;\n\n const normalized = Object.assign({}, options, {\n query,\n variables,\n fetchPolicy,\n errorPolicy,\n returnPartialData,\n notifyOnNetworkStatusChange,\n context,\n });\n\n const fromVariables = (variables: TVars) => {\n // Since normalized is always a fresh copy of options, it's safe to\n // modify its properties here, rather than creating yet another new\n // WatchQueryOptions object.\n normalized.variables = variables;\n\n const sourcesWithInfo = this.fetchQueryByPolicy(\n queryInfo,\n normalized,\n networkStatus\n );\n\n if (\n // If we're in standby, postpone advancing options.fetchPolicy using\n // applyNextFetchPolicy.\n normalized.fetchPolicy !== \"standby\" &&\n // The \"standby\" policy currently returns [] from fetchQueryByPolicy, so\n // this is another way to detect when nothing was done/fetched.\n sourcesWithInfo.sources.length > 0 &&\n queryInfo.observableQuery\n ) {\n queryInfo.observableQuery[\"applyNextFetchPolicy\"](\n \"after-fetch\",\n options\n );\n }\n\n return sourcesWithInfo;\n };\n\n // This cancel function needs to be set before the concast is created,\n // in case concast creation synchronously cancels the request.\n const cleanupCancelFn = () => this.fetchCancelFns.delete(queryId);\n this.fetchCancelFns.set(queryId, (reason) => {\n cleanupCancelFn();\n // This delay ensures the concast variable has been initialized.\n setTimeout(() => concast.cancel(reason));\n });\n\n let concast: Concast>,\n containsDataFromLink: boolean;\n // If the query has @export(as: ...) directives, then we need to\n // process those directives asynchronously. When there are no\n // @export directives (the common case), we deliberately avoid\n // wrapping the result of this.fetchQueryByPolicy in a Promise,\n // since the timing of result delivery is (unfortunately) important\n // for backwards compatibility. TODO This code could be simpler if\n // we deprecated and removed LocalState.\n if (this.getDocumentInfo(normalized.query).hasClientExports) {\n concast = new Concast(\n this.localState\n .addExportedVariables(\n normalized.query,\n normalized.variables,\n normalized.context\n )\n .then(fromVariables)\n .then((sourcesWithInfo) => sourcesWithInfo.sources)\n );\n // there is just no way we can synchronously get the *right* value here,\n // so we will assume `true`, which is the behaviour before the bug fix in\n // #10597. This means that bug is not fixed in that case, and is probably\n // un-fixable with reasonable effort for the edge case of @export as\n // directives.\n containsDataFromLink = true;\n } else {\n const sourcesWithInfo = fromVariables(normalized.variables);\n containsDataFromLink = sourcesWithInfo.fromLink;\n concast = new Concast(sourcesWithInfo.sources);\n }\n\n concast.promise.then(cleanupCancelFn, cleanupCancelFn);\n\n return {\n concast,\n fromLink: containsDataFromLink,\n };\n }\n\n public refetchQueries({\n updateCache,\n include,\n optimistic = false,\n removeOptimistic = optimistic ? makeUniqueId(\"refetchQueries\") : void 0,\n onQueryUpdated,\n }: InternalRefetchQueriesOptions<\n ApolloCache,\n TResult\n >): InternalRefetchQueriesMap {\n const includedQueriesById = new Map<\n string,\n {\n oq: ObservableQuery;\n lastDiff?: Cache.DiffResult;\n diff?: Cache.DiffResult;\n }\n >();\n\n if (include) {\n this.getObservableQueries(include).forEach((oq, queryId) => {\n includedQueriesById.set(queryId, {\n oq,\n lastDiff: this.getQuery(queryId).getDiff(),\n });\n });\n }\n\n const results: InternalRefetchQueriesMap = new Map();\n\n if (updateCache) {\n this.cache.batch({\n update: updateCache,\n\n // Since you can perform any combination of cache reads and/or writes in\n // the cache.batch update function, its optimistic option can be either\n // a boolean or a string, representing three distinct modes of\n // operation:\n //\n // * false: read/write only the root layer\n // * true: read/write the topmost layer\n // * string: read/write a fresh optimistic layer with that ID string\n //\n // When typeof optimistic === \"string\", a new optimistic layer will be\n // temporarily created within cache.batch with that string as its ID. If\n // we then pass that same string as the removeOptimistic option, we can\n // make cache.batch immediately remove the optimistic layer after\n // running the updateCache function, triggering only one broadcast.\n //\n // However, the refetchQueries method accepts only true or false for its\n // optimistic option (not string). We interpret true to mean a temporary\n // optimistic layer should be created, to allow efficiently rolling back\n // the effect of the updateCache function, which involves passing a\n // string instead of true as the optimistic option to cache.batch, when\n // refetchQueries receives optimistic: true.\n //\n // In other words, we are deliberately not supporting the use case of\n // writing to an *existing* optimistic layer (using the refetchQueries\n // updateCache function), since that would potentially interfere with\n // other optimistic updates in progress. Instead, you can read/write\n // only the root layer by passing optimistic: false to refetchQueries,\n // or you can read/write a brand new optimistic layer that will be\n // automatically removed by passing optimistic: true.\n optimistic: (optimistic && removeOptimistic) || false,\n\n // The removeOptimistic option can also be provided by itself, even if\n // optimistic === false, to remove some previously-added optimistic\n // layer safely and efficiently, like we do in markMutationResult.\n //\n // If an explicit removeOptimistic string is provided with optimistic:\n // true, the removeOptimistic string will determine the ID of the\n // temporary optimistic layer, in case that ever matters.\n removeOptimistic,\n\n onWatchUpdated(watch, diff, lastDiff) {\n const oq =\n watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;\n\n if (oq) {\n if (onQueryUpdated) {\n // Since we're about to handle this query now, remove it from\n // includedQueriesById, in case it was added earlier because of\n // options.include.\n includedQueriesById.delete(oq.queryId);\n\n let result: TResult | boolean | Promise> =\n onQueryUpdated(oq, diff, lastDiff);\n\n if (result === true) {\n // The onQueryUpdated function requested the default refetching\n // behavior by returning true.\n result = oq.refetch();\n }\n\n // Record the result in the results Map, as long as onQueryUpdated\n // did not return false to skip/ignore this result.\n if (result !== false) {\n results.set(\n oq,\n result as InternalRefetchQueriesResult\n );\n }\n\n // Allow the default cache broadcast to happen, except when\n // onQueryUpdated returns false.\n return result;\n }\n\n if (onQueryUpdated !== null) {\n // If we don't have an onQueryUpdated function, and onQueryUpdated\n // was not disabled by passing null, make sure this query is\n // \"included\" like any other options.include-specified query.\n includedQueriesById.set(oq.queryId, { oq, lastDiff, diff });\n }\n }\n },\n });\n }\n\n if (includedQueriesById.size) {\n includedQueriesById.forEach(({ oq, lastDiff, diff }, queryId) => {\n let result:\n | TResult\n | boolean\n | Promise>\n | undefined;\n\n // If onQueryUpdated is provided, we want to use it for all included\n // queries, even the QueryOptions ones.\n if (onQueryUpdated) {\n if (!diff) {\n const info = oq[\"queryInfo\"];\n info.reset(); // Force info.getDiff() to read from cache.\n diff = info.getDiff();\n }\n result = onQueryUpdated(oq, diff, lastDiff);\n }\n\n // Otherwise, we fall back to refetching.\n if (!onQueryUpdated || result === true) {\n result = oq.refetch();\n }\n\n if (result !== false) {\n results.set(oq, result as InternalRefetchQueriesResult);\n }\n\n if (queryId.indexOf(\"legacyOneTimeQuery\") >= 0) {\n this.stopQueryNoBroadcast(queryId);\n }\n });\n }\n\n if (removeOptimistic) {\n // In case no updateCache callback was provided (so cache.batch was not\n // called above, and thus did not already remove the optimistic layer),\n // remove it here. Since this is a no-op when the layer has already been\n // removed, we do it even if we called cache.batch above, since it's\n // possible this.cache is an instance of some ApolloCache subclass other\n // than InMemoryCache, and does not fully support the removeOptimistic\n // option for cache.batch.\n this.cache.removeOptimistic(removeOptimistic);\n }\n\n return results;\n }\n\n private noCacheWarningsByQueryId = new Set();\n\n public maskOperation(\n options: MaskOperationOptions\n ): MaybeMasked {\n const { document, data } = options;\n\n if (__DEV__) {\n const { fetchPolicy, id } = options;\n const operationType = getOperationDefinition(document)?.operation;\n const operationId = (operationType?.[0] ?? \"o\") + id;\n\n if (\n this.dataMasking &&\n fetchPolicy === \"no-cache\" &&\n !isFullyUnmaskedOperation(document) &&\n !this.noCacheWarningsByQueryId.has(operationId)\n ) {\n this.noCacheWarningsByQueryId.add(operationId);\n\n invariant.warn(\n '[%s]: Fragments masked by data masking are inaccessible when using fetch policy \"no-cache\". Please add `@unmask` to each fragment spread to access the data.',\n getOperationName(document) ??\n `Unnamed ${operationType ?? \"operation\"}`\n );\n }\n }\n\n return (\n this.dataMasking ?\n maskOperation(data, document, this.cache)\n : data) as MaybeMasked;\n }\n\n public maskFragment(options: MaskFragmentOptions) {\n const { data, fragment, fragmentName } = options;\n\n return this.dataMasking ?\n maskFragment(data, fragment, this.cache, fragmentName)\n : data;\n }\n\n private fetchQueryByPolicy(\n queryInfo: QueryInfo,\n {\n query,\n variables,\n fetchPolicy,\n refetchWritePolicy,\n errorPolicy,\n returnPartialData,\n context,\n notifyOnNetworkStatusChange,\n }: WatchQueryOptions,\n // The initial networkStatus for this fetch, most often\n // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n // or setVariables.\n networkStatus: NetworkStatus\n ): SourcesAndInfo {\n const oldNetworkStatus = queryInfo.networkStatus;\n\n queryInfo.init({\n document: query,\n variables,\n networkStatus,\n });\n\n const readCache = () => queryInfo.getDiff();\n\n const resultsFromCache = (\n diff: Cache.DiffResult,\n networkStatus = queryInfo.networkStatus || NetworkStatus.loading\n ) => {\n const data = diff.result;\n\n if (__DEV__ && !returnPartialData && !equal(data, {})) {\n logMissingFieldErrors(diff.missing);\n }\n\n const fromData = (data: TData | undefined) =>\n Observable.of({\n data,\n loading: isNetworkRequestInFlight(networkStatus),\n networkStatus,\n ...(diff.complete ? null : { partial: true }),\n } as ApolloQueryResult);\n\n if (data && this.getDocumentInfo(query).hasForcedResolvers) {\n return this.localState\n .runResolvers({\n document: query,\n remoteResult: { data },\n context,\n variables,\n onlyRunForcedResolvers: true,\n })\n .then((resolved) => fromData(resolved.data || void 0));\n }\n\n // Resolves https://github.com/apollographql/apollo-client/issues/10317.\n // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,\n // data was incorrectly returned from the cache on refetch:\n // if diff.missing exists, we should not return cache data.\n if (\n errorPolicy === \"none\" &&\n networkStatus === NetworkStatus.refetch &&\n Array.isArray(diff.missing)\n ) {\n return fromData(void 0);\n }\n\n return fromData(data);\n };\n\n const cacheWriteBehavior =\n fetchPolicy === \"no-cache\" ? CacheWriteBehavior.FORBID\n // Watched queries must opt into overwriting existing data on refetch,\n // by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n : (\n networkStatus === NetworkStatus.refetch &&\n refetchWritePolicy !== \"merge\"\n ) ?\n CacheWriteBehavior.OVERWRITE\n : CacheWriteBehavior.MERGE;\n\n const resultsFromLink = () =>\n this.getResultsFromLink(queryInfo, cacheWriteBehavior, {\n query,\n variables,\n context,\n fetchPolicy,\n errorPolicy,\n });\n\n const shouldNotify =\n notifyOnNetworkStatusChange &&\n typeof oldNetworkStatus === \"number\" &&\n oldNetworkStatus !== networkStatus &&\n isNetworkRequestInFlight(networkStatus);\n\n switch (fetchPolicy) {\n default:\n case \"cache-first\": {\n const diff = readCache();\n\n if (diff.complete) {\n return {\n fromLink: false,\n sources: [resultsFromCache(diff, queryInfo.markReady())],\n };\n }\n\n if (returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n\n case \"cache-and-network\": {\n const diff = readCache();\n\n if (diff.complete || returnPartialData || shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(diff), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n }\n\n case \"cache-only\":\n return {\n fromLink: false,\n sources: [resultsFromCache(readCache(), queryInfo.markReady())],\n };\n\n case \"network-only\":\n if (shouldNotify) {\n return {\n fromLink: true,\n sources: [resultsFromCache(readCache()), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n\n case \"no-cache\":\n if (shouldNotify) {\n return {\n fromLink: true,\n // Note that queryInfo.getDiff() for no-cache queries does not call\n // cache.diff, but instead returns a { complete: false } stub result\n // when there is no queryInfo.diff already defined.\n sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],\n };\n }\n\n return { fromLink: true, sources: [resultsFromLink()] };\n\n case \"standby\":\n return { fromLink: false, sources: [] };\n }\n }\n\n private getQuery(queryId: string): QueryInfo {\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\n private prepareContext(context = {}) {\n const newContext = this.localState.prepareContext(context);\n return {\n ...this.defaultContext,\n ...newContext,\n clientAwareness: this.clientAwareness,\n };\n }\n}\n\n// Return types used by fetchQueryByPolicy and other private methods above.\ninterface FetchConcastInfo {\n // Metadata properties that can be returned in addition to the Concast.\n fromLink: boolean;\n}\ninterface SourcesAndInfo extends FetchConcastInfo {\n sources: ConcastSourcesArray>;\n}\ninterface ConcastAndInfo extends FetchConcastInfo {\n concast: Concast>;\n}\n","import type {\n ApolloCache,\n DocumentNode,\n TypedDocumentNode,\n} from \"../core/index.js\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport {\n createFragmentMap,\n getFragmentDefinitions,\n getOperationDefinition,\n} from \"../utilities/index.js\";\nimport { maskDefinition } from \"./maskDefinition.js\";\nimport {\n MapImpl,\n SetImpl,\n warnOnImproperCacheImplementation,\n} from \"./utils.js\";\n\n/** @internal */\nexport function maskOperation(\n data: TData,\n document: DocumentNode | TypedDocumentNode,\n cache: ApolloCache\n): TData {\n if (!cache.fragmentMatches) {\n if (__DEV__) {\n warnOnImproperCacheImplementation();\n }\n\n return data;\n }\n\n const definition = getOperationDefinition(document);\n\n invariant(\n definition,\n \"Expected a parsed GraphQL document with a query, mutation, or subscription.\"\n );\n\n if (data == null) {\n // Maintain the original `null` or `undefined` value\n return data;\n }\n\n return maskDefinition(data, definition.selectionSet, {\n operationType: definition.operation,\n operationName: definition.name?.value,\n fragmentMap: createFragmentMap(getFragmentDefinitions(document)),\n cache,\n mutableTargets: new MapImpl(),\n knownChanged: new SetImpl(),\n });\n}\n","import { invariant } from \"../utilities/globals/index.js\";\n\nimport type {\n DocumentNode,\n OperationDefinitionNode,\n SelectionSetNode,\n SelectionNode,\n InlineFragmentNode,\n FragmentDefinitionNode,\n FieldNode,\n ASTNode,\n DirectiveNode,\n FragmentSpreadNode,\n ExecutableDefinitionNode,\n} from \"graphql\";\nimport { visit, BREAK, isSelectionNode } from \"graphql\";\n\nimport type { ApolloCache } from \"../cache/index.js\";\nimport type { FragmentMap, StoreObject } from \"../utilities/index.js\";\nimport {\n argumentsObjectFromField,\n buildQueryFromSelectionSet,\n createFragmentMap,\n getFragmentDefinitions,\n getMainDefinition,\n hasDirectives,\n isField,\n isInlineFragment,\n mergeDeep,\n mergeDeepArray,\n removeClientSetsFromDocument,\n resultKeyNameFromField,\n shouldInclude,\n} from \"../utilities/index.js\";\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { Resolvers, OperationVariables } from \"./types.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\nimport { cacheSlot } from \"../cache/index.js\";\n\nexport type Resolver = (\n rootValue?: any,\n args?: any,\n context?: any,\n info?: {\n field: FieldNode;\n fragmentMap: FragmentMap;\n }\n) => any;\n\nexport type VariableMap = { [name: string]: any };\n\nexport type FragmentMatcher = (\n rootValue: any,\n typeCondition: string,\n context: any\n) => boolean;\n\nexport type ExecContext = {\n fragmentMap: FragmentMap;\n context: any;\n variables: VariableMap;\n fragmentMatcher: FragmentMatcher;\n defaultOperationType: string;\n exportedVariables: Record;\n onlyRunForcedResolvers: boolean;\n selectionsToResolve: Set;\n};\n\nexport type LocalStateOptions = {\n cache: ApolloCache;\n client?: ApolloClient;\n resolvers?: Resolvers | Resolvers[];\n fragmentMatcher?: FragmentMatcher;\n};\n\nexport class LocalState {\n private cache: ApolloCache;\n private client?: ApolloClient;\n private resolvers?: Resolvers;\n private fragmentMatcher?: FragmentMatcher;\n private selectionsToResolveCache = new WeakMap<\n ExecutableDefinitionNode,\n Set\n >();\n\n constructor({\n cache,\n client,\n resolvers,\n fragmentMatcher,\n }: LocalStateOptions) {\n this.cache = cache;\n\n if (client) {\n this.client = client;\n }\n\n if (resolvers) {\n this.addResolvers(resolvers);\n }\n\n if (fragmentMatcher) {\n this.setFragmentMatcher(fragmentMatcher);\n }\n }\n\n public addResolvers(resolvers: Resolvers | Resolvers[]) {\n this.resolvers = this.resolvers || {};\n if (Array.isArray(resolvers)) {\n resolvers.forEach((resolverGroup) => {\n this.resolvers = mergeDeep(this.resolvers, resolverGroup);\n });\n } else {\n this.resolvers = mergeDeep(this.resolvers, resolvers);\n }\n }\n\n public setResolvers(resolvers: Resolvers | Resolvers[]) {\n this.resolvers = {};\n this.addResolvers(resolvers);\n }\n\n public getResolvers() {\n return this.resolvers || {};\n }\n\n // Run local client resolvers against the incoming query and remote data.\n // Locally resolved field values are merged with the incoming remote data,\n // and returned. Note that locally resolved fields will overwrite\n // remote data using the same field name.\n public async runResolvers({\n document,\n remoteResult,\n context,\n variables,\n onlyRunForcedResolvers = false,\n }: {\n document: DocumentNode | null;\n remoteResult: FetchResult;\n context?: Record;\n variables?: Record;\n onlyRunForcedResolvers?: boolean;\n }): Promise> {\n if (document) {\n return this.resolveDocument(\n document,\n remoteResult.data,\n context,\n variables,\n this.fragmentMatcher,\n onlyRunForcedResolvers\n ).then((localResult) => ({\n ...remoteResult,\n data: localResult.result,\n }));\n }\n\n return remoteResult;\n }\n\n public setFragmentMatcher(fragmentMatcher: FragmentMatcher) {\n this.fragmentMatcher = fragmentMatcher;\n }\n\n public getFragmentMatcher(): FragmentMatcher | undefined {\n return this.fragmentMatcher;\n }\n\n // Client queries contain everything in the incoming document (if a @client\n // directive is found).\n public clientQuery(document: DocumentNode) {\n if (hasDirectives([\"client\"], document)) {\n if (this.resolvers) {\n return document;\n }\n }\n return null;\n }\n\n // Server queries are stripped of all @client based selection sets.\n public serverQuery(document: DocumentNode) {\n return removeClientSetsFromDocument(document);\n }\n\n public prepareContext(context?: Record) {\n const { cache } = this;\n return {\n ...context,\n cache,\n // Getting an entry's cache key is useful for local state resolvers.\n getCacheKey(obj: StoreObject) {\n return cache.identify(obj);\n },\n };\n }\n\n // To support `@client @export(as: \"someVar\")` syntax, we'll first resolve\n // @client @export fields locally, then pass the resolved values back to be\n // used alongside the original operation variables.\n public async addExportedVariables(\n document: DocumentNode,\n variables: TVars = {} as TVars,\n context = {}\n ): /* returns at least the variables that were passed in */ Promise {\n if (document) {\n return this.resolveDocument(\n document,\n this.buildRootValueFromCache(document, variables) || {},\n this.prepareContext(context),\n variables\n ).then((data) => ({\n ...variables,\n ...data.exportedVariables,\n }));\n }\n\n return {\n ...variables,\n };\n }\n\n public shouldForceResolvers(document: ASTNode) {\n let forceResolvers = false;\n visit(document, {\n Directive: {\n enter(node) {\n if (node.name.value === \"client\" && node.arguments) {\n forceResolvers = node.arguments.some(\n (arg) =>\n 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\n // Query the cache and return matching data.\n private buildRootValueFromCache(\n document: DocumentNode,\n variables?: Record\n ) {\n return this.cache.diff({\n query: buildQueryFromSelectionSet(document),\n variables,\n returnPartialData: true,\n optimistic: false,\n }).result;\n }\n\n private async resolveDocument(\n document: DocumentNode,\n rootValue: TData,\n context: any = {},\n variables: VariableMap = {},\n fragmentMatcher: FragmentMatcher = () => true,\n onlyRunForcedResolvers: boolean = false\n ) {\n const mainDefinition = getMainDefinition(\n document\n ) as OperationDefinitionNode;\n const fragments = getFragmentDefinitions(document);\n const fragmentMap = createFragmentMap(fragments);\n const selectionsToResolve = this.collectSelectionsToResolve(\n mainDefinition,\n fragmentMap\n );\n\n const definitionOperation = mainDefinition.operation;\n\n const defaultOperationType =\n definitionOperation ?\n definitionOperation.charAt(0).toUpperCase() +\n definitionOperation.slice(1)\n : \"Query\";\n\n const { cache, client } = this;\n const execContext: ExecContext = {\n fragmentMap,\n context: {\n ...context,\n cache,\n client,\n },\n variables,\n fragmentMatcher,\n defaultOperationType,\n exportedVariables: {},\n selectionsToResolve,\n onlyRunForcedResolvers,\n };\n const isClientFieldDescendant = false;\n\n return this.resolveSelectionSet(\n mainDefinition.selectionSet,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((result) => ({\n result,\n exportedVariables: execContext.exportedVariables,\n }));\n }\n\n private async resolveSelectionSet(\n selectionSet: SelectionSetNode,\n isClientFieldDescendant: boolean,\n rootValue: TData,\n execContext: ExecContext\n ) {\n const { fragmentMap, context, variables } = execContext;\n const resultsToMerge: TData[] = [rootValue];\n\n const execute = async (selection: SelectionNode): Promise => {\n if (\n !isClientFieldDescendant &&\n !execContext.selectionsToResolve.has(selection)\n ) {\n // Skip selections without @client directives\n // (still processing if one of the ancestors or one of the child fields has @client directive)\n return;\n }\n if (!shouldInclude(selection, variables)) {\n // Skip this entirely.\n return;\n }\n\n if (isField(selection)) {\n return this.resolveField(\n selection,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((fieldResult) => {\n if (typeof fieldResult !== \"undefined\") {\n resultsToMerge.push({\n [resultKeyNameFromField(selection)]: fieldResult,\n } as TData);\n }\n });\n }\n\n let fragment: InlineFragmentNode | FragmentDefinitionNode;\n\n if (isInlineFragment(selection)) {\n fragment = selection;\n } else {\n // This is a named fragment.\n fragment = fragmentMap[selection.name.value];\n invariant(fragment, `No fragment named %s`, selection.name.value);\n }\n\n if (fragment && fragment.typeCondition) {\n const typeCondition = fragment.typeCondition.name.value;\n if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {\n return this.resolveSelectionSet(\n fragment.selectionSet,\n isClientFieldDescendant,\n rootValue,\n execContext\n ).then((fragmentResult) => {\n resultsToMerge.push(fragmentResult);\n });\n }\n }\n };\n\n return Promise.all(selectionSet.selections.map(execute)).then(function () {\n return mergeDeepArray(resultsToMerge);\n });\n }\n\n private async resolveField(\n field: FieldNode,\n isClientFieldDescendant: boolean,\n rootValue: any,\n execContext: ExecContext\n ): Promise {\n if (!rootValue) {\n return null;\n }\n\n const { variables } = execContext;\n const fieldName = field.name.value;\n const aliasedFieldName = resultKeyNameFromField(field);\n const aliasUsed = fieldName !== aliasedFieldName;\n const defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];\n let resultPromise = Promise.resolve(defaultResult);\n\n // Usually all local resolvers are run when passing through here, but\n // if we've specifically identified that we only want to run forced\n // resolvers (that is, resolvers for fields marked with\n // `@client(always: true)`), then we'll skip running non-forced resolvers.\n if (\n !execContext.onlyRunForcedResolvers ||\n this.shouldForceResolvers(field)\n ) {\n const resolverType =\n rootValue.__typename || execContext.defaultOperationType;\n const resolverMap = this.resolvers && this.resolvers[resolverType];\n if (resolverMap) {\n const resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];\n if (resolve) {\n resultPromise = Promise.resolve(\n // In case the resolve function accesses reactive variables,\n // set cacheSlot to the current cache instance.\n cacheSlot.withValue(this.cache, resolve, [\n rootValue,\n argumentsObjectFromField(field, variables),\n execContext.context,\n { field, fragmentMap: execContext.fragmentMap },\n ])\n );\n }\n }\n }\n\n return resultPromise.then((result = defaultResult) => {\n // If an @export directive is associated with the current field, store\n // the `as` export variable name and current result for later use.\n if (field.directives) {\n field.directives.forEach((directive) => {\n if (directive.name.value === \"export\" && directive.arguments) {\n directive.arguments.forEach((arg) => {\n if (arg.name.value === \"as\" && arg.value.kind === \"StringValue\") {\n execContext.exportedVariables[arg.value.value] = result;\n }\n });\n }\n });\n }\n\n // Handle all scalar types here.\n if (!field.selectionSet) {\n return result;\n }\n\n // From here down, the field has a selection set, which means it's trying\n // to query a GraphQLObjectType.\n if (result == null) {\n // Basically any field in a GraphQL response can be null, or missing\n return result;\n }\n\n const isClientField =\n field.directives?.some((d) => d.name.value === \"client\") ?? false;\n\n if (Array.isArray(result)) {\n return this.resolveSubSelectedArray(\n field,\n isClientFieldDescendant || isClientField,\n result,\n execContext\n );\n }\n\n // Returned value is an object, and the query has a sub-selection. Recurse.\n if (field.selectionSet) {\n return this.resolveSelectionSet(\n field.selectionSet,\n isClientFieldDescendant || isClientField,\n result,\n execContext\n );\n }\n });\n }\n\n private resolveSubSelectedArray(\n field: FieldNode,\n isClientFieldDescendant: boolean,\n result: any[],\n execContext: ExecContext\n ): any {\n return Promise.all(\n result.map((item) => {\n if (item === null) {\n return null;\n }\n\n // This is a nested array, recurse.\n if (Array.isArray(item)) {\n return this.resolveSubSelectedArray(\n field,\n isClientFieldDescendant,\n item,\n execContext\n );\n }\n\n // This is an object, run the selection set on it.\n if (field.selectionSet) {\n return this.resolveSelectionSet(\n field.selectionSet,\n isClientFieldDescendant,\n item,\n execContext\n );\n }\n })\n );\n }\n\n // Collect selection nodes on paths from document root down to all @client directives.\n // This function takes into account transitive fragment spreads.\n // Complexity equals to a single `visit` over the full document.\n private collectSelectionsToResolve(\n mainDefinition: OperationDefinitionNode,\n fragmentMap: FragmentMap\n ): Set {\n const isSingleASTNode = (\n node: ASTNode | readonly ASTNode[]\n ): node is ASTNode => !Array.isArray(node);\n const selectionsToResolveCache = this.selectionsToResolveCache;\n\n function collectByDefinition(\n definitionNode: ExecutableDefinitionNode\n ): Set {\n if (!selectionsToResolveCache.has(definitionNode)) {\n const matches = new Set();\n selectionsToResolveCache.set(definitionNode, matches);\n\n visit(definitionNode, {\n Directive(node: DirectiveNode, _, __, ___, ancestors) {\n if (node.name.value === \"client\") {\n ancestors.forEach((node) => {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches.add(node);\n }\n });\n }\n },\n FragmentSpread(spread: FragmentSpreadNode, _, __, ___, ancestors) {\n const fragment = fragmentMap[spread.name.value];\n invariant(fragment, `No fragment named %s`, spread.name.value);\n\n const fragmentSelections = collectByDefinition(fragment);\n if (fragmentSelections.size > 0) {\n // Fragment for this spread contains @client directive (either directly or transitively)\n // Collect selection nodes on paths from the root down to fields with the @client directive\n ancestors.forEach((node) => {\n if (isSingleASTNode(node) && isSelectionNode(node)) {\n matches.add(node);\n }\n });\n matches.add(spread);\n fragmentSelections.forEach((selection) => {\n matches.add(selection);\n });\n }\n },\n });\n }\n return selectionsToResolveCache.get(definitionNode)!;\n }\n return collectByDefinition(mainDefinition);\n }\n}\n","import { invariant, newInvariantError } from \"../utilities/globals/index.js\";\n\nimport type { DocumentNode, FormattedExecutionResult } from \"graphql\";\n\nimport type { FetchResult, GraphQLRequest } from \"../link/core/index.js\";\nimport { ApolloLink, execute } from \"../link/core/index.js\";\nimport type { ApolloCache, DataProxy, Reference } from \"../cache/index.js\";\nimport type { DocumentTransform } from \"../utilities/index.js\";\nimport type { Observable } from \"../utilities/index.js\";\nimport { version } from \"../version.js\";\nimport type { UriFunction } from \"../link/http/index.js\";\nimport { HttpLink } from \"../link/http/index.js\";\n\nimport { QueryManager } from \"./QueryManager.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\n\nimport type {\n ApolloQueryResult,\n DefaultContext,\n OperationVariables,\n Resolvers,\n RefetchQueriesOptions,\n RefetchQueriesResult,\n InternalRefetchQueriesResult,\n RefetchQueriesInclude,\n} from \"./types.js\";\n\nimport type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n SubscriptionOptions,\n WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\n\nimport type { FragmentMatcher } from \"./LocalState.js\";\nimport { LocalState } from \"./LocalState.js\";\n\nexport interface DefaultOptions {\n watchQuery?: Partial>;\n query?: Partial>;\n mutate?: Partial>;\n}\n\nexport interface DevtoolsOptions {\n /**\n * If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to this `ApolloClient` instance.\n *\n * The default value is `false` in production and `true` in development if there is a `window` object.\n */\n enabled?: boolean;\n\n /**\n * Optional name for this `ApolloClient` instance in the devtools. This is\n * useful when you instantiate multiple clients and want to be able to\n * identify them by name.\n */\n name?: string;\n}\n\nlet hasSuggestedDevtools = false;\n\nexport interface ApolloClientOptions {\n /**\n * The URI of the GraphQL endpoint that Apollo Client will communicate with.\n *\n * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.\n */\n uri?: string | UriFunction;\n credentials?: string;\n /**\n * An object representing headers to include in every HTTP request, such as `{Authorization: 'Bearer 1234'}`\n *\n * This value will be ignored when using the `link` option.\n */\n headers?: Record;\n /**\n * You can provide an `ApolloLink` instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).\n *\n * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.\n */\n link?: ApolloLink;\n /**\n * The cache that Apollo Client should use to store query results locally. The recommended cache is `InMemoryCache`, which is provided by the `@apollo/client` package.\n *\n * For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).\n */\n cache: ApolloCache;\n /**\n * The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.\n *\n * @defaultValue `0` (no delay)\n */\n ssrForceFetchDelay?: number;\n /**\n * When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to `true` so that the [`getDataFromTree` function](../react/ssr/#getdatafromtree) can work effectively.\n *\n * @defaultValue `false`\n */\n ssrMode?: boolean;\n /**\n * If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to Apollo Client.\n *\n * The default value is `false` in production and `true` in development (if there is a `window` object).\n * @deprecated Please use the `devtools.enabled` option.\n */\n connectToDevTools?: boolean;\n /**\n * If `false`, Apollo Client sends every created query to the server, even if a _completely_ identical query (identical in terms of query string, variable values, and operationName) is already in flight.\n *\n * @defaultValue `true`\n */\n queryDeduplication?: boolean;\n /**\n * Provide this object to set application-wide default values for options you can provide to the `watchQuery`, `query`, and `mutate` functions. See below for an example object.\n *\n * See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).\n */\n defaultOptions?: DefaultOptions;\n defaultContext?: Partial;\n /**\n * If `true`, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.\n *\n * @defaultValue `false`\n */\n assumeImmutableResults?: boolean;\n resolvers?: Resolvers | Resolvers[];\n typeDefs?: string | string[] | DocumentNode | DocumentNode[];\n fragmentMatcher?: FragmentMatcher;\n /**\n * A custom name (e.g., `iOS`) that identifies this particular client among your set of clients. Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n */\n name?: string;\n /**\n * A custom version that identifies the current version of this particular client (e.g., `1.2`). Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n *\n * This is **not** the version of Apollo Client that you are using, but rather any version string that helps you differentiate between versions of your client.\n */\n version?: string;\n documentTransform?: DocumentTransform;\n\n /**\n * Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.\n *\n * @since 3.11.0\n */\n devtools?: DevtoolsOptions;\n\n /**\n * Determines if data masking is enabled for the client.\n *\n * @defaultValue false\n */\n dataMasking?: boolean;\n}\n\n// Though mergeOptions now resides in @apollo/client/utilities, it was\n// previously declared and exported from this module, and then reexported from\n// @apollo/client/core. Since we need to preserve that API anyway, the easiest\n// solution is to reexport mergeOptions where it was previously declared (here).\nimport { mergeOptions } from \"../utilities/index.js\";\nimport { getApolloClientMemoryInternals } from \"../utilities/caching/getMemoryInternals.js\";\nimport type {\n WatchFragmentOptions,\n WatchFragmentResult,\n} from \"../cache/core/cache.js\";\nimport type { MaybeMasked, Unmasked } from \"../masking/index.js\";\nexport { mergeOptions };\n\n/**\n * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries\n * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,\n * receive results from the server and cache the results in a store. It also delivers updates\n * to GraphQL queries through `Observable` instances.\n */\nexport class ApolloClient implements DataProxy {\n public link: ApolloLink;\n public cache: ApolloCache;\n public disableNetworkFetches: boolean;\n public version: string;\n public queryDeduplication: boolean;\n public defaultOptions: DefaultOptions;\n public readonly typeDefs: ApolloClientOptions[\"typeDefs\"];\n public readonly devtoolsConfig: DevtoolsOptions;\n\n private queryManager: QueryManager;\n private devToolsHookCb?: Function;\n private resetStoreCallbacks: Array<() => Promise> = [];\n private clearStoreCallbacks: Array<() => Promise> = [];\n private localState: LocalState;\n\n /**\n * Constructs an instance of `ApolloClient`.\n *\n * @example\n * ```js\n * import { ApolloClient, InMemoryCache } from '@apollo/client';\n *\n * const cache = new InMemoryCache();\n *\n * const client = new ApolloClient({\n * // Provide required constructor fields\n * cache: cache,\n * uri: 'http://localhost:4000/',\n *\n * // Provide some optional constructor fields\n * name: 'react-web-client',\n * version: '1.3',\n * queryDeduplication: false,\n * defaultOptions: {\n * watchQuery: {\n * fetchPolicy: 'cache-and-network',\n * },\n * },\n * });\n * ```\n */\n constructor(options: ApolloClientOptions) {\n if (!options.cache) {\n throw newInvariantError(\n \"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\"\n );\n }\n\n const {\n uri,\n credentials,\n headers,\n cache,\n documentTransform,\n ssrMode = false,\n ssrForceFetchDelay = 0,\n // Expose the client instance as window.__APOLLO_CLIENT__ and call\n // onBroadcast in queryManager.broadcastQueries to enable browser\n // devtools, but disable them by default in production.\n connectToDevTools,\n queryDeduplication = true,\n defaultOptions,\n defaultContext,\n assumeImmutableResults = cache.assumeImmutableResults,\n resolvers,\n typeDefs,\n fragmentMatcher,\n name: clientAwarenessName,\n version: clientAwarenessVersion,\n devtools,\n dataMasking,\n } = options;\n\n let { link } = options;\n\n if (!link) {\n link =\n uri ? new HttpLink({ uri, credentials, headers }) : ApolloLink.empty();\n }\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 this.devtoolsConfig = {\n ...devtools,\n enabled: devtools?.enabled ?? connectToDevTools,\n };\n\n if (this.devtoolsConfig.enabled === undefined) {\n this.devtoolsConfig.enabled = __DEV__;\n }\n\n if (ssrForceFetchDelay) {\n setTimeout(\n () => (this.disableNetworkFetches = false),\n ssrForceFetchDelay\n );\n }\n\n this.watchQuery = this.watchQuery.bind(this);\n this.query = this.query.bind(this);\n this.mutate = this.mutate.bind(this);\n this.watchFragment = this.watchFragment.bind(this);\n this.resetStore = this.resetStore.bind(this);\n this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);\n\n this.version = version;\n\n this.localState = new LocalState({\n cache,\n client: this,\n resolvers,\n fragmentMatcher,\n });\n\n this.queryManager = new QueryManager({\n cache: this.cache,\n link: this.link,\n defaultOptions: this.defaultOptions,\n defaultContext,\n documentTransform,\n queryDeduplication,\n ssrMode,\n dataMasking: !!dataMasking,\n clientAwareness: {\n name: clientAwarenessName!,\n version: clientAwarenessVersion!,\n },\n localState: this.localState,\n assumeImmutableResults,\n onBroadcast:\n this.devtoolsConfig.enabled ?\n () => {\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 }\n : void 0,\n });\n\n if (this.devtoolsConfig.enabled) this.connectToDevTools();\n }\n\n private connectToDevTools() {\n if (typeof window === \"undefined\") {\n return;\n }\n\n type DevToolsConnector = {\n push(client: ApolloClient): void;\n };\n const windowWithDevTools = window as Window & {\n [devtoolsSymbol]?: DevToolsConnector;\n __APOLLO_CLIENT__?: ApolloClient;\n };\n const devtoolsSymbol = Symbol.for(\"apollo.devtools\");\n (windowWithDevTools[devtoolsSymbol] =\n windowWithDevTools[devtoolsSymbol] || ([] as DevToolsConnector)).push(\n this\n );\n windowWithDevTools.__APOLLO_CLIENT__ = this;\n\n /**\n * Suggest installing the devtools for developers who don't have them\n */\n if (!hasSuggestedDevtools && __DEV__) {\n hasSuggestedDevtools = true;\n if (\n window.document &&\n window.top === window.self &&\n /^(https?|file):$/.test(window.location.protocol)\n ) {\n setTimeout(() => {\n if (!(window as any).__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {\n const nav = window.navigator;\n const ua = nav && nav.userAgent;\n let url: string | undefined;\n if (typeof ua === \"string\") {\n if (ua.indexOf(\"Chrome/\") > -1) {\n url =\n \"https://chrome.google.com/webstore/detail/\" +\n \"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm\";\n } else if (ua.indexOf(\"Firefox/\") > -1) {\n url =\n \"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/\";\n }\n }\n if (url) {\n invariant.log(\n \"Download the Apollo DevTools for a better development \" +\n \"experience: %s\",\n url\n );\n }\n }\n }, 10000);\n }\n }\n }\n\n /**\n * The `DocumentTransform` used to modify GraphQL documents before a request\n * is made. If a custom `DocumentTransform` is not provided, this will be the\n * default document transform.\n */\n get documentTransform() {\n return this.queryManager.documentTransform;\n }\n\n /**\n * Call this method to terminate any active client processes, making it safe\n * to dispose of this `ApolloClient` instance.\n */\n public stop() {\n this.queryManager.stop();\n }\n\n /**\n * This watches the cache store of the query according to the options specified and\n * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and\n * receive updated results through an observer when the cache store changes.\n *\n * Note that this method is not an implementation of GraphQL subscriptions. Rather,\n * it uses Apollo's store in order to reactively deliver updates to your query results.\n *\n * For example, suppose you call watchQuery on a GraphQL query that fetches a person's\n * first and last name and this person has a particular object identifier, provided by\n * dataIdFromObject. Later, a different query fetches that same person's\n * first and last name and the first name has now changed. Then, any observers associated\n * with the results of the first query will be updated with a new result object.\n *\n * Note that if the cache does not change, the subscriber will *not* be notified.\n *\n * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for\n * a description of store reactivity.\n */\n public watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions): ObservableQuery {\n if (this.defaultOptions.watchQuery) {\n options = mergeOptions(this.defaultOptions.watchQuery, options);\n }\n\n // XXX Overwriting options is probably not the best way to do this long term...\n if (\n this.disableNetworkFetches &&\n (options.fetchPolicy === \"network-only\" ||\n options.fetchPolicy === \"cache-and-network\")\n ) {\n options = { ...options, fetchPolicy: \"cache-first\" };\n }\n\n return this.queryManager.watchQuery(options);\n }\n\n /**\n * This resolves a single query according to the options specified and\n * returns a `Promise` which is either resolved with the resulting data\n * or rejected with an error.\n *\n * @param options - An object of type `QueryOptions` that allows us to\n * describe how this query should be treated e.g. whether it should hit the\n * server at all or just resolve from the cache, etc.\n */\n public query<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(\n options: QueryOptions\n ): Promise>> {\n if (this.defaultOptions.query) {\n options = mergeOptions(this.defaultOptions.query, options);\n }\n\n invariant(\n (options.fetchPolicy as WatchQueryFetchPolicy) !== \"cache-and-network\",\n \"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.\"\n );\n\n if (this.disableNetworkFetches && options.fetchPolicy === \"network-only\") {\n options = { ...options, fetchPolicy: \"cache-first\" };\n }\n\n return this.queryManager.query(options);\n }\n\n /**\n * This resolves a single mutation according to the options specified and returns a\n * Promise which is either resolved with the resulting data or rejected with an\n * error. In some cases both `data` and `errors` might be undefined, for example\n * when `errorPolicy` is set to `'ignore'`.\n *\n * It takes options as an object with the following keys and values:\n */\n public mutate<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n TContext extends Record = DefaultContext,\n TCache extends ApolloCache = ApolloCache,\n >(\n options: MutationOptions\n ): Promise>> {\n if (this.defaultOptions.mutate) {\n options = mergeOptions(this.defaultOptions.mutate, options);\n }\n return this.queryManager.mutate(\n options\n );\n }\n\n /**\n * This subscribes to a graphql subscription according to the options specified and returns an\n * `Observable` which either emits received data or an error.\n */\n public subscribe<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(\n options: SubscriptionOptions\n ): Observable>> {\n const id = this.queryManager.generateQueryId();\n\n return this.queryManager\n .startGraphQLSubscription(options)\n .map((result) => ({\n ...result,\n data: this.queryManager.maskOperation({\n document: options.query,\n data: result.data,\n fetchPolicy: options.fetchPolicy,\n id,\n }),\n }));\n }\n\n /**\n * Tries to read some data from the store in the shape of the provided\n * GraphQL query without making a network request. This method will start at\n * the root query. To start at a specific id returned by `dataIdFromObject`\n * use `readFragment`.\n *\n * @param optimistic - Set to `true` to allow `readQuery` to return\n * optimistic results. Is `false` by default.\n */\n public readQuery(\n options: DataProxy.Query,\n optimistic: boolean = false\n ): Unmasked | null {\n return this.cache.readQuery(options, optimistic);\n }\n\n /**\n * Watches the cache store of the fragment according to the options specified\n * and returns an `Observable`. We can subscribe to this\n * `Observable` and receive updated results through an\n * observer when the cache store changes.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are reading. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n *\n * @since 3.10.0\n * @param options - An object of type `WatchFragmentOptions` that allows\n * the cache to identify the fragment and optionally specify whether to react\n * to optimistic updates.\n */\n\n public watchFragment<\n TFragmentData = unknown,\n TVariables = OperationVariables,\n >(\n options: WatchFragmentOptions\n ): Observable> {\n return this.cache.watchFragment({\n ...options,\n [Symbol.for(\"apollo.dataMasking\")]: this.queryManager.dataMasking,\n });\n }\n\n /**\n * Tries to read some data from the store in the shape of the provided\n * GraphQL fragment without making a network request. This method will read a\n * GraphQL fragment from any arbitrary id that is currently cached, unlike\n * `readQuery` which will only read from the root query.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are reading. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n *\n * @param optimistic - Set to `true` to allow `readFragment` to return\n * optimistic results. Is `false` by default.\n */\n public readFragment(\n options: DataProxy.Fragment,\n optimistic: boolean = false\n ): Unmasked | null {\n return this.cache.readFragment(options, optimistic);\n }\n\n /**\n * Writes some data in the shape of the provided GraphQL query directly to\n * the store. This method will start at the root query. To start at a\n * specific id returned by `dataIdFromObject` then use `writeFragment`.\n */\n public writeQuery(\n options: DataProxy.WriteQueryOptions\n ): Reference | undefined {\n const ref = this.cache.writeQuery(options);\n\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n\n return ref;\n }\n\n /**\n * Writes some data in the shape of the provided GraphQL fragment directly to\n * the store. This method will write to a GraphQL fragment from any arbitrary\n * id that is currently cached, unlike `writeQuery` which will only write\n * from the root query.\n *\n * You must pass in a GraphQL document with a single fragment or a document\n * with multiple fragments that represent what you are writing. If you pass\n * in a document with multiple fragments then you must also specify a\n * `fragmentName`.\n */\n public writeFragment(\n options: DataProxy.WriteFragmentOptions\n ): Reference | undefined {\n const ref = this.cache.writeFragment(options);\n\n if (options.broadcast !== false) {\n this.queryManager.broadcastQueries();\n }\n\n return ref;\n }\n\n public __actionHookForDevTools(cb: () => any) {\n this.devToolsHookCb = cb;\n }\n\n public __requestRaw(\n payload: GraphQLRequest\n ): Observable {\n return execute(this.link, payload);\n }\n\n /**\n * Resets your entire store by clearing out your cache and then re-executing\n * all of your active queries. This makes it so that you may guarantee that\n * there is no data left in your store from a time before you called this\n * method.\n *\n * `resetStore()` is useful when your user just logged out. You’ve removed the\n * user session, and you now want to make sure that any references to data you\n * might have fetched while the user session was active is gone.\n *\n * It is important to remember that `resetStore()` *will* refetch any active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n */\n public resetStore(): Promise[] | null> {\n return Promise.resolve()\n .then(() =>\n this.queryManager.clearStore({\n discardWatches: false,\n })\n )\n .then(() => Promise.all(this.resetStoreCallbacks.map((fn) => fn())))\n .then(() => this.reFetchObservableQueries());\n }\n\n /**\n * Remove all data from the store. Unlike `resetStore`, `clearStore` will\n * not refetch any active queries.\n */\n public clearStore(): Promise {\n return Promise.resolve()\n .then(() =>\n this.queryManager.clearStore({\n discardWatches: true,\n })\n )\n .then(() => Promise.all(this.clearStoreCallbacks.map((fn) => fn())));\n }\n\n /**\n * Allows callbacks to be registered that are executed when the store is\n * reset. `onResetStore` returns an unsubscribe function that can be used\n * to remove registered callbacks.\n */\n public onResetStore(cb: () => Promise): () => void {\n this.resetStoreCallbacks.push(cb);\n return () => {\n this.resetStoreCallbacks = this.resetStoreCallbacks.filter(\n (c) => c !== cb\n );\n };\n }\n\n /**\n * Allows callbacks to be registered that are executed when the store is\n * cleared. `onClearStore` returns an unsubscribe function that can be used\n * to remove registered callbacks.\n */\n public onClearStore(cb: () => Promise): () => void {\n this.clearStoreCallbacks.push(cb);\n return () => {\n this.clearStoreCallbacks = this.clearStoreCallbacks.filter(\n (c) => c !== cb\n );\n };\n }\n\n /**\n * Refetches all of your active queries.\n *\n * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage\n *\n * It is important to remember that `reFetchObservableQueries()` *will* refetch any active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.\n */\n public reFetchObservableQueries(\n includeStandby?: boolean\n ): Promise[]> {\n return this.queryManager.reFetchObservableQueries(includeStandby);\n }\n\n /**\n * Refetches specified active queries. Similar to \"reFetchObservableQueries()\" but with a specific list of queries.\n *\n * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.\n *\n * It is important to remember that `refetchQueries()` *will* refetch specified active\n * queries. This means that any components that might be mounted will execute\n * their queries again using your network interface. If you do not want to\n * re-execute any queries then you should make sure to stop watching any\n * active queries.\n */\n public refetchQueries<\n TCache extends ApolloCache = ApolloCache,\n TResult = Promise>,\n >(\n options: RefetchQueriesOptions\n ): RefetchQueriesResult {\n const map = this.queryManager.refetchQueries(\n options as RefetchQueriesOptions, TResult>\n );\n const queries: ObservableQuery[] = [];\n const results: InternalRefetchQueriesResult[] = [];\n\n map.forEach((result, obsQuery) => {\n queries.push(obsQuery);\n results.push(result);\n });\n\n const result = Promise.all(\n results as TResult[]\n ) as RefetchQueriesResult;\n\n // In case you need the raw results immediately, without awaiting\n // Promise.all(results):\n result.queries = queries;\n result.results = results;\n\n // If you decide to ignore the result Promise because you're using\n // result.queries and result.results instead, you shouldn't have to worry\n // about preventing uncaught rejections for the Promise.all result.\n result.catch((error) => {\n invariant.debug(\n `In client.refetchQueries, Promise.all promise rejected with error %o`,\n error\n );\n });\n\n return result;\n }\n\n /**\n * Get all currently active `ObservableQuery` objects, in a `Map` keyed by\n * query ID strings.\n *\n * An \"active\" query is one that has observers and a `fetchPolicy` other than\n * \"standby\" or \"cache-only\".\n *\n * You can include all `ObservableQuery` objects (including the inactive ones)\n * by passing \"all\" instead of \"active\", or you can include just a subset of\n * active queries by passing an array of query names or DocumentNode objects.\n */\n public getObservableQueries(\n include: RefetchQueriesInclude = \"active\"\n ): Map> {\n return this.queryManager.getObservableQueries(include);\n }\n\n /**\n * Exposes the cache's complete state, in a serializable format for later restoration.\n */\n public extract(optimistic?: boolean): TCacheShape {\n return this.cache.extract(optimistic);\n }\n\n /**\n * Replaces existing state in the cache (if any) with the values expressed by\n * `serializedState`.\n *\n * Called when hydrating a cache (server side rendering, or offline storage),\n * and also (potentially) during hot reloads.\n */\n public restore(serializedState: TCacheShape): ApolloCache {\n return this.cache.restore(serializedState);\n }\n\n /**\n * Add additional local resolvers.\n */\n public addResolvers(resolvers: Resolvers | Resolvers[]) {\n this.localState.addResolvers(resolvers);\n }\n\n /**\n * Set (override existing) local resolvers.\n */\n public setResolvers(resolvers: Resolvers | Resolvers[]) {\n this.localState.setResolvers(resolvers);\n }\n\n /**\n * Get all registered local resolvers.\n */\n public getResolvers() {\n return this.localState.getResolvers();\n }\n\n /**\n * Set a custom local state fragment matcher.\n */\n public setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher) {\n this.localState.setFragmentMatcher(fragmentMatcher);\n }\n\n /**\n * Define a new ApolloLink (or link chain) that Apollo Client will use.\n */\n public setLink(newLink: ApolloLink) {\n this.link = this.queryManager.link = newLink;\n }\n\n public get defaultContext() {\n return this.queryManager.defaultContext;\n }\n\n /**\n * @experimental\n * This is not a stable API - it is used in development builds to expose\n * information to the DevTools.\n * Use at your own risk!\n * For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)\n *\n * @example\n * ```ts\n * console.log(client.getMemoryInternals())\n * ```\n * Logs output in the following JSON format:\n * @example\n * ```json\n *{\n * limits: {\n * parser: 1000,\n * canonicalStringify: 1000,\n * print: 2000,\n * 'documentTransform.cache': 2000,\n * 'queryManager.getDocumentInfo': 2000,\n * 'PersistedQueryLink.persistedQueryHashes': 2000,\n * 'fragmentRegistry.transform': 2000,\n * 'fragmentRegistry.lookup': 1000,\n * 'fragmentRegistry.findFragmentSpreads': 4000,\n * 'cache.fragmentQueryDocuments': 1000,\n * 'removeTypenameFromVariables.getVariableDefinitions': 2000,\n * 'inMemoryCache.maybeBroadcastWatch': 5000,\n * 'inMemoryCache.executeSelectionSet': 10000,\n * 'inMemoryCache.executeSubSelectedArray': 5000\n * },\n * sizes: {\n * parser: 26,\n * canonicalStringify: 4,\n * print: 14,\n * addTypenameDocumentTransform: [\n * {\n * cache: 14,\n * },\n * ],\n * queryManager: {\n * getDocumentInfo: 14,\n * documentTransforms: [\n * {\n * cache: 14,\n * },\n * {\n * cache: 14,\n * },\n * ],\n * },\n * fragmentRegistry: {\n * findFragmentSpreads: 34,\n * lookup: 20,\n * transform: 14,\n * },\n * cache: {\n * fragmentQueryDocuments: 22,\n * },\n * inMemoryCache: {\n * executeSelectionSet: 4345,\n * executeSubSelectedArray: 1206,\n * maybeBroadcastWatch: 32,\n * },\n * links: [\n * {\n * PersistedQueryLink: {\n * persistedQueryHashes: 14,\n * },\n * },\n * {\n * removeTypenameFromVariables: {\n * getVariableDefinitions: 14,\n * },\n * },\n * ],\n * },\n * }\n *```\n */\n public getMemoryInternals?: typeof getApolloClientMemoryInternals;\n}\n\nif (__DEV__) {\n ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;\n}\n","import { invariant } from \"../utilities/globals/index.js\";\nimport type { DocumentNode } from \"graphql\";\nimport { equal } from \"@wry/equality\";\n\nimport { NetworkStatus, isNetworkRequestInFlight } from \"./networkStatus.js\";\nimport type {\n Concast,\n Observer,\n ObservableSubscription,\n} from \"../utilities/index.js\";\nimport {\n cloneDeep,\n compact,\n getOperationDefinition,\n Observable,\n iterateObserversSafely,\n fixObservableSubclass,\n getQueryDefinition,\n preventUnhandledRejection,\n} from \"../utilities/index.js\";\nimport { ApolloError, isApolloError } from \"../errors/index.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type {\n ApolloQueryResult,\n OperationVariables,\n TypedDocumentNode,\n} from \"./types.js\";\nimport type {\n WatchQueryOptions,\n FetchMoreQueryOptions,\n SubscribeToMoreOptions,\n NextFetchPolicyContext,\n WatchQueryFetchPolicy,\n UpdateQueryMapFn,\n UpdateQueryOptions,\n} from \"./watchQueryOptions.js\";\nimport type { QueryInfo } from \"./QueryInfo.js\";\nimport type { MissingFieldError } from \"../cache/index.js\";\nimport type { MissingTree } from \"../cache/core/types/common.js\";\nimport { equalByQuery } from \"./equalByQuery.js\";\nimport type { TODO } from \"../utilities/types/TODO.js\";\nimport type { MaybeMasked, Unmasked } from \"../masking/index.js\";\n\nconst { assign, hasOwnProperty } = Object;\n\nexport interface FetchMoreOptions<\n TData = any,\n TVariables = OperationVariables,\n> {\n updateQuery?: (\n previousQueryResult: TData,\n options: {\n fetchMoreResult?: TData;\n variables?: TVariables;\n }\n ) => TData;\n}\n\ninterface Last {\n result: ApolloQueryResult;\n variables?: TVariables;\n error?: ApolloError;\n}\n\nexport class ObservableQuery<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n> extends Observable>> {\n public readonly options: WatchQueryOptions;\n public readonly queryId: string;\n public readonly queryName?: string;\n\n // The `query` computed property will always reflect the document transformed\n // by the last run query. `this.options.query` will always reflect the raw\n // untransformed query to ensure document transforms with runtime conditionals\n // are run on the original document.\n public get query(): TypedDocumentNode {\n return this.lastQuery || this.options.query;\n }\n\n // Computed shorthand for this.options.variables, preserved for\n // backwards compatibility.\n /**\n * An object containing the variables that were provided for the query.\n */\n public get variables(): TVariables | undefined {\n return this.options.variables;\n }\n\n private isTornDown: boolean;\n private queryManager: QueryManager;\n private observers = new Set<\n Observer>>\n >();\n private subscriptions = new Set();\n\n private waitForOwnResult: boolean;\n private last?: Last;\n private lastQuery?: DocumentNode;\n\n private queryInfo: QueryInfo;\n\n // When this.concast is defined, this.observer is the Observer currently\n // subscribed to that Concast.\n private concast?: Concast>;\n private observer?: Observer>;\n\n private pollingInfo?: {\n interval: number;\n timeout: ReturnType;\n };\n\n constructor({\n queryManager,\n queryInfo,\n options,\n }: {\n queryManager: QueryManager;\n queryInfo: QueryInfo;\n options: WatchQueryOptions;\n }) {\n super((observer: Observer>>) => {\n // Zen Observable has its own error function, so in order to log correctly\n // we need to provide a custom error callback.\n try {\n var subObserver = (observer as any)._subscription._observer;\n if (subObserver && !subObserver.error) {\n subObserver.error = defaultSubscriptionObserverErrorCallback;\n }\n } catch {}\n\n const first = !this.observers.size;\n this.observers.add(observer);\n\n // Deliver most recent error or result.\n const last = this.last;\n if (last && last.error) {\n observer.error && observer.error(last.error);\n } else if (last && last.result) {\n observer.next && observer.next(this.maskResult(last.result));\n }\n\n // Initiate observation of this query if it hasn't been reported to\n // the QueryManager yet.\n if (first) {\n // Blindly catching here prevents unhandled promise rejections,\n // and is safe because the ObservableQuery handles this error with\n // this.observer.error, so we're not just swallowing the error by\n // ignoring it here.\n this.reobserve().catch(() => {});\n }\n\n return () => {\n if (this.observers.delete(observer) && !this.observers.size) {\n this.tearDownQuery();\n }\n };\n });\n\n // related classes\n this.queryInfo = queryInfo;\n this.queryManager = queryManager;\n\n // active state\n this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);\n this.isTornDown = false;\n\n this.subscribeToMore = this.subscribeToMore.bind(this);\n this.maskResult = this.maskResult.bind(this);\n\n const {\n watchQuery: { fetchPolicy: defaultFetchPolicy = \"cache-first\" } = {},\n } = queryManager.defaultOptions;\n\n const {\n fetchPolicy = defaultFetchPolicy,\n // Make sure we don't store \"standby\" as the initialFetchPolicy.\n initialFetchPolicy = fetchPolicy === \"standby\" ? defaultFetchPolicy : (\n fetchPolicy\n ),\n } = options;\n\n this.options = {\n ...options,\n\n // Remember the initial options.fetchPolicy so we can revert back to this\n // policy when variables change. This information can also be specified\n // (or overridden) by providing options.initialFetchPolicy explicitly.\n initialFetchPolicy,\n\n // This ensures this.options.fetchPolicy always has a string value, in\n // case options.fetchPolicy was not provided.\n fetchPolicy,\n };\n\n this.queryId = queryInfo.queryId || queryManager.generateQueryId();\n\n const opDef = getOperationDefinition(this.query);\n this.queryName = opDef && opDef.name && opDef.name.value;\n }\n\n public result(): Promise>> {\n return new Promise((resolve, reject) => {\n // TODO: this code doesn’t actually make sense insofar as the observer\n // will never exist in this.observers due how zen-observable wraps observables.\n // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169\n const observer: Observer>> = {\n next: (result) => {\n resolve(result);\n\n // Stop the query within the QueryManager if we can before\n // this function returns.\n //\n // We do this in order to prevent observers piling up within\n // the QueryManager. Notice that we only fully unsubscribe\n // from the subscription in a setTimeout(..., 0) call. This call can\n // actually be handled by the browser at a much later time. If queries\n // are fired in the meantime, observers that should have been removed\n // from the QueryManager will continue to fire, causing an unnecessary\n // performance hit.\n this.observers.delete(observer);\n if (!this.observers.size) {\n this.queryManager.removeQuery(this.queryId);\n }\n\n setTimeout(() => {\n subscription.unsubscribe();\n }, 0);\n },\n error: reject,\n };\n const subscription = this.subscribe(observer);\n });\n }\n\n /** @internal */\n public resetDiff() {\n this.queryInfo.resetDiff();\n }\n\n private getCurrentFullResult(\n saveAsLastResult = true\n ): ApolloQueryResult {\n // Use the last result as long as the variables match this.variables.\n const lastResult = this.getLastResult(true);\n\n const networkStatus =\n this.queryInfo.networkStatus ||\n (lastResult && lastResult.networkStatus) ||\n NetworkStatus.ready;\n\n const result = {\n ...lastResult,\n loading: isNetworkRequestInFlight(networkStatus),\n networkStatus,\n } as ApolloQueryResult;\n\n const { fetchPolicy = \"cache-first\" } = this.options;\n if (\n // These fetch policies should never deliver data from the cache, unless\n // redelivering a previously delivered result.\n skipCacheDataFor(fetchPolicy) ||\n // If this.options.query has @client(always: true) fields, we cannot\n // trust diff.result, since it was read from the cache without running\n // local resolvers (and it's too late to run resolvers now, since we must\n // return a result synchronously).\n this.queryManager.getDocumentInfo(this.query).hasForcedResolvers\n ) {\n // Fall through.\n } else if (this.waitForOwnResult) {\n // This would usually be a part of `QueryInfo.getDiff()`.\n // which we skip in the waitForOwnResult case since we are not\n // interested in the diff.\n this.queryInfo[\"updateWatch\"]();\n } else {\n const diff = this.queryInfo.getDiff();\n\n if (diff.complete || this.options.returnPartialData) {\n result.data = diff.result;\n }\n\n if (equal(result.data, {})) {\n result.data = void 0 as any;\n }\n\n if (diff.complete) {\n // Similar to setting result.partial to false, but taking advantage of the\n // falsiness of missing fields.\n delete result.partial;\n\n // If the diff is complete, and we're using a FetchPolicy that\n // terminates after a complete cache read, we can assume the next result\n // we receive will have NetworkStatus.ready and !loading.\n if (\n diff.complete &&\n result.networkStatus === NetworkStatus.loading &&\n (fetchPolicy === \"cache-first\" || fetchPolicy === \"cache-only\")\n ) {\n result.networkStatus = NetworkStatus.ready;\n result.loading = false;\n }\n } else {\n result.partial = true;\n }\n\n // We need to check for both both `error` and `errors` field because there\n // are cases where sometimes `error` is set, but not `errors` and\n // vice-versa. This will be updated in the next major version when\n // `errors` is deprecated in favor of `error`.\n if (\n result.networkStatus === NetworkStatus.ready &&\n (result.error || result.errors)\n ) {\n result.networkStatus = NetworkStatus.error;\n }\n\n if (\n __DEV__ &&\n !diff.complete &&\n !this.options.partialRefetch &&\n !result.loading &&\n !result.data &&\n !result.error\n ) {\n logMissingFieldErrors(diff.missing);\n }\n }\n\n if (saveAsLastResult) {\n this.updateLastResult(result);\n }\n\n return result;\n }\n\n public getCurrentResult(\n saveAsLastResult = true\n ): ApolloQueryResult> {\n return this.maskResult(this.getCurrentFullResult(saveAsLastResult));\n }\n\n // Compares newResult to the snapshot we took of this.lastResult when it was\n // first received.\n public isDifferentFromLastResult(\n newResult: ApolloQueryResult,\n variables?: TVariables\n ) {\n if (!this.last) {\n return true;\n }\n\n const documentInfo = this.queryManager.getDocumentInfo(this.query);\n const dataMasking = this.queryManager.dataMasking;\n const query = dataMasking ? documentInfo.nonReactiveQuery : this.query;\n\n const resultIsDifferent =\n dataMasking || documentInfo.hasNonreactiveDirective ?\n !equalByQuery(query, this.last.result, newResult, this.variables)\n : !equal(this.last.result, newResult);\n\n return (\n resultIsDifferent || (variables && !equal(this.last.variables, variables))\n );\n }\n\n private getLast>(\n key: K,\n variablesMustMatch?: boolean\n ) {\n const last = this.last;\n if (\n last &&\n last[key] &&\n (!variablesMustMatch || equal(last.variables, this.variables))\n ) {\n return last[key];\n }\n }\n\n public getLastResult(\n variablesMustMatch?: boolean\n ): ApolloQueryResult | undefined {\n return this.getLast(\"result\", variablesMustMatch);\n }\n\n public getLastError(variablesMustMatch?: boolean): ApolloError | undefined {\n return this.getLast(\"error\", variablesMustMatch);\n }\n\n public resetLastResults(): void {\n delete this.last;\n this.isTornDown = false;\n }\n\n public resetQueryStoreErrors() {\n this.queryManager.resetErrors(this.queryId);\n }\n\n /**\n * Update the variables of this observable query, and fetch the new results.\n * This method should be preferred over `setVariables` in most use cases.\n *\n * @param variables - The new set of variables. If there are missing variables,\n * the previous values of those variables will be used.\n */\n public refetch(\n variables?: Partial\n ): Promise>> {\n const reobserveOptions: Partial> = {\n // Always disable polling for refetches.\n pollInterval: 0,\n };\n\n // Unless the provided fetchPolicy always consults the network\n // (no-cache, network-only, or cache-and-network), override it with\n // network-only to force the refetch for this fetchQuery call.\n const { fetchPolicy } = this.options;\n if (fetchPolicy === \"no-cache\") {\n reobserveOptions.fetchPolicy = \"no-cache\";\n } else {\n reobserveOptions.fetchPolicy = \"network-only\";\n }\n\n if (__DEV__ && variables && hasOwnProperty.call(variables, \"variables\")) {\n const queryDef = getQueryDefinition(this.query);\n const vars = queryDef.variableDefinitions;\n if (!vars || !vars.some((v) => v.variable.name.value === \"variables\")) {\n invariant.warn(\n `Called refetch(%o) for query %o, which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?`,\n variables,\n queryDef.name?.value || queryDef\n );\n }\n }\n\n if (variables && !equal(this.options.variables, variables)) {\n // Update the existing options with new variables\n reobserveOptions.variables = this.options.variables = {\n ...this.options.variables,\n ...variables,\n } as TVariables;\n }\n\n this.queryInfo.resetLastWrite();\n return this.reobserve(reobserveOptions, NetworkStatus.refetch);\n }\n\n /**\n * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).\n */\n public fetchMore<\n TFetchData = TData,\n TFetchVars extends OperationVariables = TVariables,\n >(\n fetchMoreOptions: FetchMoreQueryOptions & {\n updateQuery?: (\n previousQueryResult: Unmasked,\n options: {\n fetchMoreResult: Unmasked;\n variables: TFetchVars;\n }\n ) => Unmasked;\n }\n ): Promise>> {\n const combinedOptions = {\n ...(fetchMoreOptions.query ? fetchMoreOptions : (\n {\n ...this.options,\n query: this.options.query,\n ...fetchMoreOptions,\n variables: {\n ...this.options.variables,\n ...fetchMoreOptions.variables,\n },\n }\n )),\n // The fetchMore request goes immediately to the network and does\n // not automatically write its result to the cache (hence no-cache\n // instead of network-only), because we allow the caller of\n // fetchMore to provide an updateQuery callback that determines how\n // the data gets written to the cache.\n fetchPolicy: \"no-cache\",\n } as WatchQueryOptions;\n\n combinedOptions.query = this.transformDocument(combinedOptions.query);\n\n const qid = this.queryManager.generateQueryId();\n\n // If a temporary query is passed to `fetchMore`, we don't want to store\n // it as the last query result since it may be an optimized query for\n // pagination. We will however run the transforms on the original document\n // as well as the document passed in `fetchMoreOptions` to ensure the cache\n // uses the most up-to-date document which may rely on runtime conditionals.\n this.lastQuery =\n fetchMoreOptions.query ?\n this.transformDocument(this.options.query)\n : combinedOptions.query;\n\n // Simulate a loading result for the original query with\n // result.networkStatus === NetworkStatus.fetchMore.\n const { queryInfo } = this;\n const originalNetworkStatus = queryInfo.networkStatus;\n queryInfo.networkStatus = NetworkStatus.fetchMore;\n if (combinedOptions.notifyOnNetworkStatusChange) {\n this.observe();\n }\n\n const updatedQuerySet = new Set();\n\n const updateQuery = fetchMoreOptions?.updateQuery;\n const isCached = this.options.fetchPolicy !== \"no-cache\";\n\n if (!isCached) {\n invariant(\n updateQuery,\n \"You must provide an `updateQuery` function when using `fetchMore` with a `no-cache` fetch policy.\"\n );\n }\n\n return this.queryManager\n .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)\n .then((fetchMoreResult) => {\n this.queryManager.removeQuery(qid);\n\n if (queryInfo.networkStatus === NetworkStatus.fetchMore) {\n queryInfo.networkStatus = originalNetworkStatus;\n }\n\n if (isCached) {\n // Performing this cache update inside a cache.batch transaction ensures\n // any affected cache.watch watchers are notified at most once about any\n // updates. Most watchers will be using the QueryInfo class, which\n // responds to notifications by calling reobserveCacheFirst to deliver\n // fetchMore cache results back to this ObservableQuery.\n this.queryManager.cache.batch({\n update: (cache) => {\n const { updateQuery } = fetchMoreOptions;\n if (updateQuery) {\n cache.updateQuery(\n {\n query: this.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n },\n (previous) =>\n updateQuery(previous! as any, {\n fetchMoreResult: fetchMoreResult.data as any,\n variables: combinedOptions.variables as TFetchVars,\n })\n );\n } else {\n // If we're using a field policy instead of updateQuery, the only\n // thing we need to do is write the new data to the cache using\n // combinedOptions.variables (instead of this.variables, which is\n // what this.updateQuery uses, because it works by abusing the\n // original field value, keyed by the original variables).\n cache.writeQuery({\n query: combinedOptions.query,\n variables: combinedOptions.variables,\n data: fetchMoreResult.data as Unmasked,\n });\n }\n },\n\n onWatchUpdated: (watch) => {\n // Record the DocumentNode associated with any watched query whose\n // data were updated by the cache writes above.\n updatedQuerySet.add(watch.query);\n },\n });\n } else {\n // There is a possibility `lastResult` may not be set when\n // `fetchMore` is called which would cause this to crash. This should\n // only happen if we haven't previously reported a result. We don't\n // quite know what the right behavior should be here since this block\n // of code runs after the fetch result has executed on the network.\n // We plan to let it crash in the meantime.\n //\n // If we get bug reports due to the `data` property access on\n // undefined, this should give us a real-world scenario that we can\n // use to test against and determine the right behavior. If we do end\n // up changing this behavior, this may require, for example, an\n // adjustment to the types on `updateQuery` since that function\n // expects that the first argument always contains previous result\n // data, but not `undefined`.\n const lastResult = this.getLast(\"result\")!;\n const data = updateQuery!(lastResult.data as Unmasked, {\n fetchMoreResult: fetchMoreResult.data as Unmasked,\n variables: combinedOptions.variables as TFetchVars,\n });\n\n this.reportResult(\n {\n ...lastResult,\n networkStatus: originalNetworkStatus!,\n loading: isNetworkRequestInFlight(originalNetworkStatus),\n data: data as TData,\n },\n this.variables\n );\n }\n\n return this.maskResult(fetchMoreResult);\n })\n .finally(() => {\n // In case the cache writes above did not generate a broadcast\n // notification (which would have been intercepted by onWatchUpdated),\n // likely because the written data were the same as what was already in\n // the cache, we still want fetchMore to deliver its final loading:false\n // result with the unchanged data.\n if (isCached && !updatedQuerySet.has(this.query)) {\n reobserveCacheFirst(this);\n }\n });\n }\n\n // XXX the subscription variables are separate from the query variables.\n // if you want to update subscription variables, right now you have to do that separately,\n // and you can only do it by stopping the subscription and then subscribing again with new variables.\n /**\n * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.\n *\n * This function returns _another_ function that you can call to terminate the subscription.\n */\n public subscribeToMore<\n TSubscriptionData = TData,\n TSubscriptionVariables extends OperationVariables = TVariables,\n >(\n options: SubscribeToMoreOptions<\n TData,\n TSubscriptionVariables,\n TSubscriptionData,\n TVariables\n >\n ): () => void {\n const subscription = this.queryManager\n .startGraphQLSubscription({\n query: options.document,\n variables: options.variables,\n context: options.context,\n })\n .subscribe({\n next: (subscriptionData: { data: Unmasked }) => {\n const { updateQuery } = options;\n if (updateQuery) {\n this.updateQuery((previous, updateOptions) =>\n updateQuery(previous, {\n subscriptionData,\n ...updateOptions,\n })\n );\n }\n },\n error: (err: any) => {\n if (options.onError) {\n options.onError(err);\n return;\n }\n invariant.error(\"Unhandled GraphQL subscription error\", err);\n },\n });\n\n this.subscriptions.add(subscription);\n\n return () => {\n if (this.subscriptions.delete(subscription)) {\n subscription.unsubscribe();\n }\n };\n }\n\n public setOptions(\n newOptions: Partial>\n ): Promise>> {\n return this.reobserve(newOptions);\n }\n\n public silentSetOptions(\n newOptions: Partial>\n ) {\n const mergedOptions = compact(this.options, newOptions || {});\n assign(this.options, mergedOptions);\n }\n\n /**\n * Update the variables of this observable query, and fetch the new results\n * if they've changed. Most users should prefer `refetch` instead of\n * `setVariables` in order to to be properly notified of results even when\n * they come from the cache.\n *\n * Note: the `next` callback will *not* fire if the variables have not changed\n * or if the result is coming from cache.\n *\n * Note: the promise will return the old results immediately if the variables\n * have not changed.\n *\n * Note: the promise will return null immediately if the query is not active\n * (there are no subscribers).\n *\n * @param variables - The new set of variables. If there are missing variables,\n * the previous values of those variables will be used.\n */\n public setVariables(\n variables: TVariables\n ): Promise> | void> {\n if (equal(this.variables, variables)) {\n // If we have no observers, then we don't actually want to make a network\n // request. As soon as someone observes the query, the request will kick\n // off. For now, we just store any changes. (See #1077)\n return this.observers.size ? this.result() : Promise.resolve();\n }\n\n this.options.variables = variables;\n\n // See comment above\n if (!this.observers.size) {\n return Promise.resolve();\n }\n\n return this.reobserve(\n {\n // Reset options.fetchPolicy to its original value.\n fetchPolicy: this.options.initialFetchPolicy,\n variables,\n },\n NetworkStatus.setVariables\n );\n }\n\n /**\n * A function that enables you to update the query's cached result without executing a followup GraphQL operation.\n *\n * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.\n */\n public updateQuery(mapFn: UpdateQueryMapFn): void {\n const { queryManager } = this;\n const { result, complete } = queryManager.cache.diff({\n query: this.options.query,\n variables: this.variables,\n returnPartialData: true,\n optimistic: false,\n });\n\n const newResult = mapFn(\n result! as Unmasked,\n {\n variables: this.variables,\n complete: !!complete,\n previousData: result,\n } as UpdateQueryOptions\n );\n\n if (newResult) {\n queryManager.cache.writeQuery({\n query: this.options.query,\n data: newResult,\n variables: this.variables,\n });\n\n queryManager.broadcastQueries();\n }\n }\n\n /**\n * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).\n */\n public startPolling(pollInterval: number) {\n this.options.pollInterval = pollInterval;\n this.updatePolling();\n }\n\n /**\n * A function that instructs the query to stop polling after a previous call to `startPolling`.\n */\n public stopPolling() {\n this.options.pollInterval = 0;\n this.updatePolling();\n }\n\n // Update options.fetchPolicy according to options.nextFetchPolicy.\n private applyNextFetchPolicy(\n reason: NextFetchPolicyContext[\"reason\"],\n // It's possible to use this method to apply options.nextFetchPolicy to\n // options.fetchPolicy even if options !== this.options, though that happens\n // most often when the options are temporary, used for only one request and\n // then thrown away, so nextFetchPolicy may not end up mattering.\n options: WatchQueryOptions\n ) {\n if (options.nextFetchPolicy) {\n const { fetchPolicy = \"cache-first\", initialFetchPolicy = fetchPolicy } =\n options;\n\n if (fetchPolicy === \"standby\") {\n // Do nothing, leaving options.fetchPolicy unchanged.\n } else if (typeof options.nextFetchPolicy === \"function\") {\n // When someone chooses \"cache-and-network\" or \"network-only\" as their\n // initial FetchPolicy, they often do not want future cache updates to\n // trigger unconditional network requests, which is what repeatedly\n // applying the \"cache-and-network\" or \"network-only\" policies would\n // seem to imply. Instead, when the cache reports an update after the\n // initial network request, it may be desirable for subsequent network\n // requests to be triggered only if the cache result is incomplete. To\n // that end, the options.nextFetchPolicy option provides an easy way to\n // update options.fetchPolicy after the initial network request, without\n // having to call observableQuery.setOptions.\n options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {\n reason,\n options,\n observable: this,\n initialFetchPolicy,\n });\n } else if (reason === \"variables-changed\") {\n options.fetchPolicy = initialFetchPolicy;\n } else {\n options.fetchPolicy = options.nextFetchPolicy;\n }\n }\n\n return options.fetchPolicy;\n }\n\n private fetch(\n options: WatchQueryOptions,\n newNetworkStatus?: NetworkStatus,\n query?: DocumentNode\n ) {\n // TODO Make sure we update the networkStatus (and infer fetchVariables)\n // before actually committing to the fetch.\n this.queryManager.setObservableQuery(this);\n return this.queryManager[\"fetchConcastWithInfo\"](\n this.queryId,\n options,\n newNetworkStatus,\n query\n );\n }\n\n // Turns polling on or off based on this.options.pollInterval.\n private updatePolling() {\n // Avoid polling in SSR mode\n if (this.queryManager.ssrMode) {\n return;\n }\n\n const {\n pollingInfo,\n options: { pollInterval },\n } = this;\n\n if (!pollInterval || !this.hasObservers()) {\n if (pollingInfo) {\n clearTimeout(pollingInfo.timeout);\n delete this.pollingInfo;\n }\n return;\n }\n\n if (pollingInfo && pollingInfo.interval === pollInterval) {\n return;\n }\n\n invariant(\n pollInterval,\n \"Attempted to start a polling query without a polling interval.\"\n );\n\n const info = pollingInfo || (this.pollingInfo = {} as any);\n info.interval = pollInterval;\n\n const maybeFetch = () => {\n if (this.pollingInfo) {\n if (\n !isNetworkRequestInFlight(this.queryInfo.networkStatus) &&\n !this.options.skipPollAttempt?.()\n ) {\n this.reobserve(\n {\n // Most fetchPolicy options don't make sense to use in a polling context, as\n // users wouldn't want to be polling the cache directly. However, network-only and\n // no-cache are both useful for when the user wants to control whether or not the\n // polled results are written to the cache.\n fetchPolicy:\n this.options.initialFetchPolicy === \"no-cache\" ?\n \"no-cache\"\n : \"network-only\",\n },\n NetworkStatus.poll\n ).then(poll, poll);\n } else {\n poll();\n }\n }\n };\n\n const poll = () => {\n const info = this.pollingInfo;\n if (info) {\n clearTimeout(info.timeout);\n info.timeout = setTimeout(maybeFetch, info.interval);\n }\n };\n\n poll();\n }\n\n private updateLastResult(\n newResult: ApolloQueryResult,\n variables = this.variables\n ) {\n let error: ApolloError | undefined = this.getLastError();\n // Preserve this.last.error unless the variables have changed.\n if (error && this.last && !equal(variables, this.last.variables)) {\n error = void 0;\n }\n return (this.last = {\n result:\n this.queryManager.assumeImmutableResults ?\n newResult\n : cloneDeep(newResult),\n variables,\n ...(error ? { error } : null),\n });\n }\n\n public reobserveAsConcast(\n newOptions?: Partial>,\n newNetworkStatus?: NetworkStatus\n ): Concast> {\n this.isTornDown = false;\n\n const useDisposableConcast =\n // Refetching uses a disposable Concast to allow refetches using different\n // options/variables, without permanently altering the options of the\n // original ObservableQuery.\n newNetworkStatus === NetworkStatus.refetch ||\n // The fetchMore method does not actually call the reobserve method, but,\n // if it did, it would definitely use a disposable Concast.\n newNetworkStatus === NetworkStatus.fetchMore ||\n // Polling uses a disposable Concast so the polling options (which force\n // fetchPolicy to be \"network-only\" or \"no-cache\") won't override the original options.\n newNetworkStatus === NetworkStatus.poll;\n\n // Save the old variables, since Object.assign may modify them below.\n const oldVariables = this.options.variables;\n const oldFetchPolicy = this.options.fetchPolicy;\n\n const mergedOptions = compact(this.options, newOptions || {});\n const options =\n useDisposableConcast ?\n // Disposable Concast fetches receive a shallow copy of this.options\n // (merged with newOptions), leaving this.options unmodified.\n mergedOptions\n : assign(this.options, mergedOptions);\n\n // Don't update options.query with the transformed query to avoid\n // overwriting this.options.query when we aren't using a disposable concast.\n // We want to ensure we can re-run the custom document transforms the next\n // time a request is made against the original query.\n const query = this.transformDocument(options.query);\n\n this.lastQuery = query;\n\n if (!useDisposableConcast) {\n // We can skip calling updatePolling if we're not changing this.options.\n this.updatePolling();\n\n // Reset options.fetchPolicy to its original value when variables change,\n // unless a new fetchPolicy was provided by newOptions.\n if (\n newOptions &&\n newOptions.variables &&\n !equal(newOptions.variables, oldVariables) &&\n // Don't mess with the fetchPolicy if it's currently \"standby\".\n options.fetchPolicy !== \"standby\" &&\n // If we're changing the fetchPolicy anyway, don't try to change it here\n // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.\n (options.fetchPolicy === oldFetchPolicy ||\n // A `nextFetchPolicy` function has even higher priority, though,\n // so in that case `applyNextFetchPolicy` must be called.\n typeof options.nextFetchPolicy === \"function\")\n ) {\n this.applyNextFetchPolicy(\"variables-changed\", options);\n if (newNetworkStatus === void 0) {\n newNetworkStatus = NetworkStatus.setVariables;\n }\n }\n }\n\n this.waitForOwnResult &&= skipCacheDataFor(options.fetchPolicy);\n const finishWaitingForOwnResult = () => {\n if (this.concast === concast) {\n this.waitForOwnResult = false;\n }\n };\n\n const variables = options.variables && { ...options.variables };\n const { concast, fromLink } = this.fetch(options, newNetworkStatus, query);\n const observer: Observer> = {\n next: (result) => {\n if (equal(this.variables, variables)) {\n finishWaitingForOwnResult();\n this.reportResult(result, variables);\n }\n },\n error: (error) => {\n if (equal(this.variables, variables)) {\n // Coming from `getResultsFromLink`, `error` here should always be an `ApolloError`.\n // However, calling `concast.cancel` can inject another type of error, so we have to\n // wrap it again here.\n if (!isApolloError(error)) {\n error = new ApolloError({ networkError: error });\n }\n finishWaitingForOwnResult();\n this.reportError(error, variables);\n }\n },\n };\n\n if (!useDisposableConcast && (fromLink || !this.concast)) {\n // We use the {add,remove}Observer methods directly to avoid wrapping\n // observer with an unnecessary SubscriptionObserver object.\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n }\n\n this.concast = concast;\n this.observer = observer;\n }\n\n concast.addObserver(observer);\n\n return concast;\n }\n\n public reobserve(\n newOptions?: Partial>,\n newNetworkStatus?: NetworkStatus\n ): Promise>> {\n return preventUnhandledRejection(\n this.reobserveAsConcast(newOptions, newNetworkStatus).promise.then(\n this.maskResult as TODO\n )\n );\n }\n\n public resubscribeAfterError(\n onNext: (value: ApolloQueryResult>) => void,\n onError?: (error: any) => void,\n onComplete?: () => void\n ): ObservableSubscription;\n\n public resubscribeAfterError(\n observer: Observer>\n ): ObservableSubscription;\n\n public resubscribeAfterError(...args: [any, any?, any?]) {\n // If `lastError` is set in the current when the subscription is re-created,\n // the subscription will immediately receive the error, which will\n // cause it to terminate again. To avoid this, we first clear\n // the last error/result from the `observableQuery` before re-starting\n // the subscription, and restore the last value afterwards so that the\n // subscription has a chance to stay open.\n const last = this.last;\n this.resetLastResults();\n\n const subscription = this.subscribe(...args);\n this.last = last;\n\n return subscription;\n }\n\n // (Re)deliver the current result to this.observers without applying fetch\n // policies or making network requests.\n private observe() {\n this.reportResult(\n // Passing false is important so that this.getCurrentResult doesn't\n // save the fetchMore result as this.lastResult, causing it to be\n // ignored due to the this.isDifferentFromLastResult check in\n // this.reportResult.\n this.getCurrentFullResult(false),\n this.variables\n );\n }\n\n private reportResult(\n result: ApolloQueryResult,\n variables: TVariables | undefined\n ) {\n const lastError = this.getLastError();\n const isDifferent = this.isDifferentFromLastResult(result, variables);\n // Update the last result even when isDifferentFromLastResult returns false,\n // because the query may be using the @nonreactive directive, and we want to\n // save the the latest version of any nonreactive subtrees (in case\n // getCurrentResult is called), even though we skip broadcasting changes.\n if (lastError || !result.partial || this.options.returnPartialData) {\n this.updateLastResult(result, variables);\n }\n if (lastError || isDifferent) {\n iterateObserversSafely(this.observers, \"next\", this.maskResult(result));\n }\n }\n\n private reportError(error: ApolloError, variables: TVariables | undefined) {\n // Since we don't get the current result on errors, only the error, we\n // must mirror the updates that occur in QueryStore.markQueryError here\n const errorResult = {\n ...this.getLastResult(),\n error,\n errors: error.graphQLErrors,\n networkStatus: NetworkStatus.error,\n loading: false,\n } as ApolloQueryResult;\n\n this.updateLastResult(errorResult, variables);\n\n iterateObserversSafely(this.observers, \"error\", (this.last!.error = error));\n }\n\n public hasObservers() {\n return this.observers.size > 0;\n }\n\n private tearDownQuery() {\n if (this.isTornDown) return;\n if (this.concast && this.observer) {\n this.concast.removeObserver(this.observer);\n delete this.concast;\n delete this.observer;\n }\n\n this.stopPolling();\n // stop all active GraphQL subscriptions\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n this.subscriptions.clear();\n this.queryManager.stopQuery(this.queryId);\n this.observers.clear();\n this.isTornDown = true;\n }\n\n private transformDocument(document: DocumentNode) {\n return this.queryManager.transform(document);\n }\n\n private maskResult(\n result: ApolloQueryResult\n ): ApolloQueryResult> {\n return result && \"data\" in result ?\n {\n ...result,\n data: this.queryManager.maskOperation({\n document: this.query,\n data: result.data,\n fetchPolicy: this.options.fetchPolicy,\n id: this.queryId,\n }),\n }\n : result;\n }\n}\n\n// Necessary because the ObservableQuery constructor has a different\n// signature than the Observable constructor.\nfixObservableSubclass(ObservableQuery);\n\n// Reobserve with fetchPolicy effectively set to \"cache-first\", triggering\n// delivery of any new data from the cache, possibly falling back to the network\n// if any cache data are missing. This allows _complete_ cache results to be\n// delivered without also kicking off unnecessary network requests when\n// this.options.fetchPolicy is \"cache-and-network\" or \"network-only\". When\n// this.options.fetchPolicy is any other policy (\"cache-first\", \"cache-only\",\n// \"standby\", or \"no-cache\"), we call this.reobserve() as usual.\nexport function reobserveCacheFirst(\n obsQuery: ObservableQuery\n) {\n const { fetchPolicy, nextFetchPolicy } = obsQuery.options;\n\n if (fetchPolicy === \"cache-and-network\" || fetchPolicy === \"network-only\") {\n return obsQuery.reobserve({\n fetchPolicy: \"cache-first\",\n // Use a temporary nextFetchPolicy function that replaces itself with the\n // previous nextFetchPolicy value and returns the original fetchPolicy.\n nextFetchPolicy(\n this: WatchQueryOptions,\n currentFetchPolicy: WatchQueryFetchPolicy,\n context: NextFetchPolicyContext\n ) {\n // Replace this nextFetchPolicy function in the options object with the\n // original this.options.nextFetchPolicy value.\n this.nextFetchPolicy = nextFetchPolicy;\n // If the original nextFetchPolicy value was a function, give it a\n // chance to decide what happens here.\n if (typeof this.nextFetchPolicy === \"function\") {\n return this.nextFetchPolicy(currentFetchPolicy, context);\n }\n // Otherwise go back to the original this.options.fetchPolicy.\n return fetchPolicy!;\n },\n });\n }\n\n return obsQuery.reobserve();\n}\n\nfunction defaultSubscriptionObserverErrorCallback(error: ApolloError) {\n invariant.error(\"Unhandled error\", error.message, error.stack);\n}\n\nexport function logMissingFieldErrors(\n missing: MissingFieldError[] | MissingTree | undefined\n) {\n if (__DEV__ && missing) {\n invariant.debug(`Missing cache result fields: %o`, missing);\n }\n}\n\nfunction skipCacheDataFor(\n fetchPolicy?: WatchQueryFetchPolicy /* `undefined` would mean `\"cache-first\"` */\n) {\n return (\n fetchPolicy === \"network-only\" ||\n fetchPolicy === \"no-cache\" ||\n fetchPolicy === \"standby\"\n );\n}\n","export function preventUnhandledRejection(promise: Promise): Promise {\n promise.catch(() => {});\n\n return promise;\n}\n","import equal from \"@wry/equality\";\n\nimport type {\n DirectiveNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n FragmentSpreadNode,\n InlineFragmentNode,\n SelectionNode,\n SelectionSetNode,\n} from \"graphql\";\n\nimport type { ApolloQueryResult, OperationVariables } from \"./types.js\";\n\nimport type { FragmentMap } from \"../utilities/index.js\";\nimport {\n createFragmentMap,\n getFragmentDefinitions,\n getFragmentFromSelection,\n getMainDefinition,\n isField,\n resultKeyNameFromField,\n shouldInclude,\n} from \"../utilities/index.js\";\n\n// Returns true if aResult and bResult are deeply equal according to the fields\n// selected by the given query, ignoring any fields marked as @nonreactive.\nexport function equalByQuery(\n query: DocumentNode,\n { data: aData, ...aRest }: Partial>,\n { data: bData, ...bRest }: Partial>,\n variables?: OperationVariables\n): boolean {\n return (\n equal(aRest, bRest) &&\n equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {\n fragmentMap: createFragmentMap(getFragmentDefinitions(query)),\n variables,\n })\n );\n}\n\n// Encapsulates the information used by equalBySelectionSet that does not change\n// during the recursion.\ninterface CompareContext {\n fragmentMap: FragmentMap;\n variables: TVariables | undefined;\n}\n\nfunction equalBySelectionSet(\n selectionSet: SelectionSetNode,\n aResult: any,\n bResult: any,\n context: CompareContext\n): boolean {\n if (aResult === bResult) {\n return true;\n }\n\n const seenSelections = new Set();\n\n // Returning true from this Array.prototype.every callback function skips the\n // current field/subtree. Returning false aborts the entire traversal\n // immediately, causing equalBySelectionSet to return false.\n return selectionSet.selections.every((selection) => {\n // Avoid re-processing the same selection at the same level of recursion, in\n // case the same field gets included via multiple indirect fragment spreads.\n if (seenSelections.has(selection)) return true;\n seenSelections.add(selection);\n\n // Ignore @skip(if: true) and @include(if: false) fields.\n if (!shouldInclude(selection, context.variables)) return true;\n\n // If the field or (named) fragment spread has a @nonreactive directive on\n // it, we don't care if it's different, so we pretend it's the same.\n if (selectionHasNonreactiveDirective(selection)) return true;\n\n if (isField(selection)) {\n const resultKey = resultKeyNameFromField(selection);\n const aResultChild = aResult && aResult[resultKey];\n const bResultChild = bResult && bResult[resultKey];\n const childSelectionSet = selection.selectionSet;\n\n if (!childSelectionSet) {\n // These are scalar values, so we can compare them with deep equal\n // without redoing the main recursive work.\n return equal(aResultChild, bResultChild);\n }\n\n const aChildIsArray = Array.isArray(aResultChild);\n const bChildIsArray = Array.isArray(bResultChild);\n if (aChildIsArray !== bChildIsArray) return false;\n if (aChildIsArray && bChildIsArray) {\n const length = aResultChild.length;\n if (bResultChild.length !== length) {\n return false;\n }\n for (let i = 0; i < length; ++i) {\n if (\n !equalBySelectionSet(\n childSelectionSet,\n aResultChild[i],\n bResultChild[i],\n context\n )\n ) {\n return false;\n }\n }\n return true;\n }\n\n return equalBySelectionSet(\n childSelectionSet,\n aResultChild,\n bResultChild,\n context\n );\n } else {\n const fragment = getFragmentFromSelection(selection, context.fragmentMap);\n if (fragment) {\n // The fragment might === selection if it's an inline fragment, but\n // could be !== if it's a named fragment ...spread.\n if (selectionHasNonreactiveDirective(fragment)) return true;\n\n return equalBySelectionSet(\n fragment.selectionSet,\n // Notice that we reuse the same aResult and bResult values here,\n // since the fragment ...spread does not specify a field name, but\n // consists of multiple fields (within the fragment's selection set)\n // that should be applied to the current result value(s).\n aResult,\n bResult,\n context\n );\n }\n }\n });\n}\n\nfunction selectionHasNonreactiveDirective(\n selection:\n | FieldNode\n | InlineFragmentNode\n | FragmentSpreadNode\n | FragmentDefinitionNode\n): boolean {\n return (\n !!selection.directives && selection.directives.some(directiveIsNonreactive)\n );\n}\n\nfunction directiveIsNonreactive(dir: DirectiveNode): boolean {\n return dir.name.value === \"nonreactive\";\n}\n","/**\n * The current status of a query’s execution in our system.\n */\nexport enum NetworkStatus {\n /**\n * The query has never been run before and the query is now currently running. A query will still\n * have this network status even if a partial data result was returned from the cache, but a\n * query was dispatched anyway.\n */\n loading = 1,\n\n /**\n * If `setVariables` was called and a query was fired because of that then the network status\n * will be `setVariables` until the result of that query comes back.\n */\n setVariables = 2,\n\n /**\n * Indicates that `fetchMore` was called on this query and that the query created is currently in\n * flight.\n */\n fetchMore = 3,\n\n /**\n * Similar to the `setVariables` network status. It means that `refetch` was called on a query\n * and the refetch request is currently in flight.\n */\n refetch = 4,\n\n /**\n * Indicates that a polling query is currently in flight. So for example if you are polling a\n * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever\n * a poll request has been sent but not resolved.\n */\n poll = 6,\n\n /**\n * No request is in flight for this query, and no errors happened. Everything is OK.\n */\n ready = 7,\n\n /**\n * No request is in flight for this query, but one or more errors were detected.\n */\n error = 8,\n}\n\n/**\n * Returns true if there is currently a network request in flight according to a given network\n * status.\n */\nexport function isNetworkRequestInFlight(\n networkStatus?: NetworkStatus\n): boolean {\n return networkStatus ? networkStatus < 7 : false;\n}\n\n/**\n * Returns true if the network request is in ready or error state according to a given network\n * status.\n */\nexport function isNetworkRequestSettled(\n networkStatus?: NetworkStatus\n): boolean {\n return networkStatus === 7 || networkStatus === 8;\n}\n","import \"../utilities/globals/index.js\";\n\nimport type {\n GraphQLError,\n GraphQLErrorExtensions,\n GraphQLFormattedError,\n} from \"graphql\";\n\nimport { isNonNullObject } from \"../utilities/index.js\";\nimport type { ServerParseError } from \"../link/http/index.js\";\nimport type { ServerError } from \"../link/utils/index.js\";\nimport type { FetchResult } from \"../link/core/index.js\";\n\n// This Symbol allows us to pass transport-specific errors from the link chain\n// into QueryManager/client internals without risking a naming collision within\n// extensions (which implementers can use as they see fit).\nexport const PROTOCOL_ERRORS_SYMBOL: unique symbol = Symbol();\n\ntype FetchResultWithSymbolExtensions = FetchResult & {\n extensions: Record;\n};\n\nexport interface ApolloErrorOptions {\n graphQLErrors?: ReadonlyArray;\n protocolErrors?: ReadonlyArray;\n clientErrors?: ReadonlyArray;\n networkError?: Error | ServerParseError | ServerError | null;\n errorMessage?: string;\n extraInfo?: any;\n}\n\nexport function graphQLResultHasProtocolErrors(\n result: FetchResult\n): result is FetchResultWithSymbolExtensions {\n if (result.extensions) {\n return Array.isArray(\n (result as FetchResultWithSymbolExtensions).extensions[\n PROTOCOL_ERRORS_SYMBOL\n ]\n );\n }\n return false;\n}\n\nexport function isApolloError(err: Error): err is ApolloError {\n return err.hasOwnProperty(\"graphQLErrors\");\n}\n\n// Sets the error message on this error according to the\n// the GraphQL and network errors that are present.\n// If the error message has already been set through the\n// constructor or otherwise, this function is a nop.\nconst generateErrorMessage = (err: ApolloError) => {\n const errors = [\n ...err.graphQLErrors,\n ...err.clientErrors,\n ...err.protocolErrors,\n ];\n if (err.networkError) errors.push(err.networkError);\n return (\n errors\n // The rest of the code sometimes unsafely types non-Error objects as GraphQLErrors\n .map(\n (err) =>\n (isNonNullObject(err) && err.message) || \"Error message not found.\"\n )\n .join(\"\\n\")\n );\n};\n\n/**\n * @deprecated This type is deprecated and will be removed in the next major version of Apollo Client.\n * It mistakenly referenced `GraqhQLError` instead of `GraphQLFormattedError`.\n *\n * Use `ReadonlyArray` instead.\n */\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport type GraphQLErrors = ReadonlyArray;\n\nexport type NetworkError = Error | ServerParseError | ServerError | null;\n\nexport class ApolloError extends Error {\n public name: string;\n public message: string;\n public graphQLErrors: ReadonlyArray;\n public protocolErrors: ReadonlyArray;\n public clientErrors: ReadonlyArray;\n public networkError: Error | ServerParseError | ServerError | null;\n /**\n * Indicates the specific original cause of the error.\n *\n * This field contains the first available `networkError`, `graphQLError`, `protocolError`, `clientError`, or `null` if none are available.\n */\n public cause:\n | ({\n readonly message: string;\n extensions?:\n | GraphQLErrorExtensions[]\n | GraphQLFormattedError[\"extensions\"];\n } & Omit & Partial, \"extensions\">)\n | null;\n\n // An object that can be used to provide some additional information\n // about an error, e.g. specifying the type of error this is. Used\n // internally within Apollo Client.\n public extraInfo: any;\n\n // Constructs an instance of ApolloError given serialized GraphQL errors,\n // client errors, protocol errors or network errors.\n // Note that one of these has to be a valid\n // value or the constructed error will be meaningless.\n constructor({\n graphQLErrors,\n protocolErrors,\n clientErrors,\n networkError,\n errorMessage,\n extraInfo,\n }: ApolloErrorOptions) {\n super(errorMessage);\n this.name = \"ApolloError\";\n this.graphQLErrors = graphQLErrors || [];\n this.protocolErrors = protocolErrors || [];\n this.clientErrors = clientErrors || [];\n this.networkError = networkError || null;\n this.message = errorMessage || generateErrorMessage(this);\n this.extraInfo = extraInfo;\n this.cause =\n [\n networkError,\n ...(graphQLErrors || []),\n ...(protocolErrors || []),\n ...(clientErrors || []),\n ].find((e) => !!e) || null;\n\n // We're not using `Object.setPrototypeOf` here as it isn't fully\n // supported on Android (see issue #3236).\n (this as any).__proto__ = ApolloError.prototype;\n }\n}\n","import { DataProxy } from \"./DataProxy.js\";\nimport type { AllFieldsModifier, Modifiers } from \"./common.js\";\nimport type { ApolloCache } from \"../cache.js\";\nimport type { Unmasked } from \"../../../masking/index.js\";\n\nexport namespace Cache {\n export type WatchCallback = (\n diff: Cache.DiffResult,\n lastDiff?: Cache.DiffResult\n ) => void;\n\n export interface ReadOptions\n extends DataProxy.Query {\n rootId?: string;\n previousResult?: any;\n optimistic: boolean;\n returnPartialData?: boolean;\n /**\n * @deprecated\n * Using `canonizeResults` can result in memory leaks so we generally do not\n * recommend using this option anymore.\n * A future version of Apollo Client will contain a similar feature without\n * the risk of memory leaks.\n */\n canonizeResults?: boolean;\n }\n\n export interface WriteOptions\n extends Omit, \"id\">,\n Omit, \"data\"> {\n dataId?: string;\n result: Unmasked;\n }\n\n export interface DiffOptions\n extends Omit, \"rootId\"> {\n // The DiffOptions interface is currently just an alias for\n // ReadOptions, though DiffOptions used to be responsible for\n // declaring the returnPartialData option.\n }\n\n export interface WatchOptions\n extends DiffOptions {\n watcher?: object;\n immediate?: boolean;\n callback: WatchCallback;\n lastDiff?: DiffResult;\n }\n\n export interface EvictOptions {\n id?: string;\n fieldName?: string;\n args?: Record;\n broadcast?: boolean;\n }\n\n // Although you can call cache.reset() without options, its behavior can be\n // configured by passing a Cache.ResetOptions object.\n export interface ResetOptions {\n discardWatches?: boolean;\n }\n\n export interface ModifyOptions<\n Entity extends Record = Record,\n > {\n id?: string;\n fields: Modifiers | AllFieldsModifier;\n optimistic?: boolean;\n broadcast?: boolean;\n }\n\n export interface BatchOptions<\n TCache extends ApolloCache,\n TUpdateResult = void,\n > {\n // Same as the first parameter of performTransaction, except the cache\n // argument will have the subclass type rather than ApolloCache.\n update(cache: TCache): TUpdateResult;\n\n // Passing a string for this option creates a new optimistic layer, with the\n // given string as its layer.id, just like passing a string for the\n // optimisticId parameter of performTransaction. Passing true is the same as\n // passing undefined to performTransaction (running the batch operation\n // against the current top layer of the cache), and passing false is the\n // same as passing null (running the operation against root/non-optimistic\n // cache data).\n optimistic?: string | boolean;\n\n // If you specify the ID of an optimistic layer using this option, that\n // layer will be removed as part of the batch transaction, triggering at\n // most one broadcast for both the transaction and the removal of the layer.\n // Note: this option is needed because calling cache.removeOptimistic during\n // the transaction function may not be not safe, since any modifications to\n // cache layers may be discarded after the transaction finishes.\n removeOptimistic?: string;\n\n // If you want to find out which watched queries were invalidated during\n // this batch operation, pass this optional callback function. Returning\n // false from the callback will prevent broadcasting this result.\n onWatchUpdated?: (\n this: TCache,\n watch: Cache.WatchOptions,\n diff: Cache.DiffResult,\n lastDiff?: Cache.DiffResult | undefined\n ) => any;\n }\n\n export import DiffResult = DataProxy.DiffResult;\n export import ReadQueryOptions = DataProxy.ReadQueryOptions;\n export import ReadFragmentOptions = DataProxy.ReadFragmentOptions;\n export import WriteQueryOptions = DataProxy.WriteQueryOptions;\n export import WriteFragmentOptions = DataProxy.WriteFragmentOptions;\n export import UpdateQueryOptions = DataProxy.UpdateQueryOptions;\n export import UpdateFragmentOptions = DataProxy.UpdateFragmentOptions;\n export import Fragment = DataProxy.Fragment;\n}\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const empty = ApolloLink.empty;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const from = ApolloLink.from;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const split = ApolloLink.split;\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const concat = ApolloLink.concat;\n","/**\n * @deprecated\n * This is not used internally any more and will be removed in\n * the next major version of Apollo Client.\n */\nexport const createSignalIfSupported = () => {\n if (typeof AbortController === \"undefined\")\n return { controller: false, signal: false };\n\n const controller = new AbortController();\n const signal = controller.signal;\n return { controller, signal };\n};\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport type { Observable } from \"../../utilities/index.js\";\n\nexport function toPromise(observable: Observable): Promise {\n let completed = false;\n return new Promise((resolve, reject) => {\n observable.subscribe({\n next: (data) => {\n if (completed) {\n invariant.warn(\n `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","import { Observable } from \"../../utilities/index.js\";\n\nexport function fromPromise(promise: Promise): Observable {\n return new Observable((observer) => {\n promise\n .then((value: T) => {\n observer.next(value);\n observer.complete();\n })\n .catch(observer.error.bind(observer));\n });\n}\n","/* Core */\n\nexport type { ApolloClientOptions, DefaultOptions } from \"./ApolloClient.js\";\nexport { ApolloClient, mergeOptions } from \"./ApolloClient.js\";\nexport type { FetchMoreOptions } from \"./ObservableQuery.js\";\nexport { ObservableQuery } from \"./ObservableQuery.js\";\nexport type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n SubscriptionOptions,\n FetchPolicy,\n WatchQueryFetchPolicy,\n MutationFetchPolicy,\n RefetchWritePolicy,\n ErrorPolicy,\n FetchMoreQueryOptions,\n SubscribeToMoreOptions,\n SubscribeToMoreFunction,\n UpdateQueryMapFn,\n UpdateQueryOptions,\n SubscribeToMoreUpdateQueryFn,\n} from \"./watchQueryOptions.js\";\nexport { NetworkStatus, isNetworkRequestSettled } from \"./networkStatus.js\";\nexport type * from \"./types.js\";\nexport type { Resolver, FragmentMatcher } from \"./LocalState.js\";\nexport { isApolloError, ApolloError } from \"../errors/index.js\";\n/* Cache */\n\nexport type {\n // All the exports (types) from ../cache, minus cacheSlot,\n // which we want to keep semi-private.\n Transaction,\n DataProxy,\n InMemoryCacheConfig,\n ReactiveVar,\n TypePolicies,\n TypePolicy,\n FieldPolicy,\n FieldReadFunction,\n FieldMergeFunction,\n FieldFunctionOptions,\n PossibleTypesMap,\n WatchFragmentOptions,\n WatchFragmentResult,\n} from \"../cache/index.js\";\nexport {\n Cache,\n ApolloCache,\n InMemoryCache,\n MissingFieldError,\n defaultDataIdFromObject,\n makeVar,\n} from \"../cache/index.js\";\n\nexport type * from \"../cache/inmemory/types.js\";\n\n/* Link */\n\nexport * from \"../link/core/index.js\";\nexport * from \"../link/http/index.js\";\nexport type { ServerError } from \"../link/utils/index.js\";\nexport {\n fromError,\n toPromise,\n fromPromise,\n throwServerError,\n} from \"../link/utils/index.js\";\n\n/* Masking */\nexport type {\n DataMasking,\n FragmentType,\n Masked,\n MaskedDocumentNode,\n MaybeMasked,\n Unmasked,\n} from \"../masking/index.js\";\n\n/* Utilities */\n\nexport type {\n DocumentTransformCacheKey,\n Observer,\n ObservableSubscription,\n Reference,\n StoreObject,\n} from \"../utilities/index.js\";\nexport {\n DocumentTransform,\n Observable,\n isReference,\n makeReference,\n} from \"../utilities/index.js\";\n\n/* Supporting */\n\n// The verbosity of invariant.{log,warn,error} can be controlled globally\n// (for anyone using the same ts-invariant package) by passing \"log\",\n// \"warn\", \"error\", or \"silent\" to setVerbosity (\"log\" is the default).\n// Note that all invariant.* logging is hidden in production.\nimport { setVerbosity } from \"ts-invariant\";\nexport { setVerbosity as setLogVerbosity };\nsetVerbosity(__DEV__ ? \"log\" : \"silent\");\n\n// Note that importing `gql` by itself, then destructuring\n// additional properties separately before exporting, is intentional.\n// Due to the way the `graphql-tag` library is setup, certain bundlers\n// can't find the properties added to the exported `gql` function without\n// additional guidance (e.g. Rollup - see\n// https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module).\n// Instead of having people that are using bundlers with `@apollo/client` add\n// extra bundler config to help `graphql-tag` exports be found (which would be\n// awkward since they aren't importing `graphql-tag` themselves), this\n// workaround of pulling the extra properties off the `gql` function,\n// then re-exporting them separately, helps keeps bundlers happy without any\n// additional config changes.\nexport {\n gql,\n resetCaches,\n disableFragmentWarnings,\n enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables,\n} from \"graphql-tag\";\n","import type { DocumentNode } from \"graphql\";\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport * as React from \"rehackt\";\n\nimport type {\n ApolloClient,\n ApolloQueryResult,\n ObservableQuery,\n OperationVariables,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { mergeOptions } from \"../../utilities/index.js\";\nimport type {\n LazyQueryHookExecOptions,\n LazyQueryHookOptions,\n LazyQueryResultTuple,\n NoInfer,\n QueryHookOptions,\n QueryResult,\n} from \"../types/types.js\";\nimport type { InternalResult } from \"./useQuery.js\";\nimport {\n createMakeWatchQueryOptions,\n getDefaultFetchPolicy,\n getObsQueryOptions,\n toQueryResult,\n useQueryInternals,\n} from \"./useQuery.js\";\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\n\n// The following methods, when called will execute the query, regardless of\n// whether the useLazyQuery execute function was called before.\nconst EAGER_METHODS = [\n \"refetch\",\n \"reobserve\",\n \"fetchMore\",\n \"updateQuery\",\n \"startPolling\",\n \"stopPolling\",\n \"subscribeToMore\",\n] as const;\n\n/**\n * A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.\n *\n * > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useLazyQuery } from \"@apollo/client\";\n *\n * const GET_GREETING = gql`\n * query GetGreeting($language: String!) {\n * greeting(language: $language) {\n * message\n * }\n * }\n * `;\n *\n * function Hello() {\n * const [loadGreeting, { called, loading, data }] = useLazyQuery(\n * GET_GREETING,\n * { variables: { language: \"english\" } }\n * );\n * if (called && loading) return

Loading ...

\n * if (!called) {\n * return \n * }\n * return

Hello {data.greeting.message}!

;\n * }\n * ```\n * @since 3.0.0\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Default options to control how the query is executed.\n * @returns A tuple in the form of `[execute, result]`\n */\nexport function useLazyQuery<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LazyQueryHookOptions, NoInfer>\n): LazyQueryResultTuple {\n const execOptionsRef =\n React.useRef>>(void 0);\n const optionsRef =\n React.useRef>(void 0);\n const queryRef = React.useRef<\n DocumentNode | TypedDocumentNode\n >(void 0);\n const merged = mergeOptions(options, execOptionsRef.current || {});\n const document = merged?.query ?? query;\n\n // Use refs to track options and the used query to ensure the `execute`\n // function remains referentially stable between renders.\n optionsRef.current = options;\n queryRef.current = document;\n\n const queryHookOptions = {\n ...merged,\n skip: !execOptionsRef.current,\n };\n const {\n obsQueryFields,\n result: useQueryResult,\n client,\n resultData,\n observable,\n onQueryExecuted,\n } = useQueryInternals(document, queryHookOptions);\n\n const initialFetchPolicy =\n observable.options.initialFetchPolicy ||\n getDefaultFetchPolicy(\n queryHookOptions.defaultOptions,\n client.defaultOptions\n );\n\n const forceUpdateState = React.useReducer((tick) => tick + 1, 0)[1];\n // We use useMemo here to make sure the eager methods have a stable identity.\n const eagerMethods = React.useMemo(() => {\n const eagerMethods: Record = {};\n for (const key of EAGER_METHODS) {\n const method = obsQueryFields[key];\n eagerMethods[key] = function () {\n if (!execOptionsRef.current) {\n execOptionsRef.current = Object.create(null);\n // Only the first time populating execOptionsRef.current matters here.\n forceUpdateState();\n }\n // @ts-expect-error this is just too generic to type\n return method.apply(this, arguments);\n };\n }\n\n return eagerMethods as typeof obsQueryFields;\n }, [forceUpdateState, obsQueryFields]);\n\n const called = !!execOptionsRef.current;\n const result = React.useMemo(\n () => ({\n ...useQueryResult,\n ...eagerMethods,\n called,\n }),\n [useQueryResult, eagerMethods, called]\n );\n\n const execute = React.useCallback[0]>(\n (executeOptions) => {\n execOptionsRef.current =\n executeOptions ?\n {\n ...executeOptions,\n fetchPolicy: executeOptions.fetchPolicy || initialFetchPolicy,\n }\n : {\n fetchPolicy: initialFetchPolicy,\n };\n\n const options = mergeOptions(optionsRef.current, {\n query: queryRef.current,\n ...execOptionsRef.current,\n });\n\n const promise = executeQuery(\n resultData,\n observable,\n client,\n document,\n { ...options, skip: false },\n onQueryExecuted\n ).then((queryResult) => Object.assign(queryResult, eagerMethods));\n\n // Because the return value of `useLazyQuery` is usually floated, we need\n // to catch the promise to prevent unhandled rejections.\n promise.catch(() => {});\n\n return promise;\n },\n [\n client,\n document,\n eagerMethods,\n initialFetchPolicy,\n observable,\n resultData,\n onQueryExecuted,\n ]\n );\n\n const executeRef = React.useRef(execute);\n useIsomorphicLayoutEffect(() => {\n executeRef.current = execute;\n });\n\n const stableExecute = React.useCallback(\n (...args) => executeRef.current(...args),\n []\n );\n return [stableExecute, result];\n}\n\nfunction executeQuery(\n resultData: InternalResult,\n observable: ObservableQuery,\n client: ApolloClient,\n currentQuery: DocumentNode,\n options: QueryHookOptions & {\n query?: DocumentNode;\n },\n onQueryExecuted: (options: WatchQueryOptions) => void\n) {\n const query = options.query || currentQuery;\n const watchQueryOptions = createMakeWatchQueryOptions(\n client,\n query,\n options,\n false\n )(observable);\n\n const concast = observable.reobserveAsConcast(\n getObsQueryOptions(observable, client, options, watchQueryOptions)\n );\n onQueryExecuted(watchQueryOptions);\n\n return new Promise<\n Omit, (typeof EAGER_METHODS)[number]>\n >((resolve) => {\n let result: ApolloQueryResult;\n\n // Subscribe to the concast independently of the ObservableQuery in case\n // the component gets unmounted before the promise resolves. This prevents\n // the concast from terminating early and resolving with `undefined` when\n // there are no more subscribers for the concast.\n concast.subscribe({\n next: (value) => {\n result = value;\n },\n error: () => {\n resolve(\n toQueryResult(\n observable.getCurrentResult(),\n resultData.previousData,\n observable,\n client\n )\n );\n },\n complete: () => {\n resolve(\n toQueryResult(\n observable[\"maskResult\"](result),\n resultData.previousData,\n observable,\n client\n )\n );\n },\n });\n });\n}\n","import * as React from \"rehackt\";\nimport type { ReactiveVar } from \"../../core/index.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\n/**\n * Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.\n *\n * @example\n * ```jsx\n * import { makeVar, useReactiveVar } from \"@apollo/client\";\n * export const cartItemsVar = makeVar([]);\n *\n * export function Cart() {\n * const cartItems = useReactiveVar(cartItemsVar);\n * // ...\n * }\n * ```\n * @since 3.2.0\n * @param rv - A reactive variable.\n * @returns The current value of the reactive variable.\n */\nexport function useReactiveVar(rv: ReactiveVar): T {\n return useSyncExternalStore(\n React.useCallback(\n (update) => {\n // By reusing the same onNext function in the nested call to\n // rv.onNextChange(onNext), we can keep using the initial clean-up function\n // returned by rv.onNextChange(function onNext(v){...}), without having to\n // register the new clean-up function (returned by the nested\n // rv.onNextChange(onNext)) with yet another callback.\n return rv.onNextChange(function onNext() {\n update();\n rv.onNextChange(onNext);\n });\n },\n [rv]\n ),\n rv,\n rv\n );\n}\n","import * as React from \"rehackt\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport { mergeDeepArray } from \"../../utilities/index.js\";\nimport type {\n Cache,\n Reference,\n StoreObject,\n MissingTree,\n} from \"../../cache/index.js\";\n\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport type { ApolloClient, OperationVariables } from \"../../core/index.js\";\nimport type { NoInfer } from \"../types/types.js\";\nimport { useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport equal from \"@wry/equality\";\nimport type { FragmentType, MaybeMasked } from \"../../masking/index.js\";\n\nexport interface UseFragmentOptions\n extends Omit<\n Cache.DiffOptions, NoInfer>,\n \"id\" | \"query\" | \"optimistic\" | \"previousResult\" | \"returnPartialData\"\n >,\n Omit<\n Cache.ReadFragmentOptions,\n \"id\" | \"variables\" | \"returnPartialData\"\n > {\n from: StoreObject | Reference | FragmentType> | string | null;\n // Override this field to make it optional (default: true).\n optimistic?: boolean;\n /**\n * The instance of `ApolloClient` to use to look up the fragment.\n *\n * By default, the instance that's passed down via context is used, but you\n * can provide a different instance here.\n *\n * @docGroup 1. Operation options\n */\n client?: ApolloClient;\n}\n\nexport type UseFragmentResult =\n | {\n data: MaybeMasked;\n complete: true;\n missing?: never;\n }\n | {\n data: DeepPartial>;\n complete: false;\n missing?: MissingTree;\n };\n\nexport function useFragment(\n options: UseFragmentOptions\n): UseFragmentResult {\n return wrapHook(\n \"useFragment\",\n // eslint-disable-next-line react-compiler/react-compiler\n useFragment_,\n useApolloClient(options.client)\n )(options);\n}\n\nfunction useFragment_(\n options: UseFragmentOptions\n): UseFragmentResult {\n const client = useApolloClient(options.client);\n const { cache } = client;\n const { from, ...rest } = options;\n\n // We calculate the cache id seperately from `stableOptions` because we don't\n // want changes to non key fields in the `from` property to affect\n // `stableOptions` and retrigger our subscription. If the cache identifier\n // stays the same between renders, we want to reuse the existing subscription.\n const id = React.useMemo(\n () =>\n typeof from === \"string\" ? from\n : from === null ? null\n : cache.identify(from),\n [cache, from]\n );\n\n const stableOptions = useDeepMemo(() => ({ ...rest, from: id! }), [rest, id]);\n\n // Since .next is async, we need to make sure that we\n // get the correct diff on the next render given new diffOptions\n const diff = React.useMemo(() => {\n const { fragment, fragmentName, from, optimistic = true } = stableOptions;\n\n if (from === null) {\n return {\n result: diffToResult({\n result: {} as TData,\n complete: false,\n }),\n };\n }\n\n const { cache } = client;\n const diff = cache.diff({\n ...stableOptions,\n returnPartialData: true,\n id: from,\n query: cache[\"getFragmentDoc\"](fragment, fragmentName),\n optimistic,\n });\n\n return {\n result: diffToResult({\n ...diff,\n result: client[\"queryManager\"].maskFragment({\n fragment,\n fragmentName,\n data: diff.result,\n }),\n }),\n };\n }, [client, stableOptions]);\n\n // Used for both getSnapshot and getServerSnapshot\n const getSnapshot = React.useCallback(() => diff.result, [diff]);\n\n return useSyncExternalStore(\n React.useCallback(\n (forceUpdate) => {\n let lastTimeout = 0;\n\n const subscription =\n stableOptions.from === null ?\n null\n : client.watchFragment(stableOptions).subscribe({\n next: (result) => {\n // Since `next` is called async by zen-observable, we want to avoid\n // unnecessarily rerendering this hook for the initial result\n // emitted from watchFragment which should be equal to\n // `diff.result`.\n if (equal(result, diff.result)) return;\n diff.result = result;\n // If we get another update before we've re-rendered, bail out of\n // the update and try again. This ensures that the relative timing\n // between useQuery and useFragment stays roughly the same as\n // fixed in https://github.com/apollographql/apollo-client/pull/11083\n clearTimeout(lastTimeout);\n lastTimeout = setTimeout(forceUpdate) as any;\n },\n });\n return () => {\n subscription?.unsubscribe();\n clearTimeout(lastTimeout);\n };\n },\n [client, stableOptions, diff]\n ),\n getSnapshot,\n getSnapshot\n );\n}\n\nfunction diffToResult(\n diff: Cache.DiffResult\n): UseFragmentResult {\n const result = {\n data: diff.result!,\n complete: !!diff.complete,\n } as UseFragmentResult;\n\n if (diff.missing) {\n result.missing = mergeDeepArray(diff.missing.map((error) => error.missing));\n }\n\n return result;\n}\n","export interface PendingPromise extends Promise {\n status: \"pending\";\n}\n\nexport interface FulfilledPromise extends Promise {\n status: \"fulfilled\";\n value: TValue;\n}\n\nexport interface RejectedPromise extends Promise {\n status: \"rejected\";\n reason: unknown;\n}\n\nexport type PromiseWithState =\n | PendingPromise\n | FulfilledPromise\n | RejectedPromise;\n\nexport function createFulfilledPromise(value: TValue) {\n const promise = Promise.resolve(value) as FulfilledPromise;\n\n promise.status = \"fulfilled\";\n promise.value = value;\n\n return promise;\n}\n\nexport function createRejectedPromise(reason: unknown) {\n const promise = Promise.reject(reason) as RejectedPromise;\n\n // prevent potential edge cases leaking unhandled error rejections\n promise.catch(() => {});\n\n promise.status = \"rejected\";\n promise.reason = reason;\n\n return promise;\n}\n\nexport function isStatefulPromise(\n promise: Promise\n): promise is PromiseWithState {\n return \"status\" in promise;\n}\n\nexport function wrapPromiseWithState(\n promise: Promise\n): PromiseWithState {\n if (isStatefulPromise(promise)) {\n return promise;\n }\n\n const pendingPromise = promise as PendingPromise;\n pendingPromise.status = \"pending\";\n\n pendingPromise.then(\n (value) => {\n if (pendingPromise.status === \"pending\") {\n const fulfilledPromise =\n pendingPromise as unknown as FulfilledPromise;\n\n fulfilledPromise.status = \"fulfilled\";\n fulfilledPromise.value = value;\n }\n },\n (reason: unknown) => {\n if (pendingPromise.status === \"pending\") {\n const rejectedPromise =\n pendingPromise as unknown as RejectedPromise;\n\n rejectedPromise.status = \"rejected\";\n rejectedPromise.reason = reason;\n }\n }\n );\n\n return promise as PromiseWithState;\n}\n","import { wrapPromiseWithState } from \"../../../utilities/index.js\";\nimport * as React from \"rehackt\";\n\ntype Use = (promise: Promise) => T;\n// Prevent webpack from complaining about our feature detection of the\n// use property of the React namespace, which is expected not\n// to exist when using current stable versions, and that's fine.\nconst useKey = \"use\" as keyof typeof React;\nconst realHook = React[useKey] as Use | undefined;\n\n// This is named with two underscores to allow this hook to evade typical rules of\n// hooks (i.e. it can be used conditionally)\nexport const __use =\n realHook ||\n function __use(promise: Promise) {\n const statefulPromise = wrapPromiseWithState(promise);\n\n switch (statefulPromise.status) {\n case \"pending\":\n throw statefulPromise;\n case \"rejected\":\n throw statefulPromise.reason;\n case \"fulfilled\":\n return statefulPromise.value;\n }\n };\n","import { equal } from \"@wry/equality\";\nimport type {\n ApolloError,\n ApolloQueryResult,\n ObservableQuery,\n OperationVariables,\n WatchQueryOptions,\n} from \"../../../core/index.js\";\nimport type {\n ObservableSubscription,\n PromiseWithState,\n} from \"../../../utilities/index.js\";\nimport {\n createFulfilledPromise,\n createRejectedPromise,\n} from \"../../../utilities/index.js\";\nimport type { QueryKey } from \"./types.js\";\nimport { wrapPromiseWithState } from \"../../../utilities/index.js\";\nimport { invariant } from \"../../../utilities/globals/invariantWrappers.js\";\nimport type { MaybeMasked } from \"../../../masking/index.js\";\n\ntype QueryRefPromise = PromiseWithState<\n ApolloQueryResult>\n>;\n\ntype Listener = (promise: QueryRefPromise) => void;\n\ntype FetchMoreOptions = Parameters<\n ObservableQuery[\"fetchMore\"]\n>[0];\n\nconst QUERY_REFERENCE_SYMBOL: unique symbol = Symbol.for(\n \"apollo.internal.queryRef\"\n);\nconst PROMISE_SYMBOL: unique symbol = Symbol.for(\"apollo.internal.refPromise\");\ndeclare const QUERY_REF_BRAND: unique symbol;\n/**\n * A `QueryReference` is an opaque object returned by `useBackgroundQuery`.\n * A child component reading the `QueryReference` via `useReadQuery` will\n * suspend until the promise resolves.\n */\nexport interface QueryRef {\n /** @internal */\n [QUERY_REF_BRAND]?(variables: TVariables): TData;\n}\n\n/**\n * @internal\n * For usage in internal helpers only.\n */\ninterface WrappedQueryRef\n extends QueryRef {\n /** @internal */\n readonly [QUERY_REFERENCE_SYMBOL]: InternalQueryReference;\n /** @internal */\n [PROMISE_SYMBOL]: QueryRefPromise;\n /** @internal */\n toPromise?(): Promise;\n}\n\n/**\n * @deprecated Please use the `QueryRef` interface instead of `QueryReference`.\n *\n * {@inheritDoc @apollo/client!QueryRef:interface}\n */\nexport interface QueryReference\n extends QueryRef {\n /**\n * @deprecated Please use the `QueryRef` interface instead of `QueryReference`.\n *\n * {@inheritDoc @apollo/client!PreloadedQueryRef#toPromise:member(1)}\n */\n toPromise?: unknown;\n}\n\n/**\n * {@inheritDoc @apollo/client!QueryRef:interface}\n */\nexport interface PreloadedQueryRef\n extends QueryRef {\n /**\n * A function that returns a promise that resolves when the query has finished\n * loading. The promise resolves with the `QueryReference` itself.\n *\n * @remarks\n * This method is useful for preloading queries in data loading routers, such\n * as [React Router](https://reactrouter.com/en/main) or [TanStack Router](https://tanstack.com/router),\n * to prevent routes from transitioning until the query has finished loading.\n * `data` is not exposed on the promise to discourage using the data in\n * `loader` functions and exposing it to your route components. Instead, we\n * prefer you rely on `useReadQuery` to access the data to ensure your\n * component can rerender with cache updates. If you need to access raw query\n * data, use `client.query()` directly.\n *\n * @example\n * Here's an example using React Router's `loader` function:\n * ```ts\n * import { createQueryPreloader } from \"@apollo/client\";\n *\n * const preloadQuery = createQueryPreloader(client);\n *\n * export async function loader() {\n * const queryRef = preloadQuery(GET_DOGS_QUERY);\n *\n * return queryRef.toPromise();\n * }\n *\n * export function RouteComponent() {\n * const queryRef = useLoaderData();\n * const { data } = useReadQuery(queryRef);\n *\n * // ...\n * }\n * ```\n *\n * @since 3.9.0\n */\n toPromise(): Promise>;\n}\n\ninterface InternalQueryReferenceOptions {\n onDispose?: () => void;\n autoDisposeTimeoutMs?: number;\n}\n\nexport function wrapQueryRef(\n internalQueryRef: InternalQueryReference\n) {\n const ref: WrappedQueryRef = {\n toPromise() {\n // We avoid resolving this promise with the query data because we want to\n // discourage using the server data directly from the queryRef. Instead,\n // the data should be accessed through `useReadQuery`. When the server\n // data is needed, its better to use `client.query()` directly.\n //\n // Here we resolve with the ref itself to make using this in React Router\n // or TanStack Router `loader` functions a bit more ergonomic e.g.\n //\n // function loader() {\n // return { queryRef: await preloadQuery(query).toPromise() }\n // }\n return getWrappedPromise(ref).then(() => ref);\n },\n [QUERY_REFERENCE_SYMBOL]: internalQueryRef,\n [PROMISE_SYMBOL]: internalQueryRef.promise,\n };\n\n return ref;\n}\n\nexport function assertWrappedQueryRef(\n queryRef: QueryRef\n): asserts queryRef is WrappedQueryRef;\nexport function assertWrappedQueryRef(\n queryRef: QueryRef | undefined | null\n): asserts queryRef is WrappedQueryRef | undefined | null;\nexport function assertWrappedQueryRef(\n queryRef: QueryRef | undefined | null\n) {\n invariant(\n !queryRef || QUERY_REFERENCE_SYMBOL in queryRef,\n \"Expected a QueryRef object, but got something else instead.\"\n );\n}\n\nexport function getWrappedPromise(\n queryRef: WrappedQueryRef\n) {\n const internalQueryRef = unwrapQueryRef(queryRef);\n\n return internalQueryRef.promise.status === \"fulfilled\" ?\n internalQueryRef.promise\n : queryRef[PROMISE_SYMBOL];\n}\n\nexport function unwrapQueryRef(\n queryRef: WrappedQueryRef\n): InternalQueryReference;\nexport function unwrapQueryRef(\n queryRef: Partial>\n): undefined | InternalQueryReference;\nexport function unwrapQueryRef(\n queryRef: Partial>\n) {\n return queryRef[QUERY_REFERENCE_SYMBOL];\n}\n\nexport function updateWrappedQueryRef(\n queryRef: WrappedQueryRef,\n promise: QueryRefPromise\n) {\n queryRef[PROMISE_SYMBOL] = promise;\n}\n\nconst OBSERVED_CHANGED_OPTIONS = [\n \"canonizeResults\",\n \"context\",\n \"errorPolicy\",\n \"fetchPolicy\",\n \"refetchWritePolicy\",\n \"returnPartialData\",\n] as const;\n\ntype ObservedOptions = Pick<\n WatchQueryOptions,\n (typeof OBSERVED_CHANGED_OPTIONS)[number]\n>;\n\nexport class InternalQueryReference {\n public result!: ApolloQueryResult>;\n public readonly key: QueryKey = {};\n public readonly observable: ObservableQuery;\n\n public promise!: QueryRefPromise;\n\n private subscription!: ObservableSubscription;\n private listeners = new Set>();\n private autoDisposeTimeoutId?: NodeJS.Timeout;\n\n private resolve:\n | ((result: ApolloQueryResult>) => void)\n | undefined;\n private reject: ((error: unknown) => void) | undefined;\n\n private references = 0;\n private softReferences = 0;\n\n constructor(\n observable: ObservableQuery,\n options: InternalQueryReferenceOptions\n ) {\n this.handleNext = this.handleNext.bind(this);\n this.handleError = this.handleError.bind(this);\n this.dispose = this.dispose.bind(this);\n this.observable = observable;\n\n if (options.onDispose) {\n this.onDispose = options.onDispose;\n }\n\n this.setResult();\n this.subscribeToQuery();\n\n // Start a timer that will automatically dispose of the query if the\n // suspended resource does not use this queryRef in the given time. This\n // helps prevent memory leaks when a component has unmounted before the\n // query has finished loading.\n const startDisposeTimer = () => {\n if (!this.references) {\n this.autoDisposeTimeoutId = setTimeout(\n this.dispose,\n options.autoDisposeTimeoutMs ?? 30_000\n );\n }\n };\n\n // We wait until the request has settled to ensure we don't dispose of the\n // query ref before the request finishes, otherwise we would leave the\n // promise in a pending state rendering the suspense boundary indefinitely.\n this.promise.then(startDisposeTimer, startDisposeTimer);\n }\n\n get disposed() {\n return this.subscription.closed;\n }\n\n get watchQueryOptions() {\n return this.observable.options;\n }\n\n reinitialize() {\n const { observable } = this;\n\n const originalFetchPolicy = this.watchQueryOptions.fetchPolicy;\n const avoidNetworkRequests =\n originalFetchPolicy === \"no-cache\" || originalFetchPolicy === \"standby\";\n\n try {\n if (avoidNetworkRequests) {\n observable.silentSetOptions({ fetchPolicy: \"standby\" });\n } else {\n observable.resetLastResults();\n observable.silentSetOptions({ fetchPolicy: \"cache-first\" });\n }\n\n this.subscribeToQuery();\n\n if (avoidNetworkRequests) {\n return;\n }\n\n observable.resetDiff();\n this.setResult();\n } finally {\n observable.silentSetOptions({ fetchPolicy: originalFetchPolicy });\n }\n }\n\n retain() {\n this.references++;\n clearTimeout(this.autoDisposeTimeoutId);\n let disposed = false;\n\n return () => {\n if (disposed) {\n return;\n }\n\n disposed = true;\n this.references--;\n\n setTimeout(() => {\n if (!this.references) {\n this.dispose();\n }\n });\n };\n }\n\n softRetain() {\n this.softReferences++;\n let disposed = false;\n\n return () => {\n // Tracking if this has already been called helps ensure that\n // multiple calls to this function won't decrement the reference\n // counter more than it should. Subsequent calls just result in a noop.\n if (disposed) {\n return;\n }\n\n disposed = true;\n this.softReferences--;\n setTimeout(() => {\n if (!this.softReferences && !this.references) {\n this.dispose();\n }\n });\n };\n }\n\n didChangeOptions(watchQueryOptions: ObservedOptions) {\n return OBSERVED_CHANGED_OPTIONS.some(\n (option) =>\n option in watchQueryOptions &&\n !equal(this.watchQueryOptions[option], watchQueryOptions[option])\n );\n }\n\n applyOptions(watchQueryOptions: ObservedOptions) {\n const {\n fetchPolicy: currentFetchPolicy,\n canonizeResults: currentCanonizeResults,\n } = this.watchQueryOptions;\n\n // \"standby\" is used when `skip` is set to `true`. Detect when we've\n // enabled the query (i.e. `skip` is `false`) to execute a network request.\n if (\n currentFetchPolicy === \"standby\" &&\n currentFetchPolicy !== watchQueryOptions.fetchPolicy\n ) {\n this.initiateFetch(this.observable.reobserve(watchQueryOptions));\n } else {\n this.observable.silentSetOptions(watchQueryOptions);\n\n if (currentCanonizeResults !== watchQueryOptions.canonizeResults) {\n this.result = { ...this.result, ...this.observable.getCurrentResult() };\n this.promise = createFulfilledPromise(this.result);\n }\n }\n\n return this.promise;\n }\n\n listen(listener: Listener) {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n refetch(variables: OperationVariables | undefined) {\n return this.initiateFetch(this.observable.refetch(variables));\n }\n\n fetchMore(options: FetchMoreOptions) {\n return this.initiateFetch(this.observable.fetchMore(options));\n }\n\n private dispose() {\n this.subscription.unsubscribe();\n this.onDispose();\n }\n\n private onDispose() {\n // noop. overridable by options\n }\n\n private handleNext(result: ApolloQueryResult>) {\n switch (this.promise.status) {\n case \"pending\": {\n // Maintain the last successful `data` value if the next result does not\n // have one.\n if (result.data === void 0) {\n result.data = this.result.data;\n }\n this.result = result;\n this.resolve?.(result);\n break;\n }\n default: {\n // This occurs when switching to a result that is fully cached when this\n // class is instantiated. ObservableQuery will run reobserve when\n // subscribing, which delivers a result from the cache.\n if (\n result.data === this.result.data &&\n result.networkStatus === this.result.networkStatus\n ) {\n return;\n }\n\n // Maintain the last successful `data` value if the next result does not\n // have one.\n if (result.data === void 0) {\n result.data = this.result.data;\n }\n\n this.result = result;\n this.promise = createFulfilledPromise(result);\n this.deliver(this.promise);\n break;\n }\n }\n }\n\n private handleError(error: ApolloError) {\n this.subscription.unsubscribe();\n this.subscription = this.observable.resubscribeAfterError(\n this.handleNext,\n this.handleError\n );\n\n switch (this.promise.status) {\n case \"pending\": {\n this.reject?.(error);\n break;\n }\n default: {\n this.promise = createRejectedPromise(error);\n this.deliver(this.promise);\n }\n }\n }\n\n private deliver(promise: QueryRefPromise) {\n this.listeners.forEach((listener) => listener(promise));\n }\n\n private initiateFetch(\n returnedPromise: Promise>>\n ) {\n this.promise = this.createPendingPromise();\n this.promise.catch(() => {});\n\n // If the data returned from the fetch is deeply equal to the data already\n // in the cache, `handleNext` will not be triggered leaving the promise we\n // created in a pending state forever. To avoid this situtation, we attempt\n // to resolve the promise if `handleNext` hasn't been run to ensure the\n // promise is resolved correctly.\n returnedPromise\n .then(() => {\n // In the case of `fetchMore`, this promise is resolved before a cache\n // result is emitted due to the fact that `fetchMore` sets a `no-cache`\n // fetch policy and runs `cache.batch` in its `.then` handler. Because\n // the timing is different, we accidentally run this update twice\n // causing an additional re-render with the `fetchMore` result by\n // itself. By wrapping in `setTimeout`, this should provide a short\n // delay to allow the `QueryInfo.notify` handler to run before this\n // promise is checked.\n // See https://github.com/apollographql/apollo-client/issues/11315 for\n // more information\n setTimeout(() => {\n if (this.promise.status === \"pending\") {\n // Use the current result from the observable instead of the value\n // resolved from the promise. This avoids issues in some cases where\n // the raw resolved value should not be the emitted value, such as\n // when a `fetchMore` call returns an empty array after it has\n // reached the end of the list.\n //\n // See the following for more information:\n // https://github.com/apollographql/apollo-client/issues/11642\n this.result = this.observable.getCurrentResult();\n this.resolve?.(this.result);\n }\n });\n })\n .catch((error) => this.reject?.(error));\n\n return returnedPromise;\n }\n\n private subscribeToQuery() {\n this.subscription = this.observable\n .filter(\n (result) => !equal(result.data, {}) && !equal(result, this.result)\n )\n .subscribe(this.handleNext, this.handleError);\n }\n\n private setResult() {\n // Don't save this result as last result to prevent delivery of last result\n // when first subscribing\n const result = this.observable.getCurrentResult(false);\n\n if (equal(result, this.result)) {\n return;\n }\n\n this.result = result;\n this.promise =\n (\n result.data &&\n (!result.partial || this.watchQueryOptions.returnPartialData)\n ) ?\n createFulfilledPromise(result)\n : this.createPendingPromise();\n }\n\n private createPendingPromise() {\n return wrapPromiseWithState(\n new Promise>>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n })\n );\n }\n}\n","import { equal } from \"@wry/equality\";\nimport type {\n WatchFragmentOptions,\n WatchFragmentResult,\n} from \"../../../cache/index.js\";\nimport type { ApolloClient } from \"../../../core/ApolloClient.js\";\nimport type { MaybeMasked } from \"../../../masking/index.js\";\nimport {\n createFulfilledPromise,\n wrapPromiseWithState,\n} from \"../../../utilities/index.js\";\nimport type {\n Observable,\n ObservableSubscription,\n PromiseWithState,\n} from \"../../../utilities/index.js\";\nimport type { FragmentKey } from \"./types.js\";\n\ntype FragmentRefPromise = PromiseWithState;\ntype Listener = (promise: FragmentRefPromise) => void;\n\ninterface FragmentReferenceOptions {\n autoDisposeTimeoutMs?: number;\n onDispose?: () => void;\n}\n\nexport class FragmentReference<\n TData = unknown,\n TVariables = Record,\n> {\n public readonly observable: Observable>;\n public readonly key: FragmentKey = {};\n public promise!: FragmentRefPromise>;\n\n private resolve: ((result: MaybeMasked) => void) | undefined;\n private reject: ((error: unknown) => void) | undefined;\n\n private subscription!: ObservableSubscription;\n private listeners = new Set>>();\n private autoDisposeTimeoutId?: NodeJS.Timeout;\n\n private references = 0;\n\n constructor(\n client: ApolloClient,\n watchFragmentOptions: WatchFragmentOptions & {\n from: string;\n },\n options: FragmentReferenceOptions\n ) {\n this.dispose = this.dispose.bind(this);\n this.handleNext = this.handleNext.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.observable = client.watchFragment(watchFragmentOptions);\n\n if (options.onDispose) {\n this.onDispose = options.onDispose;\n }\n\n const diff = this.getDiff(client, watchFragmentOptions);\n\n // Start a timer that will automatically dispose of the query if the\n // suspended resource does not use this fragmentRef in the given time. This\n // helps prevent memory leaks when a component has unmounted before the\n // query has finished loading.\n const startDisposeTimer = () => {\n if (!this.references) {\n this.autoDisposeTimeoutId = setTimeout(\n this.dispose,\n options.autoDisposeTimeoutMs ?? 30_000\n );\n }\n };\n\n this.promise =\n diff.complete ?\n createFulfilledPromise(diff.result)\n : this.createPendingPromise();\n this.subscribeToFragment();\n\n this.promise.then(startDisposeTimer, startDisposeTimer);\n }\n\n listen(listener: Listener>) {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n retain() {\n this.references++;\n clearTimeout(this.autoDisposeTimeoutId);\n let disposed = false;\n\n return () => {\n if (disposed) {\n return;\n }\n\n disposed = true;\n this.references--;\n\n setTimeout(() => {\n if (!this.references) {\n this.dispose();\n }\n });\n };\n }\n\n private dispose() {\n this.subscription.unsubscribe();\n this.onDispose();\n }\n\n private onDispose() {\n // noop. overridable by options\n }\n\n private subscribeToFragment() {\n this.subscription = this.observable.subscribe(\n this.handleNext.bind(this),\n this.handleError.bind(this)\n );\n }\n\n private handleNext(result: WatchFragmentResult) {\n switch (this.promise.status) {\n case \"pending\": {\n if (result.complete) {\n return this.resolve?.(result.data);\n }\n\n this.deliver(this.promise);\n break;\n }\n case \"fulfilled\": {\n // This can occur when we already have a result written to the cache and\n // we subscribe for the first time. We create a fulfilled promise in the\n // constructor with a value that is the same as the first emitted value\n // so we want to skip delivering it.\n if (equal(this.promise.value, result.data)) {\n return;\n }\n\n this.promise =\n result.complete ?\n createFulfilledPromise(result.data)\n : this.createPendingPromise();\n\n this.deliver(this.promise);\n }\n }\n }\n\n private handleError(error: unknown) {\n this.reject?.(error);\n }\n\n private deliver(promise: FragmentRefPromise>) {\n this.listeners.forEach((listener) => listener(promise));\n }\n\n private createPendingPromise() {\n return wrapPromiseWithState(\n new Promise>((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n })\n );\n }\n\n private getDiff(\n client: ApolloClient,\n options: WatchFragmentOptions & { from: string }\n ) {\n const { cache } = client;\n const { from, fragment, fragmentName } = options;\n\n const diff = cache.diff({\n ...options,\n query: cache[\"getFragmentDoc\"](fragment, fragmentName),\n returnPartialData: true,\n id: from,\n optimistic: true,\n });\n\n return {\n ...diff,\n result: client[\"queryManager\"].maskFragment({\n fragment,\n fragmentName,\n data: diff.result,\n }) as MaybeMasked,\n };\n }\n}\n","import { Trie } from \"@wry/trie\";\nimport type {\n ApolloClient,\n ObservableQuery,\n WatchFragmentOptions,\n} from \"../../../core/index.js\";\nimport { canUseWeakMap } from \"../../../utilities/index.js\";\nimport { InternalQueryReference } from \"./QueryReference.js\";\nimport type { CacheKey, FragmentCacheKey } from \"./types.js\";\nimport { FragmentReference } from \"./FragmentReference.js\";\n\nexport interface SuspenseCacheOptions {\n /**\n * Specifies the amount of time, in milliseconds, the suspense cache will wait\n * for a suspended component to read from the suspense cache before it\n * automatically disposes of the query. This prevents memory leaks when a\n * component unmounts before a suspended resource finishes loading. Increase\n * the timeout if your queries take longer than than the specified time to\n * prevent your queries from suspending over and over.\n *\n * Defaults to 30 seconds.\n */\n autoDisposeTimeoutMs?: number;\n}\n\nexport class SuspenseCache {\n private queryRefs = new Trie<{ current?: InternalQueryReference }>(\n canUseWeakMap\n );\n private fragmentRefs = new Trie<{ current?: FragmentReference }>(\n canUseWeakMap\n );\n\n private options: SuspenseCacheOptions;\n\n constructor(options: SuspenseCacheOptions = Object.create(null)) {\n this.options = options;\n }\n\n getQueryRef(\n cacheKey: CacheKey,\n createObservable: () => ObservableQuery\n ) {\n const ref = this.queryRefs.lookupArray(cacheKey) as {\n current?: InternalQueryReference;\n };\n\n if (!ref.current) {\n ref.current = new InternalQueryReference(createObservable(), {\n autoDisposeTimeoutMs: this.options.autoDisposeTimeoutMs,\n onDispose: () => {\n delete ref.current;\n },\n });\n }\n\n return ref.current;\n }\n\n getFragmentRef(\n cacheKey: FragmentCacheKey,\n client: ApolloClient,\n options: WatchFragmentOptions & { from: string }\n ) {\n const ref = this.fragmentRefs.lookupArray(cacheKey) as {\n current?: FragmentReference;\n };\n\n if (!ref.current) {\n ref.current = new FragmentReference(client, options, {\n autoDisposeTimeoutMs: this.options.autoDisposeTimeoutMs,\n onDispose: () => {\n delete ref.current;\n },\n });\n }\n\n return ref.current;\n }\n\n add(cacheKey: CacheKey, queryRef: InternalQueryReference) {\n const ref = this.queryRefs.lookupArray(cacheKey);\n ref.current = queryRef;\n }\n}\n","import type { SuspenseCacheOptions } from \"../index.js\";\nimport { SuspenseCache } from \"./SuspenseCache.js\";\nimport type { ApolloClient } from \"../../../core/ApolloClient.js\";\n\ndeclare module \"../../../core/ApolloClient.js\" {\n interface DefaultOptions {\n react?: {\n suspense?: Readonly;\n };\n }\n}\n\nconst suspenseCacheSymbol = Symbol.for(\"apollo.suspenseCache\");\n\nexport function getSuspenseCache(\n client: ApolloClient & {\n [suspenseCacheSymbol]?: SuspenseCache;\n }\n) {\n if (!client[suspenseCacheSymbol]) {\n client[suspenseCacheSymbol] = new SuspenseCache(\n client.defaultOptions.react?.suspense\n );\n }\n\n return client[suspenseCacheSymbol];\n}\n","export const skipToken = Symbol.for(\"apollo.skipToken\");\nexport type SkipToken = typeof skipToken;\n","import * as React from \"rehackt\";\nimport { invariant } from \"../../utilities/globals/index.js\";\nimport type {\n ApolloClient,\n ApolloQueryResult,\n DocumentNode,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryFetchPolicy,\n FetchMoreQueryOptions,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { ApolloError, NetworkStatus } from \"../../core/index.js\";\nimport type { SubscribeToMoreFunction } from \"../../core/watchQueryOptions.js\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport { isNonEmptyArray } from \"../../utilities/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport type {\n SuspenseQueryHookOptions,\n ObservableQueryFields,\n NoInfer,\n} from \"../types/types.js\";\nimport { __use, useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport { getSuspenseCache } from \"../internal/index.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport { skipToken } from \"./constants.js\";\nimport type { SkipToken } from \"./constants.js\";\nimport type { CacheKey, QueryKey } from \"../internal/index.js\";\nimport type { MaybeMasked, Unmasked } from \"../../masking/index.js\";\n\nexport interface UseSuspenseQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> {\n client: ApolloClient;\n data: MaybeMasked;\n error: ApolloError | undefined;\n fetchMore: FetchMoreFunction;\n networkStatus: NetworkStatus;\n refetch: RefetchFunction;\n subscribeToMore: SubscribeToMoreFunction;\n}\n\nexport type FetchMoreFunction = (\n fetchMoreOptions: FetchMoreQueryOptions & {\n updateQuery?: (\n previousQueryResult: Unmasked,\n options: {\n fetchMoreResult: Unmasked;\n variables: TVariables;\n }\n ) => Unmasked;\n }\n) => Promise>>;\n\nexport type RefetchFunction<\n TData,\n TVariables extends OperationVariables,\n> = ObservableQueryFields[\"refetch\"];\n\nexport function useSuspenseQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit, \"variables\">,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SuspenseQueryHookOptions, NoInfer> &\n TOptions\n): UseSuspenseQueryResult<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ?\n TOptions[\"skip\"] extends boolean ?\n DeepPartial | undefined\n : DeepPartial\n : TOptions[\"skip\"] extends boolean ? TData | undefined\n : TData,\n TVariables\n>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n skip: boolean;\n returnPartialData: true;\n }\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n }\n): UseSuspenseQueryResult, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SuspenseQueryHookOptions, NoInfer> & {\n skip: boolean;\n }\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SuspenseQueryHookOptions, NoInfer>\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | SkipToken\n | (SuspenseQueryHookOptions, NoInfer> & {\n returnPartialData: true;\n })\n): UseSuspenseQueryResult | undefined, TVariables>;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?:\n | SkipToken\n | SuspenseQueryHookOptions, NoInfer>\n): UseSuspenseQueryResult;\n\nexport function useSuspenseQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken & Partial>)\n | SuspenseQueryHookOptions = Object.create(null)\n): UseSuspenseQueryResult {\n return wrapHook(\n \"useSuspenseQuery\",\n // eslint-disable-next-line react-compiler/react-compiler\n useSuspenseQuery_,\n useApolloClient(typeof options === \"object\" ? options.client : undefined)\n )(query, options);\n}\n\nfunction useSuspenseQuery_<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken & Partial>)\n | SuspenseQueryHookOptions\n): UseSuspenseQueryResult {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({\n client,\n query,\n options,\n });\n const { fetchPolicy, variables } = watchQueryOptions;\n const { queryKey = [] } = options;\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery(watchQueryOptions)\n );\n\n let [current, setPromise] = React.useState<\n [QueryKey, Promise>]\n >([queryRef.key, queryRef.promise]);\n\n // This saves us a re-execution of the render function when a variable changed.\n if (current[0] !== queryRef.key) {\n // eslint-disable-next-line react-compiler/react-compiler\n current[0] = queryRef.key;\n current[1] = queryRef.promise;\n }\n let promise = current[1];\n\n if (queryRef.didChangeOptions(watchQueryOptions)) {\n current[1] = promise = queryRef.applyOptions(watchQueryOptions);\n }\n\n React.useEffect(() => {\n const dispose = queryRef.retain();\n\n const removeListener = queryRef.listen((promise) => {\n setPromise([queryRef.key, promise]);\n });\n\n return () => {\n removeListener();\n dispose();\n };\n }, [queryRef]);\n\n const skipResult = React.useMemo(() => {\n const error = toApolloError(queryRef.result);\n\n return {\n loading: false,\n data: queryRef.result.data,\n networkStatus: error ? NetworkStatus.error : NetworkStatus.ready,\n error,\n };\n }, [queryRef.result]);\n\n const result = fetchPolicy === \"standby\" ? skipResult : __use(promise);\n\n const fetchMore = React.useCallback<\n FetchMoreFunction\n >(\n (options) => {\n const promise = queryRef.fetchMore(options);\n setPromise([queryRef.key, queryRef.promise]);\n\n return promise;\n },\n [queryRef]\n ) as FetchMoreFunction;\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = queryRef.refetch(variables);\n setPromise([queryRef.key, queryRef.promise]);\n\n return promise;\n },\n [queryRef]\n );\n\n // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n const subscribeToMore = queryRef.observable\n .subscribeToMore as SubscribeToMoreFunction;\n\n return React.useMemo<\n UseSuspenseQueryResult\n >(() => {\n return {\n client,\n data: result.data,\n error: toApolloError(result),\n networkStatus: result.networkStatus,\n fetchMore,\n refetch,\n subscribeToMore,\n };\n }, [client, fetchMore, refetch, result, subscribeToMore]);\n}\n\nfunction validateOptions(options: WatchQueryOptions) {\n const { query, fetchPolicy, returnPartialData } = options;\n\n verifyDocumentType(query, DocumentType.Query);\n validateFetchPolicy(fetchPolicy);\n validatePartialDataReturn(fetchPolicy, returnPartialData);\n}\n\nfunction validateFetchPolicy(\n fetchPolicy: WatchQueryFetchPolicy = \"cache-first\"\n) {\n const supportedFetchPolicies: WatchQueryFetchPolicy[] = [\n \"cache-first\",\n \"network-only\",\n \"no-cache\",\n \"cache-and-network\",\n ];\n\n invariant(\n supportedFetchPolicies.includes(fetchPolicy),\n `The fetch policy \\`%s\\` is not supported with suspense.`,\n fetchPolicy\n );\n}\n\nfunction validatePartialDataReturn(\n fetchPolicy: WatchQueryFetchPolicy | undefined,\n returnPartialData: boolean | undefined\n) {\n if (fetchPolicy === \"no-cache\" && returnPartialData) {\n invariant.warn(\n \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n );\n }\n}\n\nexport function toApolloError(result: ApolloQueryResult) {\n return isNonEmptyArray(result.errors) ?\n new ApolloError({ graphQLErrors: result.errors })\n : result.error;\n}\n\ninterface UseWatchQueryOptionsHookOptions<\n TData,\n TVariables extends OperationVariables,\n> {\n client: ApolloClient;\n query: DocumentNode | TypedDocumentNode;\n options: SkipToken | SuspenseQueryHookOptions;\n}\n\nexport function useWatchQueryOptions<\n TData,\n TVariables extends OperationVariables,\n>({\n client,\n query,\n options,\n}: UseWatchQueryOptionsHookOptions): WatchQueryOptions<\n TVariables,\n TData\n> {\n return useDeepMemo>(() => {\n if (options === skipToken) {\n return { query, fetchPolicy: \"standby\" };\n }\n\n const fetchPolicy =\n options.fetchPolicy ||\n client.defaultOptions.watchQuery?.fetchPolicy ||\n \"cache-first\";\n\n const watchQueryOptions = {\n ...options,\n fetchPolicy,\n query,\n notifyOnNetworkStatusChange: false,\n nextFetchPolicy: void 0,\n };\n\n if (__DEV__) {\n validateOptions(watchQueryOptions);\n }\n\n // Assign the updated fetch policy after our validation since `standby` is\n // not a supported fetch policy on its own without the use of `skip`.\n if (options.skip) {\n watchQueryOptions.fetchPolicy = \"standby\";\n }\n\n return watchQueryOptions;\n }, [client, options, query]);\n}\n","import * as React from \"rehackt\";\nimport type {\n DocumentNode,\n FetchMoreQueryOptions,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport type { SubscribeToMoreFunction } from \"../../core/watchQueryOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n getSuspenseCache,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { CacheKey, QueryRef } from \"../internal/index.js\";\nimport type { BackgroundQueryHookOptions, NoInfer } from \"../types/types.js\";\nimport { wrapHook } from \"./internal/index.js\";\nimport { useWatchQueryOptions } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreFunction, RefetchFunction } from \"./useSuspenseQuery.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport type { DeepPartial } from \"../../utilities/index.js\";\nimport type { SkipToken } from \"./constants.js\";\n\nexport type UseBackgroundQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> = {\n /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n subscribeToMore: SubscribeToMoreFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)} */\n fetchMore: FetchMoreFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#refetch:member(1)} */\n refetch: RefetchFunction;\n};\n\ntype BackgroundQueryHookOptionsNoInfer<\n TData,\n TVariables extends OperationVariables,\n> = BackgroundQueryHookOptions, NoInfer>;\n\nexport function useBackgroundQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit, \"variables\">,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: BackgroundQueryHookOptionsNoInfer & TOptions\n): [\n (\n | QueryRef<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n >\n | (TOptions[\"skip\"] extends boolean ? undefined : never)\n ),\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): [\n QueryRef | undefined, TVariables>,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): [\n QueryRef,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n skip: boolean;\n returnPartialData: true;\n }\n): [\n QueryRef, TVariables> | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n }\n): [\n QueryRef, TVariables>,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: BackgroundQueryHookOptionsNoInfer & {\n skip: boolean;\n }\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: BackgroundQueryHookOptionsNoInfer\n): [QueryRef, UseBackgroundQueryResult];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: SkipToken\n): [undefined, UseBackgroundQueryResult];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | SkipToken\n | (BackgroundQueryHookOptionsNoInfer & {\n returnPartialData: true;\n })\n): [\n QueryRef, TVariables> | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: SkipToken | BackgroundQueryHookOptionsNoInfer\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n];\n\nexport function useBackgroundQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken &\n Partial>)\n | BackgroundQueryHookOptionsNoInfer = Object.create(null)\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n] {\n return wrapHook(\n \"useBackgroundQuery\",\n // eslint-disable-next-line react-compiler/react-compiler\n useBackgroundQuery_,\n useApolloClient(typeof options === \"object\" ? options.client : undefined)\n )(query, options);\n}\n\nfunction useBackgroundQuery_<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options:\n | (SkipToken &\n Partial>)\n | BackgroundQueryHookOptionsNoInfer\n): [\n QueryRef | undefined,\n UseBackgroundQueryResult,\n] {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n const { fetchPolicy, variables } = watchQueryOptions;\n const { queryKey = [] } = options;\n\n // This ref tracks the first time query execution is enabled to determine\n // whether to return a query ref or `undefined`. When initialized\n // in a skipped state (either via `skip: true` or `skipToken`) we return\n // `undefined` for the `queryRef` until the query has been enabled. Once\n // enabled, a query ref is always returned regardless of whether the query is\n // skipped again later.\n const didFetchResult = React.useRef(fetchPolicy !== \"standby\");\n didFetchResult.current ||= fetchPolicy !== \"standby\";\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery(watchQueryOptions as WatchQueryOptions)\n );\n\n const [wrappedQueryRef, setWrappedQueryRef] = React.useState(\n wrapQueryRef(queryRef)\n );\n if (unwrapQueryRef(wrappedQueryRef) !== queryRef) {\n setWrappedQueryRef(wrapQueryRef(queryRef));\n }\n if (queryRef.didChangeOptions(watchQueryOptions)) {\n const promise = queryRef.applyOptions(watchQueryOptions);\n updateWrappedQueryRef(wrappedQueryRef, promise);\n }\n\n // This prevents issues where rerendering useBackgroundQuery after the\n // queryRef has been disposed would cause the hook to return a new queryRef\n // instance since disposal also removes it from the suspense cache. We add\n // the queryRef back in the suspense cache so that the next render will reuse\n // this queryRef rather than initializing a new instance.\n React.useEffect(() => {\n // Since the queryRef is disposed async via `setTimeout`, we have to wait a\n // tick before checking it and adding back to the suspense cache.\n const id = setTimeout(() => {\n if (queryRef.disposed) {\n suspenseCache.add(cacheKey, queryRef);\n }\n });\n\n return () => clearTimeout(id);\n // Omitting the deps is intentional. This avoids stale closures and the\n // conditional ensures we aren't running the logic on each render.\n });\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n const promise = queryRef.fetchMore(options as FetchMoreQueryOptions);\n\n setWrappedQueryRef(wrapQueryRef(queryRef));\n\n return promise;\n },\n [queryRef]\n );\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = queryRef.refetch(variables);\n\n setWrappedQueryRef(wrapQueryRef(queryRef));\n\n return promise;\n },\n [queryRef]\n );\n\n React.useEffect(() => queryRef.softRetain(), [queryRef]);\n\n return [\n didFetchResult.current ? wrappedQueryRef : void 0,\n {\n fetchMore,\n refetch,\n // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n subscribeToMore: queryRef.observable\n .subscribeToMore as SubscribeToMoreFunction,\n },\n ];\n}\n","import type {\n ApolloClient,\n DocumentNode,\n OperationVariables,\n Reference,\n StoreObject,\n TypedDocumentNode,\n} from \"../../core/index.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { getSuspenseCache } from \"../internal/index.js\";\nimport * as React from \"rehackt\";\nimport type { FragmentKey } from \"../internal/cache/types.js\";\nimport { __use } from \"./internal/__use.js\";\nimport { wrapHook } from \"./internal/index.js\";\nimport type { FragmentType, MaybeMasked } from \"../../masking/index.js\";\nimport type { NoInfer, VariablesOption } from \"../types/types.js\";\n\ntype From =\n | StoreObject\n | Reference\n | FragmentType>\n | string\n | null;\n\nexport type UseSuspenseFragmentOptions<\n TData,\n TVariables extends OperationVariables,\n> = {\n /**\n * A GraphQL document created using the `gql` template string tag from\n * `graphql-tag` with one or more fragments which will be used to determine\n * the shape of data to read. If you provide more than one fragment in this\n * document then you must also specify `fragmentName` to select a single.\n */\n fragment: DocumentNode | TypedDocumentNode;\n\n /**\n * The name of the fragment in your GraphQL document to be used. If you do\n * not provide a `fragmentName` and there is only one fragment in your\n * `fragment` document then that fragment will be used.\n */\n fragmentName?: string;\n from: From;\n // Override this field to make it optional (default: true).\n optimistic?: boolean;\n /**\n * The instance of `ApolloClient` to use to look up the fragment.\n *\n * By default, the instance that's passed down via context is used, but you\n * can provide a different instance here.\n *\n * @docGroup 1. Operation options\n */\n client?: ApolloClient;\n} & VariablesOption>;\n\nexport type UseSuspenseFragmentResult = { data: MaybeMasked };\n\nconst NULL_PLACEHOLDER = [] as unknown as [\n FragmentKey,\n Promise | null>,\n];\n\nexport function useSuspenseFragment<\n TData,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions & {\n from: NonNullable>;\n }\n): UseSuspenseFragmentResult;\n\nexport function useSuspenseFragment<\n TData,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions & {\n from: null;\n }\n): UseSuspenseFragmentResult;\n\nexport function useSuspenseFragment<\n TData,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions & {\n from: From;\n }\n): UseSuspenseFragmentResult;\n\nexport function useSuspenseFragment<\n TData,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions\n): UseSuspenseFragmentResult;\n\nexport function useSuspenseFragment<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions\n): UseSuspenseFragmentResult {\n return wrapHook(\n \"useSuspenseFragment\",\n // eslint-disable-next-line react-compiler/react-compiler\n useSuspenseFragment_,\n useApolloClient(typeof options === \"object\" ? options.client : undefined)\n )(options);\n}\n\nfunction useSuspenseFragment_<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n options: UseSuspenseFragmentOptions\n): UseSuspenseFragmentResult {\n const client = useApolloClient(options.client);\n const { from, variables } = options;\n const { cache } = client;\n\n const id = React.useMemo(\n () =>\n typeof from === \"string\" ? from\n : from === null ? null\n : cache.identify(from),\n [cache, from]\n ) as string | null;\n\n const fragmentRef =\n id === null ? null : (\n getSuspenseCache(client).getFragmentRef(\n [id, options.fragment, canonicalStringify(variables)],\n client,\n { ...options, variables: variables as TVariables, from: id }\n )\n );\n\n let [current, setPromise] = React.useState<\n [FragmentKey, Promise | null>]\n >(\n fragmentRef === null ? NULL_PLACEHOLDER : (\n [fragmentRef.key, fragmentRef.promise]\n )\n );\n\n React.useEffect(() => {\n if (fragmentRef === null) {\n return;\n }\n\n const dispose = fragmentRef.retain();\n const removeListener = fragmentRef.listen((promise) => {\n setPromise([fragmentRef.key, promise]);\n });\n\n return () => {\n dispose();\n removeListener();\n };\n }, [fragmentRef]);\n\n if (fragmentRef === null) {\n return { data: null };\n }\n\n if (current[0] !== fragmentRef.key) {\n // eslint-disable-next-line react-compiler/react-compiler\n current[0] = fragmentRef.key;\n current[1] = fragmentRef.promise;\n }\n\n const data = __use(current[1]);\n\n return { data };\n}\n","import * as React from \"rehackt\";\n\nlet Ctx: React.Context;\n\nfunction noop() {}\nexport function useRenderGuard() {\n if (!Ctx) {\n // we want the intialization to be lazy because `createContext` would error on import in a RSC\n Ctx = React.createContext(null);\n }\n\n return React.useCallback(\n /**\n * @returns true if the hook was called during render\n */ () => {\n const orig = console.error;\n try {\n console.error = noop;\n\n /**\n * `useContext` can be called conditionally during render, so this is safe.\n * (Also, during render we would want to throw as a reaction to this anyways, so it\n * wouldn't even matter if we got the order of hooks mixed up...)\n *\n * They cannot however be called outside of Render, and that's what we're testing here.\n *\n * Different versions of React have different behaviour on an invalid hook call:\n *\n * React 16.8 - 17: throws an error\n * https://github.com/facebook/react/blob/2b93d686e359c7afa299e2ec5cf63160a32a1155/packages/react/src/ReactHooks.js#L18-L26\n *\n * React 18 & 19: `console.error` in development, then `resolveDispatcher` returns `null` and a member access on `null` throws.\n * https://github.com/facebook/react/blob/58e8304483ebfadd02a295339b5e9a989ac98c6e/packages/react/src/ReactHooks.js#L28-L35\n */\n React[\"useContext\" /* hide this from the linter */](Ctx);\n return true;\n } catch (e) {\n return false;\n } finally {\n console.error = orig;\n }\n },\n []\n );\n}\n","import * as React from \"rehackt\";\nimport type {\n DocumentNode,\n FetchMoreQueryOptions,\n OperationVariables,\n TypedDocumentNode,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport type {\n SubscribeToMoreFunction,\n SubscribeToMoreOptions,\n} from \"../../core/watchQueryOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n assertWrappedQueryRef,\n getSuspenseCache,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { CacheKey, QueryRef } from \"../internal/index.js\";\nimport type { LoadableQueryHookOptions } from \"../types/types.js\";\nimport { __use, useRenderGuard } from \"./internal/index.js\";\nimport { useWatchQueryOptions } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreFunction, RefetchFunction } from \"./useSuspenseQuery.js\";\nimport { canonicalStringify } from \"../../cache/index.js\";\nimport type {\n DeepPartial,\n OnlyRequiredProperties,\n} from \"../../utilities/index.js\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n\nexport type LoadQueryFunction = (\n // Use variadic args to handle cases where TVariables is type `never`, in\n // which case we don't want to allow a variables argument. In other\n // words, we don't want to allow variables to be passed as an argument to this\n // function if the query does not expect variables in the document.\n ...args: [TVariables] extends [never] ? []\n : {} extends OnlyRequiredProperties ? [variables?: TVariables]\n : [variables: TVariables]\n) => void;\n\ntype ResetFunction = () => void;\n\nexport type UseLoadableQueryResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> = [\n loadQuery: LoadQueryFunction,\n queryRef: QueryRef | null,\n handlers: {\n /** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */\n fetchMore: FetchMoreFunction;\n /** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */\n refetch: RefetchFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n subscribeToMore: SubscribeToMoreFunction;\n /**\n * A function that resets the `queryRef` back to `null`.\n */\n reset: ResetFunction;\n },\n];\n\nexport function useLoadableQuery<\n TData,\n TVariables extends OperationVariables,\n TOptions extends LoadableQueryHookOptions,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LoadableQueryHookOptions & TOptions\n): UseLoadableQueryResult<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n>;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseLoadableQueryResult | undefined, TVariables>;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n errorPolicy: \"ignore\" | \"all\";\n }\n): UseLoadableQueryResult;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions & {\n returnPartialData: true;\n }\n): UseLoadableQueryResult, TVariables>;\n\n/**\n * A hook for imperatively loading a query, such as responding to a user\n * interaction.\n *\n * > Refer to the [Suspense - Fetching in response to user interaction](https://www.apollographql.com/docs/react/data/suspense#fetching-in-response-to-user-interaction) section for a more in-depth overview of `useLoadableQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useLoadableQuery } from \"@apollo/client\";\n *\n * const GET_GREETING = gql`\n * query GetGreeting($language: String!) {\n * greeting(language: $language) {\n * message\n * }\n * }\n * `;\n *\n * function App() {\n * const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);\n *\n * return (\n * <>\n * \n * Loading...}>\n * {queryRef && }\n * \n * \n * );\n * }\n *\n * function Hello({ queryRef }) {\n * const { data } = useReadQuery(queryRef);\n *\n * return
{data.greeting.message}
;\n * }\n * ```\n *\n * @since 3.9.0\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Options to control how the query is executed.\n * @returns A tuple in the form of `[loadQuery, queryRef, handlers]`\n */\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options?: LoadableQueryHookOptions\n): UseLoadableQueryResult;\n\nexport function useLoadableQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: LoadableQueryHookOptions = Object.create(null)\n): UseLoadableQueryResult {\n const client = useApolloClient(options.client);\n const suspenseCache = getSuspenseCache(client);\n const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n const { queryKey = [] } = options;\n\n const [queryRef, setQueryRef] = React.useState | null>(null);\n\n assertWrappedQueryRef(queryRef);\n\n const internalQueryRef = queryRef && unwrapQueryRef(queryRef);\n\n if (queryRef && internalQueryRef?.didChangeOptions(watchQueryOptions)) {\n const promise = internalQueryRef.applyOptions(watchQueryOptions);\n updateWrappedQueryRef(queryRef, promise);\n }\n\n const calledDuringRender = useRenderGuard();\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n if (!internalQueryRef) {\n throw new Error(\n \"The query has not been loaded. Please load the query.\"\n );\n }\n\n const promise = internalQueryRef.fetchMore(\n options as FetchMoreQueryOptions\n );\n\n setQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const refetch: RefetchFunction = React.useCallback(\n (options) => {\n if (!internalQueryRef) {\n throw new Error(\n \"The query has not been loaded. Please load the query.\"\n );\n }\n\n const promise = internalQueryRef.refetch(options);\n\n setQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const loadQuery: LoadQueryFunction = React.useCallback(\n (...args) => {\n invariant(\n !calledDuringRender(),\n \"useLoadableQuery: 'loadQuery' should not be called during render. To start a query during render, use the 'useBackgroundQuery' hook.\"\n );\n\n const [variables] = args;\n\n const cacheKey: CacheKey = [\n query,\n canonicalStringify(variables),\n ...([] as any[]).concat(queryKey),\n ];\n\n const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n client.watchQuery({\n ...watchQueryOptions,\n variables,\n } as WatchQueryOptions)\n );\n\n setQueryRef(wrapQueryRef(queryRef));\n },\n [\n query,\n queryKey,\n suspenseCache,\n watchQueryOptions,\n calledDuringRender,\n client,\n ]\n );\n\n const subscribeToMore: SubscribeToMoreFunction =\n React.useCallback(\n (options) => {\n invariant(\n internalQueryRef,\n \"The query has not been loaded. Please load the query.\"\n );\n\n return internalQueryRef.observable.subscribeToMore(\n // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n options as any as SubscribeToMoreOptions\n );\n },\n [internalQueryRef]\n );\n\n const reset: ResetFunction = React.useCallback(() => {\n setQueryRef(null);\n }, []);\n\n return [loadQuery, queryRef, { fetchMore, refetch, reset, subscribeToMore }];\n}\n","import * as React from \"rehackt\";\nimport {\n assertWrappedQueryRef,\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryRef } from \"../internal/index.js\";\nimport type { OperationVariables } from \"../../core/types.js\";\nimport type { SubscribeToMoreFunction } from \"../../core/watchQueryOptions.js\";\nimport type { RefetchFunction, FetchMoreFunction } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreQueryOptions } from \"../../core/watchQueryOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { wrapHook } from \"./internal/index.js\";\nimport type { ApolloClient } from \"../../core/ApolloClient.js\";\nimport type { ObservableQuery } from \"../../core/ObservableQuery.js\";\n\nexport interface UseQueryRefHandlersResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> {\n /** {@inheritDoc @apollo/client!ObservableQuery#refetch:member(1)} */\n refetch: RefetchFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)} */\n fetchMore: FetchMoreFunction;\n /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n subscribeToMore: SubscribeToMoreFunction;\n}\n\n/**\n * A React hook that returns a `refetch` and `fetchMore` function for a given\n * `queryRef`.\n *\n * This is useful to get access to handlers for a `queryRef` that was created by\n * `createQueryPreloader` or when the handlers for a `queryRef` produced in\n * a different component are inaccessible.\n *\n * @example\n * ```tsx\n * const MyComponent({ queryRef }) {\n * const { refetch, fetchMore } = useQueryRefHandlers(queryRef);\n *\n * // ...\n * }\n * ```\n * @since 3.9.0\n * @param queryRef - A `QueryRef` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.\n */\nexport function useQueryRefHandlers<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n queryRef: QueryRef\n): UseQueryRefHandlersResult {\n const unwrapped = unwrapQueryRef(queryRef);\n const clientOrObsQuery = useApolloClient(\n unwrapped ?\n // passing an `ObservableQuery` is not supported by the types, but it will\n // return any truthy value that is passed in as an override so we cast the result\n (unwrapped[\"observable\"] as any)\n : undefined\n ) as ApolloClient | ObservableQuery;\n\n return wrapHook(\n \"useQueryRefHandlers\",\n // eslint-disable-next-line react-compiler/react-compiler\n useQueryRefHandlers_,\n clientOrObsQuery\n )(queryRef);\n}\n\nfunction useQueryRefHandlers_<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n queryRef: QueryRef\n): UseQueryRefHandlersResult {\n assertWrappedQueryRef(queryRef);\n const [previousQueryRef, setPreviousQueryRef] = React.useState(queryRef);\n const [wrappedQueryRef, setWrappedQueryRef] = React.useState(queryRef);\n const internalQueryRef = unwrapQueryRef(queryRef);\n\n // To ensure we can support React transitions, this hook needs to manage the\n // queryRef state and apply React's state value immediately to the existing\n // queryRef since this hook doesn't return the queryRef directly\n if (previousQueryRef !== queryRef) {\n setPreviousQueryRef(queryRef);\n setWrappedQueryRef(queryRef);\n } else {\n updateWrappedQueryRef(queryRef, getWrappedPromise(wrappedQueryRef));\n }\n\n const refetch: RefetchFunction = React.useCallback(\n (variables) => {\n const promise = internalQueryRef.refetch(variables);\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const fetchMore: FetchMoreFunction = React.useCallback(\n (options) => {\n const promise = internalQueryRef.fetchMore(\n options as FetchMoreQueryOptions\n );\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n return {\n refetch,\n fetchMore,\n // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n subscribeToMore: internalQueryRef.observable\n .subscribeToMore as SubscribeToMoreFunction,\n };\n}\n","import * as React from \"rehackt\";\nimport {\n assertWrappedQueryRef,\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryRef } from \"../internal/index.js\";\nimport { __use, wrapHook } from \"./internal/index.js\";\nimport { toApolloError } from \"./useSuspenseQuery.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport type { ApolloError } from \"../../errors/index.js\";\nimport type {\n ApolloClient,\n NetworkStatus,\n ObservableQuery,\n} from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport type { MaybeMasked } from \"../../masking/index.js\";\n\nexport interface UseReadQueryResult {\n /**\n * An object containing the result of your GraphQL query after it completes.\n *\n * This value might be `undefined` if a query results in one or more errors\n * (depending on the query's `errorPolicy`).\n */\n data: MaybeMasked;\n /**\n * If the query produces one or more errors, this object contains either an\n * array of `graphQLErrors` or a single `networkError`. Otherwise, this value\n * is `undefined`.\n *\n * This property can be ignored when using the default `errorPolicy` or an\n * `errorPolicy` of `none`. The hook will throw the error instead of setting\n * this property.\n */\n error: ApolloError | undefined;\n /**\n * A number indicating the current network state of the query's associated\n * request. {@link https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4 | See possible values}.\n */\n networkStatus: NetworkStatus;\n}\n\nexport function useReadQuery(\n queryRef: QueryRef\n): UseReadQueryResult {\n const unwrapped = unwrapQueryRef(queryRef);\n const clientOrObsQuery = useApolloClient(\n unwrapped ?\n // passing an `ObservableQuery` is not supported by the types, but it will\n // return any truthy value that is passed in as an override so we cast the result\n (unwrapped[\"observable\"] as any)\n : undefined\n ) as ApolloClient | ObservableQuery;\n\n return wrapHook(\n \"useReadQuery\",\n // eslint-disable-next-line react-compiler/react-compiler\n useReadQuery_,\n clientOrObsQuery\n )(queryRef);\n}\n\nfunction useReadQuery_(\n queryRef: QueryRef\n): UseReadQueryResult {\n assertWrappedQueryRef(queryRef);\n const internalQueryRef = React.useMemo(\n () => unwrapQueryRef(queryRef),\n [queryRef]\n );\n\n const getPromise = React.useCallback(\n () => getWrappedPromise(queryRef),\n [queryRef]\n );\n\n if (internalQueryRef.disposed) {\n internalQueryRef.reinitialize();\n updateWrappedQueryRef(queryRef, internalQueryRef.promise);\n }\n\n React.useEffect(() => internalQueryRef.retain(), [internalQueryRef]);\n\n const promise = useSyncExternalStore(\n React.useCallback(\n (forceUpdate) => {\n return internalQueryRef.listen((promise) => {\n updateWrappedQueryRef(queryRef, promise);\n forceUpdate();\n });\n },\n [internalQueryRef, queryRef]\n ),\n getPromise,\n getPromise\n );\n\n const result = __use(promise);\n\n return React.useMemo(() => {\n return {\n data: result.data,\n networkStatus: result.networkStatus,\n error: toApolloError(result),\n };\n }, [result]);\n}\n","import type {\n ApolloClient,\n DefaultContext,\n DocumentNode,\n ErrorPolicy,\n OperationVariables,\n RefetchWritePolicy,\n TypedDocumentNode,\n WatchQueryFetchPolicy,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport type {\n DeepPartial,\n OnlyRequiredProperties,\n} from \"../../utilities/index.js\";\nimport { InternalQueryReference, wrapQueryRef } from \"../internal/index.js\";\nimport type { PreloadedQueryRef } from \"../internal/index.js\";\nimport type { NoInfer, VariablesOption } from \"../index.js\";\nimport { wrapHook } from \"../hooks/internal/index.js\";\n\nexport type PreloadQueryFetchPolicy = Extract<\n WatchQueryFetchPolicy,\n \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n>;\n\nexport type PreloadQueryOptions<\n TVariables extends OperationVariables = OperationVariables,\n> = {\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#canonizeResults:member} */\n canonizeResults?: boolean;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n context?: DefaultContext;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n errorPolicy?: ErrorPolicy;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n fetchPolicy?: PreloadQueryFetchPolicy;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n returnPartialData?: boolean;\n /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n refetchWritePolicy?: RefetchWritePolicy;\n} & VariablesOption;\n\ntype PreloadQueryOptionsArg<\n TVariables extends OperationVariables,\n TOptions = unknown,\n> = [TVariables] extends [never] ?\n [options?: PreloadQueryOptions & TOptions]\n: {} extends OnlyRequiredProperties ?\n [\n options?: PreloadQueryOptions> &\n Omit,\n ]\n: [\n options: PreloadQueryOptions> &\n Omit,\n ];\n\n/**\n * A function that will begin loading a query when called. It's result can be\n * read by `useReadQuery` which will suspend until the query is loaded.\n * This is useful when you want to start loading a query as early as possible\n * outside of a React component.\n *\n * @example\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * const queryRef = preloadQuery(query, { variables, ...otherOptions });\n *\n * function App() {\n * return (\n * Loading}>\n * \n * \n * );\n * }\n *\n * function MyQuery() {\n * const { data } = useReadQuery(queryRef);\n *\n * // do something with `data`\n * }\n * ```\n */\nexport interface PreloadQueryFunction {\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n <\n TData,\n TVariables extends OperationVariables,\n TOptions extends Omit,\n >(\n query: DocumentNode | TypedDocumentNode,\n ...[options]: PreloadQueryOptionsArg, TOptions>\n ): PreloadedQueryRef<\n TOptions[\"errorPolicy\"] extends \"ignore\" | \"all\" ?\n TOptions[\"returnPartialData\"] extends true ?\n DeepPartial | undefined\n : TData | undefined\n : TOptions[\"returnPartialData\"] extends true ? DeepPartial\n : TData,\n TVariables\n >;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n returnPartialData: true;\n errorPolicy: \"ignore\" | \"all\";\n }\n ): PreloadedQueryRef | undefined, TVariables>;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n errorPolicy: \"ignore\" | \"all\";\n }\n ): PreloadedQueryRef;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> & {\n returnPartialData: true;\n }\n ): PreloadedQueryRef, TVariables>;\n\n /** {@inheritDoc @apollo/client!PreloadQueryFunction:interface} */\n (\n query: DocumentNode | TypedDocumentNode,\n ...[options]: PreloadQueryOptionsArg>\n ): PreloadedQueryRef;\n}\n\n/**\n * A higher order function that returns a `preloadQuery` function which\n * can be used to begin loading a query with the given `client`. This is useful\n * when you want to start loading a query as early as possible outside of a\n * React component.\n *\n * > Refer to the [Suspense - Initiating queries outside React](https://www.apollographql.com/docs/react/data/suspense#initiating-queries-outside-react) section for a more in-depth overview.\n *\n * @param client - The `ApolloClient` instance that will be used to load queries\n * from the returned `preloadQuery` function.\n * @returns The `preloadQuery` function.\n *\n * @example\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * ```\n * @since 3.9.0\n */\nexport function createQueryPreloader(\n client: ApolloClient\n): PreloadQueryFunction {\n return wrapHook(\n \"createQueryPreloader\",\n _createQueryPreloader,\n client\n )(client);\n}\n\nconst _createQueryPreloader: typeof createQueryPreloader = (client) => {\n return function preloadQuery<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n >(\n query: DocumentNode | TypedDocumentNode,\n options: PreloadQueryOptions> &\n VariablesOption = Object.create(null)\n ): PreloadedQueryRef {\n const queryRef = new InternalQueryReference(\n client.watchQuery({\n ...options,\n query,\n } as WatchQueryOptions),\n {\n autoDisposeTimeoutMs:\n client.defaultOptions.react?.suspense?.autoDisposeTimeoutMs,\n }\n );\n\n return wrapQueryRef(queryRef) as PreloadedQueryRef;\n };\n};\n","import type { FetchResult, NextLink, Operation } from \"../core/index.js\";\nimport type { ObservableSubscription } from \"../../utilities/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\n\nexport type BatchHandler = (\n operations: Operation[],\n forward?: (NextLink | undefined)[]\n) => Observable | null;\n\nexport interface BatchableRequest {\n operation: Operation;\n forward?: NextLink;\n}\n\ntype QueuedRequest = BatchableRequest & {\n observable?: Observable;\n next: Array<(result: FetchResult) => void>;\n error: Array<(error: Error) => void>;\n complete: Array<() => void>;\n subscribers: Set;\n};\n\n// Batches are primarily a Set, but may have other optional\n// properties, such as batch.subscription.\ntype RequestBatch = Set & {\n subscription?: ObservableSubscription;\n};\n\n// QueryBatcher doesn't fire requests immediately. Requests that were enqueued within\n// a certain amount of time (configurable through `batchInterval`) will be batched together\n// into one query.\nexport class OperationBatcher {\n // Queue on which the QueryBatcher will operate on a per-tick basis.\n private batchesByKey = new Map();\n\n private scheduledBatchTimerByKey = new Map<\n string,\n ReturnType\n >();\n private batchDebounce?: boolean;\n private batchInterval?: number;\n private batchMax: number;\n\n //This function is called to the queries in the queue to the server.\n private batchHandler: BatchHandler;\n private batchKey: (operation: Operation) => string;\n\n constructor({\n batchDebounce,\n batchInterval,\n batchMax,\n batchHandler,\n batchKey,\n }: {\n batchDebounce?: boolean;\n batchInterval?: number;\n batchMax?: number;\n batchHandler: BatchHandler;\n batchKey?: (operation: Operation) => string;\n }) {\n this.batchDebounce = batchDebounce;\n this.batchInterval = batchInterval;\n this.batchMax = batchMax || 0;\n this.batchHandler = batchHandler;\n this.batchKey = batchKey || (() => \"\");\n }\n\n public enqueueRequest(request: BatchableRequest): Observable {\n const requestCopy: QueuedRequest = {\n ...request,\n next: [],\n error: [],\n complete: [],\n subscribers: new Set(),\n };\n\n const key = this.batchKey(request.operation);\n\n if (!requestCopy.observable) {\n requestCopy.observable = new Observable((observer) => {\n let batch = this.batchesByKey.get(key)!;\n if (!batch) this.batchesByKey.set(key, (batch = new Set()));\n\n // These booleans seem to me (@benjamn) like they might always be the\n // same (and thus we could do with only one of them), but I'm not 100%\n // sure about that.\n const isFirstEnqueuedRequest = batch.size === 0;\n const isFirstSubscriber = requestCopy.subscribers.size === 0;\n requestCopy.subscribers.add(observer);\n if (isFirstSubscriber) {\n batch.add(requestCopy);\n }\n\n // called for each subscriber, so need to save all listeners (next, error, complete)\n if (observer.next) {\n requestCopy.next.push(observer.next.bind(observer));\n }\n\n if (observer.error) {\n requestCopy.error.push(observer.error.bind(observer));\n }\n\n if (observer.complete) {\n requestCopy.complete.push(observer.complete.bind(observer));\n }\n\n // The first enqueued request triggers the queue consumption after `batchInterval` milliseconds.\n if (isFirstEnqueuedRequest || this.batchDebounce) {\n this.scheduleQueueConsumption(key);\n }\n\n // When amount of requests reaches `batchMax`, trigger the queue consumption without waiting on the `batchInterval`.\n if (batch.size === this.batchMax) {\n this.consumeQueue(key);\n }\n\n return () => {\n // If this is last subscriber for this request, remove request from queue\n if (\n requestCopy.subscribers.delete(observer) &&\n requestCopy.subscribers.size < 1\n ) {\n // If this is last request from queue, remove queue entirely\n if (batch.delete(requestCopy) && batch.size < 1) {\n this.consumeQueue(key);\n // If queue was in flight, cancel it\n batch.subscription?.unsubscribe();\n }\n }\n };\n });\n }\n\n return requestCopy.observable;\n }\n\n // Consumes the queue.\n // Returns a list of promises (one for each query).\n public consumeQueue(\n key: string = \"\"\n ): (Observable | undefined)[] | undefined {\n const batch = this.batchesByKey.get(key);\n // Delete this batch and process it below.\n this.batchesByKey.delete(key);\n if (!batch || !batch.size) {\n // No requests to be processed.\n return;\n }\n\n const operations: QueuedRequest[\"operation\"][] = [];\n const forwards: QueuedRequest[\"forward\"][] = [];\n const observables: QueuedRequest[\"observable\"][] = [];\n const nexts: QueuedRequest[\"next\"][] = [];\n const errors: QueuedRequest[\"error\"][] = [];\n const completes: QueuedRequest[\"complete\"][] = [];\n\n // Even though batch is a Set, it preserves the order of first insertion\n // when iterating (per ECMAScript specification), so these requests will be\n // handled in the order they were enqueued (minus any deleted ones).\n batch.forEach((request) => {\n operations.push(request.operation);\n forwards.push(request.forward);\n observables.push(request.observable);\n nexts.push(request.next);\n errors.push(request.error);\n completes.push(request.complete);\n });\n\n const batchedObservable =\n this.batchHandler(operations, forwards) || Observable.of();\n\n const onError = (error: Error) => {\n //each callback list in batch\n errors.forEach((rejecters) => {\n if (rejecters) {\n //each subscriber to request\n rejecters.forEach((e) => e(error));\n }\n });\n };\n\n batch.subscription = batchedObservable.subscribe({\n next: (results) => {\n if (!Array.isArray(results)) {\n results = [results];\n }\n\n if (nexts.length !== results.length) {\n const error = new Error(\n `server returned results with length ${results.length}, expected length of ${nexts.length}`\n );\n (error as any).result = results;\n\n return onError(error);\n }\n\n results.forEach((result, index) => {\n if (nexts[index]) {\n nexts[index].forEach((next) => next(result));\n }\n });\n },\n error: onError,\n complete: () => {\n completes.forEach((complete) => {\n if (complete) {\n //each subscriber to request\n complete.forEach((c) => c());\n }\n });\n },\n });\n\n return observables;\n }\n\n private scheduleQueueConsumption(key: string): void {\n clearTimeout(this.scheduledBatchTimerByKey.get(key));\n this.scheduledBatchTimerByKey.set(\n key,\n setTimeout(() => {\n this.consumeQueue(key);\n this.scheduledBatchTimerByKey.delete(key);\n }, this.batchInterval)\n );\n }\n}\n","import type { Operation, FetchResult, NextLink } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport type { Observable } from \"../../utilities/index.js\";\nimport type { BatchHandler } from \"./batching.js\";\nimport { OperationBatcher } from \"./batching.js\";\nexport type { BatchableRequest, BatchHandler } from \"./batching.js\";\nexport { OperationBatcher } from \"./batching.js\";\n\nexport namespace BatchLink {\n export interface Options {\n /**\n * The interval at which to batch, in milliseconds.\n *\n * Defaults to 10.\n */\n batchInterval?: number;\n\n /**\n * \"batchInterval\" is a throttling behavior by default, if you instead wish\n * to debounce outbound requests, set \"batchDebounce\" to true. More useful\n * for mutations than queries.\n */\n batchDebounce?: boolean;\n\n /**\n * The maximum number of operations to include in one fetch.\n *\n * Defaults to 0 (infinite operations within the interval).\n */\n batchMax?: number;\n\n /**\n * The handler that should execute a batch of operations.\n */\n batchHandler?: BatchHandler;\n\n /**\n * creates the key for a batch\n */\n batchKey?: (operation: Operation) => string;\n }\n}\n\nexport class BatchLink extends ApolloLink {\n private batcher: OperationBatcher;\n\n constructor(fetchParams?: BatchLink.Options) {\n super();\n\n const {\n batchDebounce,\n batchInterval = 10,\n batchMax = 0,\n batchHandler = () => null,\n batchKey = () => \"\",\n } = fetchParams || {};\n\n this.batcher = new OperationBatcher({\n batchDebounce,\n batchInterval,\n batchMax,\n batchHandler,\n batchKey,\n });\n\n //make this link terminating\n if (fetchParams!.batchHandler!.length <= 1) {\n this.request = (operation) => this.batcher.enqueueRequest({ operation });\n }\n }\n\n public request(\n operation: Operation,\n forward?: NextLink\n ): Observable | null {\n return this.batcher.enqueueRequest({\n operation,\n forward,\n });\n }\n}\n","import type { Operation, FetchResult } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport {\n Observable,\n hasDirectives,\n maybe,\n removeClientSetsFromDocument,\n} from \"../../utilities/index.js\";\nimport { fromError } from \"../utils/index.js\";\nimport type { HttpOptions } from \"../http/index.js\";\nimport {\n serializeFetchParameter,\n selectURI,\n parseAndCheckHttpResponse,\n checkFetcher,\n selectHttpOptionsAndBodyInternal,\n defaultPrinter,\n fallbackHttpConfig,\n} from \"../http/index.js\";\nimport { BatchLink } from \"../batch/index.js\";\nimport { filterOperationVariables } from \"../utils/filterOperationVariables.js\";\n\nexport namespace BatchHttpLink {\n export type Options = Pick<\n BatchLink.Options,\n \"batchMax\" | \"batchDebounce\" | \"batchInterval\" | \"batchKey\"\n > &\n Omit;\n}\n\nconst backupFetch = maybe(() => fetch);\n\n/**\n * Transforms Operation for into HTTP results.\n * context can include the headers property, which will be passed to the fetch function\n */\nexport class BatchHttpLink extends ApolloLink {\n private batchDebounce?: boolean;\n private batchInterval: number;\n private batchMax: number;\n private batcher: ApolloLink;\n\n constructor(fetchParams?: BatchHttpLink.Options) {\n super();\n\n let {\n uri = \"/graphql\",\n // use default global fetch if nothing is passed in\n fetch: preferredFetch,\n print = defaultPrinter,\n includeExtensions,\n preserveHeaderCase,\n batchInterval,\n batchDebounce,\n batchMax,\n batchKey,\n includeUnusedVariables = false,\n ...requestOptions\n } = fetchParams || ({} as BatchHttpLink.Options);\n\n if (__DEV__) {\n // Make sure at least one of preferredFetch, window.fetch, or backupFetch\n // is defined, so requests won't fail at runtime.\n checkFetcher(preferredFetch || backupFetch);\n }\n\n const linkConfig = {\n http: { includeExtensions, preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n this.batchDebounce = batchDebounce;\n this.batchInterval = batchInterval || 10;\n this.batchMax = batchMax || 10;\n\n const batchHandler = (operations: Operation[]) => {\n const chosenURI = selectURI(operations[0], uri);\n\n const context = operations[0].getContext();\n\n const clientAwarenessHeaders: {\n \"apollographql-client-name\"?: string;\n \"apollographql-client-version\"?: string;\n } = {};\n if (context.clientAwareness) {\n const { name, version } = context.clientAwareness;\n if (name) {\n clientAwarenessHeaders[\"apollographql-client-name\"] = name;\n }\n if (version) {\n clientAwarenessHeaders[\"apollographql-client-version\"] = version;\n }\n }\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: { ...clientAwarenessHeaders, ...context.headers },\n };\n\n const queries = operations.map(({ query }) => {\n if (hasDirectives([\"client\"], query)) {\n return removeClientSetsFromDocument(query);\n }\n\n return query;\n });\n\n // If we have a query that returned `null` after removing client-only\n // fields, it indicates a query that is using all client-only fields.\n if (queries.some((query) => !query)) {\n return fromError(\n new Error(\n \"BatchHttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or enable the `transformOptions.removeClientFields` option.\"\n )\n );\n }\n\n //uses fallback, link, and then context to build options\n const optsAndBody = operations.map((operation, index) => {\n const result = selectHttpOptionsAndBodyInternal(\n { ...operation, query: queries[index]! },\n print,\n fallbackHttpConfig,\n linkConfig,\n contextConfig\n );\n\n if (result.body.variables && !includeUnusedVariables) {\n result.body.variables = filterOperationVariables(\n result.body.variables,\n operation.query\n );\n }\n\n return result;\n });\n\n const loadedBody = optsAndBody.map(({ body }) => body);\n const options = optsAndBody[0].options;\n\n // There's no spec for using GET with batches.\n if (options.method === \"GET\") {\n return fromError(\n new Error(\"apollo-link-batch-http does not support GET requests\")\n );\n }\n\n try {\n (options as any).body = serializeFetchParameter(loadedBody, \"Payload\");\n } catch (parseError) {\n return fromError(parseError);\n }\n\n let controller: AbortController | undefined;\n if (!options.signal && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n options.signal = controller.signal;\n }\n\n return new Observable((observer) => {\n // Prefer BatchHttpLink.Options.fetch (preferredFetch) if provided, and\n // otherwise fall back to the *current* global window.fetch function\n // (see issue #7832), or (if all else fails) the backupFetch function we\n // saved when this module was first evaluated. This last option protects\n // against the removal of window.fetch, which is unlikely but not\n // impossible.\n const currentFetch =\n preferredFetch || maybe(() => fetch) || backupFetch;\n\n currentFetch!(chosenURI, options)\n .then((response) => {\n // Make the raw response available in the context.\n operations.forEach((operation) =>\n operation.setContext({ response })\n );\n return response;\n })\n .then(parseAndCheckHttpResponse(operations))\n .then((result) => {\n controller = undefined;\n // we have data and can send it to back up the link chain\n observer.next(result);\n observer.complete();\n return result;\n })\n .catch((err) => {\n controller = undefined;\n // if it is a network error, BUT there is graphql result info\n // fire the next observer before calling error\n // this gives apollo-client (and react-apollo) the `graphqlErrors` and `networkErrors`\n // to pass to UI\n // this should only happen if we *also* have data as part of the response key per\n // the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we dont' call next, the UI can only show networkError because AC didn't\n // get andy graphqlErrors\n // this is graphql execution result info (i.e errors and possibly data)\n // this is because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next(err.result);\n }\n\n observer.error(err);\n });\n\n return () => {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller) controller.abort();\n };\n });\n };\n\n batchKey =\n batchKey ||\n ((operation: Operation) => {\n const context = operation.getContext();\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: context.headers,\n };\n\n //may throw error if config not serializable\n return selectURI(operation, uri) + JSON.stringify(contextConfig);\n });\n\n this.batcher = new BatchLink({\n batchDebounce: this.batchDebounce,\n batchInterval: this.batchInterval,\n batchMax: this.batchMax,\n batchKey,\n batchHandler,\n });\n }\n\n public request(operation: Operation): Observable | null {\n return this.batcher.request(operation);\n }\n}\n","import { newInvariantError, invariant } from \"../../utilities/globals/index.js\";\n\nimport type { Observer } from \"../../utilities/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport type {\n NextLink,\n Operation,\n RequestHandler,\n FetchResult,\n GraphQLRequest,\n} from \"./types.js\";\nimport {\n validateOperation,\n createOperation,\n transformOperation,\n} from \"../utils/index.js\";\n\nfunction passthrough(op: Operation, forward: NextLink) {\n return (forward ? forward(op) : Observable.of()) as Observable;\n}\n\nfunction toLink(handler: RequestHandler | ApolloLink) {\n return typeof handler === \"function\" ? new ApolloLink(handler) : handler;\n}\n\nfunction isTerminating(link: ApolloLink): boolean {\n return link.request.length <= 1;\n}\n\nexport class ApolloLink {\n public static empty(): ApolloLink {\n return new ApolloLink(() => Observable.of());\n }\n\n public static from(links: (ApolloLink | RequestHandler)[]): ApolloLink {\n if (links.length === 0) return ApolloLink.empty();\n return links.map(toLink).reduce((x, y) => x.concat(y)) as ApolloLink;\n }\n\n public static split(\n test: (op: Operation) => boolean,\n left: ApolloLink | RequestHandler,\n right?: ApolloLink | RequestHandler\n ): ApolloLink {\n const leftLink = toLink(left);\n const rightLink = toLink(right || new ApolloLink(passthrough));\n\n let ret: ApolloLink;\n if (isTerminating(leftLink) && isTerminating(rightLink)) {\n ret = new ApolloLink((operation) => {\n return test(operation) ?\n leftLink.request(operation) || Observable.of()\n : rightLink.request(operation) || Observable.of();\n });\n } else {\n ret = new ApolloLink((operation, forward) => {\n return test(operation) ?\n leftLink.request(operation, forward) || Observable.of()\n : rightLink.request(operation, forward) || Observable.of();\n });\n }\n return Object.assign(ret, { left: leftLink, right: rightLink });\n }\n\n public static execute(\n link: ApolloLink,\n operation: GraphQLRequest\n ): Observable {\n return (\n link.request(\n createOperation(\n operation.context,\n transformOperation(validateOperation(operation))\n )\n ) || Observable.of()\n );\n }\n\n public static concat(\n first: ApolloLink | RequestHandler,\n second: ApolloLink | RequestHandler\n ) {\n const firstLink = toLink(first);\n if (isTerminating(firstLink)) {\n invariant.warn(\n `You are calling concat on a terminating link, which will have no effect %o`,\n firstLink\n );\n return firstLink;\n }\n const nextLink = toLink(second);\n\n let ret: ApolloLink;\n if (isTerminating(nextLink)) {\n ret = new ApolloLink(\n (operation) =>\n firstLink.request(\n operation,\n (op) => nextLink.request(op) || Observable.of()\n ) || Observable.of()\n );\n } else {\n ret = new ApolloLink((operation, forward) => {\n return (\n firstLink.request(operation, (op) => {\n return nextLink.request(op, forward) || Observable.of();\n }) || Observable.of()\n );\n });\n }\n return Object.assign(ret, { left: firstLink, right: nextLink });\n }\n\n constructor(request?: RequestHandler) {\n if (request) this.request = request;\n }\n\n public split(\n test: (op: Operation) => boolean,\n left: ApolloLink | RequestHandler,\n right?: ApolloLink | RequestHandler\n ): ApolloLink {\n return this.concat(\n ApolloLink.split(test, left, right || new ApolloLink(passthrough))\n );\n }\n\n public concat(next: ApolloLink | RequestHandler): ApolloLink {\n return ApolloLink.concat(this, next);\n }\n\n public request(\n operation: Operation,\n forward?: NextLink\n ): Observable | null {\n throw newInvariantError(\"request is not implemented\");\n }\n\n protected onError(\n error: any,\n observer?: Observer\n ): false | void {\n if (observer && observer.error) {\n observer.error(error);\n // Returning false indicates that observer.error does not need to be\n // called again, since it was already called (on the previous line).\n // Calling observer.error again would not cause any real problems,\n // since only the first call matters, but custom onError functions\n // might have other reasons for wanting to prevent the default\n // behavior by returning false.\n return false;\n }\n // Throw errors will be passed to observer.error.\n throw error;\n }\n\n public setOnError(fn: ApolloLink[\"onError\"]): this {\n this.onError = fn;\n return this;\n }\n\n /**\n * @internal\n * Used to iterate through all links that are concatenations or `split` links.\n */\n readonly left?: ApolloLink;\n /**\n * @internal\n * Used to iterate through all links that are concatenations or `split` links.\n */\n readonly right?: ApolloLink;\n\n /**\n * @internal\n * Can be provided by a link that has an internal cache to report it's memory details.\n */\n getMemoryInternals?: () => unknown;\n}\n","import type { GraphQLRequest, Operation } from \"../core/index.js\";\n\nexport function createOperation(\n starting: any,\n operation: GraphQLRequest\n): Operation {\n let context = { ...starting };\n const setContext: Operation[\"setContext\"] = (next) => {\n if (typeof next === \"function\") {\n context = { ...context, ...next(context) };\n } else {\n context = { ...context, ...next };\n }\n };\n const getContext: Operation[\"getContext\"] = () => ({ ...context });\n\n Object.defineProperty(operation, \"setContext\", {\n enumerable: false,\n value: setContext,\n });\n\n Object.defineProperty(operation, \"getContext\", {\n enumerable: false,\n value: getContext,\n });\n\n return operation as Operation;\n}\n","import type { GraphQLRequest, Operation } from \"../core/index.js\";\nimport { getOperationName } from \"../../utilities/index.js\";\n\nexport function transformOperation(operation: GraphQLRequest): GraphQLRequest {\n const transformedOperation: GraphQLRequest = {\n variables: operation.variables || {},\n extensions: operation.extensions || {},\n operationName: operation.operationName,\n query: operation.query,\n };\n\n // Best guess at an operation name\n if (!transformedOperation.operationName) {\n transformedOperation.operationName =\n typeof transformedOperation.query !== \"string\" ?\n getOperationName(transformedOperation.query) || undefined\n : \"\";\n }\n\n return transformedOperation as Operation;\n}\n","import { newInvariantError } from \"../../utilities/globals/index.js\";\nimport type { GraphQLRequest } from \"../core/index.js\";\n\nexport function validateOperation(operation: GraphQLRequest): GraphQLRequest {\n const OPERATION_FIELDS = [\n \"query\",\n \"operationName\",\n \"variables\",\n \"extensions\",\n \"context\",\n ];\n for (let key of Object.keys(operation)) {\n if (OPERATION_FIELDS.indexOf(key) < 0) {\n throw newInvariantError(`illegal argument: %s`, key);\n }\n }\n\n return operation;\n}\n","import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const execute = ApolloLink.execute;\n","import type { FormattedExecutionResult, GraphQLFormattedError } from \"graphql\";\n\nimport {\n graphQLResultHasProtocolErrors,\n PROTOCOL_ERRORS_SYMBOL,\n} from \"../../errors/index.js\";\nimport type { NetworkError } from \"../../errors/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport type { Operation, FetchResult, NextLink } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\n\nexport interface ErrorResponse {\n /**\n * Errors returned in the `errors` property of the GraphQL response.\n */\n graphQLErrors?: ReadonlyArray;\n /**\n * Errors thrown during a network request. This is usually an error thrown\n * during a `fetch` call or an error while parsing the response from the\n * network.\n */\n networkError?: NetworkError;\n /**\n * Fatal transport-level errors from multipart subscriptions.\n * See the [multipart subscription protocol](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol#message-and-error-format) for more information.\n */\n protocolErrors?: ReadonlyArray;\n response?: FormattedExecutionResult;\n operation: Operation;\n forward: NextLink;\n}\n\nexport namespace ErrorLink {\n /**\n * Callback to be triggered when an error occurs within the link stack.\n */\n export interface ErrorHandler {\n (error: ErrorResponse): Observable | void;\n }\n}\n\n// For backwards compatibility.\nexport import ErrorHandler = ErrorLink.ErrorHandler;\n\nexport function onError(errorHandler: ErrorHandler): ApolloLink {\n return new ApolloLink((operation, forward) => {\n return new Observable((observer) => {\n let sub: any;\n let retriedSub: any;\n let retriedResult: any;\n\n try {\n sub = forward(operation).subscribe({\n next: (result) => {\n if (result.errors) {\n retriedResult = errorHandler({\n graphQLErrors: result.errors,\n response: result,\n operation,\n forward,\n });\n } else if (graphQLResultHasProtocolErrors(result)) {\n retriedResult = errorHandler({\n protocolErrors: result.extensions[PROTOCOL_ERRORS_SYMBOL],\n response: result,\n operation,\n forward,\n });\n }\n\n if (retriedResult) {\n retriedSub = retriedResult.subscribe({\n next: observer.next.bind(observer),\n error: observer.error.bind(observer),\n complete: observer.complete.bind(observer),\n });\n return;\n }\n\n observer.next(result);\n },\n error: (networkError) => {\n retriedResult = errorHandler({\n operation,\n networkError,\n //Network errors can return GraphQL errors on for example a 403\n graphQLErrors:\n (networkError &&\n networkError.result &&\n networkError.result.errors) ||\n void 0,\n forward,\n });\n if (retriedResult) {\n retriedSub = retriedResult.subscribe({\n next: observer.next.bind(observer),\n error: observer.error.bind(observer),\n complete: observer.complete.bind(observer),\n });\n return;\n }\n observer.error(networkError);\n },\n complete: () => {\n // disable the previous sub from calling complete on observable\n // if retry is in flight.\n if (!retriedResult) {\n observer.complete.bind(observer)();\n }\n },\n });\n } catch (e) {\n errorHandler({ networkError: e as Error, operation, forward });\n observer.error(e);\n }\n\n return () => {\n if (sub) sub.unsubscribe();\n if (retriedSub) sub.unsubscribe();\n };\n });\n });\n}\n\nexport class ErrorLink extends ApolloLink {\n private link: ApolloLink;\n constructor(errorHandler: ErrorLink.ErrorHandler) {\n super();\n this.link = onError(errorHandler);\n }\n\n public request(\n operation: Operation,\n forward: NextLink\n ): Observable | null {\n return this.link.request(operation, forward);\n }\n}\n","import { ApolloLink } from \"../core/index.js\";\nimport type { HttpOptions } from \"./selectHttpOptionsAndBody.js\";\nimport { createHttpLink } from \"./createHttpLink.js\";\n\nexport class HttpLink extends ApolloLink {\n constructor(public options: HttpOptions = {}) {\n super(createHttpLink(options).request);\n }\n}\n","import { newInvariantError } from \"../../utilities/globals/index.js\";\n\nexport const checkFetcher = (fetcher: typeof fetch | undefined) => {\n if (!fetcher && typeof fetch === \"undefined\") {\n throw newInvariantError(`\n\"fetch\" has not been found globally and no fetcher has been \\\nconfigured. To fix this, install a fetch package (like \\\nhttps://www.npmjs.com/package/cross-fetch), instantiate the \\\nfetcher, 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 `);\n }\n};\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport type { DefinitionNode } from \"graphql\";\n\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable, hasDirectives } from \"../../utilities/index.js\";\nimport { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport { selectURI } from \"./selectURI.js\";\nimport {\n handleError,\n readMultipartBody,\n parseAndCheckHttpResponse,\n} from \"./parseAndCheckHttpResponse.js\";\nimport { checkFetcher } from \"./checkFetcher.js\";\nimport type { HttpOptions } from \"./selectHttpOptionsAndBody.js\";\nimport {\n selectHttpOptionsAndBodyInternal,\n defaultPrinter,\n fallbackHttpConfig,\n} from \"./selectHttpOptionsAndBody.js\";\nimport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\nimport { fromError, filterOperationVariables } from \"../utils/index.js\";\nimport {\n maybe,\n getMainDefinition,\n removeClientSetsFromDocument,\n} from \"../../utilities/index.js\";\n\nconst backupFetch = maybe(() => fetch);\n\nexport const createHttpLink = (linkOptions: HttpOptions = {}) => {\n let {\n uri = \"/graphql\",\n // use default global fetch if nothing passed in\n fetch: preferredFetch,\n print = defaultPrinter,\n includeExtensions,\n preserveHeaderCase,\n useGETForQueries,\n includeUnusedVariables = false,\n ...requestOptions\n } = linkOptions;\n\n if (__DEV__) {\n // Make sure at least one of preferredFetch, window.fetch, or backupFetch is\n // defined, so requests won't fail at runtime.\n checkFetcher(preferredFetch || backupFetch);\n }\n\n const linkConfig = {\n http: { includeExtensions, preserveHeaderCase },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n return new ApolloLink((operation) => {\n let chosenURI = selectURI(operation, uri);\n\n const context = operation.getContext();\n\n // `apollographql-client-*` headers are automatically set if a\n // `clientAwareness` object is found in the context. These headers are\n // set first, followed by the rest of the headers pulled from\n // `context.headers`. If desired, `apollographql-client-*` headers set by\n // the `clientAwareness` object can be overridden by\n // `apollographql-client-*` headers set in `context.headers`.\n const clientAwarenessHeaders: {\n \"apollographql-client-name\"?: string;\n \"apollographql-client-version\"?: string;\n } = {};\n\n if (context.clientAwareness) {\n const { name, version } = context.clientAwareness;\n if (name) {\n clientAwarenessHeaders[\"apollographql-client-name\"] = name;\n }\n if (version) {\n clientAwarenessHeaders[\"apollographql-client-version\"] = version;\n }\n }\n\n const contextHeaders = { ...clientAwarenessHeaders, ...context.headers };\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: contextHeaders,\n };\n\n if (hasDirectives([\"client\"], operation.query)) {\n const transformedQuery = removeClientSetsFromDocument(operation.query);\n\n if (!transformedQuery) {\n return fromError(\n new Error(\n \"HttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or set the `transformOptions.removeClientFields` option to `true`.\"\n )\n );\n }\n\n operation.query = transformedQuery;\n }\n\n //uses fallback, link, and then context to build options\n const { options, body } = selectHttpOptionsAndBodyInternal(\n operation,\n print,\n fallbackHttpConfig,\n linkConfig,\n contextConfig\n );\n\n if (body.variables && !includeUnusedVariables) {\n body.variables = filterOperationVariables(\n body.variables,\n operation.query\n );\n }\n\n let controller: AbortController | undefined;\n if (!options.signal && typeof AbortController !== \"undefined\") {\n controller = new AbortController();\n options.signal = controller.signal;\n }\n\n // If requested, set method to GET if there are no mutations.\n const definitionIsMutation = (d: DefinitionNode) => {\n return d.kind === \"OperationDefinition\" && d.operation === \"mutation\";\n };\n const definitionIsSubscription = (d: DefinitionNode) => {\n return d.kind === \"OperationDefinition\" && d.operation === \"subscription\";\n };\n const isSubscription = definitionIsSubscription(\n getMainDefinition(operation.query)\n );\n // does not match custom directives beginning with @defer\n const hasDefer = hasDirectives([\"defer\"], operation.query);\n if (\n useGETForQueries &&\n !operation.query.definitions.some(definitionIsMutation)\n ) {\n options.method = \"GET\";\n }\n\n if (hasDefer || isSubscription) {\n options.headers = options.headers || {};\n let acceptHeader = \"multipart/mixed;\";\n // Omit defer-specific headers if the user attempts to defer a selection\n // set on a subscription and log a warning.\n if (isSubscription && hasDefer) {\n invariant.warn(\"Multipart-subscriptions do not support @defer\");\n }\n\n if (isSubscription) {\n acceptHeader +=\n \"boundary=graphql;subscriptionSpec=1.0,application/json\";\n } else if (hasDefer) {\n acceptHeader += \"deferSpec=20220824,application/json\";\n }\n options.headers.accept = acceptHeader;\n }\n\n if (options.method === \"GET\") {\n const { newURI, parseError } = rewriteURIForGET(chosenURI, body);\n if (parseError) {\n return fromError(parseError);\n }\n chosenURI = newURI;\n } else {\n try {\n (options as any).body = serializeFetchParameter(body, \"Payload\");\n } catch (parseError) {\n return fromError(parseError);\n }\n }\n\n return new Observable((observer) => {\n // Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise\n // fall back to the *current* global window.fetch function (see issue\n // #7832), or (if all else fails) the backupFetch function we saved when\n // this module was first evaluated. This last option protects against the\n // removal of window.fetch, which is unlikely but not impossible.\n const currentFetch = preferredFetch || maybe(() => fetch) || backupFetch;\n\n const observerNext = observer.next.bind(observer);\n currentFetch!(chosenURI, options)\n .then((response) => {\n operation.setContext({ response });\n const ctype = response.headers?.get(\"content-type\");\n\n if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n return readMultipartBody(response, observerNext);\n } else {\n return parseAndCheckHttpResponse(operation)(response).then(\n observerNext\n );\n }\n })\n .then(() => {\n controller = undefined;\n observer.complete();\n })\n .catch((err) => {\n controller = undefined;\n handleError(err, observer);\n });\n\n return () => {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller) controller.abort();\n };\n });\n });\n};\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts\n */\n\nimport type { Readable as NodeReadableStream } from \"stream\";\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface NodeStreamIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function nodeStreamIterator(\n stream: NodeReadableStream\n): AsyncIterableIterator {\n let cleanup: (() => void) | null = null;\n let error: Error | null = null;\n let done = false;\n const data: unknown[] = [];\n\n const waiting: [\n (\n value:\n | IteratorResult\n | PromiseLike>\n ) => void,\n (reason?: any) => void,\n ][] = [];\n\n function onData(chunk: any) {\n if (error) return;\n if (waiting.length) {\n const 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: Error) {\n error = err;\n const all = waiting.slice();\n all.forEach(function (pair) {\n pair[1](err);\n });\n !cleanup || cleanup();\n }\n function onEnd() {\n done = true;\n const all = waiting.slice();\n all.forEach(function (pair) {\n pair[0]({ value: undefined, done: true });\n });\n !cleanup || cleanup();\n }\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\n function getNext(): Promise> {\n return new Promise(function (resolve, reject) {\n if (error) return reject(error);\n if (data.length)\n return resolve({ value: data.shift() as T, done: false });\n if (done) return resolve({ value: undefined, done: true });\n waiting.push([resolve, reject]);\n });\n }\n\n const iterator: NodeStreamIterator = {\n next(): Promise> {\n return getNext();\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface ReaderIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function readerIterator(\n reader: ReadableStreamDefaultReader\n): AsyncIterableIterator {\n const iterator: ReaderIterator = {\n next() {\n return reader.read() as Promise<\n | ReadableStreamReadValueResult\n // DoneResult has `value` optional, which doesn't comply with an\n // `IteratorResult`, so we assert it to `T | undefined` instead\n | Required>\n >;\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator<\n T,\n T | undefined\n > {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts\n */\n\nimport type { Response as NodeResponse } from \"node-fetch\";\nimport type { Readable as NodeReadableStream } from \"stream\";\nimport { canUseAsyncIteratorSymbol } from \"../../utilities/index.js\";\n\nimport asyncIterator from \"./iterators/async.js\";\nimport nodeStreamIterator from \"./iterators/nodeStream.js\";\nimport promiseIterator from \"./iterators/promise.js\";\nimport readerIterator from \"./iterators/reader.js\";\n\nfunction isNodeResponse(value: any): value is NodeResponse {\n return !!(value as NodeResponse).body;\n}\n\nfunction isReadableStream(value: any): value is ReadableStream {\n return !!(value as ReadableStream).getReader;\n}\n\nfunction isAsyncIterableIterator(\n value: any\n): value is AsyncIterableIterator {\n return !!(\n canUseAsyncIteratorSymbol &&\n (value as AsyncIterableIterator)[Symbol.asyncIterator]\n );\n}\n\nfunction isStreamableBlob(value: any): value is Blob {\n return !!(value as Blob).stream;\n}\n\nfunction isBlob(value: any): value is Blob {\n return !!(value as Blob).arrayBuffer;\n}\n\nfunction isNodeReadableStream(value: any): value is NodeReadableStream {\n return !!(value as NodeReadableStream).pipe;\n}\n\nexport function responseIterator(\n response: Response | NodeResponse\n): AsyncIterableIterator {\n let body: unknown = response;\n\n if (isNodeResponse(response)) body = response.body;\n\n if (isAsyncIterableIterator(body)) return asyncIterator(body);\n\n if (isReadableStream(body)) return readerIterator(body.getReader());\n\n // this errors without casting to ReadableStream\n // because Blob.stream() returns a NodeJS ReadableStream\n if (isStreamableBlob(body)) {\n return readerIterator(\n (body.stream() as unknown as ReadableStream).getReader()\n );\n }\n\n if (isBlob(body)) return promiseIterator(body.arrayBuffer());\n\n if (isNodeReadableStream(body)) return nodeStreamIterator(body);\n\n throw new Error(\n \"Unknown body type for responseIterator. Please pass a streamable response.\"\n );\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\n\nexport default function asyncIterator(\n source: AsyncIterableIterator\n): AsyncIterableIterator {\n const iterator = source[Symbol.asyncIterator]();\n return {\n next(): Promise> {\n return iterator.next();\n },\n [Symbol.asyncIterator](): AsyncIterableIterator {\n return this;\n },\n };\n}\n","/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface PromiseIterator {\n next(): Promise>;\n [Symbol.asyncIterator]?(): AsyncIterator;\n}\n\nexport default function promiseIterator(\n promise: Promise\n): AsyncIterableIterator {\n let resolved = false;\n\n const iterator: PromiseIterator = {\n next(): Promise> {\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 as unknown as T, done: false });\n })\n .catch(reject);\n });\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator;\n}\n","import { responseIterator } from \"./responseIterator.js\";\nimport type { Operation } from \"../core/index.js\";\nimport { throwServerError } from \"../utils/index.js\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"../../errors/index.js\";\nimport { isApolloPayloadResult } from \"../../utilities/common/incrementalResult.js\";\nimport type { SubscriptionObserver } from \"zen-observable-ts\";\n\nconst { hasOwnProperty } = Object.prototype;\n\nexport type ServerParseError = Error & {\n response: Response;\n statusCode: number;\n bodyText: string;\n};\n\nexport async function readMultipartBody<\n T extends object = Record,\n>(response: Response, nextValue: (value: T) => void) {\n if (TextDecoder === undefined) {\n throw new Error(\n \"TextDecoder must be defined in the environment: please import a polyfill.\"\n );\n }\n const decoder = new TextDecoder(\"utf-8\");\n const contentType = response.headers?.get(\"content-type\");\n const delimiter = \"boundary=\";\n\n // parse boundary value and ignore any subsequent name/value pairs after ;\n // https://www.rfc-editor.org/rfc/rfc9110.html#name-parameters\n // e.g. multipart/mixed;boundary=\"graphql\";deferSpec=20220824\n // if no boundary is specified, default to -\n const boundaryVal =\n contentType?.includes(delimiter) ?\n contentType\n ?.substring(contentType?.indexOf(delimiter) + delimiter.length)\n .replace(/['\"]/g, \"\")\n .replace(/\\;(.*)/gm, \"\")\n .trim()\n : \"-\";\n\n const boundary = `\\r\\n--${boundaryVal}`;\n let buffer = \"\";\n const iterator = responseIterator(response);\n let running = true;\n\n while (running) {\n const { value, done } = await iterator.next();\n const chunk = typeof value === \"string\" ? value : decoder.decode(value);\n const searchFrom = buffer.length - boundary.length + 1;\n running = !done;\n buffer += chunk;\n let bi = buffer.indexOf(boundary, searchFrom);\n\n while (bi > -1) {\n let message: string;\n [message, buffer] = [\n buffer.slice(0, bi),\n buffer.slice(bi + boundary.length),\n ];\n const i = message.indexOf(\"\\r\\n\\r\\n\");\n const headers = parseHeaders(message.slice(0, i));\n const contentType = headers[\"content-type\"];\n if (\n contentType &&\n contentType.toLowerCase().indexOf(\"application/json\") === -1\n ) {\n throw new Error(\n \"Unsupported patch content type: application/json is required.\"\n );\n }\n // nb: Technically you'd want to slice off the beginning \"\\r\\n\" but since\n // this is going to be `JSON.parse`d there is no need.\n const body = message.slice(i);\n\n if (body) {\n const result = parseJsonBody(response, body);\n if (\n Object.keys(result).length > 1 ||\n \"data\" in result ||\n \"incremental\" in result ||\n \"errors\" in result ||\n \"payload\" in result\n ) {\n if (isApolloPayloadResult(result)) {\n let next = {};\n if (\"payload\" in result) {\n if (Object.keys(result).length === 1 && result.payload === null) {\n return;\n }\n next = { ...result.payload };\n }\n if (\"errors\" in result) {\n next = {\n ...next,\n extensions: {\n ...(\"extensions\" in next ? next.extensions : (null as any)),\n [PROTOCOL_ERRORS_SYMBOL]: result.errors,\n },\n };\n }\n nextValue(next as T);\n } else {\n // for the last chunk with only `hasNext: false`\n // we don't need to call observer.next as there is no data/errors\n nextValue(result);\n }\n } else if (\n // If the chunk contains only a \"hasNext: false\", we can call\n // observer.complete() immediately.\n Object.keys(result).length === 1 &&\n \"hasNext\" in result &&\n !result.hasNext\n ) {\n return;\n }\n }\n bi = buffer.indexOf(boundary);\n }\n }\n}\n\nexport function parseHeaders(headerText: string): Record {\n const headersInit: Record = {};\n headerText.split(\"\\n\").forEach((line) => {\n const i = line.indexOf(\":\");\n if (i > -1) {\n // normalize headers to lowercase\n const name = line.slice(0, i).trim().toLowerCase();\n const value = line.slice(i + 1).trim();\n headersInit[name] = value;\n }\n });\n return headersInit;\n}\n\nexport function parseJsonBody(response: Response, bodyText: string): T {\n if (response.status >= 300) {\n // Network error\n const getResult = (): Record | string => {\n try {\n return JSON.parse(bodyText);\n } catch (err) {\n return bodyText;\n }\n };\n throwServerError(\n response,\n getResult(),\n `Response not successful: Received status code ${response.status}`\n );\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch (err) {\n const parseError = err as ServerParseError;\n parseError.name = \"ServerParseError\";\n parseError.response = response;\n parseError.statusCode = response.status;\n parseError.bodyText = bodyText;\n throw parseError;\n }\n}\n\nexport function handleError(err: any, observer: SubscriptionObserver) {\n // if it is a network error, BUT there is graphql result info fire\n // the next observer before calling error this gives apollo-client\n // (and react-apollo) the `graphqlErrors` and `networkErrors` to\n // pass to UI this should only happen if we *also* have data as\n // part of the response key per the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we don't call next, the UI can only show networkError\n // because AC didn't get any graphqlErrors this is graphql\n // execution result info (i.e errors and possibly data) this is\n // because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status\n // of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next(err.result);\n }\n\n observer.error(err);\n}\n\nexport function parseAndCheckHttpResponse(operations: Operation | Operation[]) {\n return (response: Response) =>\n response\n .text()\n .then((bodyText) => parseJsonBody(response, bodyText))\n .then((result: any) => {\n if (\n !Array.isArray(result) &&\n !hasOwnProperty.call(result, \"data\") &&\n !hasOwnProperty.call(result, \"errors\")\n ) {\n // Data error\n throwServerError(\n response,\n result,\n `Server response was missing for query '${\n Array.isArray(operations) ?\n operations.map((op) => op.operationName)\n : operations.operationName\n }'.`\n );\n }\n return result;\n });\n}\n","import { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nimport type { Body } from \"./selectHttpOptionsAndBody.js\";\n\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nexport function rewriteURIForGET(chosenURI: string, body: Body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n const queryParams: string[] = [];\n const addQueryParam = (key: string, value: string) => {\n queryParams.push(`${key}=${encodeURIComponent(value)}`);\n };\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 let serializedVariables;\n try {\n serializedVariables = serializeFetchParameter(\n body.variables,\n \"Variables map\"\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam(\"variables\", serializedVariables);\n }\n if (body.extensions) {\n let serializedExtensions;\n try {\n serializedExtensions = serializeFetchParameter(\n body.extensions,\n \"Extensions map\"\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam(\"extensions\", serializedExtensions);\n }\n\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n let fragment = \"\",\n preFragment = chosenURI;\n const fragmentStart = chosenURI.indexOf(\"#\");\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n const queryParamsPrefix = preFragment.indexOf(\"?\") === -1 ? \"?\" : \"&\";\n const newURI =\n preFragment + queryParamsPrefix + queryParams.join(\"&\") + fragment;\n return { newURI };\n}\n","import type { ASTNode } from \"graphql\";\nimport { print } from \"../../utilities/index.js\";\n\nimport type { Operation } from \"../core/index.js\";\n\nexport interface Printer {\n (node: ASTNode, originalPrint: typeof print): string;\n}\n\nexport interface UriFunction {\n (operation: Operation): string;\n}\n\nexport interface Body {\n query?: string;\n operationName?: string;\n variables?: Record;\n extensions?: Record;\n}\n\nexport interface HttpOptions {\n /**\n * The URI to use when fetching operations.\n *\n * Defaults to '/graphql'.\n */\n uri?: string | UriFunction;\n\n /**\n * Passes the extensions field to your graphql server.\n *\n * Defaults to false.\n */\n includeExtensions?: boolean;\n\n /**\n * A `fetch`-compatible API to use when making requests.\n */\n fetch?: typeof fetch;\n\n /**\n * An object representing values to be sent as headers on the request.\n */\n headers?: Record;\n\n /**\n * If set to true, header names won't be automatically normalized to\n * lowercase. This allows for non-http-spec-compliant servers that might\n * expect capitalized header names.\n */\n preserveHeaderCase?: boolean;\n\n /**\n * The credentials policy you want to use for the fetch call.\n */\n credentials?: string;\n\n /**\n * Any overrides of the fetch options argument to pass to the fetch call.\n */\n fetchOptions?: any;\n\n /**\n * If set to true, use the HTTP GET method for query operations. Mutations\n * will still use the method specified in fetchOptions.method (which defaults\n * to POST).\n */\n useGETForQueries?: boolean;\n\n /**\n * If set to true, the default behavior of stripping unused variables\n * from the request will be disabled.\n *\n * Unused variables are likely to trigger server-side validation errors,\n * per https://spec.graphql.org/draft/#sec-All-Variables-Used, but this\n * includeUnusedVariables option can be useful if your server deviates\n * from the GraphQL specification by not strictly enforcing that rule.\n */\n includeUnusedVariables?: boolean;\n /**\n * A function to substitute for the default query print function. Can be\n * used to apply changes to the results of the print function.\n */\n print?: Printer;\n}\n\nexport interface HttpQueryOptions {\n includeQuery?: boolean;\n includeExtensions?: boolean;\n preserveHeaderCase?: boolean;\n}\n\nexport interface HttpConfig {\n http?: HttpQueryOptions;\n options?: any;\n headers?: Record;\n credentials?: any;\n}\n\nconst defaultHttpOptions: HttpQueryOptions = {\n includeQuery: true,\n includeExtensions: false,\n preserveHeaderCase: false,\n};\n\nconst defaultHeaders = {\n // headers are case insensitive (https://stackoverflow.com/a/5259004)\n accept: \"*/*\",\n // The content-type header describes the type of the body of the request, and\n // so it typically only is sent with requests that actually have bodies. One\n // could imagine that Apollo Client would remove this header when constructing\n // a GET request (which has no body), but we historically have not done that.\n // This means that browsers will preflight all Apollo Client requests (even\n // GET requests). Apollo Server's CSRF prevention feature (introduced in\n // AS3.7) takes advantage of this fact and does not block requests with this\n // header. If you want to drop this header from GET requests, then you should\n // probably replace it with a `apollo-require-preflight` header, or servers\n // with CSRF prevention enabled might block your GET request. See\n // https://www.apollographql.com/docs/apollo-server/security/cors/#preventing-cross-site-request-forgery-csrf\n // for more details.\n \"content-type\": \"application/json\",\n};\n\nconst defaultOptions = {\n method: \"POST\",\n};\n\nexport const fallbackHttpConfig = {\n http: defaultHttpOptions,\n headers: defaultHeaders,\n options: defaultOptions,\n};\n\nexport const defaultPrinter: Printer = (ast, printer) => printer(ast);\n\nexport function selectHttpOptionsAndBody(\n operation: Operation,\n fallbackConfig: HttpConfig,\n ...configs: Array\n) {\n configs.unshift(fallbackConfig);\n return selectHttpOptionsAndBodyInternal(\n operation,\n defaultPrinter,\n ...configs\n );\n}\n\nexport function selectHttpOptionsAndBodyInternal(\n operation: Operation,\n printer: Printer,\n ...configs: HttpConfig[]\n) {\n let options = {} as HttpConfig & Record;\n let http = {} as HttpQueryOptions;\n\n configs.forEach((config) => {\n options = {\n ...options,\n ...config.options,\n headers: {\n ...options.headers,\n ...config.headers,\n },\n };\n\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n\n http = {\n ...http,\n ...config.http,\n };\n });\n\n if (options.headers) {\n options.headers = removeDuplicateHeaders(\n options.headers,\n http.preserveHeaderCase\n );\n }\n\n //The body depends on the http options\n const { operationName, extensions, variables, query } = operation;\n const body: Body = { operationName, variables };\n\n if (http.includeExtensions) (body as any).extensions = extensions;\n\n // not sending the query (i.e persisted queries)\n if (http.includeQuery) (body as any).query = printer(query, print);\n\n return {\n options,\n body,\n };\n}\n\n// Remove potential duplicate header names, preserving last (by insertion order).\n// This is done to prevent unintentionally duplicating a header instead of\n// overwriting it (See #8447 and #8449).\nfunction removeDuplicateHeaders(\n headers: Record,\n preserveHeaderCase: boolean | undefined\n): typeof headers {\n // If we're not preserving the case, just remove duplicates w/ normalization.\n if (!preserveHeaderCase) {\n const normalizedHeaders: Record = {};\n Object.keys(Object(headers)).forEach((name) => {\n normalizedHeaders[name.toLowerCase()] = headers[name];\n });\n return normalizedHeaders;\n }\n\n // If we are preserving the case, remove duplicates w/ normalization,\n // preserving the original name.\n // This allows for non-http-spec-compliant servers that expect intentionally\n // capitalized header names (See #6741).\n const headerData: Record =\n {};\n Object.keys(Object(headers)).forEach((name) => {\n headerData[name.toLowerCase()] = {\n originalName: name,\n value: headers[name],\n };\n });\n\n const normalizedHeaders: Record = {};\n Object.keys(headerData).forEach((name) => {\n normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n });\n return normalizedHeaders;\n}\n","import type { Operation } from \"../core/index.js\";\n\nexport const selectURI = (\n operation: Operation,\n fallbackURI?: string | ((operation: Operation) => string)\n) => {\n const context = operation.getContext();\n const contextURI = context.uri;\n\n if (contextURI) {\n return contextURI;\n } else if (typeof fallbackURI === \"function\") {\n return fallbackURI(operation);\n } else {\n return (fallbackURI as string) || \"/graphql\";\n }\n};\n","import { newInvariantError } from \"../../utilities/globals/index.js\";\nimport type { InvariantError } from \"../../utilities/globals/index.js\";\n\nexport type ClientParseError = InvariantError & {\n parseError: Error;\n};\n\nexport const serializeFetchParameter = (p: any, label: string) => {\n let serialized;\n try {\n serialized = JSON.stringify(p);\n } catch (e: any) {\n const parseError = newInvariantError(\n `Network request failed. %s is not serializable: %s`,\n label,\n e.message\n ) as ClientParseError;\n parseError.parseError = e;\n throw parseError;\n }\n return serialized;\n};\n","import type { Operation, FetchResult, NextLink } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport type { ObservableSubscription } from \"../../utilities/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport type { DelayFunction, DelayFunctionOptions } from \"./delayFunction.js\";\nimport { buildDelayFunction } from \"./delayFunction.js\";\nimport type { RetryFunction, RetryFunctionOptions } from \"./retryFunction.js\";\nimport { buildRetryFunction } from \"./retryFunction.js\";\nimport type { SubscriptionObserver } from \"zen-observable-ts\";\nimport {\n ApolloError,\n graphQLResultHasProtocolErrors,\n PROTOCOL_ERRORS_SYMBOL,\n} from \"../../errors/index.js\";\n\nexport namespace RetryLink {\n export interface Options {\n /**\n * Configuration for the delay strategy to use, or a custom delay strategy.\n */\n delay?: DelayFunctionOptions | DelayFunction;\n\n /**\n * Configuration for the retry strategy to use, or a custom retry strategy.\n */\n attempts?: RetryFunctionOptions | RetryFunction;\n }\n}\n\n/**\n * Tracking and management of operations that may be (or currently are) retried.\n */\nclass RetryableOperation {\n private retryCount: number = 0;\n private currentSubscription: ObservableSubscription | null = null;\n private timerId: number | undefined;\n\n constructor(\n private observer: SubscriptionObserver,\n private operation: Operation,\n private forward: NextLink,\n private delayFor: DelayFunction,\n private retryIf: RetryFunction\n ) {\n this.try();\n }\n\n /**\n * Stop retrying for the operation, and cancel any in-progress requests.\n */\n public cancel() {\n if (this.currentSubscription) {\n this.currentSubscription.unsubscribe();\n }\n clearTimeout(this.timerId);\n this.timerId = undefined;\n this.currentSubscription = null;\n }\n\n private try() {\n this.currentSubscription = this.forward(this.operation).subscribe({\n next: (result) => {\n if (graphQLResultHasProtocolErrors(result)) {\n this.onError(\n new ApolloError({\n protocolErrors: result.extensions[PROTOCOL_ERRORS_SYMBOL],\n })\n );\n // Unsubscribe from the current subscription to prevent the `complete`\n // handler to be called as a result of the stream closing.\n this.currentSubscription?.unsubscribe();\n return;\n }\n\n this.observer.next(result);\n },\n error: this.onError,\n complete: this.observer.complete.bind(this.observer),\n });\n }\n\n private onError = async (error: any) => {\n this.retryCount += 1;\n\n // Should we retry?\n const shouldRetry = await this.retryIf(\n this.retryCount,\n this.operation,\n error\n );\n if (shouldRetry) {\n this.scheduleRetry(this.delayFor(this.retryCount, this.operation, error));\n return;\n }\n\n this.observer.error(error);\n };\n\n private scheduleRetry(delay: number) {\n if (this.timerId) {\n throw new Error(`RetryLink BUG! Encountered overlapping retries`);\n }\n\n this.timerId = setTimeout(() => {\n this.timerId = undefined;\n this.try();\n }, delay) as any as number;\n }\n}\n\nexport class RetryLink extends ApolloLink {\n private delayFor: DelayFunction;\n private retryIf: RetryFunction;\n\n constructor(options?: RetryLink.Options) {\n super();\n const { attempts, delay } = options || ({} as RetryLink.Options);\n this.delayFor =\n typeof delay === \"function\" ? delay : buildDelayFunction(delay);\n this.retryIf =\n typeof attempts === \"function\" ? attempts : buildRetryFunction(attempts);\n }\n\n public request(\n operation: Operation,\n nextLink: NextLink\n ): Observable {\n return new Observable((observer) => {\n const retryable = new RetryableOperation(\n observer,\n operation,\n nextLink,\n this.delayFor,\n this.retryIf\n );\n return () => {\n retryable.cancel();\n };\n });\n }\n}\n","import type { Operation } from \"../core/index.js\";\n\n/**\n * Advanced mode: a function that implements the strategy for calculating delays\n * for particular responses.\n */\nexport interface DelayFunction {\n (count: number, operation: Operation, error: any): number;\n}\n\nexport interface DelayFunctionOptions {\n /**\n * The number of milliseconds to wait before attempting the first retry.\n *\n * Delays will increase exponentially for each attempt. E.g. if this is\n * set to 100, subsequent retries will be delayed by 200, 400, 800, etc,\n * until they reach maxDelay.\n *\n * Note that if jittering is enabled, this is the _average_ delay.\n *\n * Defaults to 300.\n */\n initial?: number;\n\n /**\n * The maximum number of milliseconds that the link should wait for any\n * retry.\n *\n * Defaults to Infinity.\n */\n max?: number;\n\n /**\n * Whether delays between attempts should be randomized.\n *\n * This helps avoid thundering herd type situations by better distributing\n * load during major outages.\n *\n * Defaults to true.\n */\n jitter?: boolean;\n}\n\nexport function buildDelayFunction(\n delayOptions?: DelayFunctionOptions\n): DelayFunction {\n const { initial = 300, jitter = true, max = Infinity } = delayOptions || {};\n // If we're jittering, baseDelay is half of the maximum delay for that\n // attempt (and is, on average, the delay we will encounter).\n // If we're not jittering, adjust baseDelay so that the first attempt\n // lines up with initialDelay, for everyone's sanity.\n const baseDelay = jitter ? initial : initial / 2;\n\n return function delayFunction(count: number) {\n let delay = Math.min(max, baseDelay * 2 ** count);\n if (jitter) {\n // We opt for a full jitter approach for a mostly uniform distribution,\n // but bound it within initialDelay and delay for everyone's sanity.\n delay = Math.random() * delay;\n }\n\n return delay;\n };\n}\n","import type { Operation } from \"../core/index.js\";\n\n/**\n * Advanced mode: a function that determines both whether a particular\n * response should be retried.\n */\nexport interface RetryFunction {\n (count: number, operation: Operation, error: any): boolean | Promise;\n}\n\nexport interface RetryFunctionOptions {\n /**\n * The max number of times to try a single operation before giving up.\n *\n * Note that this INCLUDES the initial request as part of the count.\n * E.g. maxTries of 1 indicates no retrying should occur.\n *\n * Defaults to 5. Pass Infinity for infinite retries.\n */\n max?: number;\n\n /**\n * Predicate function that determines whether a particular error should\n * trigger a retry.\n *\n * For example, you may want to not retry 4xx class HTTP errors.\n *\n * By default, all errors are retried.\n */\n retryIf?: (error: any, operation: Operation) => boolean | Promise;\n}\n\nexport function buildRetryFunction(\n retryOptions?: RetryFunctionOptions\n): RetryFunction {\n const { retryIf, max = 5 } = retryOptions || ({} as RetryFunctionOptions);\n return function retryFunction(count, operation, error) {\n if (count >= max) return false;\n return retryIf ? retryIf(error, operation) : !!error;\n };\n}\n","import type { VariableDefinitionNode, DocumentNode } from \"graphql\";\nimport { visit } from \"graphql\";\n\nexport function filterOperationVariables(\n variables: Record,\n query: DocumentNode\n) {\n const result = { ...variables };\n const unusedNames = new Set(Object.keys(variables));\n visit(query, {\n Variable(node, _key, parent) {\n // A variable type definition at the top level of a query is not\n // enough to silence server-side errors about the variable being\n // unused, so variable definitions do not count as usage.\n // https://spec.graphql.org/draft/#sec-All-Variables-Used\n if (\n parent &&\n (parent as VariableDefinitionNode).kind !== \"VariableDefinition\"\n ) {\n unusedNames.delete(node.name.value);\n }\n },\n });\n unusedNames.forEach((name) => {\n delete result![name];\n });\n return result;\n}\n","import { Observable } from \"../../utilities/index.js\";\n\nexport function fromError(errorValue: any): Observable {\n return new Observable((observer) => {\n observer.error(errorValue);\n });\n}\n","export type ServerError = Error & {\n response: Response;\n result: Record | string;\n statusCode: number;\n};\n\nexport const throwServerError = (\n response: Response,\n result: any,\n message: string\n) => {\n const error = new Error(message) as ServerError;\n error.name = \"ServerError\";\n error.response = response;\n error.statusCode = response.status;\n error.result = result;\n throw error;\n};\n","import { Kind } from \"graphql\";\nimport type { FragmentDefinitionNode, SelectionSetNode } from \"graphql\";\nimport {\n getFragmentMaskMode,\n maybeDeepFreeze,\n resultKeyNameFromField,\n} from \"../utilities/index.js\";\nimport type { FragmentMap } from \"../utilities/index.js\";\nimport type { ApolloCache } from \"../cache/index.js\";\nimport { disableWarningsSlot } from \"./utils.js\";\nimport { invariant } from \"../utilities/globals/index.js\";\n\ninterface MaskingContext {\n operationType: \"query\" | \"mutation\" | \"subscription\" | \"fragment\";\n operationName: string | undefined;\n fragmentMap: FragmentMap;\n cache: ApolloCache;\n mutableTargets: WeakMap;\n knownChanged: WeakSet;\n}\n\nexport function maskDefinition(\n data: Record,\n selectionSet: SelectionSetNode,\n context: MaskingContext\n) {\n return disableWarningsSlot.withValue(true, () => {\n const masked = maskSelectionSet(data, selectionSet, context, false);\n\n if (Object.isFrozen(data)) {\n maybeDeepFreeze(masked);\n }\n return masked;\n });\n}\n\nfunction getMutableTarget(\n data: Record,\n mutableTargets: WeakMap\n): typeof data {\n if (mutableTargets.has(data)) {\n return mutableTargets.get(data);\n }\n\n const mutableTarget = Array.isArray(data) ? [] : Object.create(null);\n mutableTargets.set(data, mutableTarget);\n return mutableTarget;\n}\n\nfunction maskSelectionSet(\n data: any,\n selectionSet: SelectionSetNode,\n context: MaskingContext,\n migration: boolean,\n path?: string | undefined\n): typeof data {\n const { knownChanged } = context;\n const memo = getMutableTarget(data, context.mutableTargets);\n\n if (Array.isArray(data)) {\n for (const [index, item] of Array.from(data.entries())) {\n if (item === null) {\n memo[index] = null;\n continue;\n }\n\n const masked = maskSelectionSet(\n item,\n selectionSet,\n context,\n migration,\n __DEV__ ? `${path || \"\"}[${index}]` : void 0\n );\n if (knownChanged.has(masked)) {\n knownChanged.add(memo);\n }\n\n memo[index] = masked;\n }\n\n return knownChanged.has(memo) ? memo : data;\n }\n\n for (const selection of selectionSet.selections) {\n let value: any;\n\n // we later want to add acessor warnings to the final result\n // so we need a new object to add the accessor warning to\n if (migration) {\n knownChanged.add(memo);\n }\n\n if (selection.kind === Kind.FIELD) {\n const keyName = resultKeyNameFromField(selection);\n const childSelectionSet = selection.selectionSet;\n\n value = memo[keyName] || data[keyName];\n\n if (value === void 0) {\n continue;\n }\n\n if (childSelectionSet && value !== null) {\n const masked = maskSelectionSet(\n data[keyName],\n childSelectionSet,\n context,\n migration,\n __DEV__ ? `${path || \"\"}.${keyName}` : void 0\n );\n\n if (knownChanged.has(masked)) {\n value = masked;\n }\n }\n\n if (!__DEV__) {\n memo[keyName] = value;\n }\n if (__DEV__) {\n if (\n migration &&\n keyName !== \"__typename\" &&\n // either the field is not present in the memo object\n // or it has a `get` descriptor, not a `value` descriptor\n // => it is a warning accessor and we can overwrite it\n // with another accessor\n !Object.getOwnPropertyDescriptor(memo, keyName)?.value\n ) {\n Object.defineProperty(\n memo,\n keyName,\n getAccessorWarningDescriptor(\n keyName,\n value,\n path || \"\",\n context.operationName,\n context.operationType\n )\n );\n } else {\n delete memo[keyName];\n memo[keyName] = value;\n }\n }\n }\n\n if (\n selection.kind === Kind.INLINE_FRAGMENT &&\n (!selection.typeCondition ||\n context.cache.fragmentMatches!(selection, data.__typename))\n ) {\n value = maskSelectionSet(\n data,\n selection.selectionSet,\n context,\n migration,\n path\n );\n }\n\n if (selection.kind === Kind.FRAGMENT_SPREAD) {\n const fragmentName = selection.name.value;\n const fragment: FragmentDefinitionNode | null =\n context.fragmentMap[fragmentName] ||\n (context.fragmentMap[fragmentName] =\n context.cache.lookupFragment(fragmentName)!);\n invariant(\n fragment,\n \"Could not find fragment with name '%s'.\",\n fragmentName\n );\n\n const mode = getFragmentMaskMode(selection);\n\n if (mode !== \"mask\") {\n value = maskSelectionSet(\n data,\n fragment.selectionSet,\n context,\n mode === \"migrate\",\n path\n );\n }\n }\n\n if (knownChanged.has(value)) {\n knownChanged.add(memo);\n }\n }\n\n if (\"__typename\" in data && !(\"__typename\" in memo)) {\n memo.__typename = data.__typename;\n }\n\n // This check prevents cases where masked fields may accidentally be\n // returned as part of this object when the fragment also selects\n // additional fields from the same child selection.\n if (Object.keys(memo).length !== Object.keys(data).length) {\n knownChanged.add(memo);\n }\n\n return knownChanged.has(memo) ? memo : data;\n}\n\nfunction getAccessorWarningDescriptor(\n fieldName: string,\n value: any,\n path: string,\n operationName: string | undefined,\n operationType: string\n): PropertyDescriptor {\n let getValue = () => {\n if (disableWarningsSlot.getValue()) {\n return value;\n }\n\n invariant.warn(\n \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n operationName ?\n `${operationType} '${operationName}'`\n : `anonymous ${operationType}`,\n `${path}.${fieldName}`.replace(/^\\./, \"\")\n );\n\n getValue = () => value;\n\n return value;\n };\n\n return {\n get() {\n return getValue();\n },\n set(newValue) {\n getValue = () => newValue;\n },\n enumerable: true,\n configurable: true,\n };\n}\n","import { Kind } from \"graphql\";\nimport type { FragmentDefinitionNode } from \"graphql\";\nimport type {\n ApolloCache,\n DocumentNode,\n TypedDocumentNode,\n} from \"../core/index.js\";\nimport {\n MapImpl,\n SetImpl,\n warnOnImproperCacheImplementation,\n} from \"./utils.js\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport equal from \"@wry/equality\";\nimport { maskDefinition } from \"./maskDefinition.js\";\nimport {\n createFragmentMap,\n getFragmentDefinitions,\n} from \"../utilities/index.js\";\n\n/** @internal */\nexport function maskFragment(\n data: TData,\n document: TypedDocumentNode | DocumentNode,\n cache: ApolloCache,\n fragmentName?: string\n): TData {\n if (!cache.fragmentMatches) {\n if (__DEV__) {\n warnOnImproperCacheImplementation();\n }\n\n return data;\n }\n\n const fragments = document.definitions.filter(\n (node): node is FragmentDefinitionNode =>\n node.kind === Kind.FRAGMENT_DEFINITION\n );\n\n if (typeof fragmentName === \"undefined\") {\n invariant(\n fragments.length === 1,\n `Found %s fragments. \\`fragmentName\\` must be provided when there is not exactly 1 fragment.`,\n fragments.length\n );\n fragmentName = fragments[0].name.value;\n }\n\n const fragment = fragments.find(\n (fragment) => fragment.name.value === fragmentName\n );\n\n invariant(\n !!fragment,\n `Could not find fragment with name \"%s\".`,\n fragmentName\n );\n\n if (data == null) {\n // Maintain the original `null` or `undefined` value\n return data;\n }\n\n if (equal(data, {})) {\n // Return early and skip the masking algorithm if we don't have any data\n // yet. This can happen when cache.diff returns an empty object which is\n // used from watchFragment.\n return data;\n }\n\n return maskDefinition(data, fragment.selectionSet, {\n operationType: \"fragment\",\n operationName: fragment.name.value,\n fragmentMap: createFragmentMap(getFragmentDefinitions(document)),\n cache,\n mutableTargets: new MapImpl(),\n knownChanged: new SetImpl(),\n });\n}\n","import { Slot } from \"optimism\";\nimport { invariant } from \"../utilities/globals/index.js\";\nimport { canUseWeakMap, canUseWeakSet } from \"../utilities/index.js\";\n\nexport const MapImpl = canUseWeakMap ? WeakMap : Map;\nexport const SetImpl = canUseWeakSet ? WeakSet : Set;\n\n// Contextual slot that allows us to disable accessor warnings on fields when in\n// migrate mode.\n/** @internal */\nexport const disableWarningsSlot = new Slot();\n\nlet issuedWarning = false;\nexport function warnOnImproperCacheImplementation() {\n if (!issuedWarning) {\n issuedWarning = true;\n invariant.warn(\n \"The configured cache does not support data masking which effectively disables it. Please use a cache that supports data masking or disable data masking to silence this warning.\"\n );\n }\n}\n","// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds\n// object keys weakly, yet can also hold non-object keys, unlike the\n// native `WeakMap`.\n\n// If no makeData function is supplied, the looked-up data will be an empty,\n// null-prototype Object.\nconst defaultMakeData = () => Object.create(null);\n\n// Useful for processing arguments objects as well as arrays.\nconst { forEach, slice } = Array.prototype;\nconst { hasOwnProperty } = Object.prototype;\n\nexport class Trie {\n // Since a `WeakMap` cannot hold primitive values as keys, we need a\n // backup `Map` instance to hold primitive keys. Both `this._weakMap`\n // and `this._strongMap` are lazily initialized.\n private weak?: WeakMap>;\n private strong?: Map>;\n private data?: Data;\n\n constructor(\n private weakness = true,\n private makeData: (array: any[]) => Data = defaultMakeData,\n ) {}\n\n public lookup(...array: T): Data;\n public lookup(): Data {\n return this.lookupArray(arguments);\n }\n\n public lookupArray(array: T): Data {\n let node: Trie = this;\n forEach.call(array, key => node = node.getChildTrie(key));\n return hasOwnProperty.call(node, \"data\")\n ? node.data as Data\n : node.data = this.makeData(slice.call(array));\n }\n\n public peek(...array: T): Data | undefined;\n public peek(): Data | undefined {\n return this.peekArray(arguments);\n }\n\n public peekArray(array: T): Data | undefined {\n let node: Trie | undefined = this;\n\n for (let i = 0, len = array.length; node && i < len; ++i) {\n const map = node.mapFor(array[i], false);\n node = map && map.get(array[i]);\n }\n\n return node && node.data;\n }\n\n public remove(...array: any[]): Data | undefined;\n public remove(): Data | undefined {\n return this.removeArray(arguments);\n }\n\n public removeArray(array: T): Data | undefined {\n let data: Data | undefined;\n\n if (array.length) {\n const head = array[0];\n const map = this.mapFor(head, false);\n const child = map && map.get(head);\n if (child) {\n data = child.removeArray(slice.call(array, 1));\n if (!child.data && !child.weak && !(child.strong && child.strong.size)) {\n map.delete(head);\n }\n }\n } else {\n data = this.data;\n delete this.data;\n }\n\n return data;\n }\n\n private getChildTrie(key: any) {\n const map = this.mapFor(key, true)!;\n let child = map.get(key);\n if (!child) map.set(key, child = new Trie(this.weakness, this.makeData));\n return child;\n }\n\n private mapFor(key: any, create: boolean): Trie[\"weak\" | \"strong\"] | undefined {\n return this.weakness && isObjRef(key)\n ? this.weak || (create ? this.weak = new WeakMap : void 0)\n : this.strong || (create ? this.strong = new Map : void 0);\n }\n}\n\nfunction isObjRef(value: any) {\n switch (typeof value) {\n case \"object\":\n if (value === null) break;\n // Fall through to return true...\n case \"function\":\n return true;\n }\n return false;\n}\n","const genericMessage = \"Invariant Violation\";\nconst {\n setPrototypeOf = function (obj: any, proto: any) {\n obj.__proto__ = proto;\n return obj;\n },\n} = Object as any;\n\nexport class InvariantError extends Error {\n framesToPop = 1;\n name = genericMessage;\n constructor(message: string | number = genericMessage) {\n super(\n typeof message === \"number\"\n ? `${genericMessage}: ${message} (see https://github.com/apollographql/invariant-packages)`\n : message\n );\n setPrototypeOf(this, InvariantError.prototype);\n }\n}\n\nexport function invariant(\n condition: any,\n message?: string | number,\n): asserts condition {\n if (!condition) {\n throw new InvariantError(message);\n }\n}\n\nconst verbosityLevels = [\"debug\", \"log\", \"warn\", \"error\", \"silent\"] as const;\nexport type VerbosityLevel = (typeof verbosityLevels)[number];\nexport type ConsoleMethodName = Exclude;\nlet verbosityLevel = verbosityLevels.indexOf(\"log\");\n\nfunction wrapConsoleMethod(name: M) {\n return function () {\n if (verbosityLevels.indexOf(name) >= verbosityLevel) {\n // Default to console.log if this host environment happens not to provide\n // all the console.* methods we need.\n const method = console[name] || console.log;\n return method.apply(console, arguments as any);\n }\n } as (typeof console)[M];\n}\n\nexport namespace invariant {\n export const debug = wrapConsoleMethod(\"debug\");\n export const log = wrapConsoleMethod(\"log\");\n export const warn = wrapConsoleMethod(\"warn\");\n export const error = wrapConsoleMethod(\"error\");\n}\n\nexport function setVerbosity(level: VerbosityLevel): VerbosityLevel {\n const old = verbosityLevels[verbosityLevel];\n verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));\n return old;\n}\n\nexport default invariant;\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\n\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"./ApolloContext.js\";\n\nexport interface ApolloConsumerProps {\n children: (client: ApolloClient) => ReactTypes.ReactNode;\n}\n\nexport const ApolloConsumer: ReactTypes.FC = (props) => {\n const ApolloContext = getApolloContext();\n return (\n \n {(context: any) => {\n invariant(\n context && context.client,\n 'Could not find \"client\" in the context of ApolloConsumer. ' +\n \"Wrap the root component in an .\"\n );\n return props.children(context.client);\n }}\n \n );\n};\n","import * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { canUseSymbol } from \"../../utilities/index.js\";\nimport type { RenderPromises } from \"../ssr/index.js\";\nimport { invariant } from \"../../utilities/globals/index.js\";\n\nexport interface ApolloContextValue {\n client?: ApolloClient;\n renderPromises?: RenderPromises;\n}\n\n// To make sure Apollo Client doesn't create more than one React context\n// (which can lead to problems like having an Apollo Client instance added\n// in one context, then attempting to retrieve it from another different\n// context), a single Apollo context is created and tracked in global state.\nconst contextKey =\n canUseSymbol ? Symbol.for(\"__APOLLO_CONTEXT__\") : \"__APOLLO_CONTEXT__\";\n\nexport function getApolloContext(): ReactTypes.Context {\n invariant(\n \"createContext\" in React,\n \"Invoking `getApolloContext` in an environment where `React.createContext` is not available.\\n\" +\n \"The Apollo Client functionality you are trying to use is only available in React Client Components.\\n\" +\n 'Please make sure to add \"use client\" at the top of your file.\\n' +\n // TODO: change to React documentation once React documentation contains information about Client Components\n \"For more information, see https://nextjs.org/docs/getting-started/react-essentials#client-components\"\n );\n\n let context = (React.createContext as any)[\n contextKey\n ] as React.Context;\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}\n\n/**\n * @deprecated This function has no \"resetting\" effect since Apollo Client 3.4.12,\n * and will be removed in the next major version of Apollo Client.\n * If you want to get the Apollo Context, use `getApolloContext` instead.\n */\nexport const resetApolloContext = getApolloContext;\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport type * as ReactTypes from \"react\";\n\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"./ApolloContext.js\";\n\nexport interface ApolloProviderProps {\n client: ApolloClient;\n children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n}\n\nexport const ApolloProvider: ReactTypes.FC> = ({\n client,\n children,\n}) => {\n const ApolloContext = getApolloContext();\n const parentContext = React.useContext(ApolloContext);\n\n const context = React.useMemo(() => {\n return {\n ...parentContext,\n client: client || parentContext.client,\n };\n }, [parentContext, client]);\n\n invariant(\n context.client,\n \"ApolloProvider was not passed a client instance. Make \" +\n 'sure you pass in your client via the \"client\" prop.'\n );\n\n return (\n {children}\n );\n};\n","import type { DependencyList } from \"react\";\nimport * as React from \"rehackt\";\nimport { equal } from \"@wry/equality\";\n\nexport function useDeepMemo(\n memoFn: () => TValue,\n deps: DependencyList\n) {\n const ref = React.useRef<{ deps: DependencyList; value: TValue }>(void 0);\n\n if (!ref.current || !equal(ref.current.deps, deps)) {\n // eslint-disable-next-line react-compiler/react-compiler\n ref.current = { value: memoFn(), deps };\n }\n\n return ref.current.value;\n}\n","import * as React from \"rehackt\";\nimport { canUseDOM } from \"../../../utilities/index.js\";\n\n// use canUseDOM here instead of canUseLayoutEffect because we want to be able\n// to use useLayoutEffect in our jest tests. useLayoutEffect seems to work fine\n// in useSuspenseQuery tests, but to honor the original comment about the\n// warnings for useSyncExternalStore implementation, canUseLayoutEffect is left\n// alone.\nexport const useIsomorphicLayoutEffect =\n canUseDOM ? React.useLayoutEffect : React.useEffect;\n","import type {\n useQuery,\n useSuspenseQuery,\n useBackgroundQuery,\n useReadQuery,\n useFragment,\n useQueryRefHandlers,\n useSuspenseFragment,\n} from \"../index.js\";\nimport type { QueryManager } from \"../../../core/QueryManager.js\";\nimport type { ApolloClient } from \"../../../core/ApolloClient.js\";\nimport type { ObservableQuery } from \"../../../core/ObservableQuery.js\";\nimport type { createQueryPreloader } from \"../../query-preloader/createQueryPreloader.js\";\n\nconst wrapperSymbol = Symbol.for(\"apollo.hook.wrappers\");\n\ninterface WrappableHooks {\n createQueryPreloader: typeof createQueryPreloader;\n useQuery: typeof useQuery;\n useSuspenseQuery: typeof useSuspenseQuery;\n useSuspenseFragment: typeof useSuspenseFragment;\n useBackgroundQuery: typeof useBackgroundQuery;\n useReadQuery: typeof useReadQuery;\n useFragment: typeof useFragment;\n useQueryRefHandlers: typeof useQueryRefHandlers;\n}\n\n/**\n * @internal\n * Can be used to correctly type the [Symbol.for(\"apollo.hook.wrappers\")] property of\n * `QueryManager`, to override/wrap hook functionality.\n */\nexport type HookWrappers = {\n [K in keyof WrappableHooks]?: (\n originalHook: WrappableHooks[K]\n ) => WrappableHooks[K];\n};\n\ninterface QueryManagerWithWrappers extends QueryManager {\n [wrapperSymbol]?: HookWrappers;\n}\n\n/**\n * @internal\n *\n * Makes an Apollo Client hook \"wrappable\".\n * That means that the Apollo Client instance can expose a \"wrapper\" that will be\n * used to wrap the original hook implementation with additional logic.\n * @example\n * ```tsx\n * // this is already done in `@apollo/client` for all wrappable hooks (see `WrappableHooks`)\n * // following this pattern\n * function useQuery() {\n * return wrapHook('useQuery', _useQuery, options.client)(query, options);\n * }\n * function _useQuery(query, options) {\n * // original implementation\n * }\n *\n * // this is what a library like `@apollo/client-react-streaming` would do\n * class ApolloClientWithStreaming extends ApolloClient {\n * constructor(options) {\n * super(options);\n * this.queryManager[Symbol.for(\"apollo.hook.wrappers\")] = {\n * useQuery: (original) => (query, options) => {\n * console.log(\"useQuery was called with options\", options);\n * return original(query, options);\n * }\n * }\n * }\n * }\n *\n * // this will now log the options and then call the original `useQuery`\n * const client = new ApolloClientWithStreaming({ ... });\n * useQuery(query, { client });\n * ```\n */\nexport function wrapHook any>(\n hookName: keyof WrappableHooks,\n useHook: Hook,\n clientOrObsQuery: ObservableQuery | ApolloClient\n): Hook {\n const queryManager = (\n clientOrObsQuery as unknown as {\n // both `ApolloClient` and `ObservableQuery` have a `queryManager` property\n // but they're both `private`, so we have to cast around for a bit here.\n queryManager: QueryManagerWithWrappers;\n }\n )[\"queryManager\"];\n const wrappers = queryManager && queryManager[wrapperSymbol];\n const wrapper: undefined | ((wrap: Hook) => Hook) =\n wrappers && (wrappers[hookName] as any);\n return wrapper ? wrapper(useHook) : useHook;\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"../context/index.js\";\n\n/**\n * @example\n * ```jsx\n * import { useApolloClient } from '@apollo/client';\n *\n * function SomeComponent() {\n * const client = useApolloClient();\n * // `client` is now set to the `ApolloClient` instance being used by the\n * // application (that was configured using something like `ApolloProvider`)\n * }\n * ```\n *\n * @since 3.0.0\n * @returns The `ApolloClient` instance being used by the application.\n */\nexport function useApolloClient(\n override?: ApolloClient\n): ApolloClient {\n const context = React.useContext(getApolloContext());\n const client = override || context.client;\n invariant(\n !!client,\n 'Could not find \"client\" in the context or passed in as an option. ' +\n \"Wrap the root component in an , or pass an ApolloClient \" +\n \"instance in via options.\"\n );\n\n return client;\n}\n","import * as React from \"rehackt\";\nimport type { DocumentNode } from \"graphql\";\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport type {\n MutationFunctionOptions,\n MutationHookOptions,\n MutationResult,\n MutationTuple,\n NoInfer,\n} from \"../types/types.js\";\n\nimport type {\n ApolloCache,\n DefaultContext,\n MutationOptions,\n OperationVariables,\n} from \"../../core/index.js\";\nimport { mergeOptions } from \"../../utilities/index.js\";\nimport { equal } from \"@wry/equality\";\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport { ApolloError } from \"../../errors/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\n\n/**\n *\n *\n * > Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of `useMutation`.\n *\n * @example\n * ```jsx\n * import { gql, useMutation } from '@apollo/client';\n *\n * const ADD_TODO = gql`\n * mutation AddTodo($type: String!) {\n * addTodo(type: $type) {\n * id\n * type\n * }\n * }\n * `;\n *\n * function AddTodo() {\n * let input;\n * const [addTodo, { data }] = useMutation(ADD_TODO);\n *\n * return (\n *
\n * {\n * e.preventDefault();\n * addTodo({ variables: { type: input.value } });\n * input.value = '';\n * }}\n * >\n * {\n * input = node;\n * }}\n * />\n * \n * \n *
\n * );\n * }\n * ```\n * @since 3.0.0\n * @param mutation - A GraphQL mutation document parsed into an AST by `gql`.\n * @param options - Options to control how the mutation is executed.\n * @returns A tuple in the form of `[mutate, result]`\n */\nexport function useMutation<\n TData = any,\n TVariables = OperationVariables,\n TContext = DefaultContext,\n TCache extends ApolloCache = ApolloCache,\n>(\n mutation: DocumentNode | TypedDocumentNode,\n options?: MutationHookOptions<\n NoInfer,\n NoInfer,\n TContext,\n TCache\n >\n): MutationTuple {\n const client = useApolloClient(options?.client);\n verifyDocumentType(mutation, DocumentType.Mutation);\n const [result, setResult] = React.useState>({\n called: false,\n loading: false,\n client,\n });\n\n const ref = React.useRef({\n result,\n mutationId: 0,\n isMounted: true,\n client,\n mutation,\n options,\n });\n\n useIsomorphicLayoutEffect(() => {\n Object.assign(ref.current, { client, options, mutation });\n });\n\n const execute = React.useCallback(\n (\n executeOptions: MutationFunctionOptions<\n TData,\n TVariables,\n TContext,\n TCache\n > = {}\n ) => {\n const { options, mutation } = ref.current;\n const baseOptions = { ...options, mutation };\n const client = executeOptions.client || ref.current.client;\n\n if (\n !ref.current.result.loading &&\n !baseOptions.ignoreResults &&\n ref.current.isMounted\n ) {\n setResult(\n (ref.current.result = {\n loading: true,\n error: void 0,\n data: void 0,\n called: true,\n client,\n })\n );\n }\n\n const mutationId = ++ref.current.mutationId;\n const clientOptions = mergeOptions(baseOptions, executeOptions);\n\n return client\n .mutate(clientOptions as MutationOptions)\n .then(\n (response) => {\n const { data, errors } = response;\n const error =\n errors && errors.length > 0 ?\n new ApolloError({ graphQLErrors: errors })\n : void 0;\n\n const onError =\n executeOptions.onError || ref.current.options?.onError;\n\n if (error && onError) {\n onError(\n error,\n clientOptions as MutationOptions\n );\n }\n\n if (\n mutationId === ref.current.mutationId &&\n !clientOptions.ignoreResults\n ) {\n const result = {\n called: true,\n loading: false,\n data,\n error,\n client,\n };\n\n if (ref.current.isMounted && !equal(ref.current.result, result)) {\n setResult((ref.current.result = result));\n }\n }\n\n const onCompleted =\n executeOptions.onCompleted || ref.current.options?.onCompleted;\n\n if (!error) {\n onCompleted?.(\n response.data!,\n clientOptions as MutationOptions\n );\n }\n\n return response;\n },\n (error) => {\n if (\n mutationId === ref.current.mutationId &&\n ref.current.isMounted\n ) {\n const result = {\n loading: false,\n error,\n data: void 0,\n called: true,\n client,\n };\n\n if (!equal(ref.current.result, result)) {\n setResult((ref.current.result = result));\n }\n }\n\n const onError =\n executeOptions.onError || ref.current.options?.onError;\n\n if (onError) {\n onError(\n error,\n clientOptions as MutationOptions\n );\n\n // TODO(brian): why are we returning this here???\n return { data: void 0, errors: error };\n }\n\n throw error;\n }\n );\n },\n []\n );\n\n const reset = React.useCallback(() => {\n if (ref.current.isMounted) {\n const result = {\n called: false,\n loading: false,\n client: ref.current.client,\n };\n Object.assign(ref.current, { mutationId: 0, result });\n setResult(result);\n }\n }, []);\n\n React.useEffect(() => {\n const current = ref.current;\n // eslint-disable-next-line react-compiler/react-compiler\n current.isMounted = true;\n\n return () => {\n current.isMounted = false;\n };\n }, []);\n\n return [execute, { reset, ...result }];\n}\n","/**\n * Function parameters in this file try to follow a common order for the sake of\n * readability and consistency. The order is as follows:\n *\n * resultData\n * observable\n * client\n * query\n * options\n * watchQueryOptions\n * makeWatchQueryOptions\n * isSSRAllowed\n * disableNetworkFetches\n * partialRefetch\n * renderPromises\n * isSyncSSR\n * callbacks\n */\n/** */\nimport { invariant } from \"../../utilities/globals/index.js\";\n\nimport * as React from \"rehackt\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport { equal } from \"@wry/equality\";\n\nimport type {\n ApolloClient,\n DefaultOptions,\n OperationVariables,\n WatchQueryFetchPolicy,\n} from \"../../core/index.js\";\nimport { mergeOptions } from \"../../utilities/index.js\";\nimport { getApolloContext } from \"../context/index.js\";\nimport { ApolloError } from \"../../errors/index.js\";\nimport type {\n ApolloQueryResult,\n ObservableQuery,\n DocumentNode,\n TypedDocumentNode,\n WatchQueryOptions,\n} from \"../../core/index.js\";\nimport { NetworkStatus } from \"../../core/index.js\";\nimport type {\n QueryHookOptions,\n QueryResult,\n ObservableQueryFields,\n NoInfer,\n} from \"../types/types.js\";\n\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport {\n compact,\n isNonEmptyArray,\n maybeDeepFreeze,\n} from \"../../utilities/index.js\";\nimport { wrapHook } from \"./internal/index.js\";\nimport type { RenderPromises } from \"../ssr/RenderPromises.js\";\nimport type { MaybeMasked } from \"../../masking/index.js\";\n\nconst {\n prototype: { hasOwnProperty },\n} = Object;\n\ntype InternalQueryResult = Omit<\n QueryResult,\n Exclude, \"variables\">\n>;\n\nfunction noop() {}\nconst lastWatchOptions = Symbol();\n\ninterface ObsQueryWithMeta\n extends ObservableQuery {\n [lastWatchOptions]?: WatchQueryOptions;\n}\n\nexport interface InternalResult {\n // These members are populated by getCurrentResult and setResult, and it's\n // okay/normal for them to be initially undefined.\n current?: undefined | InternalQueryResult;\n previousData?: undefined | MaybeMasked;\n}\n\ninterface InternalState {\n client: ReturnType;\n query: DocumentNode | TypedDocumentNode;\n observable: ObsQueryWithMeta;\n resultData: InternalResult;\n}\n\nexport type UpdateInternalState<\n TData,\n TVariables extends OperationVariables,\n> = (state: InternalState) => void;\n\ninterface Callbacks {\n // Defining these methods as no-ops on the prototype allows us to call\n // state.onCompleted and/or state.onError without worrying about whether a\n // callback was provided.\n onCompleted(data: MaybeMasked): void;\n onError(error: ApolloError): void;\n}\n\n/**\n * A hook for executing queries in an Apollo application.\n *\n * To run a query within a React component, call `useQuery` and pass it a GraphQL query document.\n *\n * When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.\n *\n * > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.\n *\n * @example\n * ```jsx\n * import { gql, useQuery } from '@apollo/client';\n *\n * const GET_GREETING = gql`\n * query GetGreeting($language: String!) {\n * greeting(language: $language) {\n * message\n * }\n * }\n * `;\n *\n * function Hello() {\n * const { loading, error, data } = useQuery(GET_GREETING, {\n * variables: { language: 'english' },\n * });\n * if (loading) return

Loading ...

;\n * return

Hello {data.greeting.message}!

;\n * }\n * ```\n * @since 3.0.0\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Options to control how the query is executed.\n * @returns Query result object\n */\nexport function useQuery<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: QueryHookOptions<\n NoInfer,\n NoInfer\n > = Object.create(null)\n): QueryResult {\n return wrapHook(\n \"useQuery\",\n // eslint-disable-next-line react-compiler/react-compiler\n useQuery_,\n useApolloClient(options && options.client)\n )(query, options);\n}\n\nfunction useQuery_<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: QueryHookOptions, NoInfer>\n) {\n const { result, obsQueryFields } = useQueryInternals(query, options);\n return React.useMemo(\n () => ({ ...result, ...obsQueryFields }),\n [result, obsQueryFields]\n );\n}\n\nfunction useInternalState<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n client: ApolloClient,\n query: DocumentNode | TypedDocumentNode,\n options: QueryHookOptions, NoInfer>,\n renderPromises: RenderPromises | undefined,\n makeWatchQueryOptions: () => WatchQueryOptions\n) {\n function createInternalState(previous?: InternalState) {\n verifyDocumentType(query, DocumentType.Query);\n\n const internalState: InternalState = {\n client,\n query,\n observable:\n // See if there is an existing observable that was used to fetch the same\n // data and if so, use it instead since it will contain the proper queryId\n // to fetch the result set. This is used during SSR.\n (renderPromises &&\n renderPromises.getSSRObservable(makeWatchQueryOptions())) ||\n client.watchQuery(\n getObsQueryOptions(void 0, client, options, makeWatchQueryOptions())\n ),\n resultData: {\n // Reuse previousData from previous InternalState (if any) to provide\n // continuity of previousData even if/when the query or client changes.\n previousData: previous?.resultData.current?.data,\n },\n };\n\n return internalState as InternalState;\n }\n\n let [internalState, updateInternalState] =\n React.useState(createInternalState);\n\n /**\n * Used by `useLazyQuery` when a new query is executed.\n * We keep this logic here since it needs to update things in unsafe\n * ways and here we at least can keep track of that in a single place.\n */\n function onQueryExecuted(\n watchQueryOptions: WatchQueryOptions\n ) {\n // this needs to be set to prevent an immediate `resubscribe` in the\n // next rerender of the `useQuery` internals\n Object.assign(internalState.observable, {\n [lastWatchOptions]: watchQueryOptions,\n });\n const resultData = internalState.resultData;\n updateInternalState({\n ...internalState,\n // might be a different query\n query: watchQueryOptions.query,\n resultData: Object.assign(resultData, {\n // We need to modify the previous `resultData` object as we rely on the\n // object reference in other places\n previousData: resultData.current?.data || resultData.previousData,\n current: undefined,\n }),\n });\n }\n\n if (client !== internalState.client || query !== internalState.query) {\n // If the client or query have changed, we need to create a new InternalState.\n // This will trigger a re-render with the new state, but it will also continue\n // to run the current render function to completion.\n // Since we sometimes trigger some side-effects in the render function, we\n // re-assign `state` to the new state to ensure that those side-effects are\n // triggered with the new state.\n const newInternalState = createInternalState(internalState);\n updateInternalState(newInternalState);\n return [newInternalState, onQueryExecuted] as const;\n }\n\n return [internalState, onQueryExecuted] as const;\n}\n\nexport function useQueryInternals<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n query: DocumentNode | TypedDocumentNode,\n options: QueryHookOptions, NoInfer>\n) {\n const client = useApolloClient(options.client);\n\n const renderPromises = React.useContext(getApolloContext()).renderPromises;\n const isSyncSSR = !!renderPromises;\n const disableNetworkFetches = client.disableNetworkFetches;\n const ssrAllowed = options.ssr !== false && !options.skip;\n const partialRefetch = options.partialRefetch;\n\n const makeWatchQueryOptions = createMakeWatchQueryOptions(\n client,\n query,\n options,\n isSyncSSR\n );\n\n const [{ observable, resultData }, onQueryExecuted] = useInternalState(\n client,\n query,\n options,\n renderPromises,\n makeWatchQueryOptions\n );\n\n const watchQueryOptions: Readonly> =\n makeWatchQueryOptions(observable);\n\n useResubscribeIfNecessary(\n resultData, // might get mutated during render\n observable, // might get mutated during render\n client,\n options,\n watchQueryOptions\n );\n\n const obsQueryFields = React.useMemo(\n () => bindObservableMethods(observable),\n [observable]\n );\n\n useRegisterSSRObservable(observable, renderPromises, ssrAllowed);\n\n const result = useObservableSubscriptionResult(\n resultData,\n observable,\n client,\n options,\n watchQueryOptions,\n disableNetworkFetches,\n partialRefetch,\n isSyncSSR,\n {\n onCompleted: options.onCompleted || noop,\n onError: options.onError || noop,\n }\n );\n\n return {\n result,\n obsQueryFields,\n observable,\n resultData,\n client,\n onQueryExecuted,\n };\n}\n\nfunction useObservableSubscriptionResult<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n resultData: InternalResult,\n observable: ObservableQuery,\n client: ApolloClient,\n options: QueryHookOptions, NoInfer>,\n watchQueryOptions: Readonly>,\n disableNetworkFetches: boolean,\n partialRefetch: boolean | undefined,\n isSyncSSR: boolean,\n callbacks: {\n onCompleted: (data: MaybeMasked) => void;\n onError: (error: ApolloError) => void;\n }\n) {\n const callbackRef = React.useRef>(callbacks);\n React.useEffect(() => {\n // Make sure state.onCompleted and state.onError always reflect the latest\n // options.onCompleted and options.onError callbacks provided to useQuery,\n // since those functions are often recreated every time useQuery is called.\n // Like the forceUpdate method, the versions of these methods inherited from\n // InternalState.prototype are empty no-ops, but we can override them on the\n // base state object (without modifying the prototype).\n // eslint-disable-next-line react-compiler/react-compiler\n callbackRef.current = callbacks;\n });\n\n const resultOverride =\n (\n (isSyncSSR || disableNetworkFetches) &&\n options.ssr === false &&\n !options.skip\n ) ?\n // If SSR has been explicitly disabled, and this function has been called\n // on the server side, return the default loading state.\n ssrDisabledResult\n : options.skip || watchQueryOptions.fetchPolicy === \"standby\" ?\n // When skipping a query (ie. we're not querying for data but still want to\n // render children), make sure the `data` is cleared out and `loading` is\n // set to `false` (since we aren't loading anything).\n //\n // NOTE: We no longer think this is the correct behavior. Skipping should\n // not automatically set `data` to `undefined`, but instead leave the\n // previous data in place. In other words, skipping should not mandate that\n // previously received data is all of a sudden removed. Unfortunately,\n // changing this is breaking, so we'll have to wait until Apollo Client 4.0\n // to address this.\n skipStandbyResult\n : void 0;\n\n const previousData = resultData.previousData;\n const currentResultOverride = React.useMemo(\n () =>\n resultOverride &&\n toQueryResult(resultOverride, previousData, observable, client),\n [client, observable, resultOverride, previousData]\n );\n\n return useSyncExternalStore(\n React.useCallback(\n (handleStoreChange) => {\n // reference `disableNetworkFetches` here to ensure that the rules of hooks\n // keep it as a dependency of this effect, even though it's not used\n disableNetworkFetches;\n\n if (isSyncSSR) {\n return () => {};\n }\n\n const onNext = () => {\n const previousResult = resultData.current;\n // We use `getCurrentResult()` instead of the onNext argument because\n // the values differ slightly. Specifically, loading results will have\n // an empty object for data instead of `undefined` for some reason.\n const result = observable.getCurrentResult();\n // Make sure we're not attempting to re-render similar results\n if (\n previousResult &&\n previousResult.loading === result.loading &&\n previousResult.networkStatus === result.networkStatus &&\n equal(previousResult.data, result.data)\n ) {\n return;\n }\n\n setResult(\n result,\n resultData,\n observable,\n client,\n partialRefetch,\n handleStoreChange,\n callbackRef.current\n );\n };\n\n const onError = (error: Error) => {\n subscription.current.unsubscribe();\n subscription.current = observable.resubscribeAfterError(\n onNext,\n onError\n );\n\n if (!hasOwnProperty.call(error, \"graphQLErrors\")) {\n // The error is not a GraphQL error\n throw error;\n }\n\n const previousResult = resultData.current;\n if (\n !previousResult ||\n (previousResult && previousResult.loading) ||\n !equal(error, previousResult.error)\n ) {\n setResult(\n {\n data: (previousResult &&\n previousResult.data) as MaybeMasked,\n error: error as ApolloError,\n loading: false,\n networkStatus: NetworkStatus.error,\n },\n resultData,\n observable,\n client,\n partialRefetch,\n handleStoreChange,\n callbackRef.current\n );\n }\n };\n\n // TODO evaluate if we keep this in\n // React Compiler cannot handle scoped `let` access, but a mutable object\n // like this is fine.\n // was:\n // let subscription = observable.subscribe(onNext, onError);\n const subscription = { current: observable.subscribe(onNext, onError) };\n\n // Do the \"unsubscribe\" with a short delay.\n // This way, an existing subscription can be reused without an additional\n // request if \"unsubscribe\" and \"resubscribe\" to the same ObservableQuery\n // happen in very fast succession.\n return () => {\n setTimeout(() => subscription.current.unsubscribe());\n };\n },\n\n [\n disableNetworkFetches,\n isSyncSSR,\n observable,\n resultData,\n partialRefetch,\n client,\n ]\n ),\n () =>\n currentResultOverride ||\n getCurrentResult(\n resultData,\n observable,\n callbackRef.current,\n partialRefetch,\n client\n ),\n () =>\n currentResultOverride ||\n getCurrentResult(\n resultData,\n observable,\n callbackRef.current,\n partialRefetch,\n client\n )\n );\n}\n\nfunction useRegisterSSRObservable(\n observable: ObsQueryWithMeta,\n renderPromises: RenderPromises | undefined,\n ssrAllowed: boolean\n) {\n if (renderPromises && ssrAllowed) {\n renderPromises.registerSSRObservable(observable);\n\n if (observable.getCurrentResult().loading) {\n // TODO: This is a legacy API which could probably be cleaned up\n renderPromises.addObservableQueryPromise(observable);\n }\n }\n}\n\n// this hook is not compatible with any rules of React, and there's no good way to rewrite it.\n// it should stay a separate hook that will not be optimized by the compiler\nfunction useResubscribeIfNecessary<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n /** this hook will mutate properties on `resultData` */\n resultData: InternalResult,\n /** this hook will mutate properties on `observable` */\n observable: ObsQueryWithMeta,\n client: ApolloClient,\n options: QueryHookOptions, NoInfer>,\n watchQueryOptions: Readonly>\n) {\n if (\n observable[lastWatchOptions] &&\n !equal(observable[lastWatchOptions], watchQueryOptions)\n ) {\n // Though it might be tempting to postpone this reobserve call to the\n // useEffect block, we need getCurrentResult to return an appropriate\n // loading:true result synchronously (later within the same call to\n // useQuery). Since we already have this.observable here (not true for\n // the very first call to useQuery), we are not initiating any new\n // subscriptions, though it does feel less than ideal that reobserve\n // (potentially) kicks off a network request (for example, when the\n // variables have changed), which is technically a side-effect.\n observable.reobserve(\n getObsQueryOptions(observable, client, options, watchQueryOptions)\n );\n\n // Make sure getCurrentResult returns a fresh ApolloQueryResult,\n // but save the current data as this.previousData, just like setResult\n // usually does.\n resultData.previousData =\n resultData.current?.data || resultData.previousData;\n resultData.current = void 0;\n }\n observable[lastWatchOptions] = watchQueryOptions;\n}\n\n/*\n * A function to massage options before passing them to ObservableQuery.\n * This is two-step curried because we want to reuse the `make` function,\n * but the `observable` might differ between calls to `make`.\n */\nexport function createMakeWatchQueryOptions<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n client: ApolloClient,\n query: DocumentNode | TypedDocumentNode,\n {\n skip,\n ssr,\n onCompleted,\n onError,\n defaultOptions,\n // The above options are useQuery-specific, so this ...otherOptions spread\n // makes otherOptions almost a WatchQueryOptions object, except for the\n // query property that we add below.\n ...otherOptions\n }: QueryHookOptions = {},\n isSyncSSR: boolean\n) {\n return (\n observable?: ObservableQuery\n ): WatchQueryOptions => {\n // This Object.assign is safe because otherOptions is a fresh ...rest object\n // that did not exist until just now, so modifications are still allowed.\n const watchQueryOptions: WatchQueryOptions =\n Object.assign(otherOptions, { query });\n\n if (\n isSyncSSR &&\n (watchQueryOptions.fetchPolicy === \"network-only\" ||\n watchQueryOptions.fetchPolicy === \"cache-and-network\")\n ) {\n // this behavior was added to react-apollo without explanation in this PR\n // https://github.com/apollographql/react-apollo/pull/1579\n watchQueryOptions.fetchPolicy = \"cache-first\";\n }\n\n if (!watchQueryOptions.variables) {\n watchQueryOptions.variables = {} as TVariables;\n }\n\n if (skip) {\n // When skipping, we set watchQueryOptions.fetchPolicy initially to\n // \"standby\", but we also need/want to preserve the initial non-standby\n // fetchPolicy that would have been used if not skipping.\n watchQueryOptions.initialFetchPolicy =\n watchQueryOptions.initialFetchPolicy ||\n watchQueryOptions.fetchPolicy ||\n getDefaultFetchPolicy(defaultOptions, client.defaultOptions);\n watchQueryOptions.fetchPolicy = \"standby\";\n } else if (!watchQueryOptions.fetchPolicy) {\n watchQueryOptions.fetchPolicy =\n observable?.options.initialFetchPolicy ||\n getDefaultFetchPolicy(defaultOptions, client.defaultOptions);\n }\n\n return watchQueryOptions;\n };\n}\n\nexport function getObsQueryOptions<\n TData,\n TVariables extends OperationVariables,\n>(\n observable: ObservableQuery | undefined,\n client: ApolloClient,\n queryHookOptions: QueryHookOptions,\n watchQueryOptions: Partial>\n): WatchQueryOptions {\n const toMerge: Array>> = [];\n\n const globalDefaults = client.defaultOptions.watchQuery;\n if (globalDefaults) toMerge.push(globalDefaults);\n\n if (queryHookOptions.defaultOptions) {\n toMerge.push(queryHookOptions.defaultOptions);\n }\n\n // We use compact rather than mergeOptions for this part of the merge,\n // because we want watchQueryOptions.variables (if defined) to replace\n // this.observable.options.variables whole. This replacement allows\n // removing variables by removing them from the variables input to\n // useQuery. If the variables were always merged together (rather than\n // replaced), there would be no way to remove existing variables.\n // However, the variables from options.defaultOptions and globalDefaults\n // (if provided) should be merged, to ensure individual defaulted\n // variables always have values, if not otherwise defined in\n // observable.options or watchQueryOptions.\n toMerge.push(compact(observable && observable.options, watchQueryOptions));\n\n return toMerge.reduce(mergeOptions) as WatchQueryOptions;\n}\n\nfunction setResult(\n nextResult: ApolloQueryResult>,\n resultData: InternalResult,\n observable: ObservableQuery,\n client: ApolloClient,\n partialRefetch: boolean | undefined,\n forceUpdate: () => void,\n callbacks: Callbacks\n) {\n const previousResult = resultData.current;\n if (previousResult && previousResult.data) {\n resultData.previousData = previousResult.data;\n }\n\n if (!nextResult.error && isNonEmptyArray(nextResult.errors)) {\n // Until a set naming convention for networkError and graphQLErrors is\n // decided upon, we map errors (graphQLErrors) to the error options.\n // TODO: Is it possible for both result.error and result.errors to be\n // defined here?\n nextResult.error = new ApolloError({ graphQLErrors: nextResult.errors });\n }\n\n resultData.current = toQueryResult(\n unsafeHandlePartialRefetch(nextResult, observable, partialRefetch),\n resultData.previousData,\n observable,\n client\n );\n // Calling state.setResult always triggers an update, though some call sites\n // perform additional equality checks before committing to an update.\n forceUpdate();\n handleErrorOrCompleted(nextResult, previousResult?.networkStatus, callbacks);\n}\n\nfunction handleErrorOrCompleted(\n result: ApolloQueryResult>,\n previousNetworkStatus: NetworkStatus | undefined,\n callbacks: Callbacks\n) {\n if (!result.loading) {\n const error = toApolloError(result);\n\n // wait a tick in case we are in the middle of rendering a component\n Promise.resolve()\n .then(() => {\n if (error) {\n callbacks.onError(error);\n } else if (\n result.data &&\n previousNetworkStatus !== result.networkStatus &&\n result.networkStatus === NetworkStatus.ready\n ) {\n callbacks.onCompleted(result.data);\n }\n })\n .catch((error) => {\n invariant.warn(error);\n });\n }\n}\n\nfunction getCurrentResult(\n resultData: InternalResult,\n observable: ObservableQuery,\n callbacks: Callbacks,\n partialRefetch: boolean | undefined,\n client: ApolloClient\n): InternalQueryResult {\n // Using this.result as a cache ensures getCurrentResult continues returning\n // the same (===) result object, unless state.setResult has been called, or\n // we're doing server rendering and therefore override the result below.\n if (!resultData.current) {\n // WARNING: SIDE-EFFECTS IN THE RENDER FUNCTION\n // this could call unsafeHandlePartialRefetch\n setResult(\n observable.getCurrentResult(),\n resultData,\n observable,\n client,\n partialRefetch,\n () => {},\n callbacks\n );\n }\n return resultData.current!;\n}\n\nexport function getDefaultFetchPolicy<\n TData,\n TVariables extends OperationVariables,\n>(\n queryHookDefaultOptions?: Partial>,\n clientDefaultOptions?: DefaultOptions\n): WatchQueryFetchPolicy {\n return (\n queryHookDefaultOptions?.fetchPolicy ||\n clientDefaultOptions?.watchQuery?.fetchPolicy ||\n \"cache-first\"\n );\n}\n\nexport function toApolloError(\n result: Pick, \"errors\" | \"error\">\n): ApolloError | undefined {\n return isNonEmptyArray(result.errors) ?\n new ApolloError({ graphQLErrors: result.errors })\n : result.error;\n}\n\nexport function toQueryResult(\n result: ApolloQueryResult>,\n previousData: MaybeMasked | undefined,\n observable: ObservableQuery,\n client: ApolloClient\n): InternalQueryResult {\n const { data, partial, ...resultWithoutPartial } = result;\n const queryResult: InternalQueryResult = {\n data, // Ensure always defined, even if result.data is missing.\n ...resultWithoutPartial,\n client: client,\n observable: observable,\n variables: observable.variables,\n called: result !== ssrDisabledResult && result !== skipStandbyResult,\n previousData,\n };\n return queryResult;\n}\n\nfunction unsafeHandlePartialRefetch<\n TData,\n TVariables extends OperationVariables,\n>(\n result: ApolloQueryResult>,\n observable: ObservableQuery,\n partialRefetch: boolean | undefined\n): ApolloQueryResult> {\n // TODO: This code should be removed when the partialRefetch option is\n // removed. I was unable to get this hook to behave reasonably in certain\n // edge cases when this block was put in an effect.\n if (\n result.partial &&\n partialRefetch &&\n !result.loading &&\n (!result.data || Object.keys(result.data).length === 0) &&\n observable.options.fetchPolicy !== \"cache-only\"\n ) {\n observable.refetch();\n return {\n ...result,\n loading: true,\n networkStatus: NetworkStatus.refetch,\n };\n }\n return result;\n}\n\nconst ssrDisabledResult = maybeDeepFreeze({\n loading: true,\n data: void 0 as any,\n error: void 0,\n networkStatus: NetworkStatus.loading,\n});\n\nconst skipStandbyResult = maybeDeepFreeze({\n loading: false,\n data: void 0 as any,\n error: void 0,\n networkStatus: NetworkStatus.ready,\n});\n\nfunction bindObservableMethods(\n observable: ObservableQuery\n): Omit, \"variables\"> {\n return {\n refetch: observable.refetch.bind(observable),\n reobserve: observable.reobserve.bind(observable),\n fetchMore: observable.fetchMore.bind(observable),\n updateQuery: observable.updateQuery.bind(observable),\n startPolling: observable.startPolling.bind(observable),\n stopPolling: observable.stopPolling.bind(observable),\n subscribeToMore: observable.subscribeToMore.bind(observable),\n };\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\nimport type { DocumentNode } from \"graphql\";\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\n\nimport { DocumentType, verifyDocumentType } from \"../parser/index.js\";\nimport type {\n NoInfer,\n SubscriptionHookOptions,\n SubscriptionResult,\n} from \"../types/types.js\";\nimport type {\n ApolloClient,\n DefaultContext,\n ErrorPolicy,\n FetchPolicy,\n FetchResult,\n OperationVariables,\n} from \"../../core/index.js\";\nimport { ApolloError, Observable } from \"../../core/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useDeepMemo } from \"./internal/useDeepMemo.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport { toApolloError } from \"./useQuery.js\";\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\nimport type { MaybeMasked } from \"../../masking/index.js\";\n\n/**\n * > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.\n *\n * @example\n * ```jsx\n * const COMMENTS_SUBSCRIPTION = gql`\n * subscription OnCommentAdded($repoFullName: String!) {\n * commentAdded(repoFullName: $repoFullName) {\n * id\n * content\n * }\n * }\n * `;\n *\n * function DontReadTheComments({ repoFullName }) {\n * const {\n * data: { commentAdded },\n * loading,\n * } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });\n * return

New comment: {!loading && commentAdded.content}

;\n * }\n * ```\n * @remarks\n * #### Consider using `onData` instead of `useEffect`\n *\n * If you want to react to incoming data, please use the `onData` option instead of `useEffect`.\n * State updates you make inside a `useEffect` hook might cause additional rerenders, and `useEffect` is mostly meant for side effects of rendering, not as an event handler.\n * State updates made in an event handler like `onData` might - depending on the React version - be batched and cause only a single rerender.\n *\n * Consider the following component:\n *\n * ```jsx\n * export function Subscriptions() {\n * const { data, error, loading } = useSubscription(query);\n * const [accumulatedData, setAccumulatedData] = useState([]);\n *\n * useEffect(() => {\n * setAccumulatedData((prev) => [...prev, data]);\n * }, [data]);\n *\n * return (\n * <>\n * {loading &&

Loading...

}\n * {JSON.stringify(accumulatedData, undefined, 2)}\n * \n * );\n * }\n * ```\n *\n * Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:\n *\n * ```jsx\n * export function Subscriptions() {\n * const [accumulatedData, setAccumulatedData] = useState([]);\n * const { data, error, loading } = useSubscription(\n * query,\n * {\n * onData({ data }) {\n * setAccumulatedData((prev) => [...prev, data])\n * }\n * }\n * );\n *\n * return (\n * <>\n * {loading &&

Loading...

}\n * {JSON.stringify(accumulatedData, undefined, 2)}\n * \n * );\n * }\n * ```\n *\n * > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.\n *\n * Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.\n *\n * @since 3.0.0\n * @param subscription - A GraphQL subscription document parsed into an AST by `gql`.\n * @param options - Options to control how the subscription is executed.\n * @returns Query result object\n */\nexport function useSubscription<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n subscription: DocumentNode | TypedDocumentNode,\n options: SubscriptionHookOptions<\n NoInfer,\n NoInfer\n > = Object.create(null)\n) {\n const hasIssuedDeprecationWarningRef = React.useRef(false);\n const client = useApolloClient(options.client);\n verifyDocumentType(subscription, DocumentType.Subscription);\n\n if (!hasIssuedDeprecationWarningRef.current) {\n // eslint-disable-next-line react-compiler/react-compiler\n hasIssuedDeprecationWarningRef.current = true;\n\n if (options.onSubscriptionData) {\n invariant.warn(\n options.onData ?\n \"'useSubscription' supports only the 'onSubscriptionData' or 'onData' option, but not both. Only the 'onData' option will be used.\"\n : \"'onSubscriptionData' is deprecated and will be removed in a future major version. Please use the 'onData' option instead.\"\n );\n }\n\n if (options.onSubscriptionComplete) {\n invariant.warn(\n options.onComplete ?\n \"'useSubscription' supports only the 'onSubscriptionComplete' or 'onComplete' option, but not both. Only the 'onComplete' option will be used.\"\n : \"'onSubscriptionComplete' is deprecated and will be removed in a future major version. Please use the 'onComplete' option instead.\"\n );\n }\n }\n\n const {\n skip,\n fetchPolicy,\n errorPolicy,\n shouldResubscribe,\n context,\n extensions,\n ignoreResults,\n } = options;\n const variables = useDeepMemo(() => options.variables, [options.variables]);\n\n const recreate = () =>\n createSubscription(\n client,\n subscription,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n extensions\n );\n\n let [observable, setObservable] = React.useState(\n options.skip ? null : recreate\n );\n\n const recreateRef = React.useRef(recreate);\n useIsomorphicLayoutEffect(() => {\n recreateRef.current = recreate;\n });\n\n if (skip) {\n if (observable) {\n setObservable((observable = null));\n }\n } else if (\n !observable ||\n ((client !== observable.__.client ||\n subscription !== observable.__.query ||\n fetchPolicy !== observable.__.fetchPolicy ||\n errorPolicy !== observable.__.errorPolicy ||\n !equal(variables, observable.__.variables)) &&\n (typeof shouldResubscribe === \"function\" ?\n !!shouldResubscribe(options!)\n : shouldResubscribe) !== false)\n ) {\n setObservable((observable = recreate()));\n }\n\n const optionsRef = React.useRef(options);\n React.useEffect(() => {\n optionsRef.current = options;\n });\n\n const fallbackLoading = !skip && !ignoreResults;\n const fallbackResult = React.useMemo>(\n () => ({\n loading: fallbackLoading,\n error: void 0,\n data: void 0,\n variables,\n }),\n [fallbackLoading, variables]\n );\n\n const ignoreResultsRef = React.useRef(ignoreResults);\n useIsomorphicLayoutEffect(() => {\n // We cannot reference `ignoreResults` directly in the effect below\n // it would add a dependency to the `useEffect` deps array, which means the\n // subscription would be recreated if `ignoreResults` changes\n // As a result, on resubscription, the last result would be re-delivered,\n // rendering the component one additional time, and re-triggering `onData`.\n // The same applies to `fetchPolicy`, which results in a new `observable`\n // being created. We cannot really avoid it in that case, but we can at least\n // avoid it for `ignoreResults`.\n ignoreResultsRef.current = ignoreResults;\n });\n\n const ret = useSyncExternalStore>(\n React.useCallback(\n (update) => {\n if (!observable) {\n return () => {};\n }\n\n let subscriptionStopped = false;\n const variables = observable.__.variables;\n const client = observable.__.client;\n const subscription = observable.subscribe({\n next(fetchResult) {\n if (subscriptionStopped) {\n return;\n }\n\n const result = {\n loading: false,\n // TODO: fetchResult.data can be null but SubscriptionResult.data\n // expects TData | undefined only\n data: fetchResult.data!,\n error: toApolloError(fetchResult),\n variables,\n };\n observable.__.setResult(result);\n if (!ignoreResultsRef.current) update();\n\n if (result.error) {\n optionsRef.current.onError?.(result.error);\n } else if (optionsRef.current.onData) {\n optionsRef.current.onData({\n client,\n data: result,\n });\n } else if (optionsRef.current.onSubscriptionData) {\n optionsRef.current.onSubscriptionData({\n client,\n subscriptionData: result,\n });\n }\n },\n error(error) {\n error =\n error instanceof ApolloError ? error : (\n new ApolloError({ protocolErrors: [error] })\n );\n if (!subscriptionStopped) {\n observable.__.setResult({\n loading: false,\n data: void 0,\n error,\n variables,\n });\n if (!ignoreResultsRef.current) update();\n optionsRef.current.onError?.(error);\n }\n },\n complete() {\n if (!subscriptionStopped) {\n if (optionsRef.current.onComplete) {\n optionsRef.current.onComplete();\n } else if (optionsRef.current.onSubscriptionComplete) {\n optionsRef.current.onSubscriptionComplete();\n }\n }\n },\n });\n\n return () => {\n // immediately stop receiving subscription values, but do not unsubscribe\n // until after a short delay in case another useSubscription hook is\n // reusing the same underlying observable and is about to subscribe\n subscriptionStopped = true;\n setTimeout(() => {\n subscription.unsubscribe();\n });\n };\n },\n [observable]\n ),\n () =>\n observable && !skip && !ignoreResults ?\n observable.__.result\n : fallbackResult,\n () => fallbackResult\n );\n\n const restart = React.useCallback(() => {\n invariant(\n !optionsRef.current.skip,\n \"A subscription that is skipped cannot be restarted.\"\n );\n setObservable(recreateRef.current());\n }, [optionsRef, recreateRef]);\n\n return React.useMemo(() => ({ ...ret, restart }), [ret, restart]);\n}\n\nfunction createSubscription<\n TData = any,\n TVariables extends OperationVariables = OperationVariables,\n>(\n client: ApolloClient,\n query: TypedDocumentNode,\n variables: TVariables | undefined,\n fetchPolicy: FetchPolicy | undefined,\n errorPolicy: ErrorPolicy | undefined,\n context: DefaultContext | undefined,\n extensions: Record | undefined\n) {\n const options = {\n query,\n variables,\n fetchPolicy,\n errorPolicy,\n context,\n extensions,\n };\n const __ = {\n ...options,\n client,\n result: {\n loading: true,\n data: void 0,\n error: void 0,\n variables,\n } as SubscriptionResult,\n setResult(result: SubscriptionResult) {\n __.result = result;\n },\n };\n\n let observable: Observable>> | null = null;\n return Object.assign(\n new Observable>>((observer) => {\n // lazily start the subscription when the first observer subscribes\n // to get around strict mode\n if (!observable) {\n observable = client.subscribe(options);\n }\n const sub = observable.subscribe(observer);\n return () => sub.unsubscribe();\n }),\n {\n /**\n * A tracking object to store details about the observable and the latest result of the subscription.\n */\n __,\n }\n );\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\n\nimport { canUseLayoutEffect } from \"../../utilities/index.js\";\n\nlet didWarnUncachedGetSnapshot = false;\n\ntype RealUseSESHookType =\n // This import depends only on the @types/use-sync-external-store package, not\n // the actual use-sync-external-store package, which is not installed. It\n // might be nice to get this type from React 18, but it still needs to work\n // when only React 17 or earlier is installed.\n typeof import(\"use-sync-external-store\").useSyncExternalStore;\n\n// Prevent webpack from complaining about our feature detection of the\n// useSyncExternalStore property of the React namespace, which is expected not\n// to exist when using React 17 and earlier, and that's fine.\nconst uSESKey = \"useSyncExternalStore\" as keyof typeof React;\nconst realHook = React[uSESKey] as RealUseSESHookType | undefined;\n\n// Adapted from https://www.npmjs.com/package/use-sync-external-store, with\n// Apollo Client deviations called out by \"// DEVIATION ...\" comments.\n\n// When/if React.useSyncExternalStore is defined, delegate fully to it.\nexport const useSyncExternalStore: RealUseSESHookType =\n realHook ||\n ((subscribe, getSnapshot, getServerSnapshot) => {\n // Read the current snapshot from the store on every render. Again, this\n // breaks the rules of React, and only works here because of specific\n // implementation details, most importantly that updates are\n // always synchronous.\n const value = getSnapshot();\n if (\n // DEVIATION: Using __DEV__\n __DEV__ &&\n !didWarnUncachedGetSnapshot &&\n // DEVIATION: Not using Object.is because we know our snapshots will never\n // be exotic primitive values like NaN, which is !== itself.\n value !== getSnapshot()\n ) {\n didWarnUncachedGetSnapshot = true;\n // DEVIATION: Using invariant.error instead of console.error directly.\n invariant.error(\n \"The result of getSnapshot should be cached to avoid an infinite loop\"\n );\n }\n\n // Because updates are synchronous, we don't queue them. Instead we force a\n // re-render whenever the subscribed state changes by updating an some\n // arbitrary useState hook. Then, during render, we call getSnapshot to read\n // the current value.\n //\n // Because we don't actually use the state returned by the useState hook, we\n // can save a bit of memory by storing other stuff in that slot.\n //\n // To implement the early bailout, we need to track some things on a mutable\n // object. Usually, we would put that in a useRef hook, but we can stash it in\n // our useState hook instead.\n //\n // To force a re-render, we call forceUpdate({inst}). That works because the\n // new object always fails an equality check.\n const [{ inst }, forceUpdate] = React.useState({\n inst: { value, getSnapshot },\n });\n\n // Track the latest getSnapshot function with a ref. This needs to be updated\n // in the layout phase so we can access it during the tearing check that\n // happens on subscribe.\n if (canUseLayoutEffect) {\n // DEVIATION: We avoid calling useLayoutEffect when !canUseLayoutEffect,\n // which may seem like a conditional hook, but this code ends up behaving\n // unconditionally (one way or the other) because canUseLayoutEffect is\n // constant.\n React.useLayoutEffect(() => {\n Object.assign(inst, { value, getSnapshot });\n // Whenever getSnapshot or subscribe changes, we need to check in the\n // commit phase if there was an interleaved mutation. In concurrent mode\n // this can happen all the time, but even in synchronous mode, an earlier\n // effect may have mutated the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({ inst });\n }\n // React Hook React.useLayoutEffect has a missing dependency: 'inst'. Either include it or remove the dependency array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [subscribe, value, getSnapshot]);\n } else {\n Object.assign(inst, { value, getSnapshot });\n }\n\n React.useEffect(() => {\n // Check for changes right before subscribing. Subsequent changes will be\n // detected in the subscription handler.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({ inst });\n }\n\n // Subscribe to the store and return a clean-up function.\n return subscribe(function handleStoreChange() {\n // TODO: Because there is no cross-renderer API for batching updates, it's\n // up to the consumer of this library to wrap their subscription event\n // with unstable_batchedUpdates. Should we try to detect when this isn't\n // the case and print a warning in development?\n\n // The store changed. Check if the snapshot changed since the last time we\n // read from the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({ inst });\n }\n });\n // React Hook React.useEffect has a missing dependency: 'inst'. Either include it or remove the dependency array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [subscribe]);\n\n return value;\n });\n\nfunction checkIfSnapshotChanged({\n value,\n getSnapshot,\n}: {\n value: Snapshot;\n getSnapshot: () => Snapshot;\n}): boolean {\n try {\n return value !== getSnapshot();\n } catch {\n return true;\n }\n}\n","import { invariant } from \"../../utilities/globals/index.js\";\n\nimport type {\n DocumentNode,\n DefinitionNode,\n VariableDefinitionNode,\n OperationDefinitionNode,\n} from \"graphql\";\nimport {\n AutoCleanedWeakCache,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/index.js\";\nimport { registerGlobalCache } from \"../../utilities/caching/getMemoryInternals.js\";\n\nexport enum DocumentType {\n Query,\n Mutation,\n Subscription,\n}\n\nexport interface IDocumentDefinition {\n type: DocumentType;\n name: string;\n variables: ReadonlyArray;\n}\n\nlet cache:\n | undefined\n | AutoCleanedWeakCache<\n DocumentNode,\n {\n name: string;\n type: DocumentType;\n variables: readonly VariableDefinitionNode[];\n }\n >;\n\nexport function operationName(type: DocumentType) {\n let 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}\n\n// This parser is mostly used to safety check incoming documents.\nexport function parser(document: DocumentNode): IDocumentDefinition {\n if (!cache) {\n cache = new AutoCleanedWeakCache(\n cacheSizes.parser || defaultCacheSizes.parser\n );\n }\n const cached = cache.get(document);\n if (cached) return cached;\n\n let variables, type, name;\n\n invariant(\n !!document && !!document.kind,\n `Argument of %s 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`,\n document\n );\n\n const fragments: DefinitionNode[] = [];\n const queries: DefinitionNode[] = [];\n const mutations: DefinitionNode[] = [];\n const subscriptions: DefinitionNode[] = [];\n\n for (const x of document.definitions) {\n if (x.kind === \"FragmentDefinition\") {\n fragments.push(x);\n continue;\n }\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\n invariant(\n !fragments.length ||\n queries.length ||\n mutations.length ||\n subscriptions.length,\n `Passing only a fragment to 'graphql' is not yet supported. ` +\n `You must include a query, subscription or mutation as well`\n );\n\n invariant(\n queries.length + mutations.length + subscriptions.length <= 1,\n `react-apollo only supports a query, subscription, or a mutation per HOC. ` +\n `%s had %s queries, %s ` +\n `subscriptions and %s mutations. ` +\n `You can use 'compose' to join multiple operation types to a component`,\n document,\n queries.length,\n subscriptions.length,\n mutations.length\n );\n\n type = queries.length ? DocumentType.Query : DocumentType.Mutation;\n if (!queries.length && !mutations.length) type = DocumentType.Subscription;\n\n const definitions =\n queries.length ? queries\n : mutations.length ? mutations\n : subscriptions;\n\n invariant(\n definitions.length === 1,\n `react-apollo only supports one definition per HOC. %s had ` +\n `%s definitions. ` +\n `You can use 'compose' to join multiple operation types to a component`,\n document,\n definitions.length\n );\n\n const definition = definitions[0] as OperationDefinitionNode;\n variables = definition.variableDefinitions || [];\n\n if (definition.name && definition.name.kind === \"Name\") {\n name = definition.name.value;\n } else {\n name = \"data\"; // fallback to using data if no name\n }\n\n const payload = { name, type, variables };\n cache.set(document, payload);\n return payload;\n}\n\nparser.resetCache = () => {\n cache = undefined;\n};\n\nif (__DEV__) {\n registerGlobalCache(\"parser\", () => (cache ? cache.size : 0));\n}\n\nexport function verifyDocumentType(document: DocumentNode, type: DocumentType) {\n const operation = parser(document);\n const requiredOperationName = operationName(type);\n const usedOperationName = operationName(operation.type);\n invariant(\n operation.type === type,\n `Running a %s requires a graphql ` + `%s, but a %s was used instead.`,\n requiredOperationName,\n requiredOperationName,\n usedOperationName\n );\n}\n","import { WeakCache, StrongCache } from \"@wry/caches\";\n\ninterface CleanableCache {\n size: number;\n max?: number;\n clean: () => void;\n}\nconst scheduledCleanup = new WeakSet();\nfunction schedule(cache: CleanableCache) {\n if (cache.size <= (cache.max || -1)) {\n return;\n }\n if (!scheduledCleanup.has(cache)) {\n scheduledCleanup.add(cache);\n setTimeout(() => {\n cache.clean();\n scheduledCleanup.delete(cache);\n }, 100);\n }\n}\n/**\n * @internal\n * A version of WeakCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of WeakCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `WeakCache`.\n */\nexport const AutoCleanedWeakCache = function (\n max?: number | undefined,\n dispose?: ((value: any, key: any) => void) | undefined\n) {\n /*\n Some builds of `WeakCache` are function prototypes, some are classes.\n This library still builds with an ES5 target, so we can't extend the\n real classes.\n Instead, we have to use this workaround until we switch to a newer build\n target.\n */\n const cache = new WeakCache(max, dispose);\n cache.set = function (key: any, value: any) {\n const ret = WeakCache.prototype.set.call(this, key, value);\n schedule(this as any as CleanableCache);\n return ret;\n };\n return cache;\n} as any as typeof WeakCache;\n/**\n * @internal\n */\nexport type AutoCleanedWeakCache = WeakCache;\n\n/**\n * @internal\n * A version of StrongCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of StrongCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `StrongCache`.\n */\nexport const AutoCleanedStrongCache = function (\n max?: number | undefined,\n dispose?: ((value: any, key: any) => void) | undefined\n) {\n /*\n Some builds of `StrongCache` are function prototypes, some are classes.\n This library still builds with an ES5 target, so we can't extend the\n real classes.\n Instead, we have to use this workaround until we switch to a newer build\n target.\n */\n const cache = new StrongCache(max, dispose);\n cache.set = function (key: any, value: any) {\n const ret = StrongCache.prototype.set.call(this, key, value);\n schedule(this as any as CleanableCache);\n return ret;\n };\n return cache;\n} as any as typeof StrongCache;\n/**\n * @internal\n */\nexport type AutoCleanedStrongCache = StrongCache;\n","import type { OptimisticWrapperFunction } from \"optimism\";\nimport type {\n InMemoryCache,\n DocumentTransform,\n ApolloLink,\n ApolloCache,\n} from \"../../core/index.js\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport type { CacheSizes } from \"./sizes.js\";\nimport { cacheSizes, defaultCacheSizes } from \"./sizes.js\";\n\nconst globalCaches: {\n print?: () => number;\n parser?: () => number;\n canonicalStringify?: () => number;\n} = {};\n\nexport function registerGlobalCache(\n name: keyof typeof globalCaches,\n getSize: () => number\n) {\n globalCaches[name] = getSize;\n}\n\n/**\n * Transformative helper type to turn a function of the form\n * ```ts\n * (this: any) => R\n * ```\n * into a function of the form\n * ```ts\n * () => R\n * ```\n * preserving the return type, but removing the `this` parameter.\n *\n * @remarks\n *\n * Further down in the definitions of `_getApolloClientMemoryInternals`,\n * `_getApolloCacheMemoryInternals` and `_getInMemoryCacheMemoryInternals`,\n * having the `this` parameter annotation is extremely useful for type checking\n * inside the function.\n *\n * If this is preserved in the exported types, though, it leads to a situation\n * where `ApolloCache.getMemoryInternals` is a function that requires a `this`\n * of the type `ApolloCache`, while the extending class `InMemoryCache` has a\n * `getMemoryInternals` function that requires a `this` of the type\n * `InMemoryCache`.\n * This is not compatible with TypeScript's inheritence system (although it is\n * perfectly correct), and so TypeScript will complain loudly.\n *\n * We still want to define our functions with the `this` annotation, though,\n * and have the return type inferred.\n * (This requirement for return type inference here makes it impossible to use\n * a function overload that is more explicit on the inner overload than it is\n * on the external overload.)\n *\n * So in the end, we use this helper to remove the `this` annotation from the\n * exported function types, while keeping it in the internal implementation.\n *\n */\ntype RemoveThis = T extends (this: any) => infer R ? () => R : never;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloClientMemoryInternals =\n __DEV__ ?\n (_getApolloClientMemoryInternals as RemoveThis<\n typeof _getApolloClientMemoryInternals\n >)\n : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getInMemoryCacheMemoryInternals =\n __DEV__ ?\n (_getInMemoryCacheMemoryInternals as RemoveThis<\n typeof _getInMemoryCacheMemoryInternals\n >)\n : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloCacheMemoryInternals =\n __DEV__ ?\n (_getApolloCacheMemoryInternals as RemoveThis<\n typeof _getApolloCacheMemoryInternals\n >)\n : undefined;\n\nfunction getCurrentCacheSizes() {\n // `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here\n const defaults: Record = {\n parser: defaultCacheSizes[\"parser\"],\n canonicalStringify: defaultCacheSizes[\"canonicalStringify\"],\n print: defaultCacheSizes[\"print\"],\n \"documentTransform.cache\": defaultCacheSizes[\"documentTransform.cache\"],\n \"queryManager.getDocumentInfo\":\n defaultCacheSizes[\"queryManager.getDocumentInfo\"],\n \"PersistedQueryLink.persistedQueryHashes\":\n defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"],\n \"fragmentRegistry.transform\":\n defaultCacheSizes[\"fragmentRegistry.transform\"],\n \"fragmentRegistry.lookup\": defaultCacheSizes[\"fragmentRegistry.lookup\"],\n \"fragmentRegistry.findFragmentSpreads\":\n defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"],\n \"cache.fragmentQueryDocuments\":\n defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n \"removeTypenameFromVariables.getVariableDefinitions\":\n defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"],\n \"inMemoryCache.maybeBroadcastWatch\":\n defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n \"inMemoryCache.executeSelectionSet\":\n defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n \"inMemoryCache.executeSubSelectedArray\":\n defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n };\n return Object.fromEntries(\n Object.entries(defaults).map(([k, v]) => [\n k,\n cacheSizes[k as keyof CacheSizes] || v,\n ])\n );\n}\n\nfunction _getApolloClientMemoryInternals(this: ApolloClient) {\n if (!__DEV__) throw new Error(\"only supported in development mode\");\n\n return {\n limits: getCurrentCacheSizes(),\n sizes: {\n print: globalCaches.print?.(),\n parser: globalCaches.parser?.(),\n canonicalStringify: globalCaches.canonicalStringify?.(),\n links: linkInfo(this.link),\n queryManager: {\n getDocumentInfo: this[\"queryManager\"][\"transformCache\"].size,\n documentTransforms: transformInfo(\n this[\"queryManager\"].documentTransform\n ),\n },\n ...(this.cache.getMemoryInternals?.() as Partial<\n ReturnType\n > &\n Partial>),\n },\n };\n}\n\nfunction _getApolloCacheMemoryInternals(this: ApolloCache) {\n return {\n cache: {\n fragmentQueryDocuments: getWrapperInformation(this[\"getFragmentDoc\"]),\n },\n };\n}\n\nfunction _getInMemoryCacheMemoryInternals(this: InMemoryCache) {\n const fragments = this.config.fragments as\n | undefined\n | {\n findFragmentSpreads?: Function;\n transform?: Function;\n lookup?: Function;\n };\n\n return {\n ..._getApolloCacheMemoryInternals.apply(this as any),\n addTypenameDocumentTransform: transformInfo(this[\"addTypenameTransform\"]),\n inMemoryCache: {\n executeSelectionSet: getWrapperInformation(\n this[\"storeReader\"][\"executeSelectionSet\"]\n ),\n executeSubSelectedArray: getWrapperInformation(\n this[\"storeReader\"][\"executeSubSelectedArray\"]\n ),\n maybeBroadcastWatch: getWrapperInformation(this[\"maybeBroadcastWatch\"]),\n },\n fragmentRegistry: {\n findFragmentSpreads: getWrapperInformation(\n fragments?.findFragmentSpreads\n ),\n lookup: getWrapperInformation(fragments?.lookup),\n transform: getWrapperInformation(fragments?.transform),\n },\n };\n}\n\nfunction isWrapper(f?: Function): f is OptimisticWrapperFunction {\n return !!f && \"dirtyKey\" in f;\n}\n\nfunction getWrapperInformation(f?: Function) {\n return isWrapper(f) ? f.size : undefined;\n}\n\nfunction isDefined(value: T | undefined | null): value is T {\n return value != null;\n}\n\nfunction transformInfo(transform?: DocumentTransform) {\n return recurseTransformInfo(transform).map((cache) => ({ cache }));\n}\n\nfunction recurseTransformInfo(transform?: DocumentTransform): number[] {\n return transform ?\n [\n getWrapperInformation(transform?.[\"performWork\"]),\n ...recurseTransformInfo(transform?.[\"left\"]),\n ...recurseTransformInfo(transform?.[\"right\"]),\n ].filter(isDefined)\n : [];\n}\n\nfunction linkInfo(link?: ApolloLink): unknown[] {\n return link ?\n [\n link?.getMemoryInternals?.(),\n ...linkInfo(link?.left),\n ...linkInfo(link?.right),\n ].filter(isDefined)\n : [];\n}\n","import { global } from \"../globals/index.js\";\n\ndeclare global {\n interface Window {\n [cacheSizeSymbol]?: Partial;\n }\n}\n\n/**\n * The cache sizes used by various Apollo Client caches.\n *\n * @remarks\n * All configurable caches hold memoized values. If an item is\n * cache-collected, it incurs only a small performance impact and\n * doesn't cause data loss. A smaller cache size might save you memory.\n *\n * You should choose cache sizes appropriate for storing a reasonable\n * number of values rather than every value. To prevent too much recalculation,\n * choose cache sizes that are at least large enough to hold memoized values for\n * all hooks/queries on the screen at any given time.\n */\n/*\n * We assume a \"base value\" of 1000 here, which is already very generous.\n * In most applications, it will be very unlikely that 1000 different queries\n * are on screen at the same time.\n */\nexport interface CacheSizes {\n /**\n * Cache size for the [`print`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/print.ts) function.\n *\n * It is called with transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @remarks\n * This method is called to transform a GraphQL query AST parsed by `gql`\n * back into a GraphQL string.\n *\n * @privateRemarks\n * This method is called from the `QueryManager` and various `ApolloLink`s,\n * always with the \"serverQuery\", so the server-facing part of a transformed\n * `DocumentNode`.\n */\n print: number;\n /**\n * Cache size for the [`parser`](https://github.com/apollographql/apollo-client/blob/main/src/react/parser/index.ts) function.\n *\n * It is called with user-provided `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `1000`.\n *\n * @remarks\n * This method is called by HOCs and hooks.\n *\n * @privateRemarks\n * This function is used directly in HOCs, and nowadays mainly accessed by\n * calling `verifyDocumentType` from various hooks.\n * It is called with a user-provided DocumentNode.\n */\n parser: number;\n /**\n * Cache size for the cache of [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts)\n * instances with the `cache` option set to `true`.\n *\n * Can be called with user-defined or already-transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @remarks\n * The cache size here should be chosen with other `DocumentTransform`s in mind.\n * For example, if there was a `DocumentTransform` that would take `x` `DocumentNode`s,\n * and returned a differently-transformed `DocumentNode` depending if the app is\n * online or offline, then we assume that the cache returns `2*x` documents.\n * If that were concatenated with another `DocumentTransform` that would\n * also duplicate the cache size, you'd need to account for `4*x` documents\n * returned by the second transform.\n *\n * Due to an implementation detail of Apollo Client, if you use custom document\n * transforms you should always add `n` (the \"base\" number of user-provided\n * Documents) to the resulting cache size.\n *\n * If we assume that the user-provided transforms receive `n` documents and\n * return `n` documents, the cache size should be `2*n`.\n *\n * If we assume that the chain of user-provided transforms receive `n` documents and\n * return `4*n` documents, the cache size should be `5*n`.\n *\n * This size should also then be used in every other cache that mentions that\n * it operates on a \"transformed\" `DocumentNode`.\n *\n * @privateRemarks\n * Cache size for the `performWork` method of each [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts).\n *\n * No user-provided DocumentNode will actually be \"the last one\", as we run the\n * `defaultDocumentTransform` before *and* after the user-provided transforms.\n * For that reason, we need the extra `n` here - `n` for \"before transformation\"\n * plus the actual maximum cache size of the user-provided transform chain.\n *\n * This method is called from `transformDocument`, which is called from\n * `QueryManager` with a user-provided DocumentNode.\n * It is also called with already-transformed DocumentNodes, assuming the\n * user provided additional transforms.\n *\n */\n \"documentTransform.cache\": number;\n /**\n * A cache inside of [`QueryManager`](https://github.com/apollographql/apollo-client/blob/main/src/core/QueryManager.ts).\n *\n * It is called with transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @privateRemarks\n * Cache size for the `transformCache` used in the `getDocumentInfo` method of `QueryManager`.\n * Called throughout the `QueryManager` with transformed DocumentNodes.\n */\n \"queryManager.getDocumentInfo\": number;\n /**\n * A cache inside of [`PersistedQueryLink`](https://github.com/apollographql/apollo-client/blob/main/src/link/persisted-queries/index.ts).\n *\n * It is called with transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @remarks\n * This cache is used to cache the hashes of persisted queries.\n *\n * @privateRemarks\n * Cache size for the `hashesByQuery` cache in the `PersistedQueryLink`.\n */\n \"PersistedQueryLink.persistedQueryHashes\": number;\n /**\n * Cache used by [`canonicalStringify`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/common/canonicalStringify.ts).\n *\n * @defaultValue\n * Defaults to `1000`.\n *\n * @remarks\n * This cache contains the sorted keys of objects that are stringified by\n * `canonicalStringify`.\n * It uses the stringified unsorted keys of objects as keys.\n * The cache will not grow beyond the size of different object **shapes**\n * encountered in an application, no matter how much actual data gets stringified.\n *\n * @privateRemarks\n * Cache size for the `sortingMap` in `canonicalStringify`.\n */\n canonicalStringify: number;\n /**\n * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n *\n * Can be called with user-defined or already-transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @privateRemarks\n *\n * Cache size for the `transform` method of FragmentRegistry.\n * This function is called as part of the `defaultDocumentTransform` which will be called with\n * user-provided and already-transformed DocumentNodes.\n *\n */\n \"fragmentRegistry.transform\": number;\n /**\n * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n *\n * This function is called with fragment names in the form of a string.\n *\n * @defaultValue\n * Defaults to `1000`.\n *\n * @remarks\n * The size of this case should be chosen with the number of fragments in\n * your application in mind.\n *\n * Note:\n * This function is a dependency of `fragmentRegistry.transform`, so having too small of a cache size here\n * might involuntarily invalidate values in the `transform` cache.\n *\n * @privateRemarks\n * Cache size for the `lookup` method of FragmentRegistry.\n */\n \"fragmentRegistry.lookup\": number;\n /**\n * Cache size for the `findFragmentSpreads` method of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n *\n * This function is called with transformed `DocumentNode`s, as well as recursively\n * with every fragment spread referenced within that, or a fragment referenced by a\n * fragment spread.\n *\n * @defaultValue\n * Defaults to `4000`.\n *\n * @remarks\n *\n * Note: This function is a dependency of `fragmentRegistry.transform`, so having too small of cache size here\n * might involuntarily invalidate values in the `transform` cache.\n */\n \"fragmentRegistry.findFragmentSpreads\": number;\n /**\n * Cache size for the `getFragmentDoc` method of [`ApolloCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/core/cache.ts).\n *\n * This function is called with user-provided fragment definitions.\n *\n * @defaultValue\n * Defaults to `1000`.\n *\n * @remarks\n * This function is called from `readFragment` with user-provided fragment definitions.\n */\n \"cache.fragmentQueryDocuments\": number;\n /**\n * Cache used in [`removeTypenameFromVariables`](https://github.com/apollographql/apollo-client/blob/main/src/link/remove-typename/removeTypenameFromVariables.ts).\n *\n * This function is called transformed `DocumentNode`s.\n *\n * @defaultValue\n * Defaults to `2000`.\n *\n * @privateRemarks\n * Cache size for the `getVariableDefinitions` function of `removeTypenameFromVariables`.\n */\n \"removeTypenameFromVariables.getVariableDefinitions\": number;\n /**\n * Cache size for the `maybeBroadcastWatch` method on [`InMemoryCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/inMemoryCache.ts).\n *\n * Note: `maybeBroadcastWatch` will be set to the `resultCacheMaxSize` option and\n * will fall back to this configuration value if the option is not set.\n *\n * @defaultValue\n * Defaults to `5000`.\n *\n * @remarks\n * This method is used for dependency tracking in the `InMemoryCache` and\n * prevents from unnecessary re-renders.\n * It is recommended to keep this value significantly higher than the number of\n * possible subscribers you will have active at the same time in your application\n * at any time.\n */\n \"inMemoryCache.maybeBroadcastWatch\": number;\n /**\n * Cache size for the `executeSelectionSet` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n *\n * Note:\n * `executeSelectionSet` will be set to the `resultCacheMaxSize` option and\n * will fall back to this configuration value if the option is not set.\n *\n * @defaultValue\n * Defaults to `50000`.\n *\n * @remarks\n * Every object that is read from the cache will be cached here, so it is\n * recommended to set this to a high value.\n */\n \"inMemoryCache.executeSelectionSet\": number;\n /**\n * Cache size for the `executeSubSelectedArray` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n *\n * Note:\n * `executeSubSelectedArray` will be set to the `resultCacheMaxSize` option and\n * will fall back to this configuration value if the option is not set.\n *\n * @defaultValue\n * Defaults to `10000`.\n *\n * @remarks\n * Every array that is read from the cache will be cached here, so it is\n * recommended to set this to a high value.\n */\n \"inMemoryCache.executeSubSelectedArray\": number;\n}\n\nconst cacheSizeSymbol = Symbol.for(\"apollo.cacheSize\");\n/**\n *\n * The global cache size configuration for Apollo Client.\n *\n * @remarks\n *\n * You can directly modify this object, but any modification will\n * only have an effect on caches that are created after the modification.\n *\n * So for global caches, such as `parser`, `canonicalStringify` and `print`,\n * you might need to call `.reset` on them, which will essentially re-create them.\n *\n * Alternatively, you can set `globalThis[Symbol.for(\"apollo.cacheSize\")]` before\n * you load the Apollo Client package:\n *\n * @example\n * ```ts\n * globalThis[Symbol.for(\"apollo.cacheSize\")] = {\n * parser: 100\n * } satisfies Partial // the `satisfies` is optional if using TypeScript\n * ```\n */\nexport const cacheSizes: Partial = { ...global[cacheSizeSymbol] };\n\nexport const enum defaultCacheSizes {\n parser = 1000,\n canonicalStringify = 1000,\n print = 2000,\n \"documentTransform.cache\" = 2000,\n \"queryManager.getDocumentInfo\" = 2000,\n \"PersistedQueryLink.persistedQueryHashes\" = 2000,\n \"fragmentRegistry.transform\" = 2000,\n \"fragmentRegistry.lookup\" = 1000,\n \"fragmentRegistry.findFragmentSpreads\" = 4000,\n \"cache.fragmentQueryDocuments\" = 1000,\n \"removeTypenameFromVariables.getVariableDefinitions\" = 2000,\n \"inMemoryCache.maybeBroadcastWatch\" = 5000,\n \"inMemoryCache.executeSelectionSet\" = 50000,\n \"inMemoryCache.executeSubSelectedArray\" = 10000,\n}\n","// A version of Array.isArray that works better with readonly arrays.\nexport const isArray: (a: any) => a is any[] | readonly any[] = Array.isArray;\n\nexport function isNonEmptyArray(value?: ArrayLike): value is Array {\n return Array.isArray(value) && value.length > 0;\n}\n","import { maybe } from \"../globals/index.js\";\n\nconst isReactNative = maybe(() => navigator.product) == \"ReactNative\";\n\nexport const canUseWeakMap =\n typeof WeakMap === \"function\" &&\n !(isReactNative && !(global as any).HermesInternal);\n\nexport const canUseWeakSet = typeof WeakSet === \"function\";\n\nexport const canUseSymbol =\n typeof Symbol === \"function\" && typeof Symbol.for === \"function\";\n\nexport const canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;\n\nexport const canUseDOM =\n typeof maybe(() => window.document.createElement) === \"function\";\n\nconst usingJSDOM: boolean =\n // Following advice found in this comment from @domenic (maintainer of jsdom):\n // https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n //\n // Since we control the version of Jest and jsdom used when running Apollo\n // Client tests, and that version is recent enought to include \" jsdom/x.y.z\"\n // at the end of the user agent string, I believe this case is all we need to\n // check. Testing for \"Node.js\" was recommended for backwards compatibility\n // with older version of jsdom, but we don't have that problem.\n maybe(() => navigator.userAgent.indexOf(\"jsdom\") >= 0) || false;\n\n// Our tests should all continue to pass if we remove this !usingJSDOM\n// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,\n// if we allow useLayoutEffect, then useSyncExternalStore generates many\n// warnings about useLayoutEffect doing nothing on the server. While these\n// warnings are harmless, this !usingJSDOM condition seems to be the best way to\n// prevent them (i.e. skipping useLayoutEffect when using jsdom).\nexport const canUseLayoutEffect = (canUseDOM || isReactNative) && !usingJSDOM;\n","import {\n AutoCleanedStrongCache,\n cacheSizes,\n defaultCacheSizes,\n} from \"../../utilities/caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n\n/**\n * Like JSON.stringify, but with object keys always sorted in the same order.\n *\n * To achieve performant sorting, this function uses a Map from JSON-serialized\n * arrays of keys (in any order) to sorted arrays of the same keys, with a\n * single sorted array reference shared by all permutations of the keys.\n *\n * As a drawback, this function will add a little bit more memory for every\n * object encountered that has different (more, less, a different order of) keys\n * than in the past.\n *\n * In a typical application, this extra memory usage should not play a\n * significant role, as `canonicalStringify` will be called for only a limited\n * number of object shapes, and the cache will not grow beyond a certain point.\n * But in some edge cases, this could be a problem, so we provide\n * canonicalStringify.reset() as a way of clearing the cache.\n * */\nexport const canonicalStringify = Object.assign(\n function canonicalStringify(value: any): string {\n return JSON.stringify(value, stableObjectReplacer);\n },\n {\n reset() {\n // Clearing the sortingMap will reclaim all cached memory, without\n // affecting the logical results of canonicalStringify, but potentially\n // sacrificing performance until the cache is refilled.\n sortingMap = new AutoCleanedStrongCache(\n cacheSizes.canonicalStringify || defaultCacheSizes.canonicalStringify\n );\n },\n }\n);\n\nif (__DEV__) {\n registerGlobalCache(\"canonicalStringify\", () => sortingMap.size);\n}\n\n// Values are JSON-serialized arrays of object keys (in any order), and values\n// are sorted arrays of the same keys.\nlet sortingMap!: AutoCleanedStrongCache;\ncanonicalStringify.reset();\n\n// The JSON.stringify function takes an optional second argument called a\n// replacer function. This function is called for each key-value pair in the\n// object being stringified, and its return value is used instead of the\n// original value. If the replacer function returns a new value, that value is\n// stringified as JSON instead of the original value of the property.\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter\nfunction stableObjectReplacer(key: string, value: any) {\n if (value && typeof value === \"object\") {\n const proto = Object.getPrototypeOf(value);\n // We don't want to mess with objects that are not \"plain\" objects, which\n // means their prototype is either Object.prototype or null. This check also\n // prevents needlessly rearranging the indices of arrays.\n if (proto === Object.prototype || proto === null) {\n const keys = Object.keys(value);\n // If keys is already sorted, let JSON.stringify serialize the original\n // value instead of creating a new object with keys in the same order.\n if (keys.every(everyKeyInOrder)) return value;\n const unsortedKey = JSON.stringify(keys);\n let sortedKeys = sortingMap.get(unsortedKey);\n if (!sortedKeys) {\n keys.sort();\n const sortedKey = JSON.stringify(keys);\n // Checking for sortedKey in the sortingMap allows us to share the same\n // sorted array reference for all permutations of the same set of keys.\n sortedKeys = sortingMap.get(sortedKey) || keys;\n sortingMap.set(unsortedKey, sortedKeys);\n sortingMap.set(sortedKey, sortedKeys);\n }\n const sortedObject = Object.create(proto);\n // Reassigning the keys in sorted order will cause JSON.stringify to\n // serialize them in sorted order.\n sortedKeys.forEach((key) => {\n sortedObject[key] = value[key];\n });\n return sortedObject;\n }\n }\n return value;\n}\n\n// Since everything that happens in stableObjectReplacer benefits from being as\n// efficient as possible, we use a static function as the callback for\n// keys.every in order to test if the provided keys are already sorted without\n// allocating extra memory for a callback.\nfunction everyKeyInOrder(\n key: string,\n i: number,\n keys: readonly string[]\n): boolean {\n return i === 0 || keys[i - 1] <= key;\n}\n","const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep(value: T): T {\n return cloneDeepHelper(value);\n}\n\nfunction cloneDeepHelper(val: T, seen?: Map): T {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n const copy: T & any[] = (val as any).slice(0);\n seen.set(val, copy);\n copy.forEach(function (child, i) {\n copy[i] = cloneDeepHelper(child, seen);\n });\n return copy;\n }\n\n case \"[object Object]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n // possible in all JS environments, so we will assume they exist/work.\n const copy = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy);\n Object.keys(val as T & Record).forEach((key) => {\n copy[key] = cloneDeepHelper((val as any)[key], seen);\n });\n return copy;\n }\n\n default:\n return val;\n }\n}\n","import type { TupleToIntersection } from \"./mergeDeep.js\";\n\n/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n */\nexport function compact(\n ...objects: TArgs\n): TupleToIntersection {\n const result = Object.create(null);\n\n objects.forEach((obj) => {\n if (!obj) return;\n Object.keys(obj).forEach((key) => {\n const value = (obj as any)[key];\n if (value !== void 0) {\n result[key] = value;\n }\n });\n });\n\n return result;\n}\n","import type {\n ExecutionPatchIncrementalResult,\n ExecutionPatchInitialResult,\n ExecutionPatchResult,\n ApolloPayloadResult,\n FetchResult,\n} from \"../../link/core/index.js\";\nimport { isNonNullObject } from \"./objects.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { DeepMerger } from \"./mergeDeep.js\";\n\nexport function isExecutionPatchIncrementalResult(\n value: FetchResult\n): value is ExecutionPatchIncrementalResult {\n return \"incremental\" in value;\n}\n\nexport function isExecutionPatchInitialResult(\n value: FetchResult\n): value is ExecutionPatchInitialResult {\n return \"hasNext\" in value && \"data\" in value;\n}\n\nexport function isExecutionPatchResult(\n value: FetchResult\n): value is ExecutionPatchResult {\n return (\n isExecutionPatchIncrementalResult(value) ||\n isExecutionPatchInitialResult(value)\n );\n}\n\n// This function detects an Apollo payload result before it is transformed\n// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult\n// once it leaves the link chain.\nexport function isApolloPayloadResult(\n value: unknown\n): value is ApolloPayloadResult {\n return isNonNullObject(value) && \"payload\" in value;\n}\n\nexport function mergeIncrementalData(\n prevResult: TData,\n result: ExecutionPatchResult\n) {\n let mergedData = prevResult;\n const merger = new DeepMerger();\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach(({ data, path }) => {\n for (let i = path.length - 1; i >= 0; --i) {\n const key = path[i];\n const isNumericKey = !isNaN(+key);\n const parent: Record = isNumericKey ? [] : {};\n parent[key] = data;\n data = parent as typeof data;\n }\n mergedData = merger.merge(mergedData, data);\n });\n }\n return mergedData as TData;\n}\n","const prefixCounts = new Map();\n\n// These IDs won't be globally unique, but they will be unique within this\n// process, thanks to the counter, and unguessable thanks to the random suffix.\nexport function makeUniqueId(prefix: string) {\n const count = prefixCounts.get(prefix) || 1;\n prefixCounts.set(prefix, count + 1);\n return `${prefix}:${count}:${Math.random().toString(36).slice(2)}`;\n}\n","import { isNonNullObject } from \"./objects.js\";\n\nexport function deepFreeze(value: any) {\n const workSet = new Set([value]);\n workSet.forEach((obj) => {\n if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n Object.getOwnPropertyNames(obj).forEach((name) => {\n if (isNonNullObject(obj[name])) workSet.add(obj[name]);\n });\n }\n });\n return value;\n}\n\nfunction shallowFreeze(obj: T): T | null {\n if (__DEV__ && !Object.isFrozen(obj)) {\n try {\n Object.freeze(obj);\n } catch (e) {\n // Some types like Uint8Array and Node.js's Buffer cannot be frozen, but\n // they all throw a TypeError when you try, so we re-throw any exceptions\n // that are not TypeErrors, since that would be unexpected.\n if (e instanceof TypeError) return null;\n throw e;\n }\n }\n return obj;\n}\n\nexport function maybeDeepFreeze(obj: T): T {\n if (__DEV__) {\n deepFreeze(obj);\n }\n return obj;\n}\n","import { isNonNullObject } from \"./objects.js\";\n\nconst { hasOwnProperty } = Object.prototype;\n\n// These mergeDeep and mergeDeepArray utilities merge any number of objects\n// together, sharing as much memory as possible with the source objects, while\n// remaining careful to avoid modifying any source objects.\n\n// Logically, the return type of mergeDeep should be the intersection of\n// all the argument types. The binary call signature is by far the most\n// common, but we support 0- through 5-ary as well. After that, the\n// resulting type is just the inferred array element type. Note to nerds:\n// there is a more clever way of doing this that converts the tuple type\n// first to a union type (easy enough: T[number]) and then converts the\n// union to an intersection type using distributive conditional type\n// inference, but that approach has several fatal flaws (boolean becomes\n// true & false, and the inferred type ends up as unknown in many cases),\n// in addition to being nearly impossible to explain/understand.\nexport type TupleToIntersection =\n T extends [infer A] ? A\n : T extends [infer A, infer B] ? A & B\n : T extends [infer A, infer B, infer C] ? A & B & C\n : T extends [infer A, infer B, infer C, infer D] ? A & B & C & D\n : T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E\n : T extends (infer U)[] ? U\n : any;\n\nexport function mergeDeep(\n ...sources: T\n): TupleToIntersection {\n return mergeDeepArray(sources);\n}\n\n// In almost any situation where you could succeed in getting the\n// TypeScript compiler to infer a tuple type for the sources array, you\n// could just use mergeDeep instead of mergeDeepArray, so instead of\n// trying to convert T[] to an intersection type we just infer the array\n// element type, which works perfectly when the sources array has a\n// consistent element type.\nexport function mergeDeepArray(sources: T[]): T {\n let target = sources[0] || ({} as T);\n const count = sources.length;\n if (count > 1) {\n const merger = new DeepMerger();\n for (let i = 1; i < count; ++i) {\n target = merger.merge(target, sources[i]);\n }\n }\n return target;\n}\n\nexport type ReconcilerFunction = (\n this: DeepMerger,\n target: Record,\n source: Record,\n property: string | number,\n ...context: TContextArgs\n) => any;\n\nconst defaultReconciler: ReconcilerFunction = function (\n target,\n source,\n property\n) {\n return this.merge(target[property], source[property]);\n};\n\nexport class DeepMerger {\n constructor(\n private reconciler: ReconcilerFunction = defaultReconciler as any as ReconcilerFunction\n ) {}\n\n public merge(target: any, source: any, ...context: TContextArgs): any {\n if (isNonNullObject(source) && isNonNullObject(target)) {\n Object.keys(source).forEach((sourceKey) => {\n if (hasOwnProperty.call(target, sourceKey)) {\n const targetValue = target[sourceKey];\n if (source[sourceKey] !== targetValue) {\n const result = this.reconciler(\n target,\n source,\n sourceKey,\n ...context\n );\n // A well-implemented reconciler may return targetValue to indicate\n // the merge changed nothing about the structure of the target.\n if (result !== targetValue) {\n target = this.shallowCopyForMerge(target);\n target[sourceKey] = result;\n }\n }\n } else {\n // If there is no collision, the target can safely share memory with\n // the source, and the recursion can terminate here.\n target = this.shallowCopyForMerge(target);\n target[sourceKey] = source[sourceKey];\n }\n });\n\n return target;\n }\n\n // If source (or target) is not an object, let source replace target.\n return source;\n }\n\n public isObject = isNonNullObject;\n\n private pastCopies = new Set();\n\n public shallowCopyForMerge(value: T): T {\n if (isNonNullObject(value)) {\n if (!this.pastCopies.has(value)) {\n if (Array.isArray(value)) {\n value = (value as any).slice(0);\n } else {\n value = {\n __proto__: Object.getPrototypeOf(value),\n ...value,\n };\n }\n this.pastCopies.add(value);\n }\n }\n return value;\n }\n}\n","import type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n OperationVariables,\n} from \"../../core/index.js\";\n\nimport { compact } from \"./compact.js\";\n\ntype OptionsUnion =\n | WatchQueryOptions\n | QueryOptions\n | MutationOptions;\n\nexport function mergeOptions<\n TDefaultOptions extends Partial>,\n TOptions extends TDefaultOptions,\n>(\n defaults: TDefaultOptions | Partial | undefined,\n options: TOptions | Partial\n): TOptions & TDefaultOptions {\n return compact(\n defaults,\n options,\n options.variables && {\n variables: compact({\n ...(defaults && defaults.variables),\n ...options.variables,\n }),\n }\n );\n}\n","export function isNonNullObject(obj: any): obj is Record {\n return obj !== null && typeof obj === \"object\";\n}\n\nexport function isPlainObject(obj: any): obj is Record {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n (Object.getPrototypeOf(obj) === Object.prototype ||\n Object.getPrototypeOf(obj) === null)\n );\n}\n","import { makeUniqueId } from \"./makeUniqueId.js\";\n\nexport function stringifyForDisplay(value: any, space = 0): string {\n const undefId = makeUniqueId(\"stringifyForDisplay\");\n return JSON.stringify(\n value,\n (key, value) => {\n return value === void 0 ? undefId : value;\n },\n space\n )\n .split(JSON.stringify(undefId))\n .join(\"\");\n}\n","import { maybe } from \"./maybe.js\";\n\ndeclare global {\n const __DEV__: boolean; // will be removed in `dist` by the `postprocessDist` script\n interface Window {\n __DEV__?: boolean;\n }\n}\n\nexport default (maybe(() => globalThis) ||\n maybe(() => window) ||\n maybe(() => self) ||\n maybe(() => global) ||\n // We don't expect the Function constructor ever to be invoked at runtime, as\n // long as at least one of globalThis, window, self, or global is defined, so\n // we are under no obligation to make it easy for static analysis tools to\n // detect syntactic usage of the Function constructor. If you think you can\n // improve your static analysis to detect this obfuscation, think again. This\n // is an arms race you cannot win, at least not in JavaScript.\n maybe(function () {\n return maybe.constructor(\"return this\")();\n })) as typeof globalThis & Window;\n","import {\n invariant,\n newInvariantError,\n InvariantError,\n} from \"./invariantWrappers.js\";\n\nexport { maybe } from \"./maybe.js\";\nexport { default as global } from \"./global.js\";\nexport { invariant, newInvariantError, InvariantError };\n\n/**\n * @deprecated we do not use this internally anymore,\n * it is just exported for backwards compatibility\n */\n// this file is extempt from automatic `__DEV__` replacement\n// so we have to write it out here\n// @ts-ignore\nexport const DEV = globalThis.__DEV__ !== false;\nexport { DEV as __DEV__ };\n","import { invariant as originalInvariant, InvariantError } from \"ts-invariant\";\nimport { version } from \"../../version.js\";\nimport global from \"./global.js\";\nimport type { ErrorCodes } from \"../../invariantErrorCodes.js\";\nimport { stringifyForDisplay } from \"../common/stringifyForDisplay.js\";\n\nfunction wrap(fn: (msg?: string, ...args: any[]) => void) {\n return function (message?: string | number, ...args: any[]) {\n if (typeof message === \"number\") {\n const arg0 = message;\n message = getHandledErrorMsg(arg0);\n if (!message) {\n message = getFallbackErrorMsg(arg0, args);\n args = [];\n }\n }\n fn(...[message].concat(args));\n };\n}\n\ntype LogFunction = {\n /**\n * Logs a `$level` message if the user used `ts-invariant`'s `setVerbosity` to set\n * a verbosity level of `$level` or lower. (defaults to `\"log\"`).\n *\n * The user will either be presented with a link to the documentation for the message,\n * or they can use the `loadDevMessages` to add the message strings to the bundle.\n * The documentation will display the message without argument substitution.\n * Instead, the arguments will be printed on the console after the link.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n *\n * String substitutions like %s, %o, %d or %f are supported.\n */\n (message?: any, ...optionalParams: unknown[]): void;\n};\n\ntype WrappedInvariant = {\n /**\n * Throws and InvariantError with the given message if the condition is false.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n *\n * The user will either be presented with a link to the documentation for the message,\n * or they can use the `loadErrorMessages` to add the message strings to the bundle.\n * The documentation will display the message with the arguments substituted.\n *\n * String substitutions with %s are supported and will also return\n * pretty-stringified objects.\n * Excess `optionalParams` will be swallowed.\n */\n (\n condition: any,\n message?: string | number,\n ...optionalParams: unknown[]\n ): asserts condition;\n\n debug: LogFunction;\n log: LogFunction;\n warn: LogFunction;\n error: LogFunction;\n};\nconst invariant: WrappedInvariant = Object.assign(\n function invariant(\n condition: any,\n message?: string | number,\n ...args: unknown[]\n ): asserts condition {\n if (!condition) {\n originalInvariant(\n condition,\n getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args)\n );\n }\n },\n {\n debug: wrap(originalInvariant.debug),\n log: wrap(originalInvariant.log),\n warn: wrap(originalInvariant.warn),\n error: wrap(originalInvariant.error),\n }\n);\n\n/**\n * Returns an InvariantError.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n * String substitutions with %s are supported and will also return\n * pretty-stringified objects.\n * Excess `optionalParams` will be swallowed.\n */\nfunction newInvariantError(\n message?: string | number,\n ...optionalParams: unknown[]\n) {\n return new InvariantError(\n getHandledErrorMsg(message, optionalParams) ||\n getFallbackErrorMsg(message, optionalParams)\n );\n}\n\nconst ApolloErrorMessageHandler = Symbol.for(\n \"ApolloErrorMessageHandler_\" + version\n);\ndeclare global {\n interface Window {\n [ApolloErrorMessageHandler]?: {\n (message: string | number, args: string[]): string | undefined;\n } & ErrorCodes;\n }\n}\n\nfunction stringify(arg: any) {\n if (typeof arg == \"string\") {\n return arg;\n }\n\n try {\n return stringifyForDisplay(arg, 2).slice(0, 1000);\n } catch {\n return \"\";\n }\n}\n\nfunction getHandledErrorMsg(\n message?: string | number,\n messageArgs: unknown[] = []\n) {\n if (!message) return;\n return (\n global[ApolloErrorMessageHandler] &&\n global[ApolloErrorMessageHandler](message, messageArgs.map(stringify))\n );\n}\n\nfunction getFallbackErrorMsg(\n message?: string | number,\n messageArgs: unknown[] = []\n) {\n if (!message) return;\n return `An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#${encodeURIComponent(\n JSON.stringify({\n version,\n message,\n args: messageArgs.map(stringify),\n })\n )}`;\n}\n\nexport {\n invariant,\n InvariantError,\n newInvariantError,\n ApolloErrorMessageHandler,\n};\n","export function maybe(thunk: () => T): T | undefined {\n try {\n return thunk();\n } catch {}\n}\n","import { Trie } from \"@wry/trie\";\nimport { canUseWeakMap, canUseWeakSet } from \"../common/canUse.js\";\nimport { checkDocument } from \"./getFromAST.js\";\nimport { invariant } from \"../globals/index.js\";\nimport type { DocumentNode } from \"graphql\";\nimport { WeakCache } from \"@wry/caches\";\nimport { wrap } from \"optimism\";\nimport { cacheSizes } from \"../caching/index.js\";\n\nexport type DocumentTransformCacheKey = ReadonlyArray;\n\ntype TransformFn = (document: DocumentNode) => DocumentNode;\n\ninterface DocumentTransformOptions {\n /**\n * Determines whether to cache the transformed GraphQL document. Caching can speed up repeated calls to the document transform for the same input document. Set to `false` to completely disable caching for the document transform. When disabled, this option takes precedence over the [`getCacheKey`](#getcachekey) option.\n *\n * The default value is `true`.\n */\n cache?: boolean;\n /**\n * Defines a custom cache key for a GraphQL document that will determine whether to re-run the document transform when given the same input GraphQL document. Returns an array that defines the cache key. Return `undefined` to disable caching for that GraphQL document.\n *\n * > **Note:** The items in the array may be any type, but also need to be referentially stable to guarantee a stable cache key.\n *\n * The default implementation of this function returns the `document` as the cache key.\n */\n getCacheKey?: (\n document: DocumentNode\n ) => DocumentTransformCacheKey | undefined;\n}\n\nfunction identity(document: DocumentNode) {\n return document;\n}\n\nexport class DocumentTransform {\n private readonly transform: TransformFn;\n private cached: boolean;\n\n private readonly resultCache =\n canUseWeakSet ? new WeakSet() : new Set();\n\n // This default implementation of getCacheKey can be overridden by providing\n // options.getCacheKey to the DocumentTransform constructor. In general, a\n // getCacheKey function may either return an array of keys (often including\n // the document) to be used as a cache key, or undefined to indicate the\n // transform for this document should not be cached.\n private getCacheKey(\n document: DocumentNode\n ): DocumentTransformCacheKey | undefined {\n return [document];\n }\n\n static identity() {\n // No need to cache this transform since it just returns the document\n // unchanged. This should save a bit of memory that would otherwise be\n // needed to populate the `documentCache` of this transform.\n return new DocumentTransform(identity, { cache: false });\n }\n\n static split(\n predicate: (document: DocumentNode) => boolean,\n left: DocumentTransform,\n right: DocumentTransform = DocumentTransform.identity()\n ) {\n return Object.assign(\n new DocumentTransform(\n (document) => {\n const documentTransform = predicate(document) ? left : right;\n\n return documentTransform.transformDocument(document);\n },\n // Reasonably assume both `left` and `right` transforms handle their own caching\n { cache: false }\n ),\n { left, right }\n );\n }\n\n constructor(\n transform: TransformFn,\n options: DocumentTransformOptions = Object.create(null)\n ) {\n this.transform = transform;\n\n if (options.getCacheKey) {\n // Override default `getCacheKey` function, which returns [document].\n this.getCacheKey = options.getCacheKey;\n }\n this.cached = options.cache !== false;\n\n this.resetCache();\n }\n\n /**\n * Resets the internal cache of this transform, if it has one.\n */\n resetCache() {\n if (this.cached) {\n const stableCacheKeys = new Trie(canUseWeakMap);\n this.performWork = wrap(\n DocumentTransform.prototype.performWork.bind(this),\n {\n makeCacheKey: (document) => {\n const cacheKeys = this.getCacheKey(document);\n if (cacheKeys) {\n invariant(\n Array.isArray(cacheKeys),\n \"`getCacheKey` must return an array or undefined\"\n );\n return stableCacheKeys.lookupArray(cacheKeys);\n }\n },\n max: cacheSizes[\"documentTransform.cache\"],\n cache: WeakCache,\n }\n );\n }\n }\n\n private performWork(document: DocumentNode) {\n checkDocument(document);\n return this.transform(document);\n }\n\n transformDocument(document: DocumentNode) {\n // If a user passes an already transformed result back to this function,\n // immediately return it.\n if (this.resultCache.has(document)) {\n return document;\n }\n\n const transformedDocument = this.performWork(document);\n\n this.resultCache.add(transformedDocument);\n\n return transformedDocument;\n }\n\n concat(otherTransform: DocumentTransform): DocumentTransform {\n return Object.assign(\n new DocumentTransform(\n (document) => {\n return otherTransform.transformDocument(\n this.transformDocument(document)\n );\n },\n // Reasonably assume both transforms handle their own caching\n { cache: false }\n ),\n {\n left: this,\n right: otherTransform,\n }\n );\n }\n\n /**\n * @internal\n * Used to iterate through all transforms that are concatenations or `split` links.\n */\n readonly left?: DocumentTransform;\n /**\n * @internal\n * Used to iterate through all transforms that are concatenations or `split` links.\n */\n readonly right?: DocumentTransform;\n}\n","import { invariant } from \"../globals/index.js\";\n\n// Provides the methods that allow QueryManager to handle the `skip` and\n// `include` directives within GraphQL.\nimport type {\n SelectionNode,\n VariableNode,\n BooleanValueNode,\n DirectiveNode,\n DocumentNode,\n ArgumentNode,\n ValueNode,\n ASTNode,\n FragmentSpreadNode,\n} from \"graphql\";\nimport { visit, BREAK, Kind } from \"graphql\";\n\nexport type DirectiveInfo = {\n [fieldName: string]: { [argName: string]: any };\n};\n\nexport function shouldInclude(\n { directives }: SelectionNode,\n variables?: Record\n): boolean {\n if (!directives || !directives.length) {\n return true;\n }\n return getInclusionDirectives(directives).every(\n ({ directive, ifArgument }) => {\n let evaledValue: boolean = false;\n if (ifArgument.value.kind === \"Variable\") {\n evaledValue =\n variables && variables[(ifArgument.value as VariableNode).name.value];\n invariant(\n evaledValue !== void 0,\n `Invalid variable referenced in @%s directive.`,\n directive.name.value\n );\n } else {\n evaledValue = (ifArgument.value as BooleanValueNode).value;\n }\n return directive.name.value === \"skip\" ? !evaledValue : evaledValue;\n }\n );\n}\n\nexport function getDirectiveNames(root: ASTNode) {\n const names: string[] = [];\n\n visit(root, {\n Directive(node: DirectiveNode) {\n names.push(node.name.value);\n },\n });\n\n return names;\n}\n\nexport const hasAnyDirectives = (names: string[], root: ASTNode) =>\n hasDirectives(names, root, false);\n\nexport const hasAllDirectives = (names: string[], root: ASTNode) =>\n hasDirectives(names, root, true);\n\nexport function hasDirectives(names: string[], root: ASTNode, all?: boolean) {\n const nameSet = new Set(names);\n const uniqueCount = nameSet.size;\n\n visit(root, {\n Directive(node) {\n if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {\n return BREAK;\n }\n },\n });\n\n // If we found all the names, nameSet will be empty. If we only care about\n // finding some of them, the < condition is sufficient.\n return all ? !nameSet.size : nameSet.size < uniqueCount;\n}\n\nexport function hasClientExports(document: DocumentNode) {\n return document && hasDirectives([\"client\", \"export\"], document, true);\n}\n\nexport type InclusionDirectives = Array<{\n directive: DirectiveNode;\n ifArgument: ArgumentNode;\n}>;\n\nfunction isInclusionDirective({ name: { value } }: DirectiveNode): boolean {\n return value === \"skip\" || value === \"include\";\n}\n\nexport function getInclusionDirectives(\n directives: ReadonlyArray\n): InclusionDirectives {\n const result: InclusionDirectives = [];\n\n if (directives && directives.length) {\n directives.forEach((directive) => {\n if (!isInclusionDirective(directive)) return;\n\n const directiveArguments = directive.arguments;\n const directiveName = directive.name.value;\n\n invariant(\n directiveArguments && directiveArguments.length === 1,\n `Incorrect number of arguments for the @%s directive.`,\n directiveName\n );\n\n const ifArgument = directiveArguments![0];\n invariant(\n ifArgument.name && ifArgument.name.value === \"if\",\n `Invalid argument for the @%s directive.`,\n directiveName\n );\n\n const ifValue: ValueNode = ifArgument.value;\n\n // means it has to be a variable value if this is a valid @skip or @include directive\n invariant(\n ifValue &&\n (ifValue.kind === \"Variable\" || ifValue.kind === \"BooleanValue\"),\n `Argument for the @%s directive must be a variable or a boolean value.`,\n directiveName\n );\n\n result.push({ directive, ifArgument });\n });\n }\n\n return result;\n}\n\n/** @internal */\nexport function getFragmentMaskMode(\n fragment: FragmentSpreadNode\n): \"mask\" | \"migrate\" | \"unmask\" {\n const directive = fragment.directives?.find(\n ({ name }) => name.value === \"unmask\"\n );\n\n if (!directive) {\n return \"mask\";\n }\n\n const modeArg = directive.arguments?.find(\n ({ name }) => name.value === \"mode\"\n );\n\n if (__DEV__) {\n if (modeArg) {\n if (modeArg.value.kind === Kind.VARIABLE) {\n invariant.warn(\"@unmask 'mode' argument does not support variables.\");\n } else if (modeArg.value.kind !== Kind.STRING) {\n invariant.warn(\"@unmask 'mode' argument must be of type string.\");\n } else if (modeArg.value.value !== \"migrate\") {\n invariant.warn(\n \"@unmask 'mode' argument does not recognize value '%s'.\",\n modeArg.value.value\n );\n }\n }\n }\n\n if (\n modeArg &&\n \"value\" in modeArg.value &&\n modeArg.value.value === \"migrate\"\n ) {\n return \"migrate\";\n }\n\n return \"unmask\";\n}\n","import { invariant, newInvariantError } from \"../globals/index.js\";\n\nimport { BREAK, visit } from \"graphql\";\nimport type {\n DocumentNode,\n FragmentDefinitionNode,\n InlineFragmentNode,\n SelectionNode,\n} from \"graphql\";\n\n// TODO(brian): A hack until this issue is resolved (https://github.com/graphql/graphql-js/issues/3356)\ntype Kind = any;\ntype OperationTypeNode = any;\n/**\n * Returns a query document which adds a single query operation that only\n * spreads the target fragment inside of it.\n *\n * So for example a document of:\n *\n * ```graphql\n * fragment foo on Foo { a b c }\n * ```\n *\n * Turns into:\n *\n * ```graphql\n * { ...foo }\n *\n * fragment foo on Foo { a b c }\n * ```\n *\n * The target fragment will either be the only fragment in the document, or a\n * fragment specified by the provided `fragmentName`. If there is more than one\n * fragment, but a `fragmentName` was not defined then an error will be thrown.\n */\nexport function getFragmentQueryDocument(\n document: DocumentNode,\n fragmentName?: string\n): DocumentNode {\n let actualFragmentName = fragmentName;\n\n // Build an array of all our fragment definitions that will be used for\n // validations. We also do some validations on the other definitions in the\n // document while building this list.\n const fragments: Array = [];\n document.definitions.forEach((definition) => {\n // Throw an error if we encounter an operation definition because we will\n // define our own operation definition later on.\n if (definition.kind === \"OperationDefinition\") {\n throw newInvariantError(\n `Found a %s operation%s. ` +\n \"No operations are allowed when using a fragment as a query. Only fragments are allowed.\",\n definition.operation,\n definition.name ? ` named '${definition.name.value}'` : \"\"\n );\n }\n // Add our definition to the fragments array if it is a fragment\n // definition.\n if (definition.kind === \"FragmentDefinition\") {\n fragments.push(definition);\n }\n });\n\n // If the user did not give us a fragment name then let us try to get a\n // name from a single fragment in the definition.\n if (typeof actualFragmentName === \"undefined\") {\n invariant(\n fragments.length === 1,\n `Found %s fragments. \\`fragmentName\\` must be provided when there is not exactly 1 fragment.`,\n fragments.length\n );\n actualFragmentName = fragments[0].name.value;\n }\n\n // Generate a query document with an operation that simply spreads the\n // fragment inside of it.\n const query: DocumentNode = {\n ...document,\n definitions: [\n {\n kind: \"OperationDefinition\" as Kind,\n // OperationTypeNode is an enum\n operation: \"query\" as OperationTypeNode,\n selectionSet: {\n kind: \"SelectionSet\" as Kind,\n selections: [\n {\n kind: \"FragmentSpread\" as Kind,\n name: {\n kind: \"Name\" as Kind,\n value: actualFragmentName,\n },\n },\n ],\n },\n },\n ...document.definitions,\n ],\n };\n\n return query;\n}\n\n/**\n * This is an interface that describes a map from fragment names to fragment definitions.\n */\nexport interface FragmentMap {\n [fragmentName: string]: FragmentDefinitionNode;\n}\n\nexport type FragmentMapFunction = (\n fragmentName: string\n) => FragmentDefinitionNode | null;\n\n// Utility function that takes a list of fragment definitions and makes a hash out of them\n// that maps the name of the fragment to the fragment definition.\nexport function createFragmentMap(\n fragments: FragmentDefinitionNode[] = []\n): FragmentMap {\n const symTable: FragmentMap = {};\n fragments.forEach((fragment) => {\n symTable[fragment.name.value] = fragment;\n });\n return symTable;\n}\n\nexport function getFragmentFromSelection(\n selection: SelectionNode,\n fragmentMap?: FragmentMap | FragmentMapFunction\n): InlineFragmentNode | FragmentDefinitionNode | null {\n switch (selection.kind) {\n case \"InlineFragment\":\n return selection;\n case \"FragmentSpread\": {\n const fragmentName = selection.name.value;\n if (typeof fragmentMap === \"function\") {\n return fragmentMap(fragmentName);\n }\n const fragment = fragmentMap && fragmentMap[fragmentName];\n invariant(fragment, `No fragment named %s`, fragmentName);\n return fragment || null;\n }\n default:\n return null;\n }\n}\n\nexport function isFullyUnmaskedOperation(document: DocumentNode) {\n let isUnmasked = true;\n\n visit(document, {\n FragmentSpread: (node) => {\n isUnmasked =\n !!node.directives &&\n node.directives.some((directive) => directive.name.value === \"unmask\");\n\n if (!isUnmasked) {\n return BREAK;\n }\n },\n });\n\n return isUnmasked;\n}\n","import { invariant, newInvariantError } from \"../globals/index.js\";\n\nimport type {\n DocumentNode,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n ValueNode,\n} from \"graphql\";\n\nimport { valueToObjectRepresentation } from \"./storeUtils.js\";\n\ntype OperationDefinitionWithName = OperationDefinitionNode & {\n name: NonNullable;\n};\n\n// Checks the document for errors and throws an exception if there is an error.\nexport function checkDocument(doc: DocumentNode) {\n invariant(\n doc && doc.kind === \"Document\",\n `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n );\n\n const operations = doc.definitions\n .filter((d) => d.kind !== \"FragmentDefinition\")\n .map((definition) => {\n if (definition.kind !== \"OperationDefinition\") {\n throw newInvariantError(\n `Schema type definitions not allowed in queries. Found: \"%s\"`,\n definition.kind\n );\n }\n return definition;\n });\n\n invariant(\n operations.length <= 1,\n `Ambiguous GraphQL document: contains %s operations`,\n operations.length\n );\n\n return doc;\n}\n\nexport function getOperationDefinition(\n doc: DocumentNode\n): OperationDefinitionNode | undefined {\n checkDocument(doc);\n return doc.definitions.filter(\n (definition): definition is OperationDefinitionNode =>\n definition.kind === \"OperationDefinition\"\n )[0];\n}\n\nexport function getOperationName(doc: DocumentNode): string | null {\n return (\n doc.definitions\n .filter(\n (definition): definition is OperationDefinitionWithName =>\n definition.kind === \"OperationDefinition\" && !!definition.name\n )\n .map((x) => x.name.value)[0] || null\n );\n}\n\n// Returns the FragmentDefinitions from a particular document as an array\nexport function getFragmentDefinitions(\n doc: DocumentNode\n): FragmentDefinitionNode[] {\n return doc.definitions.filter(\n (definition): definition is FragmentDefinitionNode =>\n definition.kind === \"FragmentDefinition\"\n );\n}\n\nexport function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode {\n const queryDef = getOperationDefinition(doc)!;\n\n invariant(\n queryDef && queryDef.operation === \"query\",\n \"Must contain a query definition.\"\n );\n\n return queryDef;\n}\n\nexport function getFragmentDefinition(\n doc: DocumentNode\n): FragmentDefinitionNode {\n invariant(\n doc.kind === \"Document\",\n `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n );\n\n invariant(\n doc.definitions.length <= 1,\n \"Fragment must have exactly one definition.\"\n );\n\n const fragmentDef = doc.definitions[0] as FragmentDefinitionNode;\n\n invariant(\n fragmentDef.kind === \"FragmentDefinition\",\n \"Must be a fragment definition.\"\n );\n\n return fragmentDef as FragmentDefinitionNode;\n}\n\n/**\n * Returns the first operation definition found in this document.\n * If no operation definition is found, the first fragment definition will be returned.\n * If no definitions are found, an error will be thrown.\n */\nexport function getMainDefinition(\n queryDoc: DocumentNode\n): OperationDefinitionNode | FragmentDefinitionNode {\n checkDocument(queryDoc);\n\n let fragmentDefinition;\n\n for (let definition of queryDoc.definitions) {\n if (definition.kind === \"OperationDefinition\") {\n const operation = (definition as OperationDefinitionNode).operation;\n if (\n operation === \"query\" ||\n operation === \"mutation\" ||\n operation === \"subscription\"\n ) {\n return definition as OperationDefinitionNode;\n }\n }\n if (definition.kind === \"FragmentDefinition\" && !fragmentDefinition) {\n // we do this because we want to allow multiple fragment definitions\n // to precede an operation definition.\n fragmentDefinition = definition as FragmentDefinitionNode;\n }\n }\n\n if (fragmentDefinition) {\n return fragmentDefinition;\n }\n\n throw newInvariantError(\n \"Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.\"\n );\n}\n\nexport function getDefaultValues(\n definition: OperationDefinitionNode | undefined\n): Record {\n const defaultValues = Object.create(null);\n const defs = definition && definition.variableDefinitions;\n if (defs && defs.length) {\n defs.forEach((def) => {\n if (def.defaultValue) {\n valueToObjectRepresentation(\n defaultValues,\n def.variable.name,\n def.defaultValue as ValueNode\n );\n }\n });\n }\n return defaultValues;\n}\n","import type { ASTNode } from \"graphql\";\nimport { print as origPrint } from \"graphql\";\nimport {\n AutoCleanedWeakCache,\n cacheSizes,\n defaultCacheSizes,\n} from \"../caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n\nlet printCache!: AutoCleanedWeakCache;\nexport const print = Object.assign(\n (ast: ASTNode) => {\n let result = printCache.get(ast);\n\n if (!result) {\n result = origPrint(ast);\n printCache.set(ast, result);\n }\n return result;\n },\n {\n reset() {\n printCache = new AutoCleanedWeakCache(\n cacheSizes.print || defaultCacheSizes.print\n );\n },\n }\n);\nprint.reset();\n\nif (__DEV__) {\n registerGlobalCache(\"print\", () => (printCache ? printCache.size : 0));\n}\n","import { newInvariantError } from \"../globals/index.js\";\n\nimport type {\n DirectiveNode,\n FieldNode,\n IntValueNode,\n FloatValueNode,\n StringValueNode,\n BooleanValueNode,\n ObjectValueNode,\n ListValueNode,\n EnumValueNode,\n NullValueNode,\n VariableNode,\n InlineFragmentNode,\n ValueNode,\n SelectionNode,\n NameNode,\n SelectionSetNode,\n DocumentNode,\n FragmentSpreadNode,\n} from \"graphql\";\n\nimport { isNonNullObject } from \"../common/objects.js\";\nimport type { FragmentMap } from \"./fragments.js\";\nimport { getFragmentFromSelection } from \"./fragments.js\";\nimport { canonicalStringify } from \"../common/canonicalStringify.js\";\n\nexport interface Reference {\n readonly __ref: string;\n}\n\nexport function makeReference(id: string): Reference {\n return { __ref: String(id) };\n}\n\nexport function isReference(obj: any): obj is Reference {\n return Boolean(\n obj && typeof obj === \"object\" && typeof obj.__ref === \"string\"\n );\n}\n\nexport type StoreValue =\n | number\n | string\n | string[]\n | Reference\n | Reference[]\n | null\n | undefined\n | void\n | Object;\n\nexport interface StoreObject {\n __typename?: string;\n [storeFieldName: string]: StoreValue;\n}\n\n/**\n * Workaround for a TypeScript quirk:\n * types per default have an implicit index signature that makes them\n * assignable to `StoreObject`.\n * interfaces do not have that implicit index signature, so they cannot\n * be assigned to `StoreObject`.\n * This type just maps over a type or interface that is passed in,\n * implicitly adding the index signature.\n * That way, the result can be assigned to `StoreObject`.\n *\n * This is important if some user-defined interface is used e.g.\n * in cache.modify, where the `toReference` method expects a\n * `StoreObject` as input.\n */\nexport type AsStoreObject = {\n [K in keyof T]: T[K];\n};\n\nexport function isDocumentNode(value: any): value is DocumentNode {\n return (\n isNonNullObject(value) &&\n (value as DocumentNode).kind === \"Document\" &&\n Array.isArray((value as DocumentNode).definitions)\n );\n}\n\nfunction isStringValue(value: ValueNode): value is StringValueNode {\n return value.kind === \"StringValue\";\n}\n\nfunction isBooleanValue(value: ValueNode): value is BooleanValueNode {\n return value.kind === \"BooleanValue\";\n}\n\nfunction isIntValue(value: ValueNode): value is IntValueNode {\n return value.kind === \"IntValue\";\n}\n\nfunction isFloatValue(value: ValueNode): value is FloatValueNode {\n return value.kind === \"FloatValue\";\n}\n\nfunction isVariable(value: ValueNode): value is VariableNode {\n return value.kind === \"Variable\";\n}\n\nfunction isObjectValue(value: ValueNode): value is ObjectValueNode {\n return value.kind === \"ObjectValue\";\n}\n\nfunction isListValue(value: ValueNode): value is ListValueNode {\n return value.kind === \"ListValue\";\n}\n\nfunction isEnumValue(value: ValueNode): value is EnumValueNode {\n return value.kind === \"EnumValue\";\n}\n\nfunction isNullValue(value: ValueNode): value is NullValueNode {\n return value.kind === \"NullValue\";\n}\n\nexport function valueToObjectRepresentation(\n argObj: any,\n name: NameNode,\n value: ValueNode,\n variables?: Object\n) {\n if (isIntValue(value) || isFloatValue(value)) {\n argObj[name.value] = Number(value.value);\n } else if (isBooleanValue(value) || isStringValue(value)) {\n argObj[name.value] = value.value;\n } else if (isObjectValue(value)) {\n const nestedArgObj = {};\n value.fields.map((obj) =>\n valueToObjectRepresentation(nestedArgObj, obj.name, obj.value, variables)\n );\n argObj[name.value] = nestedArgObj;\n } else if (isVariable(value)) {\n const variableValue = (variables || ({} as any))[value.name.value];\n argObj[name.value] = variableValue;\n } else if (isListValue(value)) {\n argObj[name.value] = value.values.map((listValue) => {\n const nestedArgArrayObj = {};\n valueToObjectRepresentation(\n nestedArgArrayObj,\n name,\n listValue,\n variables\n );\n return (nestedArgArrayObj as any)[name.value];\n });\n } else if (isEnumValue(value)) {\n argObj[name.value] = (value as EnumValueNode).value;\n } else if (isNullValue(value)) {\n argObj[name.value] = null;\n } else {\n throw newInvariantError(\n `The inline argument \"%s\" of kind \"%s\"` +\n \"is not supported. Use variables instead of inline arguments to \" +\n \"overcome this limitation.\",\n name.value,\n (value as any).kind\n );\n }\n}\n\nexport function storeKeyNameFromField(\n field: FieldNode,\n variables?: Object\n): string {\n let directivesObj: any = null;\n if (field.directives) {\n directivesObj = {};\n field.directives.forEach((directive) => {\n directivesObj[directive.name.value] = {};\n\n if (directive.arguments) {\n directive.arguments.forEach(({ name, value }) =>\n valueToObjectRepresentation(\n directivesObj[directive.name.value],\n name,\n value,\n variables\n )\n );\n }\n });\n }\n\n let argObj: any = null;\n if (field.arguments && field.arguments.length) {\n argObj = {};\n field.arguments.forEach(({ name, value }) =>\n valueToObjectRepresentation(argObj, name, value, variables)\n );\n }\n\n return getStoreKeyName(field.name.value, argObj, directivesObj);\n}\n\nexport type Directives = {\n [directiveName: string]: {\n [argName: string]: any;\n };\n};\n\nconst KNOWN_DIRECTIVES: string[] = [\n \"connection\",\n \"include\",\n \"skip\",\n \"client\",\n \"rest\",\n \"export\",\n \"nonreactive\",\n];\n\n// Default stable JSON.stringify implementation used by getStoreKeyName. Can be\n// updated/replaced with something better by calling\n// getStoreKeyName.setStringify(newStringifyFunction).\nlet storeKeyNameStringify: (value: any) => string = canonicalStringify;\n\nexport const getStoreKeyName = Object.assign(\n function (\n fieldName: string,\n args?: Record | null,\n directives?: Directives\n ): string {\n if (\n args &&\n directives &&\n directives[\"connection\"] &&\n directives[\"connection\"][\"key\"]\n ) {\n if (\n directives[\"connection\"][\"filter\"] &&\n (directives[\"connection\"][\"filter\"] as string[]).length > 0\n ) {\n const filterKeys =\n directives[\"connection\"][\"filter\"] ?\n (directives[\"connection\"][\"filter\"] as string[])\n : [];\n filterKeys.sort();\n\n const filteredArgs = {} as { [key: string]: any };\n filterKeys.forEach((key) => {\n filteredArgs[key] = args[key];\n });\n\n return `${directives[\"connection\"][\"key\"]}(${storeKeyNameStringify(\n filteredArgs\n )})`;\n } else {\n return directives[\"connection\"][\"key\"];\n }\n }\n\n let completeFieldName: string = fieldName;\n\n if (args) {\n // We can't use `JSON.stringify` here since it's non-deterministic,\n // and can lead to different store key names being created even though\n // the `args` object used during creation has the same properties/values.\n const stringifiedArgs: string = storeKeyNameStringify(args);\n completeFieldName += `(${stringifiedArgs})`;\n }\n\n if (directives) {\n Object.keys(directives).forEach((key) => {\n if (KNOWN_DIRECTIVES.indexOf(key) !== -1) return;\n if (directives[key] && Object.keys(directives[key]).length) {\n completeFieldName += `@${key}(${storeKeyNameStringify(\n directives[key]\n )})`;\n } else {\n completeFieldName += `@${key}`;\n }\n });\n }\n\n return completeFieldName;\n },\n {\n setStringify(s: typeof storeKeyNameStringify) {\n const previous = storeKeyNameStringify;\n storeKeyNameStringify = s;\n return previous;\n },\n }\n);\n\nexport function argumentsObjectFromField(\n field: FieldNode | DirectiveNode,\n variables?: Record\n): Object | null {\n if (field.arguments && field.arguments.length) {\n const argObj: Object = {};\n field.arguments.forEach(({ name, value }) =>\n valueToObjectRepresentation(argObj, name, value, variables)\n );\n return argObj;\n }\n return null;\n}\n\nexport function resultKeyNameFromField(field: FieldNode): string {\n return field.alias ? field.alias.value : field.name.value;\n}\n\nexport function getTypenameFromResult(\n result: Record,\n selectionSet: SelectionSetNode,\n fragmentMap?: FragmentMap\n): string | undefined {\n let fragments: undefined | Array;\n for (const selection of selectionSet.selections) {\n if (isField(selection)) {\n if (selection.name.value === \"__typename\") {\n return result[resultKeyNameFromField(selection)];\n }\n } else if (fragments) {\n fragments.push(selection);\n } else {\n fragments = [selection];\n }\n }\n if (typeof result.__typename === \"string\") {\n return result.__typename;\n }\n if (fragments) {\n for (const selection of fragments) {\n const typename = getTypenameFromResult(\n result,\n getFragmentFromSelection(selection, fragmentMap)!.selectionSet,\n fragmentMap\n );\n if (typeof typename === \"string\") {\n return typename;\n }\n }\n }\n}\n\nexport function isField(selection: SelectionNode): selection is FieldNode {\n return selection.kind === \"Field\";\n}\n\nexport function isInlineFragment(\n selection: SelectionNode\n): selection is InlineFragmentNode {\n return selection.kind === \"InlineFragment\";\n}\n\nexport type VariableValue = (node: VariableNode) => any;\n","import { invariant } from \"../globals/index.js\";\n\nimport type {\n DocumentNode,\n SelectionNode,\n SelectionSetNode,\n OperationDefinitionNode,\n FieldNode,\n DirectiveNode,\n FragmentDefinitionNode,\n ArgumentNode,\n FragmentSpreadNode,\n VariableDefinitionNode,\n ASTNode,\n ASTVisitFn,\n InlineFragmentNode,\n} from \"graphql\";\nimport { visit, Kind } from \"graphql\";\n\nimport {\n checkDocument,\n getOperationDefinition,\n getFragmentDefinition,\n getFragmentDefinitions,\n getMainDefinition,\n} from \"./getFromAST.js\";\nimport { isField } from \"./storeUtils.js\";\nimport type { FragmentMap } from \"./fragments.js\";\nimport { createFragmentMap } from \"./fragments.js\";\nimport { isArray, isNonEmptyArray } from \"../common/arrays.js\";\n\n// https://github.com/graphql/graphql-js/blob/8d7c8fccf5a9846a50785de04abda58a7eb13fc0/src/language/visitor.ts#L20-L23\ninterface EnterLeaveVisitor {\n readonly enter?: ASTVisitFn;\n readonly leave?: ASTVisitFn;\n}\n\nexport type RemoveNodeConfig = {\n name?: string;\n test?: (node: N) => boolean;\n remove?: boolean;\n};\n\nexport type GetNodeConfig = {\n name?: string;\n test?: (node: N) => boolean;\n};\n\nexport type RemoveDirectiveConfig = RemoveNodeConfig;\nexport type GetDirectiveConfig = GetNodeConfig;\nexport type RemoveArgumentsConfig = RemoveNodeConfig;\nexport type GetFragmentSpreadConfig = GetNodeConfig;\nexport type RemoveFragmentSpreadConfig = RemoveNodeConfig;\nexport type RemoveFragmentDefinitionConfig =\n RemoveNodeConfig;\nexport type RemoveVariableDefinitionConfig =\n RemoveNodeConfig;\n\nconst TYPENAME_FIELD: FieldNode = {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: \"__typename\",\n },\n};\n\nfunction isEmpty(\n op: OperationDefinitionNode | FragmentDefinitionNode,\n fragmentMap: FragmentMap\n): boolean {\n return (\n !op ||\n op.selectionSet.selections.every(\n (selection) =>\n selection.kind === Kind.FRAGMENT_SPREAD &&\n isEmpty(fragmentMap[selection.name.value], fragmentMap)\n )\n );\n}\n\nfunction nullIfDocIsEmpty(doc: DocumentNode) {\n return (\n isEmpty(\n getOperationDefinition(doc) || getFragmentDefinition(doc),\n createFragmentMap(getFragmentDefinitions(doc))\n )\n ) ?\n null\n : doc;\n}\n\nfunction getDirectiveMatcher(\n configs: (RemoveDirectiveConfig | GetDirectiveConfig)[]\n) {\n const names = new Map();\n\n const tests = new Map<\n (directive: DirectiveNode) => boolean,\n RemoveDirectiveConfig | GetDirectiveConfig\n >();\n\n configs.forEach((directive) => {\n if (directive) {\n if (directive.name) {\n names.set(directive.name, directive);\n } else if (directive.test) {\n tests.set(directive.test, directive);\n }\n }\n });\n\n return (directive: DirectiveNode) => {\n let config = names.get(directive.name.value);\n if (!config && tests.size) {\n tests.forEach((testConfig, test) => {\n if (test(directive)) {\n config = testConfig;\n }\n });\n }\n return config;\n };\n}\n\n// Helper interface and function used by removeDirectivesFromDocument to keep\n// track of variable references and fragments spreads found within a given\n// operation or fragment definition.\ninterface InternalInUseInfo {\n variables: Set;\n fragmentSpreads: Set;\n // Set to true when we deliberately remove a fragment definition, so we can\n // make sure also to remove dangling ...spreads that refer to it.\n removed?: boolean;\n // Populated by the populateTransitiveVars helper function below.\n transitiveVars?: Set;\n}\nfunction makeInUseGetterFunction(defaultKey: TKey) {\n const map = new Map();\n\n return function inUseGetterFunction(\n key: TKey = defaultKey\n ): InternalInUseInfo {\n let inUse = map.get(key);\n if (!inUse) {\n map.set(\n key,\n (inUse = {\n // Variable and fragment spread names used directly within this\n // operation or fragment definition, as identified by key. These sets\n // will be populated during the first traversal of the document in\n // removeDirectivesFromDocument below.\n variables: new Set(),\n fragmentSpreads: new Set(),\n })\n );\n }\n return inUse;\n };\n}\n\nexport function removeDirectivesFromDocument(\n directives: RemoveDirectiveConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n checkDocument(doc);\n\n // Passing empty strings to makeInUseGetterFunction means we handle anonymous\n // operations as if their names were \"\". Anonymous fragment definitions are\n // not supposed to be possible, but the same default naming strategy seems\n // appropriate for that case as well.\n const getInUseByOperationName = makeInUseGetterFunction(\"\");\n const getInUseByFragmentName = makeInUseGetterFunction(\"\");\n const getInUse = (\n ancestors: readonly (ASTNode | readonly ASTNode[])[]\n ): InternalInUseInfo | null => {\n for (\n let p = 0, ancestor: ASTNode | readonly ASTNode[];\n p < ancestors.length && (ancestor = ancestors[p]);\n ++p\n ) {\n if (isArray(ancestor)) continue;\n if (ancestor.kind === Kind.OPERATION_DEFINITION) {\n // If an operation is anonymous, we use the empty string as its key.\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 invariant.error(`Could not find operation or fragment`);\n return null;\n };\n\n let operationCount = 0;\n for (let i = doc.definitions.length - 1; i >= 0; --i) {\n if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n ++operationCount;\n }\n }\n\n const directiveMatcher = getDirectiveMatcher(directives);\n const shouldRemoveField = (nodeDirectives: FieldNode[\"directives\"]) =>\n isNonEmptyArray(nodeDirectives) &&\n nodeDirectives\n .map(directiveMatcher)\n .some(\n (config: RemoveDirectiveConfig | undefined) => config && config.remove\n );\n\n const originalFragmentDefsByPath = new Map();\n\n // Any time the first traversal of the document below makes a change like\n // removing a fragment (by returning null), this variable should be set to\n // true. Once it becomes true, it should never be set to false again. If this\n // variable remains false throughout the traversal, then we can return the\n // original doc immediately without any modifications.\n let firstVisitMadeChanges = false;\n\n const fieldOrInlineFragmentVisitor: EnterLeaveVisitor<\n FieldNode | InlineFragmentNode\n > = {\n enter(node) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n };\n\n const docWithoutDirectiveSubtrees = visit(doc, {\n // These two AST node types share the same implementation, defined above.\n Field: fieldOrInlineFragmentVisitor,\n InlineFragment: fieldOrInlineFragmentVisitor,\n\n VariableDefinition: {\n enter() {\n // VariableDefinition nodes do not count as variables in use, though\n // they do contain Variable nodes that might be visited below. To avoid\n // counting variable declarations as usages, we skip visiting the\n // contents of this VariableDefinition node by returning false.\n return false;\n },\n },\n\n Variable: {\n enter(node, _key, _parent, _path, ancestors) {\n const inUse = getInUse(ancestors);\n if (inUse) {\n inUse.variables.add(node.name.value);\n }\n },\n },\n\n FragmentSpread: {\n enter(node, _key, _parent, _path, ancestors) {\n if (shouldRemoveField(node.directives)) {\n firstVisitMadeChanges = true;\n return null;\n }\n const inUse = getInUse(ancestors);\n if (inUse) {\n inUse.fragmentSpreads.add(node.name.value);\n }\n // We might like to remove this FragmentSpread by returning null here if\n // the corresponding FragmentDefinition node is also going to be removed\n // by the logic below, but we can't control the relative order of those\n // events, so we have to postpone the removal of dangling FragmentSpread\n // nodes until after the current visit of the document has finished.\n },\n },\n\n FragmentDefinition: {\n enter(node, _key, _parent, path) {\n originalFragmentDefsByPath.set(JSON.stringify(path), node);\n },\n leave(node, _key, _parent, path) {\n const originalNode = originalFragmentDefsByPath.get(\n JSON.stringify(path)\n );\n if (node === originalNode) {\n // If the FragmentNode received by this leave function is identical to\n // the one received by the corresponding enter function (above), then\n // the visitor must not have made any changes within this\n // FragmentDefinition node. This fragment definition may still be\n // removed if there are no ...spread references to it, but it won't be\n // removed just because it has only a __typename field.\n return node;\n }\n\n if (\n // This logic applies only if the document contains one or more\n // operations, since removing all fragments from a document containing\n // only fragments makes the document useless.\n operationCount > 0 &&\n node.selectionSet.selections.every(\n (selection) =>\n selection.kind === Kind.FIELD &&\n selection.name.value === \"__typename\"\n )\n ) {\n // This is a somewhat opinionated choice: if a FragmentDefinition ends\n // up having no fields other than __typename, we remove the whole\n // fragment definition, and later prune ...spread references to it.\n getInUseByFragmentName(node.name.value).removed = true;\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n\n Directive: {\n leave(node) {\n // If a matching directive is found, remove the directive itself. Note\n // that this does not remove the target (field, argument, etc) of the\n // directive, but only the directive itself.\n if (directiveMatcher(node)) {\n firstVisitMadeChanges = true;\n return null;\n }\n },\n },\n });\n\n if (!firstVisitMadeChanges) {\n // If our first pass did not change anything about the document, then there\n // is no cleanup we need to do, and we can return the original doc.\n return doc;\n }\n\n // Utility for making sure inUse.transitiveVars is recursively populated.\n // Because this logic assumes inUse.fragmentSpreads has been completely\n // populated and inUse.removed has been set if appropriate,\n // populateTransitiveVars must be called after that information has been\n // collected by the first traversal of the document.\n const populateTransitiveVars = (inUse: InternalInUseInfo) => {\n if (!inUse.transitiveVars) {\n inUse.transitiveVars = new Set(inUse.variables);\n if (!inUse.removed) {\n inUse.fragmentSpreads.forEach((childFragmentName) => {\n populateTransitiveVars(\n getInUseByFragmentName(childFragmentName)\n ).transitiveVars!.forEach((varName) => {\n inUse.transitiveVars!.add(varName);\n });\n });\n }\n }\n return inUse;\n };\n\n // Since we've been keeping track of fragment spreads used by particular\n // operations and fragment definitions, we now need to compute the set of all\n // spreads used (transitively) by any operations in the document.\n const allFragmentNamesUsed = new Set();\n docWithoutDirectiveSubtrees.definitions.forEach((def) => {\n if (def.kind === Kind.OPERATION_DEFINITION) {\n populateTransitiveVars(\n getInUseByOperationName(def.name && def.name.value)\n ).fragmentSpreads.forEach((childFragmentName) => {\n allFragmentNamesUsed.add(childFragmentName);\n });\n } else if (\n def.kind === Kind.FRAGMENT_DEFINITION &&\n // If there are no operations in the document, then all fragment\n // definitions count as usages of their own fragment names. This heuristic\n // prevents accidentally removing all fragment definitions from the\n // document just because it contains no operations that use the fragments.\n operationCount === 0 &&\n !getInUseByFragmentName(def.name.value).removed\n ) {\n allFragmentNamesUsed.add(def.name.value);\n }\n });\n // Now that we have added all fragment spreads used by operations to the\n // allFragmentNamesUsed set, we can complete the set by transitively adding\n // all fragment spreads used by those fragments, and so on.\n allFragmentNamesUsed.forEach((fragmentName) => {\n // Once all the childFragmentName strings added here have been seen already,\n // the top-level allFragmentNamesUsed.forEach loop will terminate.\n populateTransitiveVars(\n getInUseByFragmentName(fragmentName)\n ).fragmentSpreads.forEach((childFragmentName) => {\n allFragmentNamesUsed.add(childFragmentName);\n });\n });\n\n const fragmentWillBeRemoved = (fragmentName: string) =>\n !!(\n // A fragment definition will be removed if there are no spreads that refer\n // to it, or the fragment was explicitly removed because it had no fields\n // other than __typename.\n (\n !allFragmentNamesUsed.has(fragmentName) ||\n getInUseByFragmentName(fragmentName).removed\n )\n );\n\n const enterVisitor: EnterLeaveVisitor<\n FragmentSpreadNode | FragmentDefinitionNode\n > = {\n enter(node) {\n if (fragmentWillBeRemoved(node.name.value)) {\n return null;\n }\n },\n };\n\n return nullIfDocIsEmpty(\n visit(docWithoutDirectiveSubtrees, {\n // If the fragment is going to be removed, then leaving any dangling\n // FragmentSpread nodes with the same name would be a mistake.\n FragmentSpread: enterVisitor,\n\n // This is where the fragment definition is actually removed.\n FragmentDefinition: enterVisitor,\n\n OperationDefinition: {\n leave(node) {\n // Upon leaving each operation in the depth-first AST traversal, prune\n // any variables that are declared by the operation but unused within.\n if (node.variableDefinitions) {\n const usedVariableNames = populateTransitiveVars(\n // If an operation is anonymous, we use the empty string as its key.\n getInUseByOperationName(node.name && node.name.value)\n ).transitiveVars!;\n\n // According to the GraphQL spec, all variables declared by an\n // operation must either be used by that operation or used by some\n // fragment included transitively into that operation:\n // https://spec.graphql.org/draft/#sec-All-Variables-Used\n //\n // To stay on the right side of this validation rule, if/when we\n // remove the last $var references from an operation or its fragments,\n // we must also remove the corresponding $var declaration from the\n // enclosing operation. This pruning applies only to operations and\n // not fragment definitions, at the moment. Fragments may be able to\n // declare variables eventually, but today they can only consume them.\n if (usedVariableNames.size < node.variableDefinitions.length) {\n return {\n ...node,\n variableDefinitions: node.variableDefinitions.filter((varDef) =>\n usedVariableNames.has(varDef.variable.name.value)\n ),\n };\n }\n }\n },\n },\n })\n );\n}\n\nexport const addTypenameToDocument = Object.assign(\n function (doc: TNode): TNode {\n return visit(doc, {\n SelectionSet: {\n enter(node, _key, parent) {\n // Don't add __typename to OperationDefinitions.\n if (\n parent &&\n (parent as OperationDefinitionNode).kind ===\n Kind.OPERATION_DEFINITION\n ) {\n return;\n }\n\n // No changes if no selections.\n const { selections } = node;\n if (!selections) {\n return;\n }\n\n // If selections already have a __typename, or are part of an\n // introspection query, do nothing.\n const skip = selections.some((selection) => {\n return (\n isField(selection) &&\n (selection.name.value === \"__typename\" ||\n selection.name.value.lastIndexOf(\"__\", 0) === 0)\n );\n });\n if (skip) {\n return;\n }\n\n // If this SelectionSet is @export-ed as an input variable, it should\n // not have a __typename field (see issue #4691).\n const field = parent as FieldNode;\n if (\n isField(field) &&\n field.directives &&\n field.directives.some((d) => d.name.value === \"export\")\n ) {\n return;\n }\n\n // Create and return a new SelectionSet with a __typename Field.\n return {\n ...node,\n selections: [...selections, TYPENAME_FIELD],\n };\n },\n },\n });\n },\n {\n added(field: FieldNode): boolean {\n return field === TYPENAME_FIELD;\n },\n }\n);\n\nconst connectionRemoveConfig = {\n test: (directive: DirectiveNode) => {\n const willRemove = directive.name.value === \"connection\";\n if (willRemove) {\n if (\n !directive.arguments ||\n !directive.arguments.some((arg) => arg.name.value === \"key\")\n ) {\n invariant.warn(\n \"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 }\n\n return willRemove;\n },\n};\n\nexport function removeConnectionDirectiveFromDocument(doc: DocumentNode) {\n return removeDirectivesFromDocument(\n [connectionRemoveConfig],\n checkDocument(doc)\n );\n}\n\nfunction hasDirectivesInSelectionSet(\n directives: GetDirectiveConfig[],\n selectionSet: SelectionSetNode | undefined,\n nestedCheck = true\n): boolean {\n return (\n !!selectionSet &&\n selectionSet.selections &&\n selectionSet.selections.some((selection) =>\n hasDirectivesInSelection(directives, selection, nestedCheck)\n )\n );\n}\n\nfunction hasDirectivesInSelection(\n directives: GetDirectiveConfig[],\n selection: SelectionNode,\n nestedCheck = true\n): boolean {\n if (!isField(selection)) {\n return true;\n }\n\n if (!selection.directives) {\n return false;\n }\n\n return (\n selection.directives.some(getDirectiveMatcher(directives)) ||\n (nestedCheck &&\n hasDirectivesInSelectionSet(\n directives,\n selection.selectionSet,\n nestedCheck\n ))\n );\n}\n\nfunction getArgumentMatcher(config: RemoveArgumentsConfig[]) {\n return function argumentMatcher(argument: ArgumentNode) {\n return config.some(\n (aConfig: RemoveArgumentsConfig) =>\n 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}\n\nexport function removeArgumentsFromDocument(\n config: RemoveArgumentsConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n const argMatcher = getArgumentMatcher(config);\n\n return nullIfDocIsEmpty(\n visit(doc, {\n OperationDefinition: {\n enter(node) {\n return {\n ...node,\n // Remove matching top level variables definitions.\n variableDefinitions:\n node.variableDefinitions ?\n node.variableDefinitions.filter(\n (varDef) =>\n !config.some(\n (arg) => arg.name === varDef.variable.name.value\n )\n )\n : [],\n };\n },\n },\n\n Field: {\n enter(node) {\n // If `remove` is set to true for an argument, and an argument match\n // is found for a field, remove the field as well.\n const shouldRemoveField = config.some(\n (argConfig) => argConfig.remove\n );\n\n if (shouldRemoveField) {\n let argMatchCount = 0;\n if (node.arguments) {\n node.arguments.forEach((arg) => {\n if (argMatcher(arg)) {\n argMatchCount += 1;\n }\n });\n }\n\n if (argMatchCount === 1) {\n return null;\n }\n }\n },\n },\n\n Argument: {\n enter(node) {\n // Remove all matching arguments.\n if (argMatcher(node)) {\n return null;\n }\n },\n },\n })\n );\n}\n\nexport function removeFragmentSpreadFromDocument(\n config: RemoveFragmentSpreadConfig[],\n doc: DocumentNode\n): DocumentNode | null {\n function enter(\n node: FragmentSpreadNode | FragmentDefinitionNode\n ): null | void {\n if (config.some((def) => def.name === node.name.value)) {\n return null;\n }\n }\n\n return nullIfDocIsEmpty(\n visit(doc, {\n FragmentSpread: { enter },\n FragmentDefinition: { enter },\n })\n );\n}\n\n// If the incoming document is a query, return it as is. Otherwise, build a\n// new document containing a query operation based on the selection set\n// of the previous main operation.\nexport function buildQueryFromSelectionSet(\n document: DocumentNode\n): DocumentNode {\n const definition = getMainDefinition(document);\n const definitionOperation = (definition).operation;\n\n if (definitionOperation === \"query\") {\n // Already a query, so return the existing document.\n return document;\n }\n\n // Build a new query using the selection set of the main operation.\n const modifiedDoc = visit(document, {\n OperationDefinition: {\n enter(node) {\n return {\n ...node,\n operation: \"query\",\n };\n },\n },\n });\n return modifiedDoc;\n}\n\n// Remove fields / selection sets that include an @client directive.\nexport function removeClientSetsFromDocument(\n document: DocumentNode\n): DocumentNode | null {\n checkDocument(document);\n\n let modifiedDoc = removeDirectivesFromDocument(\n [\n {\n test: (directive: DirectiveNode) => directive.name.value === \"client\",\n remove: true,\n },\n ],\n document\n );\n\n return modifiedDoc;\n}\n\nexport function addNonReactiveToNamedFragments(document: DocumentNode) {\n checkDocument(document);\n\n return visit(document, {\n FragmentSpread: (node) => {\n // Do not add `@nonreactive` if the fragment is marked with `@unmask`\n // since we want to react to changes in this fragment.\n if (\n node.directives?.some((directive) => directive.name.value === \"unmask\")\n ) {\n return;\n }\n\n return {\n ...node,\n directives: [\n ...(node.directives || []),\n {\n kind: Kind.DIRECTIVE,\n name: { kind: Kind.NAME, value: \"nonreactive\" },\n } satisfies DirectiveNode,\n ],\n };\n },\n });\n}\n","import type { Observer } from \"./Observable.js\";\n\nexport function iterateObserversSafely(\n observers: Set>,\n method: keyof Observer,\n argument?: A\n) {\n // In case observers is modified during iteration, we need to commit to the\n // original elements, which also provides an opportunity to filter them down\n // to just the observers with the given method.\n const observersWithMethod: Observer[] = [];\n observers.forEach((obs) => obs[method] && observersWithMethod.push(obs));\n observersWithMethod.forEach((obs) => (obs as any)[method](argument));\n}\n","import { Observable } from \"./Observable.js\";\nimport { canUseSymbol } from \"../common/canUse.js\";\n\n// Generic implementations of Observable.prototype methods like map and\n// filter need to know how to create a new Observable from an Observable\n// subclass (like Concast or ObservableQuery). Those methods assume\n// (perhaps unwisely?) that they can call the subtype's constructor with a\n// Subscriber function, even though the subclass constructor might expect\n// different parameters. Defining this static Symbol.species property on\n// the subclass is a hint to generic Observable code to use the default\n// constructor instead of trying to do `new Subclass(observer => ...)`.\nexport function fixObservableSubclass<\n S extends new (...args: any[]) => Observable,\n>(subclass: S): S {\n function set(key: symbol | string) {\n // Object.defineProperty is necessary because the Symbol.species\n // property is a getter by default in modern JS environments, so we\n // can't assign to it with a normal assignment expression.\n Object.defineProperty(subclass, key, { value: Observable });\n }\n if (canUseSymbol && Symbol.species) {\n set(Symbol.species);\n }\n // The \"@@species\" string is used as a fake Symbol.species value in some\n // polyfill systems (including the SymbolSpecies variable used by\n // zen-observable), so we should set it as well, to be safe.\n set(\"@@species\");\n return subclass;\n}\n","export const version = \"local\";\n"],"names":["Object","defineProperty","exports","value","operationType","operation","ellapsed","headerCss","parts","operationName","push","join","concat","_client","_formatMessage2","_interopRequireDefault","_logging2","obj","__esModule","default","_toConsumableArray","arr","Array","isArray","i","arr2","length","from","loggerLink","ApolloLink","forward","startTime","Date","getTime","map","result","query","definitions","group","groupCollapsed","apply","log","groupEnd","prefix","consoleLog","consoleGroup","bindToConsole","consoleMethod","polyfill","bind","console","logging","undefined","arguments","_console","_len","args","_key","error","_console2","_len2","_key2","slice","extendStatics","d","b","setPrototypeOf","__proto__","p","hasOwnProperty","assign","t","s","n","prototype","call","this","Map","WeakMap","navigator","product","create","message","link","__","constructor","tslib_1.__extends","Error","isTerminating","request","createOperation","starting","context","enumerable","next","variables","JSON","stringify","getKey","passthrough","op","toLink","handler","empty","links","reduce","x","y","split","test","left","right","leftLink","rightLink","first","second","firstLink","nextLink","execute","transformedOperation","extensions","filter","definition","kind","name","transformOperation","OPERATION_FIELDS","keys","key","indexOf","validateOperation","rawAsap","freeTasks","pendingErrors","requestErrorThrow","makeRequestCallFromTimer","shift","asap","task","rawTask","pop","RawTask","module","onerror","queue","requestFlush","index","flush","currentIndex","scan","newLength","toggle","observer","node","scope","g","self","BrowserMutationObserver","MutationObserver","WebKitMutationObserver","callback","timeoutHandle","setTimeout","handleTimer","intervalHandle","setInterval","clearTimeout","clearInterval","document","createTextNode","observe","characterData","data","assumeImmutableResults","getFragmentDoc","max","cache","lookupFragment","fragmentName","batch","options","updateResult","optimisticId","optimistic","performTransaction","update","recordOptimisticTransaction","transaction","transformDocument","transformForLink","identify","object","gc","modify","readQuery","read","rootId","id","watchFragment","fragment","otherOptions","dataMasking","Symbol","for","actualFragmentName","latestDiff","diffOptions","returnPartialData","watch","immediate","diff","complete","missing","readFragment","writeQuery","write","dataId","writeFragment","updateQuery","updateFragment","ApolloCache","getMemoryInternals","path","MissingFieldError","hasOwn","isNullish","defaultDataIdFromObject","__typename","_id","keyObject","defaultConfig","dataIdFromObject","addTypename","resultCaching","canonizeResults","normalizeConfig","config","shouldCanonizeResults","getTypenameFromStoreObject","store","objectOrReference","get","__ref","TypeOrFieldNameRegExp","fieldNameFromStoreName","storeFieldName","match","selectionSetMatchesResult","selectionSet","every","item","selections","field","storeValueIsStoreObject","makeProcessedFieldsMerger","extractFragmentContext","fragments","fragmentMap","def","lookup","DELETE","delModifier","INVALIDATE","policies","rootIds","refs","getFieldValue","maybeDeepFreeze","canRead","objOrRef","has","toReference","objOrIdOrRef","mergeIntoStore","ref","merge","toObject","fieldName","depend","storeObject","rootTypenamesById","Layer","parent","dependOnExistence","older","newer","existing","incoming","merged","storeObjectReconciler","caching","__exists","forEach","hasKeyArgs","dirty","fields","isReference","readField","fieldNameOrOptions","fieldValue","newValue","storage","getStorage","checkReference","evicted","extraRootIds","count","ids","layerId","known","canUse","WeakSet","Set","pool","passes","keysByJSON","admit","isKnown","pass","copy","getPrototypeOf","shallowCopy","set","original","array","lookupArray","add","freeze","sortedKeys","json","sorted","sort","execSelectionSetKeyArgs","knownResults","compact","canon","ObjectCanon","executeSelectionSet","peekArgs","other","peek","maybeDependOnExistenceOfEntity","enclosingRef","execSelectionSetImpl","resultCacheMaxSize","keyArgs","makeCacheKey","supportsResultCaching","varString","executeSubSelectedArray","execSubSelectedArrayImpl","resetCanon","diffQueryAgainstStore","rootRef","execResult","canonicalStringify","firstMissing","isFresh","latest","typename","objectsToMerge","missingMerger","handleMissing","resultName","rootIdsByTypename","workSet","selection","fragmentMatches","finalResult","mergeDeep","frozen","childResult","assertSelectionSetForIdValue","tree","_","specifierInfoCache","lookupSpecifierInfo","spec","cacheKey","keyFieldsFnFromSpecifier","specifier","info","keyFieldsFn","firstChar","directiveArgs","toMerge","argsFromFieldSpecifier","nullKeyFieldsFn","simpleKeyArgsFn","_args","mergeTrueFn","mergeObjects","mergeFalseFn","typePolicies","toBeAdded","supertypeMap","fuzzySubtypes","usingPossibleTypes","setRootTypename","possibleTypes","addPossibleTypes","addTypePolicies","partialContext","ROOT_QUERY","normalizeReadFieldOptions","policy","getTypePolicy","keyFn","specifierOrId","String","queryType","mutationType","subscriptionType","updateTypePolicy","keyFields","setMerge","getFieldPolicy","keyArgsFnFromSpecifier","which","toUpperCase","old","supertype","getSupertypeSet","subtype","RegExp","size","regExp","fuzzy","fuzzySupertypes","rest","inbox","splice","createIfMissing","fieldPolicies","supertypeSet","typeCondition","typenameSupertypeSet","needToCheckFuzzySubtypes","checkingFuzzySubtypes","fuzzyString","getStoreFieldName","fieldSpec","specifierOrString","readOptions","makeFieldFunctionOptions","getReadFunction","getMergeFunction","parentTypename","childTypename","runMergeFunction","makeMergeObjectsFunction","overwrite","readFieldArgs","argc","eType","iType","getContextFlavor","clientOnly","deferred","flavored","flavors","reader","writeToStore","operationDefinition","merger","written","incomingById","processSelectionSet","mergeTree","fieldNodeSet","entityRef","applied","applyMerges","childTree","Boolean","existingRef","incomingObj","getChild","child","parentType","typeDotName","warnings","childTypenames","includes","warnAboutDataLoss","retain","flattenFields","resultFieldKey","getChildMergeTree","incomingValue","processFieldValue","maybeRecycleChildMergeTree","e","dataRef","sets","mergeMergeTrees","mergeTreeIsEmpty","fieldMap","limitingTrie","flatten","inheritedContext","visitedNode","visited","directives","dir","if","getStorageArgs","eVal","iVal","aVal","emptyMergeTreePool","needToMergeMaps","leftTree","delete","watches","addTypenameTransform","DocumentTransform","makeVar","txCount","Policies","init","rootStore","EntityStore","Root","optimisticData","stump","resetResultCache","resetResultIdentities","previousReader","storeReader","storeWriter","StoreWriter","StoreReader","maybeBroadcastWatch","c","broadcastWatch","resetCaching","restore","replace","extract","broadcast","broadcastWatches","forget","print","resetCache","resetCaches","release","evict","reset","discardWatches","clear","Promise","resolve","removeOptimistic","idToRemove","newOptimisticData","removeLayer","onWatchUpdated","perform","layer","alreadyDirty","addLayer","addTypenameToDocument","addFragmentsToDocument","transform","lastDiff","fromOptimisticTransaction","InMemoryCache","cacheSlot","cacheInfoMap","getCacheInfo","vars","dep","forgetCache","rv","recallCache","attachCache","caches","listeners","oldListeners","listener","getValue","attach","onNextChange","asyncMap","observable","mapFn","catchFn","promiseQueue","then","makeCallback","examiner","arg","both","closed","sub","subscribe","unsubscribe","graphQLResultHasError","errors","getGraphQLErrorsFromResult","graphQLErrors","incremental","incrementalResult","isPromiseLike","sources","addObserver","removeObserver","observers","promise","reject","handlers","notify","obs","nextResultListeners","cancel","reason","catch","iterable","start","deliverLastMessage","nextOrError","method","beforeNext","called","Concast","destructiveMethodCounts","wrapDestructiveCacheMethod","methodName","cancelNotifyTimeout","queryManager","queryId","generateQueryId","lastRequestId","stopped","observableQuery","networkStatus","networkError","setObservableQuery","resetDiff","getDiff","getDiffOptions","updateWatch","oq","fetchPolicy","updateLastDiff","setDiff","oldDiff","getLastError","notifyTimeout","oqListener","shouldNotify","stop","QueryInfo","stopPolling","watchOptions","watcher","lastWatch","resetLastWrite","lastWrite","shouldWrite","dmCount","markResult","cacheWriteBehavior","mergedData","hasNext","shouldWriteResult","errorPolicy","markReady","markError","ignoreErrors","writeWithErrors","IGNORE","clientAwareness","queries","fetchCancelFns","transformCache","queryIdCounter","requestIdCounter","mutationIdCounter","inFlightLinkObservables","noCacheWarningsByQueryId","defaultDocumentTransform","defaultOptions","queryDeduplication","localState","ssrMode","documentTransform","defaultContext","onBroadcast","mutationStore","_info","stopQueryNoBroadcast","cancelPendingFetches","mutate","mutation","optimisticResponse","updateQueries","refetchQueries","awaitRefetchQueries","updateWithProxyFn","onQueryUpdated","keepRootFields","mutationId","generateMutationId","hasClientExports","getDocumentInfo","getVariables","addExportedVariables","mutationStoreValue","loading","isOptimistic","markMutationOptimistic","broadcastQueries","getObservableFromLink","storeResult","markMutationResult","maskOperation","err","cacheWrites","skipCache","asQuery","queryName","updater","currentQueryResult","nextQueryResult","mutationResult","queryVariables","updateCache","isFinalResult","include","all","fetchQuery","fetchConcastWithInfo","concast","getQueryStore","resetErrors","queryInfo","cacheEntry","hasForcedResolvers","shouldForceResolvers","hasNonreactiveDirective","nonReactiveQuery","clientQuery","serverQuery","remove","defaultVars","watchQuery","notifyOnNetworkStatusChange","ObservableQuery","desc","legacyQueryOptions","hasProtocolErrors","aqr","includedQueriesById","maskDefinition","mutableTargets","knownChanged","fromData","fromLink","client","resolvers","fragmentMatcher","selectionsToResolveCache","addResolvers","setFragmentMatcher","resolverGroup","setResolvers","getResolvers","runResolvers","remoteResult","onlyRunForcedResolvers","resolveDocument","localResult","getFragmentMatcher","prepareContext","getCacheKey","buildRootValueFromCache","exportedVariables","forceResolvers","Directive","enter","some","rootValue","mainDefinition","selectionsToResolve","collectSelectionsToResolve","definitionOperation","defaultOperationType","charAt","execContext","resolveSelectionSet","isClientFieldDescendant","resultsToMerge","resolveField","fieldResult","fragmentResult","aliasedFieldName","aliasUsed","defaultResult","resultPromise","resolverType","resolverMap","directive","isClientField","resolveSubSelectedArray","isSingleASTNode","collectByDefinition","definitionNode","___","ancestors","FragmentSpread","spread","fragmentSelections","hasSuggestedDevtools","resetStoreCallbacks","clearStoreCallbacks","devtoolsConfig","connectToDevTools","subObserver","_subscription","_observer","defaultSubscriptionObserverErrorCallback","last","maskResult","reobserve","tearDownQuery","subscriptions","waitForOwnResult","skipCacheDataFor","isTornDown","subscribeToMore","defaultFetchPolicy","initialFetchPolicy","opDef","lastQuery","removeQuery","subscription","getCurrentFullResult","saveAsLastResult","lastResult","getLastResult","partial","partialRefetch","logMissingFieldErrors","updateLastResult","getCurrentResult","isDifferentFromLastResult","newResult","documentInfo","equalByQuery","getLast","variablesMustMatch","resetLastResults","resetQueryStoreErrors","refetch","reobserveOptions","pollInterval","queryDef","variableDefinitions","v","variable","newOptions","pollingInfo","mergedOptions","nextFetchPolicy","aData","aRest","bData","bRest","equalBySelectionSet","aResult","bResult","seenSelections","selectionHasNonreactiveDirective","resultKey","aResultChild","bResultChild","childSelectionSet","aChildIsArray","bChildIsArray","directiveIsNonreactive","NetworkStatus","isNetworkRequestInFlight","isNetworkRequestSettled","PROTOCOL_ERRORS_SYMBOL","graphQLResultHasProtocolErrors","isApolloError","protocolErrors","clientErrors","errorMessage","extraInfo","cause","find","ApolloError","Cache","createSignalIfSupported","AbortController","controller","signal","toPromise","completed","fromPromise","EAGER_METHODS","useLazyQuery","execOptionsRef","optionsRef","queryRef","mergeOptions","current","queryHookOptions","skip","useQuery","obsQueryFields","useQueryResult","resultData","onQueryExecuted","forceUpdateState","tick","eagerMethods","executeOptions","currentQuery","watchQueryOptions","reobserveAsConcast","previousData","executeQuery","queryResult","executeRef","useIsomorphicLayoutEffect","stableExecute","useReactiveVar","useSyncExternalStore","onNext","useFragment","wrapHook","useFragment_","useApolloClient","stableOptions","useDeepMemo","diffToResult","maskFragment","getSnapshot","forceUpdate","lastTimeout","createFulfilledPromise","status","wrapPromiseWithState","isStatefulPromise","pendingPromise","fulfilledPromise","rejectedPromise","__use","statefulPromise","QUERY_REFERENCE_SYMBOL","PROMISE_SYMBOL","wrapQueryRef","internalQueryRef","getWrappedPromise","assertWrappedQueryRef","unwrapQueryRef","updateWrappedQueryRef","OBSERVED_CHANGED_OPTIONS","references","softReferences","handleNext","handleError","dispose","onDispose","setResult","subscribeToQuery","startDisposeTimer","autoDisposeTimeoutId","autoDisposeTimeoutMs","reinitialize","originalFetchPolicy","avoidNetworkRequests","silentSetOptions","disposed","softRetain","didChangeOptions","option","applyOptions","currentFetchPolicy","currentCanonizeResults","initiateFetch","listen","fetchMore","deliver","resubscribeAfterError","returnedPromise","createPendingPromise","watchFragmentOptions","subscribeToFragment","queryRefs","fragmentRefs","getQueryRef","createObservable","InternalQueryReference","getFragmentRef","FragmentReference","suspenseCacheSymbol","getSuspenseCache","SuspenseCache","react","suspense","skipToken","useSuspenseQuery","useSuspenseQuery_","suspenseCache","useWatchQueryOptions","queryKey","setPromise","removeListener","skipResult","toApolloError","validateOptions","supportedFetchPolicies","validateFetchPolicy","validatePartialDataReturn","useBackgroundQuery","useBackgroundQuery_","didFetchResult","wrappedQueryRef","setWrappedQueryRef","Ctx","NULL_PLACEHOLDER","useSuspenseFragment","useSuspenseFragment_","fragmentRef","noop","useLoadableQuery","setQueryRef","calledDuringRender","orig","loadQuery","useQueryRefHandlers","unwrapped","clientOrObsQuery","useQueryRefHandlers_","previousQueryRef","setPreviousQueryRef","useReadQuery","useReadQuery_","getPromise","createQueryPreloader","_createQueryPreloader","batchDebounce","batchInterval","batchMax","batchHandler","batchKey","batchesByKey","scheduledBatchTimerByKey","enqueueRequest","requestCopy","subscribers","isFirstEnqueuedRequest","isFirstSubscriber","scheduleQueueConsumption","consumeQueue","operations","forwards","observables","nexts","completes","batchedObservable","onError","rejecters","results","fetchParams","batcher","OperationBatcher","backupFetch","fetch","uri","preferredFetch","includeExtensions","preserveHeaderCase","includeUnusedVariables","requestOptions","checkFetcher","linkConfig","http","fetchOptions","credentials","headers","getContext","contextConfig","selectURI","BatchLink","chosenURI","clientAwarenessHeaders","version","fromError","optsAndBody","selectHttpOptionsAndBody","body","filterOperationVariables","loadedBody","serializeFetchParameter","parseError","response","setContext","parseAndCheckHttpResponse","abort","ret","setOnError","fn","errorHandler","retriedSub","retriedResult","fetcher","createHttpLink","linkOptions","useGETForQueries","contextHeaders","transformedQuery","isSubscription","hasDefer","acceptHeader","accept","newURI","currentFetch","observerNext","ctype","nodeStreamIterator","stream","cleanup","done","waiting","onData","chunk","shiftedArr","pair","onEnd","on","iterator","asyncIterator","readerIterator","responseIterator","isAsyncIterableIterator","getReader","isReadableStream","isStreamableBlob","arrayBuffer","isBlob","resolved","promiseIterator","pipe","isNodeReadableStream","readMultipartBody","nextValue","TextDecoder","decoder","contentType","delimiter","boundaryVal","substring","trim","boundary","buffer","running","decode","searchFrom","bi","parseHeaders","toLowerCase","parseJsonBody","payload","headerText","headersInit","line","bodyText","throwServerError","parse","getResult","statusCode","text","rewriteURIForGET","queryParams","addQueryParam","encodeURIComponent","serializedVariables","serializedExtensions","preFragment","fragmentStart","substr","queryParamsPrefix","fallbackHttpConfig","includeQuery","defaultPrinter","ast","printer","fallbackConfig","configs","unshift","selectHttpOptionsAndBodyInternal","headerData","originalName","normalizedHeaders","removeDuplicateHeaders","fallbackURI","contextURI","label","serialized","delayFor","retryIf","retryCount","currentSubscription","scheduleRetry","try","timerId","delay","attempts","delayOptions","initial","jitter","Infinity","baseDelay","Math","min","random","buildDelayFunction","retryOptions","buildRetryFunction","retryable","RetryableOperation","unusedNames","Variable","errorValue","masked","maskSelectionSet","isFrozen","migration","memo","mutableTarget","getMutableTarget","entries","keyName","getOwnPropertyDescriptor","getAccessorWarningDescriptor","mode","configurable","MapImpl","SetImpl","disableWarningsSlot","issuedWarning","warnOnImproperCacheImplementation","defaultMakeData","Trie","weakness","makeData","getChildTrie","peekArray","len","mapFor","removeArray","head","weak","strong","isObjRef","genericMessage","proto","framesToPop","InvariantError","invariant","condition","verbosityLevels","verbosityLevel","wrapConsoleMethod","setVerbosity","level","debug","warn","ApolloConsumer","props","ApolloContext","Consumer","contextKey","getApolloContext","ApolloProvider","children","parentContext","memoFn","deps","wrapperSymbol","hookName","useHook","wrappers","wrapper","override","useMutation","isMounted","baseOptions","ignoreResults","clientOptions","onCompleted","lastWatchOptions","useQuery_","useQueryInternals","renderPromises","isSyncSSR","disableNetworkFetches","ssrAllowed","ssr","makeWatchQueryOptions","createMakeWatchQueryOptions","createInternalState","previous","getSSRObservable","getObsQueryOptions","internalState","updateInternalState","newInternalState","useInternalState","useResubscribeIfNecessary","startPolling","bindObservableMethods","registerSSRObservable","addObservableQueryPromise","useRegisterSSRObservable","callbacks","callbackRef","resultOverride","skipStandbyResult","ssrDisabledResult","currentResultOverride","toQueryResult","handleStoreChange","previousResult","useObservableSubscriptionResult","getDefaultFetchPolicy","globalDefaults","nextResult","unsafeHandlePartialRefetch","previousNetworkStatus","handleErrorOrCompleted","queryHookDefaultOptions","clientDefaultOptions","resultWithoutPartial","useSubscription","hasIssuedDeprecationWarningRef","onSubscriptionData","didWarnUncachedGetSnapshot","getServerSnapshot","inst","checkIfSnapshotChanged","DocumentType","type","Query","Mutation","Subscription","parser","cached","scheduledCleanup","schedule","clean","AutoCleanedWeakCache","AutoCleanedStrongCache","globalCaches","registerGlobalCache","getSize","getApolloClientMemoryInternals","limits","fromEntries","k","sizes","linkInfo","documentTransforms","transformInfo","getInMemoryCacheMemoryInternals","_getApolloCacheMemoryInternals","addTypenameDocumentTransform","inMemoryCache","getWrapperInformation","fragmentRegistry","findFragmentSpreads","getApolloCacheMemoryInternals","fragmentQueryDocuments","f","isWrapper","isDefined","recurseTransformInfo","cacheSizeSymbol","cacheSizes","isNonEmptyArray","isReactNative","canUseWeakMap","global","HermesInternal","canUseWeakSet","canUseSymbol","canUseAsyncIteratorSymbol","canUseDOM","window","createElement","usingJSDOM","userAgent","canUseLayoutEffect","sortingMap","stableObjectReplacer","everyKeyInOrder","unsortedKey","sortedKey","toString","cloneDeep","cloneDeepHelper","val","seen","objects","isExecutionPatchIncrementalResult","isExecutionPatchResult","isExecutionPatchInitialResult","isApolloPayloadResult","mergeIncrementalData","prevResult","isNaN","prefixCounts","makeUniqueId","deepFreeze","TypeError","shallowFreeze","getOwnPropertyNames","mergeDeepArray","target","DeepMerger","defaultReconciler","source","property","reconciler","isObject","pastCopies","sourceKey","targetValue","shallowCopyForMerge","defaults","isNonNullObject","stringifyForDisplay","space","undefId","globalThis","__DEV__","wrap","arg0","getHandledErrorMsg","getFallbackErrorMsg","newInvariantError","optionalParams","ApolloErrorMessageHandler","messageArgs","maybe","thunk","identity","resultCache","predicate","performWork","cacheKeys","transformedDocument","otherTransform","shouldInclude","isInclusionDirective","directiveArguments","directiveName","ifArgument","ifValue","getInclusionDirectives","evaledValue","hasDirectives","names","root","nameSet","uniqueCount","getFragmentMaskMode","modeArg","getFragmentQueryDocument","checkDocument","doc","getOperationDefinition","getOperationName","getFragmentDefinitions","getQueryDefinition","getFragmentDefinition","fragmentDef","getMainDefinition","queryDoc","fragmentDefinition","getDefaultValues","defaultValues","defs","defaultValue","printCache","makeReference","isDocumentNode","valueToObjectRepresentation","argObj","isIntValue","isFloatValue","Number","isBooleanValue","isStringValue","isObjectValue","isVariable","variableValue","isListValue","values","listValue","nestedArgArrayObj","isEnumValue","isNullValue","directivesObj","filterKeys","TYPENAME_FIELD","isEmpty","nullIfDocIsEmpty","getDirectiveMatcher","tests","testConfig","makeInUseGetterFunction","defaultKey","inUse","fragmentSpreads","removeDirectivesFromDocument","getInUseByOperationName","getInUseByFragmentName","getInUse","ancestor","operationCount","directiveMatcher","shouldRemoveField","nodeDirectives","originalFragmentDefsByPath","firstVisitMadeChanges","fieldOrInlineFragmentVisitor","docWithoutDirectiveSubtrees","Field","InlineFragment","VariableDefinition","_parent","_path","FragmentDefinition","leave","removed","populateTransitiveVars","transitiveVars","childFragmentName","varName","allFragmentNamesUsed","enterVisitor","OperationDefinition","varDef","SelectionSet","lastIndexOf","added","iterateObserversSafely","argument","observersWithMethod","fixObservableSubclass","subclass","species"],"sourceRoot":""}