@adaptic/lumic-utils 1.0.5 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/apollo-client.client-DE7JUXjy.js +3693 -0
  2. package/dist/apollo-client.client-DE7JUXjy.js.map +1 -0
  3. package/dist/apollo-client.client-DlG4HsFm.js +3704 -0
  4. package/dist/apollo-client.client-DlG4HsFm.js.map +1 -0
  5. package/dist/apollo-client.server-D1QJea5_.js +16319 -0
  6. package/dist/apollo-client.server-D1QJea5_.js.map +1 -0
  7. package/dist/apollo-client.server-uqalq3yp.js +16321 -0
  8. package/dist/apollo-client.server-uqalq3yp.js.map +1 -0
  9. package/dist/index-Bd84zcTQ.js +74944 -0
  10. package/dist/index-Bd84zcTQ.js.map +1 -0
  11. package/dist/index-CZKOqrJ4.js +75137 -0
  12. package/dist/index-CZKOqrJ4.js.map +1 -0
  13. package/dist/index-CsKfs4nG.js +12108 -0
  14. package/dist/index-CsKfs4nG.js.map +1 -0
  15. package/dist/{index-CcXQeJz8.js → index-Cstek604.js} +182 -22
  16. package/dist/index-Cstek604.js.map +1 -0
  17. package/dist/{index-CcgbRft2.js → index-DZZCd-1T.js} +182 -22
  18. package/dist/index-DZZCd-1T.js.map +1 -0
  19. package/dist/index-aP9ow8_W.js +12271 -0
  20. package/dist/index-aP9ow8_W.js.map +1 -0
  21. package/dist/index.cjs +122 -11417
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.mjs +39 -11399
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/test.cjs +24 -7
  26. package/dist/test.cjs.map +1 -1
  27. package/dist/test.mjs +24 -7
  28. package/dist/test.mjs.map +1 -1
  29. package/dist/types/aws-types.ts +1 -1
  30. package/dist/types/config/__tests__/secrets.test.d.ts +1 -0
  31. package/dist/types/config/secrets.d.ts +186 -0
  32. package/dist/types/errors/__tests__/errors.test.d.ts +1 -0
  33. package/dist/types/errors/index.d.ts +77 -0
  34. package/dist/types/functions/__tests__/aws-lambda.test.d.ts +1 -0
  35. package/dist/types/functions/__tests__/aws-s3-utils.test.d.ts +1 -0
  36. package/dist/types/functions/__tests__/json-llm-tools.test.d.ts +1 -0
  37. package/dist/types/functions/__tests__/json-tools.test.d.ts +1 -0
  38. package/dist/types/functions/__tests__/slack-utils.test.d.ts +1 -0
  39. package/dist/types/functions/aws-lambda.d.ts +1 -1
  40. package/dist/types/functions/aws-s3-utils.d.ts +2 -2
  41. package/dist/types/functions/google-sheets.d.ts +4 -4
  42. package/dist/types/functions/json-llm-tools.d.ts +25 -3
  43. package/dist/types/functions/llm-call.d.ts +2 -2
  44. package/dist/types/functions/llm-deepseek.d.ts +1 -1
  45. package/dist/types/functions/llm-openai.d.ts +3 -2
  46. package/dist/types/functions/llm-utils.d.ts +24 -1
  47. package/dist/types/functions/slack-utils.d.ts +3 -4
  48. package/dist/types/functions/utils.d.ts +2 -14
  49. package/dist/types/functions/zip-utils.d.ts +12 -10
  50. package/dist/types/google-types.ts +6 -3
  51. package/dist/types/index.d.ts +30 -0
  52. package/dist/types/index.ts +1 -1
  53. package/dist/types/openai-types.ts +165 -6
  54. package/dist/types/schemas/aws-schemas.d.ts +210 -0
  55. package/dist/types/schemas/google-sheets-schemas.d.ts +32 -0
  56. package/dist/types/schemas/index.d.ts +17 -0
  57. package/dist/types/schemas/openai-schemas.d.ts +834 -0
  58. package/dist/types/schemas/perplexity-schemas.d.ts +338 -0
  59. package/dist/types/schemas/validation-helpers.d.ts +33 -0
  60. package/dist/types/types/aws-types.d.ts +1 -1
  61. package/dist/types/types/google-types.d.ts +5 -3
  62. package/dist/types/types/index.d.ts +1 -1
  63. package/dist/types/types/openai-types.d.ts +149 -3
  64. package/dist/types/utils/__tests__/circuit-breaker.test.d.ts +1 -0
  65. package/dist/types/utils/__tests__/correlation.test.d.ts +1 -0
  66. package/dist/types/utils/__tests__/input-validator.test.d.ts +1 -0
  67. package/dist/types/utils/__tests__/llm-cost-tracker.test.d.ts +1 -0
  68. package/dist/types/utils/__tests__/logger.test.d.ts +1 -0
  69. package/dist/types/utils/__tests__/metrics.test.d.ts +1 -0
  70. package/dist/types/utils/__tests__/retry.test.d.ts +1 -0
  71. package/dist/types/utils/__tests__/sanitizer.test.d.ts +1 -0
  72. package/dist/types/utils/__tests__/timeouts.test.d.ts +1 -0
  73. package/dist/types/utils/aws-initialise.d.ts +6 -1
  74. package/dist/types/utils/circuit-breaker.d.ts +99 -0
  75. package/dist/types/utils/correlation.d.ts +43 -0
  76. package/dist/types/utils/health-check.d.ts +50 -0
  77. package/dist/types/utils/input-validator.d.ts +51 -0
  78. package/dist/types/utils/llm-cost-tracker.d.ts +174 -0
  79. package/dist/types/utils/logger.d.ts +8 -0
  80. package/dist/types/utils/metrics.d.ts +61 -0
  81. package/dist/types/utils/rate-limiter.d.ts +85 -0
  82. package/dist/types/utils/retry.d.ts +58 -0
  83. package/dist/types/utils/sanitizer.d.ts +30 -0
  84. package/dist/types/utils/timeouts.d.ts +44 -0
  85. package/package.json +17 -4
  86. package/dist/index-CcXQeJz8.js.map +0 -1
  87. package/dist/index-CcgbRft2.js.map +0 -1
@@ -0,0 +1,3704 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index-aP9ow8_W.js');
4
+ var index$1 = require('./index-CZKOqrJ4.js');
5
+ require('openai');
6
+ require('zod');
7
+ require('@aws-sdk/client-s3');
8
+ require('@aws-sdk/client-lambda');
9
+ require('axios');
10
+ require('fs');
11
+ require('path');
12
+ require('os');
13
+ require('adm-zip');
14
+ require('stream');
15
+ require('fs/promises');
16
+ require('crypto');
17
+ require('stream/promises');
18
+ require('node:path');
19
+ require('node:fs');
20
+ require('node:fs/promises');
21
+ require('graphql-fields');
22
+ require('date-fns');
23
+ require('date-fns-tz');
24
+ require('ms');
25
+ require('events');
26
+ require('https');
27
+ require('http');
28
+ require('net');
29
+ require('tls');
30
+ require('url');
31
+ require('zlib');
32
+ require('buffer');
33
+ require('readline');
34
+ require('assert');
35
+ require('tty');
36
+ require('util');
37
+ require('pdfkit');
38
+ require('marked');
39
+ require('google-auth-library');
40
+ require('http2');
41
+ require('process');
42
+ require('node:async_hooks');
43
+
44
+ /**
45
+ * The current status of a query’s execution in our system.
46
+ */
47
+ var NetworkStatus;
48
+ (function (NetworkStatus) {
49
+ /**
50
+ * The query has never been run before and the query is now currently running. A query will still
51
+ * have this network status even if a partial data result was returned from the cache, but a
52
+ * query was dispatched anyway.
53
+ */
54
+ NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
55
+ /**
56
+ * If `setVariables` was called and a query was fired because of that then the network status
57
+ * will be `setVariables` until the result of that query comes back.
58
+ */
59
+ NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
60
+ /**
61
+ * Indicates that `fetchMore` was called on this query and that the query created is currently in
62
+ * flight.
63
+ */
64
+ NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
65
+ /**
66
+ * Similar to the `setVariables` network status. It means that `refetch` was called on a query
67
+ * and the refetch request is currently in flight.
68
+ */
69
+ NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
70
+ /**
71
+ * Indicates that a polling query is currently in flight. So for example if you are polling a
72
+ * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever
73
+ * a poll request has been sent but not resolved.
74
+ */
75
+ NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
76
+ /**
77
+ * No request is in flight for this query, and no errors happened. Everything is OK.
78
+ */
79
+ NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
80
+ /**
81
+ * No request is in flight for this query, but one or more errors were detected.
82
+ */
83
+ NetworkStatus[NetworkStatus["error"] = 8] = "error";
84
+ })(NetworkStatus || (NetworkStatus = {}));
85
+ /**
86
+ * Returns true if there is currently a network request in flight according to a given network
87
+ * status.
88
+ */
89
+ function isNetworkRequestInFlight(networkStatus) {
90
+ return networkStatus ? networkStatus < 7 : false;
91
+ }
92
+
93
+ var assign = Object.assign, hasOwnProperty$1 = Object.hasOwnProperty;
94
+ var ObservableQuery = /** @class */ (function (_super) {
95
+ index.__extends(ObservableQuery, _super);
96
+ function ObservableQuery(_a) {
97
+ var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
98
+ var _this = this;
99
+ var startedInactive = ObservableQuery.inactiveOnCreation.getValue();
100
+ _this = _super.call(this, function (observer) {
101
+ _this._getOrCreateQuery();
102
+ // Zen Observable has its own error function, so in order to log correctly
103
+ // we need to provide a custom error callback.
104
+ try {
105
+ var subObserver = observer._subscription._observer;
106
+ if (subObserver && !subObserver.error) {
107
+ subObserver.error = defaultSubscriptionObserverErrorCallback;
108
+ }
109
+ }
110
+ catch (_a) { }
111
+ var first = !_this.observers.size;
112
+ _this.observers.add(observer);
113
+ // Deliver most recent error or result.
114
+ var last = _this.last;
115
+ if (last && last.error) {
116
+ observer.error && observer.error(last.error);
117
+ }
118
+ else if (last && last.result) {
119
+ observer.next && observer.next(_this.maskResult(last.result));
120
+ }
121
+ // Initiate observation of this query if it hasn't been reported to
122
+ // the QueryManager yet.
123
+ if (first) {
124
+ // Blindly catching here prevents unhandled promise rejections,
125
+ // and is safe because the ObservableQuery handles this error with
126
+ // this.observer.error, so we're not just swallowing the error by
127
+ // ignoring it here.
128
+ _this.reobserve().catch(function () { });
129
+ }
130
+ return function () {
131
+ if (_this.observers.delete(observer) && !_this.observers.size) {
132
+ _this.tearDownQuery();
133
+ }
134
+ };
135
+ }) || this;
136
+ _this.observers = new Set();
137
+ _this.subscriptions = new Set();
138
+ _this.dirty = false;
139
+ _this._getOrCreateQuery = function () {
140
+ if (startedInactive) {
141
+ queryManager["queries"].set(_this.queryId, queryInfo);
142
+ startedInactive = false;
143
+ }
144
+ return _this.queryManager.getOrCreateQuery(_this.queryId);
145
+ };
146
+ // related classes
147
+ _this.queryInfo = queryInfo;
148
+ _this.queryManager = queryManager;
149
+ // active state
150
+ _this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);
151
+ _this.isTornDown = false;
152
+ _this.subscribeToMore = _this.subscribeToMore.bind(_this);
153
+ _this.maskResult = _this.maskResult.bind(_this);
154
+ var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
155
+ var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e,
156
+ // Make sure we don't store "standby" as the initialFetchPolicy.
157
+ _f = options.initialFetchPolicy,
158
+ // Make sure we don't store "standby" as the initialFetchPolicy.
159
+ initialFetchPolicy = _f === void 0 ? fetchPolicy === "standby" ? defaultFetchPolicy : (fetchPolicy) : _f;
160
+ _this.options = index.__assign(index.__assign({}, options), {
161
+ // Remember the initial options.fetchPolicy so we can revert back to this
162
+ // policy when variables change. This information can also be specified
163
+ // (or overridden) by providing options.initialFetchPolicy explicitly.
164
+ initialFetchPolicy: initialFetchPolicy,
165
+ // This ensures this.options.fetchPolicy always has a string value, in
166
+ // case options.fetchPolicy was not provided.
167
+ fetchPolicy: fetchPolicy });
168
+ _this.queryId = queryInfo.queryId || queryManager.generateQueryId();
169
+ var opDef = index.getOperationDefinition(_this.query);
170
+ _this.queryName = opDef && opDef.name && opDef.name.value;
171
+ return _this;
172
+ }
173
+ Object.defineProperty(ObservableQuery.prototype, "query", {
174
+ // The `query` computed property will always reflect the document transformed
175
+ // by the last run query. `this.options.query` will always reflect the raw
176
+ // untransformed query to ensure document transforms with runtime conditionals
177
+ // are run on the original document.
178
+ get: function () {
179
+ return this.lastQuery || this.options.query;
180
+ },
181
+ enumerable: false,
182
+ configurable: true
183
+ });
184
+ Object.defineProperty(ObservableQuery.prototype, "variables", {
185
+ // Computed shorthand for this.options.variables, preserved for
186
+ // backwards compatibility.
187
+ /**
188
+ * An object containing the variables that were provided for the query.
189
+ */
190
+ get: function () {
191
+ return this.options.variables;
192
+ },
193
+ enumerable: false,
194
+ configurable: true
195
+ });
196
+ /**
197
+ * @deprecated `result` will be removed in Apollo Client 4.0.
198
+ *
199
+ * **Recommended now**
200
+ *
201
+ * If you continue to need this functionality, subscribe to `ObservableQuery`
202
+ * to get the first value emitted from the observable, then immediately unsubscribe.
203
+ *
204
+ * **When upgrading**
205
+ *
206
+ * Use RxJS's [`firstResultFrom`](https://rxjs.dev/api/index/function/firstValueFrom) function to mimic this functionality.
207
+ *
208
+ * ```ts
209
+ * const result = await firstValueFrom(from(observableQuery));
210
+ * ```
211
+ */
212
+ ObservableQuery.prototype.result = function () {
213
+ var _this = this;
214
+ if (globalThis.__DEV__ !== false) {
215
+ index.warnDeprecated("observableQuery.result", function () {
216
+ globalThis.__DEV__ !== false && index.invariant.warn(23);
217
+ });
218
+ }
219
+ return new Promise(function (resolve, reject) {
220
+ // TODO: this code doesn’t actually make sense insofar as the observer
221
+ // will never exist in this.observers due how zen-observable wraps observables.
222
+ // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169
223
+ var observer = {
224
+ next: function (result) {
225
+ resolve(result);
226
+ // Stop the query within the QueryManager if we can before
227
+ // this function returns.
228
+ //
229
+ // We do this in order to prevent observers piling up within
230
+ // the QueryManager. Notice that we only fully unsubscribe
231
+ // from the subscription in a setTimeout(..., 0) call. This call can
232
+ // actually be handled by the browser at a much later time. If queries
233
+ // are fired in the meantime, observers that should have been removed
234
+ // from the QueryManager will continue to fire, causing an unnecessary
235
+ // performance hit.
236
+ _this.observers.delete(observer);
237
+ if (!_this.observers.size) {
238
+ _this.queryManager.removeQuery(_this.queryId);
239
+ }
240
+ setTimeout(function () {
241
+ subscription.unsubscribe();
242
+ }, 0);
243
+ },
244
+ error: reject,
245
+ };
246
+ var subscription = _this.subscribe(observer);
247
+ });
248
+ };
249
+ /** @internal */
250
+ ObservableQuery.prototype.resetDiff = function () {
251
+ this.queryInfo.resetDiff();
252
+ };
253
+ ObservableQuery.prototype.getCurrentFullResult = function (saveAsLastResult) {
254
+ var _this = this;
255
+ if (saveAsLastResult === void 0) { saveAsLastResult = true; }
256
+ // Use the last result as long as the variables match this.variables.
257
+ var lastResult = index.muteDeprecations("getLastResult", function () {
258
+ return _this.getLastResult(true);
259
+ });
260
+ var networkStatus = this.queryInfo.networkStatus ||
261
+ (lastResult && lastResult.networkStatus) ||
262
+ NetworkStatus.ready;
263
+ var result = index.__assign(index.__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
264
+ var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
265
+ if (
266
+ // These fetch policies should never deliver data from the cache, unless
267
+ // redelivering a previously delivered result.
268
+ skipCacheDataFor(fetchPolicy) ||
269
+ // If this.options.query has @client(always: true) fields, we cannot
270
+ // trust diff.result, since it was read from the cache without running
271
+ // local resolvers (and it's too late to run resolvers now, since we must
272
+ // return a result synchronously).
273
+ this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) ;
274
+ else if (this.waitForOwnResult) {
275
+ // This would usually be a part of `QueryInfo.getDiff()`.
276
+ // which we skip in the waitForOwnResult case since we are not
277
+ // interested in the diff.
278
+ this.queryInfo["updateWatch"]();
279
+ }
280
+ else {
281
+ var diff = this.queryInfo.getDiff();
282
+ if (diff.complete || this.options.returnPartialData) {
283
+ result.data = diff.result;
284
+ }
285
+ if (index.equal(result.data, {})) {
286
+ result.data = void 0;
287
+ }
288
+ if (diff.complete) {
289
+ // Similar to setting result.partial to false, but taking advantage of the
290
+ // falsiness of missing fields.
291
+ delete result.partial;
292
+ // If the diff is complete, and we're using a FetchPolicy that
293
+ // terminates after a complete cache read, we can assume the next result
294
+ // we receive will have NetworkStatus.ready and !loading.
295
+ if (diff.complete &&
296
+ result.networkStatus === NetworkStatus.loading &&
297
+ (fetchPolicy === "cache-first" || fetchPolicy === "cache-only")) {
298
+ result.networkStatus = NetworkStatus.ready;
299
+ result.loading = false;
300
+ }
301
+ }
302
+ else {
303
+ result.partial = true;
304
+ }
305
+ // We need to check for both both `error` and `errors` field because there
306
+ // are cases where sometimes `error` is set, but not `errors` and
307
+ // vice-versa. This will be updated in the next major version when
308
+ // `errors` is deprecated in favor of `error`.
309
+ if (result.networkStatus === NetworkStatus.ready &&
310
+ (result.error || result.errors)) {
311
+ result.networkStatus = NetworkStatus.error;
312
+ }
313
+ if (globalThis.__DEV__ !== false &&
314
+ !diff.complete &&
315
+ !this.options.partialRefetch &&
316
+ !result.loading &&
317
+ !result.data &&
318
+ !result.error) {
319
+ logMissingFieldErrors(diff.missing);
320
+ }
321
+ }
322
+ if (saveAsLastResult) {
323
+ this.updateLastResult(result);
324
+ }
325
+ return result;
326
+ };
327
+ ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
328
+ if (saveAsLastResult === void 0) { saveAsLastResult = true; }
329
+ return this.maskResult(this.getCurrentFullResult(saveAsLastResult));
330
+ };
331
+ // Compares newResult to the snapshot we took of this.lastResult when it was
332
+ // first received.
333
+ ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
334
+ if (!this.last) {
335
+ return true;
336
+ }
337
+ var documentInfo = this.queryManager.getDocumentInfo(this.query);
338
+ var dataMasking = this.queryManager.dataMasking;
339
+ var query = dataMasking ? documentInfo.nonReactiveQuery : this.query;
340
+ var resultIsDifferent = dataMasking || documentInfo.hasNonreactiveDirective ?
341
+ !index.equalByQuery(query, this.last.result, newResult, this.variables)
342
+ : !index.equal(this.last.result, newResult);
343
+ return (resultIsDifferent || (variables && !index.equal(this.last.variables, variables)));
344
+ };
345
+ ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
346
+ var last = this.last;
347
+ if (last &&
348
+ last[key] &&
349
+ (!variablesMustMatch || index.equal(last.variables, this.variables))) {
350
+ return last[key];
351
+ }
352
+ };
353
+ /**
354
+ * @deprecated `getLastResult` will be removed in Apollo Client 4.0. Please
355
+ * discontinue using this method.
356
+ */
357
+ ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
358
+ if (globalThis.__DEV__ !== false) {
359
+ index.warnDeprecated("getLastResult", function () {
360
+ globalThis.__DEV__ !== false && index.invariant.warn(24);
361
+ });
362
+ }
363
+ return this.getLast("result", variablesMustMatch);
364
+ };
365
+ /**
366
+ * @deprecated `getLastError` will be removed in Apollo Client 4.0. Please
367
+ * discontinue using this method.
368
+ */
369
+ ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
370
+ if (globalThis.__DEV__ !== false) {
371
+ index.warnDeprecated("getLastError", function () {
372
+ globalThis.__DEV__ !== false && index.invariant.warn(25);
373
+ });
374
+ }
375
+ return this.getLast("error", variablesMustMatch);
376
+ };
377
+ /**
378
+ * @deprecated `resetLastResults` will be removed in Apollo Client 4.0. Please
379
+ * discontinue using this method.
380
+ */
381
+ ObservableQuery.prototype.resetLastResults = function () {
382
+ if (globalThis.__DEV__ !== false) {
383
+ index.warnDeprecated("resetLastResults", function () {
384
+ globalThis.__DEV__ !== false && index.invariant.warn(26);
385
+ });
386
+ }
387
+ delete this.last;
388
+ this.isTornDown = false;
389
+ };
390
+ /**
391
+ * @deprecated `resetQueryStoreErrors` will be removed in Apollo Client 4.0.
392
+ * Please discontinue using this method.
393
+ */
394
+ ObservableQuery.prototype.resetQueryStoreErrors = function () {
395
+ if (globalThis.__DEV__ !== false) {
396
+ globalThis.__DEV__ !== false && index.invariant.warn(27);
397
+ }
398
+ this.queryManager.resetErrors(this.queryId);
399
+ };
400
+ /**
401
+ * Update the variables of this observable query, and fetch the new results.
402
+ * This method should be preferred over `setVariables` in most use cases.
403
+ *
404
+ * @param variables - The new set of variables. If there are missing variables,
405
+ * the previous values of those variables will be used.
406
+ */
407
+ ObservableQuery.prototype.refetch = function (variables) {
408
+ var _a;
409
+ var reobserveOptions = {
410
+ // Always disable polling for refetches.
411
+ pollInterval: 0,
412
+ };
413
+ // Unless the provided fetchPolicy always consults the network
414
+ // (no-cache, network-only, or cache-and-network), override it with
415
+ // network-only to force the refetch for this fetchQuery call.
416
+ var fetchPolicy = this.options.fetchPolicy;
417
+ if (fetchPolicy === "no-cache") {
418
+ reobserveOptions.fetchPolicy = "no-cache";
419
+ }
420
+ else {
421
+ reobserveOptions.fetchPolicy = "network-only";
422
+ }
423
+ if (globalThis.__DEV__ !== false && variables && hasOwnProperty$1.call(variables, "variables")) {
424
+ var queryDef = index.getQueryDefinition(this.query);
425
+ var vars = queryDef.variableDefinitions;
426
+ if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
427
+ globalThis.__DEV__ !== false && index.invariant.warn(
428
+ 28,
429
+ variables,
430
+ ((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef
431
+ );
432
+ }
433
+ }
434
+ if (variables && !index.equal(this.options.variables, variables)) {
435
+ // Update the existing options with new variables
436
+ reobserveOptions.variables = this.options.variables = index.__assign(index.__assign({}, this.options.variables), variables);
437
+ }
438
+ this.queryInfo.resetLastWrite();
439
+ return this.reobserve(reobserveOptions, NetworkStatus.refetch);
440
+ };
441
+ /**
442
+ * 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/).
443
+ */
444
+ ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
445
+ var _this = this;
446
+ var combinedOptions = index.__assign(index.__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (index.__assign(index.__assign(index.__assign(index.__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: index.__assign(index.__assign({}, this.options.variables), fetchMoreOptions.variables) })))), {
447
+ // The fetchMore request goes immediately to the network and does
448
+ // not automatically write its result to the cache (hence no-cache
449
+ // instead of network-only), because we allow the caller of
450
+ // fetchMore to provide an updateQuery callback that determines how
451
+ // the data gets written to the cache.
452
+ fetchPolicy: "no-cache" });
453
+ combinedOptions.query = this.transformDocument(combinedOptions.query);
454
+ var qid = this.queryManager.generateQueryId();
455
+ // If a temporary query is passed to `fetchMore`, we don't want to store
456
+ // it as the last query result since it may be an optimized query for
457
+ // pagination. We will however run the transforms on the original document
458
+ // as well as the document passed in `fetchMoreOptions` to ensure the cache
459
+ // uses the most up-to-date document which may rely on runtime conditionals.
460
+ this.lastQuery =
461
+ fetchMoreOptions.query ?
462
+ this.transformDocument(this.options.query)
463
+ : combinedOptions.query;
464
+ // Simulate a loading result for the original query with
465
+ // result.networkStatus === NetworkStatus.fetchMore.
466
+ var queryInfo = this.queryInfo;
467
+ var originalNetworkStatus = queryInfo.networkStatus;
468
+ queryInfo.networkStatus = NetworkStatus.fetchMore;
469
+ if (combinedOptions.notifyOnNetworkStatusChange) {
470
+ this.observe();
471
+ }
472
+ var updatedQuerySet = new Set();
473
+ var updateQuery = fetchMoreOptions === null || fetchMoreOptions === void 0 ? void 0 : fetchMoreOptions.updateQuery;
474
+ var isCached = this.options.fetchPolicy !== "no-cache";
475
+ if (!isCached) {
476
+ index.invariant(updateQuery, 29);
477
+ }
478
+ return this.queryManager
479
+ .fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)
480
+ .then(function (fetchMoreResult) {
481
+ _this.queryManager.removeQuery(qid);
482
+ if (queryInfo.networkStatus === NetworkStatus.fetchMore) {
483
+ queryInfo.networkStatus = originalNetworkStatus;
484
+ }
485
+ if (isCached) {
486
+ // Performing this cache update inside a cache.batch transaction ensures
487
+ // any affected cache.watch watchers are notified at most once about any
488
+ // updates. Most watchers will be using the QueryInfo class, which
489
+ // responds to notifications by calling reobserveCacheFirst to deliver
490
+ // fetchMore cache results back to this ObservableQuery.
491
+ _this.queryManager.cache.batch({
492
+ update: function (cache) {
493
+ var updateQuery = fetchMoreOptions.updateQuery;
494
+ if (updateQuery) {
495
+ cache.updateQuery({
496
+ query: _this.query,
497
+ variables: _this.variables,
498
+ returnPartialData: true,
499
+ optimistic: false,
500
+ }, function (previous) {
501
+ return updateQuery(previous, {
502
+ fetchMoreResult: fetchMoreResult.data,
503
+ variables: combinedOptions.variables,
504
+ });
505
+ });
506
+ }
507
+ else {
508
+ // If we're using a field policy instead of updateQuery, the only
509
+ // thing we need to do is write the new data to the cache using
510
+ // combinedOptions.variables (instead of this.variables, which is
511
+ // what this.updateQuery uses, because it works by abusing the
512
+ // original field value, keyed by the original variables).
513
+ cache.writeQuery({
514
+ query: combinedOptions.query,
515
+ variables: combinedOptions.variables,
516
+ data: fetchMoreResult.data,
517
+ });
518
+ }
519
+ },
520
+ onWatchUpdated: function (watch) {
521
+ // Record the DocumentNode associated with any watched query whose
522
+ // data were updated by the cache writes above.
523
+ updatedQuerySet.add(watch.query);
524
+ },
525
+ });
526
+ }
527
+ else {
528
+ // There is a possibility `lastResult` may not be set when
529
+ // `fetchMore` is called which would cause this to crash. This should
530
+ // only happen if we haven't previously reported a result. We don't
531
+ // quite know what the right behavior should be here since this block
532
+ // of code runs after the fetch result has executed on the network.
533
+ // We plan to let it crash in the meantime.
534
+ //
535
+ // If we get bug reports due to the `data` property access on
536
+ // undefined, this should give us a real-world scenario that we can
537
+ // use to test against and determine the right behavior. If we do end
538
+ // up changing this behavior, this may require, for example, an
539
+ // adjustment to the types on `updateQuery` since that function
540
+ // expects that the first argument always contains previous result
541
+ // data, but not `undefined`.
542
+ var lastResult = _this.getLast("result");
543
+ var data = updateQuery(lastResult.data, {
544
+ fetchMoreResult: fetchMoreResult.data,
545
+ variables: combinedOptions.variables,
546
+ });
547
+ _this.reportResult(index.__assign(index.__assign({}, lastResult), { networkStatus: originalNetworkStatus, loading: isNetworkRequestInFlight(originalNetworkStatus), data: data }), _this.variables);
548
+ }
549
+ return _this.maskResult(fetchMoreResult);
550
+ })
551
+ .finally(function () {
552
+ // In case the cache writes above did not generate a broadcast
553
+ // notification (which would have been intercepted by onWatchUpdated),
554
+ // likely because the written data were the same as what was already in
555
+ // the cache, we still want fetchMore to deliver its final loading:false
556
+ // result with the unchanged data.
557
+ if (isCached && !updatedQuerySet.has(_this.query)) {
558
+ _this.reobserveCacheFirst();
559
+ }
560
+ });
561
+ };
562
+ // XXX the subscription variables are separate from the query variables.
563
+ // if you want to update subscription variables, right now you have to do that separately,
564
+ // and you can only do it by stopping the subscription and then subscribing again with new variables.
565
+ /**
566
+ * 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.
567
+ *
568
+ * This function returns _another_ function that you can call to terminate the subscription.
569
+ */
570
+ ObservableQuery.prototype.subscribeToMore = function (options) {
571
+ var _this = this;
572
+ var subscription = this.queryManager
573
+ .startGraphQLSubscription({
574
+ query: options.document,
575
+ variables: options.variables,
576
+ context: options.context,
577
+ })
578
+ .subscribe({
579
+ next: function (subscriptionData) {
580
+ var updateQuery = options.updateQuery;
581
+ if (updateQuery) {
582
+ _this.updateQuery(function (previous, updateOptions) {
583
+ return updateQuery(previous, index.__assign({ subscriptionData: subscriptionData }, updateOptions));
584
+ });
585
+ }
586
+ },
587
+ error: function (err) {
588
+ if (options.onError) {
589
+ options.onError(err);
590
+ return;
591
+ }
592
+ globalThis.__DEV__ !== false && index.invariant.error(30, err);
593
+ },
594
+ });
595
+ this.subscriptions.add(subscription);
596
+ return function () {
597
+ if (_this.subscriptions.delete(subscription)) {
598
+ subscription.unsubscribe();
599
+ }
600
+ };
601
+ };
602
+ /**
603
+ * @deprecated `setOptions` will be removed in Apollo Client 4.0. Please use
604
+ * `observableQuery.reobserve(newOptions)` instead.
605
+ */
606
+ ObservableQuery.prototype.setOptions = function (newOptions) {
607
+ if (globalThis.__DEV__ !== false) {
608
+ index.warnRemovedOption(newOptions, "canonizeResults", "setOptions");
609
+ index.warnDeprecated("setOptions", function () {
610
+ globalThis.__DEV__ !== false && index.invariant.warn(31);
611
+ });
612
+ }
613
+ return this.reobserve(newOptions);
614
+ };
615
+ ObservableQuery.prototype.silentSetOptions = function (newOptions) {
616
+ var mergedOptions = index.compact(this.options, newOptions || {});
617
+ assign(this.options, mergedOptions);
618
+ };
619
+ /**
620
+ * Update the variables of this observable query, and fetch the new results
621
+ * if they've changed. Most users should prefer `refetch` instead of
622
+ * `setVariables` in order to to be properly notified of results even when
623
+ * they come from the cache.
624
+ *
625
+ * Note: the `next` callback will *not* fire if the variables have not changed
626
+ * or if the result is coming from cache.
627
+ *
628
+ * Note: the promise will return the old results immediately if the variables
629
+ * have not changed.
630
+ *
631
+ * Note: the promise will return null immediately if the query is not active
632
+ * (there are no subscribers).
633
+ *
634
+ * @param variables - The new set of variables. If there are missing variables,
635
+ * the previous values of those variables will be used.
636
+ */
637
+ ObservableQuery.prototype.setVariables = function (variables) {
638
+ var _this = this;
639
+ if (index.equal(this.variables, variables)) {
640
+ // If we have no observers, then we don't actually want to make a network
641
+ // request. As soon as someone observes the query, the request will kick
642
+ // off. For now, we just store any changes. (See #1077)
643
+ return this.observers.size ?
644
+ index.muteDeprecations("observableQuery.result", function () { return _this.result(); })
645
+ : Promise.resolve();
646
+ }
647
+ this.options.variables = variables;
648
+ // See comment above
649
+ if (!this.observers.size) {
650
+ return Promise.resolve();
651
+ }
652
+ return this.reobserve({
653
+ // Reset options.fetchPolicy to its original value.
654
+ fetchPolicy: this.options.initialFetchPolicy,
655
+ variables: variables,
656
+ }, NetworkStatus.setVariables);
657
+ };
658
+ /**
659
+ * A function that enables you to update the query's cached result without executing a followup GraphQL operation.
660
+ *
661
+ * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
662
+ */
663
+ ObservableQuery.prototype.updateQuery = function (mapFn) {
664
+ var queryManager = this.queryManager;
665
+ var _a = queryManager.cache.diff({
666
+ query: this.options.query,
667
+ variables: this.variables,
668
+ returnPartialData: true,
669
+ optimistic: false,
670
+ }), result = _a.result, complete = _a.complete;
671
+ var newResult = mapFn(result, {
672
+ variables: this.variables,
673
+ complete: !!complete,
674
+ previousData: result,
675
+ });
676
+ if (newResult) {
677
+ queryManager.cache.writeQuery({
678
+ query: this.options.query,
679
+ data: newResult,
680
+ variables: this.variables,
681
+ });
682
+ queryManager.broadcastQueries();
683
+ }
684
+ };
685
+ /**
686
+ * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
687
+ */
688
+ ObservableQuery.prototype.startPolling = function (pollInterval) {
689
+ this.options.pollInterval = pollInterval;
690
+ this.updatePolling();
691
+ };
692
+ /**
693
+ * A function that instructs the query to stop polling after a previous call to `startPolling`.
694
+ */
695
+ ObservableQuery.prototype.stopPolling = function () {
696
+ this.options.pollInterval = 0;
697
+ this.updatePolling();
698
+ };
699
+ // Update options.fetchPolicy according to options.nextFetchPolicy.
700
+ ObservableQuery.prototype.applyNextFetchPolicy = function (reason,
701
+ // It's possible to use this method to apply options.nextFetchPolicy to
702
+ // options.fetchPolicy even if options !== this.options, though that happens
703
+ // most often when the options are temporary, used for only one request and
704
+ // then thrown away, so nextFetchPolicy may not end up mattering.
705
+ options) {
706
+ if (options.nextFetchPolicy) {
707
+ var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
708
+ if (fetchPolicy === "standby") ;
709
+ else if (typeof options.nextFetchPolicy === "function") {
710
+ // When someone chooses "cache-and-network" or "network-only" as their
711
+ // initial FetchPolicy, they often do not want future cache updates to
712
+ // trigger unconditional network requests, which is what repeatedly
713
+ // applying the "cache-and-network" or "network-only" policies would
714
+ // seem to imply. Instead, when the cache reports an update after the
715
+ // initial network request, it may be desirable for subsequent network
716
+ // requests to be triggered only if the cache result is incomplete. To
717
+ // that end, the options.nextFetchPolicy option provides an easy way to
718
+ // update options.fetchPolicy after the initial network request, without
719
+ // having to call observableQuery.setOptions.
720
+ options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
721
+ reason: reason,
722
+ options: options,
723
+ observable: this,
724
+ initialFetchPolicy: initialFetchPolicy,
725
+ });
726
+ }
727
+ else if (reason === "variables-changed") {
728
+ options.fetchPolicy = initialFetchPolicy;
729
+ }
730
+ else {
731
+ options.fetchPolicy = options.nextFetchPolicy;
732
+ }
733
+ }
734
+ return options.fetchPolicy;
735
+ };
736
+ ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {
737
+ // TODO Make sure we update the networkStatus (and infer fetchVariables)
738
+ // before actually committing to the fetch.
739
+ var queryInfo = this._getOrCreateQuery();
740
+ queryInfo.setObservableQuery(this);
741
+ return this.queryManager["fetchConcastWithInfo"](queryInfo, options, newNetworkStatus, query);
742
+ };
743
+ // Turns polling on or off based on this.options.pollInterval.
744
+ ObservableQuery.prototype.updatePolling = function () {
745
+ var _this = this;
746
+ // Avoid polling in SSR mode
747
+ if (this.queryManager.ssrMode) {
748
+ return;
749
+ }
750
+ var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
751
+ if (!pollInterval || !this.hasObservers()) {
752
+ if (pollingInfo) {
753
+ clearTimeout(pollingInfo.timeout);
754
+ delete this.pollingInfo;
755
+ }
756
+ return;
757
+ }
758
+ if (pollingInfo && pollingInfo.interval === pollInterval) {
759
+ return;
760
+ }
761
+ index.invariant(pollInterval, 32);
762
+ var info = pollingInfo || (this.pollingInfo = {});
763
+ info.interval = pollInterval;
764
+ var maybeFetch = function () {
765
+ var _a, _b;
766
+ if (_this.pollingInfo) {
767
+ if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&
768
+ !((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {
769
+ _this.reobserve({
770
+ // Most fetchPolicy options don't make sense to use in a polling context, as
771
+ // users wouldn't want to be polling the cache directly. However, network-only and
772
+ // no-cache are both useful for when the user wants to control whether or not the
773
+ // polled results are written to the cache.
774
+ fetchPolicy: _this.options.initialFetchPolicy === "no-cache" ?
775
+ "no-cache"
776
+ : "network-only",
777
+ }, NetworkStatus.poll).then(poll, poll);
778
+ }
779
+ else {
780
+ poll();
781
+ }
782
+ }
783
+ };
784
+ var poll = function () {
785
+ var info = _this.pollingInfo;
786
+ if (info) {
787
+ clearTimeout(info.timeout);
788
+ info.timeout = setTimeout(maybeFetch, info.interval);
789
+ }
790
+ };
791
+ poll();
792
+ };
793
+ ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
794
+ var _this = this;
795
+ if (variables === void 0) { variables = this.variables; }
796
+ var error = index.muteDeprecations("getLastError", function () {
797
+ return _this.getLastError();
798
+ });
799
+ // Preserve this.last.error unless the variables have changed.
800
+ if (error && this.last && !index.equal(variables, this.last.variables)) {
801
+ error = void 0;
802
+ }
803
+ return (this.last = index.__assign({ result: this.queryManager.assumeImmutableResults ?
804
+ newResult
805
+ : index.cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));
806
+ };
807
+ ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
808
+ var _this = this;
809
+ this.isTornDown = false;
810
+ var useDisposableConcast =
811
+ // Refetching uses a disposable Concast to allow refetches using different
812
+ // options/variables, without permanently altering the options of the
813
+ // original ObservableQuery.
814
+ newNetworkStatus === NetworkStatus.refetch ||
815
+ // The fetchMore method does not actually call the reobserve method, but,
816
+ // if it did, it would definitely use a disposable Concast.
817
+ newNetworkStatus === NetworkStatus.fetchMore ||
818
+ // Polling uses a disposable Concast so the polling options (which force
819
+ // fetchPolicy to be "network-only" or "no-cache") won't override the original options.
820
+ newNetworkStatus === NetworkStatus.poll;
821
+ // Save the old variables, since Object.assign may modify them below.
822
+ var oldVariables = this.options.variables;
823
+ var oldFetchPolicy = this.options.fetchPolicy;
824
+ var mergedOptions = index.compact(this.options, newOptions || {});
825
+ var options = useDisposableConcast ?
826
+ // Disposable Concast fetches receive a shallow copy of this.options
827
+ // (merged with newOptions), leaving this.options unmodified.
828
+ mergedOptions
829
+ : assign(this.options, mergedOptions);
830
+ // Don't update options.query with the transformed query to avoid
831
+ // overwriting this.options.query when we aren't using a disposable concast.
832
+ // We want to ensure we can re-run the custom document transforms the next
833
+ // time a request is made against the original query.
834
+ var query = this.transformDocument(options.query);
835
+ this.lastQuery = query;
836
+ if (!useDisposableConcast) {
837
+ // We can skip calling updatePolling if we're not changing this.options.
838
+ this.updatePolling();
839
+ // Reset options.fetchPolicy to its original value when variables change,
840
+ // unless a new fetchPolicy was provided by newOptions.
841
+ if (newOptions &&
842
+ newOptions.variables &&
843
+ !index.equal(newOptions.variables, oldVariables) &&
844
+ // Don't mess with the fetchPolicy if it's currently "standby".
845
+ options.fetchPolicy !== "standby" &&
846
+ // If we're changing the fetchPolicy anyway, don't try to change it here
847
+ // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.
848
+ (options.fetchPolicy === oldFetchPolicy ||
849
+ // A `nextFetchPolicy` function has even higher priority, though,
850
+ // so in that case `applyNextFetchPolicy` must be called.
851
+ typeof options.nextFetchPolicy === "function")) {
852
+ this.applyNextFetchPolicy("variables-changed", options);
853
+ if (newNetworkStatus === void 0) {
854
+ newNetworkStatus = NetworkStatus.setVariables;
855
+ }
856
+ }
857
+ }
858
+ this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));
859
+ var finishWaitingForOwnResult = function () {
860
+ if (_this.concast === concast) {
861
+ _this.waitForOwnResult = false;
862
+ }
863
+ };
864
+ var variables = options.variables && index.__assign({}, options.variables);
865
+ var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;
866
+ var observer = {
867
+ next: function (result) {
868
+ if (index.equal(_this.variables, variables)) {
869
+ finishWaitingForOwnResult();
870
+ _this.reportResult(result, variables);
871
+ }
872
+ },
873
+ error: function (error) {
874
+ if (index.equal(_this.variables, variables)) {
875
+ // Coming from `getResultsFromLink`, `error` here should always be an `ApolloError`.
876
+ // However, calling `concast.cancel` can inject another type of error, so we have to
877
+ // wrap it again here.
878
+ if (!index.isApolloError(error)) {
879
+ error = new index.ApolloError({ networkError: error });
880
+ }
881
+ finishWaitingForOwnResult();
882
+ _this.reportError(error, variables);
883
+ }
884
+ },
885
+ };
886
+ if (!useDisposableConcast && (fromLink || !this.concast)) {
887
+ // We use the {add,remove}Observer methods directly to avoid wrapping
888
+ // observer with an unnecessary SubscriptionObserver object.
889
+ if (this.concast && this.observer) {
890
+ this.concast.removeObserver(this.observer);
891
+ }
892
+ this.concast = concast;
893
+ this.observer = observer;
894
+ }
895
+ concast.addObserver(observer);
896
+ return concast;
897
+ };
898
+ ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
899
+ return index.preventUnhandledRejection(this.reobserveAsConcast(newOptions, newNetworkStatus).promise.then(this.maskResult));
900
+ };
901
+ ObservableQuery.prototype.resubscribeAfterError = function () {
902
+ var _this = this;
903
+ var args = [];
904
+ for (var _i = 0; _i < arguments.length; _i++) {
905
+ args[_i] = arguments[_i];
906
+ }
907
+ // If `lastError` is set in the current when the subscription is re-created,
908
+ // the subscription will immediately receive the error, which will
909
+ // cause it to terminate again. To avoid this, we first clear
910
+ // the last error/result from the `observableQuery` before re-starting
911
+ // the subscription, and restore the last value afterwards so that the
912
+ // subscription has a chance to stay open.
913
+ var last = this.last;
914
+ index.muteDeprecations("resetLastResults", function () { return _this.resetLastResults(); });
915
+ var subscription = this.subscribe.apply(this, args);
916
+ this.last = last;
917
+ return subscription;
918
+ };
919
+ // (Re)deliver the current result to this.observers without applying fetch
920
+ // policies or making network requests.
921
+ ObservableQuery.prototype.observe = function () {
922
+ this.reportResult(
923
+ // Passing false is important so that this.getCurrentResult doesn't
924
+ // save the fetchMore result as this.lastResult, causing it to be
925
+ // ignored due to the this.isDifferentFromLastResult check in
926
+ // this.reportResult.
927
+ this.getCurrentFullResult(false), this.variables);
928
+ };
929
+ ObservableQuery.prototype.reportResult = function (result, variables) {
930
+ var _this = this;
931
+ var lastError = index.muteDeprecations("getLastError", function () {
932
+ return _this.getLastError();
933
+ });
934
+ var isDifferent = this.isDifferentFromLastResult(result, variables);
935
+ // Update the last result even when isDifferentFromLastResult returns false,
936
+ // because the query may be using the @nonreactive directive, and we want to
937
+ // save the the latest version of any nonreactive subtrees (in case
938
+ // getCurrentResult is called), even though we skip broadcasting changes.
939
+ if (lastError || !result.partial || this.options.returnPartialData) {
940
+ this.updateLastResult(result, variables);
941
+ }
942
+ if (lastError || isDifferent) {
943
+ index.iterateObserversSafely(this.observers, "next", this.maskResult(result));
944
+ }
945
+ };
946
+ ObservableQuery.prototype.reportError = function (error, variables) {
947
+ var _this = this;
948
+ // Since we don't get the current result on errors, only the error, we
949
+ // must mirror the updates that occur in QueryStore.markQueryError here
950
+ var errorResult = index.__assign(index.__assign({}, index.muteDeprecations("getLastResult", function () { return _this.getLastResult(); })), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });
951
+ this.updateLastResult(errorResult, variables);
952
+ index.iterateObserversSafely(this.observers, "error", (this.last.error = error));
953
+ };
954
+ ObservableQuery.prototype.hasObservers = function () {
955
+ return this.observers.size > 0;
956
+ };
957
+ ObservableQuery.prototype.tearDownQuery = function () {
958
+ if (this.isTornDown)
959
+ return;
960
+ if (this.concast && this.observer) {
961
+ this.concast.removeObserver(this.observer);
962
+ delete this.concast;
963
+ delete this.observer;
964
+ }
965
+ this.stopPolling();
966
+ // stop all active GraphQL subscriptions
967
+ this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
968
+ this.subscriptions.clear();
969
+ this.queryManager.stopQuery(this.queryId);
970
+ this.observers.clear();
971
+ this.isTornDown = true;
972
+ };
973
+ ObservableQuery.prototype.transformDocument = function (document) {
974
+ return this.queryManager.transform(document);
975
+ };
976
+ ObservableQuery.prototype.maskResult = function (result) {
977
+ return result && "data" in result ? index.__assign(index.__assign({}, result), { data: this.queryManager.maskOperation({
978
+ document: this.query,
979
+ data: result.data,
980
+ fetchPolicy: this.options.fetchPolicy,
981
+ id: this.queryId,
982
+ }) }) : result;
983
+ };
984
+ /** @internal */
985
+ ObservableQuery.prototype.resetNotifications = function () {
986
+ this.cancelNotifyTimeout();
987
+ this.dirty = false;
988
+ };
989
+ ObservableQuery.prototype.cancelNotifyTimeout = function () {
990
+ if (this.notifyTimeout) {
991
+ clearTimeout(this.notifyTimeout);
992
+ this.notifyTimeout = void 0;
993
+ }
994
+ };
995
+ /** @internal */
996
+ ObservableQuery.prototype.scheduleNotify = function () {
997
+ var _this = this;
998
+ if (this.dirty)
999
+ return;
1000
+ this.dirty = true;
1001
+ if (!this.notifyTimeout) {
1002
+ this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
1003
+ }
1004
+ };
1005
+ /** @internal */
1006
+ ObservableQuery.prototype.notify = function () {
1007
+ this.cancelNotifyTimeout();
1008
+ if (this.dirty) {
1009
+ if (this.options.fetchPolicy == "cache-only" ||
1010
+ this.options.fetchPolicy == "cache-and-network" ||
1011
+ !isNetworkRequestInFlight(this.queryInfo.networkStatus)) {
1012
+ var diff = this.queryInfo.getDiff();
1013
+ if (diff.fromOptimisticTransaction) {
1014
+ // If this diff came from an optimistic transaction, deliver the
1015
+ // current cache data to the ObservableQuery, but don't perform a
1016
+ // reobservation, since oq.reobserveCacheFirst might make a network
1017
+ // request, and we never want to trigger network requests in the
1018
+ // middle of optimistic updates.
1019
+ this.observe();
1020
+ }
1021
+ else {
1022
+ // Otherwise, make the ObservableQuery "reobserve" the latest data
1023
+ // using a temporary fetch policy of "cache-first", so complete cache
1024
+ // results have a chance to be delivered without triggering additional
1025
+ // network requests, even when options.fetchPolicy is "network-only"
1026
+ // or "cache-and-network". All other fetch policies are preserved by
1027
+ // this method, and are handled by calling oq.reobserve(). If this
1028
+ // reobservation is spurious, isDifferentFromLastResult still has a
1029
+ // chance to catch it before delivery to ObservableQuery subscribers.
1030
+ this.reobserveCacheFirst();
1031
+ }
1032
+ }
1033
+ }
1034
+ this.dirty = false;
1035
+ };
1036
+ // Reobserve with fetchPolicy effectively set to "cache-first", triggering
1037
+ // delivery of any new data from the cache, possibly falling back to the network
1038
+ // if any cache data are missing. This allows _complete_ cache results to be
1039
+ // delivered without also kicking off unnecessary network requests when
1040
+ // this.options.fetchPolicy is "cache-and-network" or "network-only". When
1041
+ // this.options.fetchPolicy is any other policy ("cache-first", "cache-only",
1042
+ // "standby", or "no-cache"), we call this.reobserve() as usual.
1043
+ ObservableQuery.prototype.reobserveCacheFirst = function () {
1044
+ var _a = this.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
1045
+ if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
1046
+ return this.reobserve({
1047
+ fetchPolicy: "cache-first",
1048
+ // Use a temporary nextFetchPolicy function that replaces itself with the
1049
+ // previous nextFetchPolicy value and returns the original fetchPolicy.
1050
+ nextFetchPolicy: function (currentFetchPolicy, context) {
1051
+ // Replace this nextFetchPolicy function in the options object with the
1052
+ // original this.options.nextFetchPolicy value.
1053
+ this.nextFetchPolicy = nextFetchPolicy;
1054
+ // If the original nextFetchPolicy value was a function, give it a
1055
+ // chance to decide what happens here.
1056
+ if (typeof this.nextFetchPolicy === "function") {
1057
+ return this.nextFetchPolicy(currentFetchPolicy, context);
1058
+ }
1059
+ // Otherwise go back to the original this.options.fetchPolicy.
1060
+ return fetchPolicy;
1061
+ },
1062
+ });
1063
+ }
1064
+ return this.reobserve();
1065
+ };
1066
+ /**
1067
+ * @internal
1068
+ * A slot used by the `useQuery` hook to indicate that `client.watchQuery`
1069
+ * should not register the query immediately, but instead wait for the query to
1070
+ * be started registered with the `QueryManager` when `useSyncExternalStore`
1071
+ * actively subscribes to it.
1072
+ */
1073
+ ObservableQuery.inactiveOnCreation = new index.Slot();
1074
+ return ObservableQuery;
1075
+ }(index.Observable));
1076
+ // Necessary because the ObservableQuery constructor has a different
1077
+ // signature than the Observable constructor.
1078
+ index.fixObservableSubclass(ObservableQuery);
1079
+ function defaultSubscriptionObserverErrorCallback(error) {
1080
+ globalThis.__DEV__ !== false && index.invariant.error(33, error.message, error.stack);
1081
+ }
1082
+ function logMissingFieldErrors(missing) {
1083
+ if (globalThis.__DEV__ !== false && missing) {
1084
+ globalThis.__DEV__ !== false && index.invariant.debug(34, missing);
1085
+ }
1086
+ }
1087
+ function skipCacheDataFor(fetchPolicy /* `undefined` would mean `"cache-first"` */) {
1088
+ return (fetchPolicy === "network-only" ||
1089
+ fetchPolicy === "no-cache" ||
1090
+ fetchPolicy === "standby");
1091
+ }
1092
+
1093
+ var destructiveMethodCounts = new (index.canUseWeakMap ? WeakMap : Map)();
1094
+ function wrapDestructiveCacheMethod(cache, methodName) {
1095
+ var original = cache[methodName];
1096
+ if (typeof original === "function") {
1097
+ // @ts-expect-error this is just too generic to be typed correctly
1098
+ cache[methodName] = function () {
1099
+ destructiveMethodCounts.set(cache,
1100
+ // The %1e15 allows the count to wrap around to 0 safely every
1101
+ // quadrillion evictions, so there's no risk of overflow. To be
1102
+ // clear, this is more of a pedantic principle than something
1103
+ // that matters in any conceivable practical scenario.
1104
+ (destructiveMethodCounts.get(cache) + 1) % 1e15);
1105
+ // @ts-expect-error this is just too generic to be typed correctly
1106
+ return original.apply(this, arguments);
1107
+ };
1108
+ }
1109
+ }
1110
+ // A QueryInfo object represents a single query managed by the
1111
+ // QueryManager, which tracks all QueryInfo objects by queryId in its
1112
+ // this.queries Map. QueryInfo objects store the latest results and errors
1113
+ // for the given query, and are responsible for reporting those results to
1114
+ // the corresponding ObservableQuery, via the QueryInfo.notify method.
1115
+ // Results are reported asynchronously whenever setDiff marks the
1116
+ // QueryInfo object as dirty, though a call to the QueryManager's
1117
+ // broadcastQueries method may trigger the notification before it happens
1118
+ // automatically. This class used to be a simple interface type without
1119
+ // any field privacy or meaningful methods, which is why it still has so
1120
+ // many public fields. The effort to lock down and simplify the QueryInfo
1121
+ // interface is ongoing, and further improvements are welcome.
1122
+ var QueryInfo = /** @class */ (function () {
1123
+ function QueryInfo(queryManager, queryId) {
1124
+ if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
1125
+ this.queryId = queryId;
1126
+ this.document = null;
1127
+ this.lastRequestId = 1;
1128
+ this.stopped = false;
1129
+ this.observableQuery = null;
1130
+ var cache = (this.cache = queryManager.cache);
1131
+ // Track how often cache.evict is called, since we want eviction to
1132
+ // override the feud-stopping logic in the markResult method, by
1133
+ // causing shouldWrite to return true. Wrapping the cache.evict method
1134
+ // is a bit of a hack, but it saves us from having to make eviction
1135
+ // counting an official part of the ApolloCache API.
1136
+ if (!destructiveMethodCounts.has(cache)) {
1137
+ destructiveMethodCounts.set(cache, 0);
1138
+ wrapDestructiveCacheMethod(cache, "evict");
1139
+ wrapDestructiveCacheMethod(cache, "modify");
1140
+ wrapDestructiveCacheMethod(cache, "reset");
1141
+ }
1142
+ }
1143
+ QueryInfo.prototype.init = function (query) {
1144
+ var networkStatus = query.networkStatus || NetworkStatus.loading;
1145
+ if (this.variables &&
1146
+ this.networkStatus !== NetworkStatus.loading &&
1147
+ !index.equal(this.variables, query.variables)) {
1148
+ networkStatus = NetworkStatus.setVariables;
1149
+ }
1150
+ if (!index.equal(query.variables, this.variables)) {
1151
+ this.lastDiff = void 0;
1152
+ // Ensure we don't continue to receive cache updates for old variables
1153
+ this.cancel();
1154
+ }
1155
+ Object.assign(this, {
1156
+ document: query.document,
1157
+ variables: query.variables,
1158
+ networkError: null,
1159
+ graphQLErrors: this.graphQLErrors || [],
1160
+ networkStatus: networkStatus,
1161
+ });
1162
+ if (query.observableQuery) {
1163
+ this.setObservableQuery(query.observableQuery);
1164
+ }
1165
+ if (query.lastRequestId) {
1166
+ this.lastRequestId = query.lastRequestId;
1167
+ }
1168
+ return this;
1169
+ };
1170
+ QueryInfo.prototype.resetDiff = function () {
1171
+ this.lastDiff = void 0;
1172
+ };
1173
+ QueryInfo.prototype.getDiff = function () {
1174
+ var _this = this;
1175
+ var options = this.getDiffOptions();
1176
+ if (this.lastDiff && index.equal(options, this.lastDiff.options)) {
1177
+ return this.lastDiff.diff;
1178
+ }
1179
+ this.updateWatch(this.variables);
1180
+ var oq = this.observableQuery;
1181
+ if (oq && oq.options.fetchPolicy === "no-cache") {
1182
+ return { complete: false };
1183
+ }
1184
+ var diff = index.muteDeprecations("canonizeResults", function () {
1185
+ return _this.cache.diff(options);
1186
+ });
1187
+ this.updateLastDiff(diff, options);
1188
+ return diff;
1189
+ };
1190
+ QueryInfo.prototype.updateLastDiff = function (diff, options) {
1191
+ this.lastDiff =
1192
+ diff ?
1193
+ {
1194
+ diff: diff,
1195
+ options: options || this.getDiffOptions(),
1196
+ }
1197
+ : void 0;
1198
+ };
1199
+ QueryInfo.prototype.getDiffOptions = function (variables) {
1200
+ var _a;
1201
+ if (variables === void 0) { variables = this.variables; }
1202
+ return {
1203
+ query: this.document,
1204
+ variables: variables,
1205
+ returnPartialData: true,
1206
+ optimistic: true,
1207
+ canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
1208
+ };
1209
+ };
1210
+ QueryInfo.prototype.setDiff = function (diff) {
1211
+ var _this = this;
1212
+ var _a;
1213
+ var oldDiff = this.lastDiff && this.lastDiff.diff;
1214
+ // If we are trying to deliver an incomplete cache result, we avoid
1215
+ // reporting it if the query has errored, otherwise we let the broadcast try
1216
+ // and repair the partial result by refetching the query. This check avoids
1217
+ // a situation where a query that errors and another succeeds with
1218
+ // overlapping data does not report the partial data result to the errored
1219
+ // query.
1220
+ //
1221
+ // See https://github.com/apollographql/apollo-client/issues/11400 for more
1222
+ // information on this issue.
1223
+ if (diff &&
1224
+ !diff.complete &&
1225
+ index.muteDeprecations("getLastError", function () { var _a; return (_a = _this.observableQuery) === null || _a === void 0 ? void 0 : _a.getLastError(); })) {
1226
+ return;
1227
+ }
1228
+ this.updateLastDiff(diff);
1229
+ if (!index.equal(oldDiff && oldDiff.result, diff && diff.result)) {
1230
+ (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["scheduleNotify"]();
1231
+ }
1232
+ };
1233
+ QueryInfo.prototype.setObservableQuery = function (oq) {
1234
+ if (oq === this.observableQuery)
1235
+ return;
1236
+ this.observableQuery = oq;
1237
+ if (oq) {
1238
+ oq["queryInfo"] = this;
1239
+ }
1240
+ };
1241
+ QueryInfo.prototype.stop = function () {
1242
+ var _a;
1243
+ if (!this.stopped) {
1244
+ this.stopped = true;
1245
+ // Cancel the pending notify timeout
1246
+ (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1247
+ this.cancel();
1248
+ var oq = this.observableQuery;
1249
+ if (oq)
1250
+ oq.stopPolling();
1251
+ }
1252
+ };
1253
+ QueryInfo.prototype.cancel = function () {
1254
+ var _a;
1255
+ (_a = this.cancelWatch) === null || _a === void 0 ? void 0 : _a.call(this);
1256
+ this.cancelWatch = void 0;
1257
+ };
1258
+ QueryInfo.prototype.updateWatch = function (variables) {
1259
+ var _this = this;
1260
+ if (variables === void 0) { variables = this.variables; }
1261
+ var oq = this.observableQuery;
1262
+ if (oq && oq.options.fetchPolicy === "no-cache") {
1263
+ return;
1264
+ }
1265
+ var watchOptions = index.__assign(index.__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
1266
+ if (!this.lastWatch || !index.equal(watchOptions, this.lastWatch)) {
1267
+ this.cancel();
1268
+ this.cancelWatch = this.cache.watch((this.lastWatch = watchOptions));
1269
+ }
1270
+ };
1271
+ QueryInfo.prototype.resetLastWrite = function () {
1272
+ this.lastWrite = void 0;
1273
+ };
1274
+ QueryInfo.prototype.shouldWrite = function (result, variables) {
1275
+ var lastWrite = this.lastWrite;
1276
+ return !(lastWrite &&
1277
+ // If cache.evict has been called since the last time we wrote this
1278
+ // data into the cache, there's a chance writing this result into
1279
+ // the cache will repair what was evicted.
1280
+ lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
1281
+ index.equal(variables, lastWrite.variables) &&
1282
+ index.equal(result.data, lastWrite.result.data));
1283
+ };
1284
+ QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
1285
+ var _this = this;
1286
+ var _a;
1287
+ var merger = new index.DeepMerger();
1288
+ var graphQLErrors = index.isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
1289
+ // Cancel the pending notify timeout (if it exists) to prevent extraneous network
1290
+ // requests. To allow future notify timeouts, diff and dirty are reset as well.
1291
+ (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1292
+ if ("incremental" in result && index.isNonEmptyArray(result.incremental)) {
1293
+ var mergedData = index.mergeIncrementalData(this.getDiff().result, result);
1294
+ result.data = mergedData;
1295
+ // Detect the first chunk of a deferred query and merge it with existing
1296
+ // cache data. This ensures a `cache-first` fetch policy that returns
1297
+ // partial cache data or a `cache-and-network` fetch policy that already
1298
+ // has full data in the cache does not complain when trying to merge the
1299
+ // initial deferred server data with existing cache data.
1300
+ }
1301
+ else if ("hasNext" in result && result.hasNext) {
1302
+ var diff = this.getDiff();
1303
+ result.data = merger.merge(diff.result, result.data);
1304
+ }
1305
+ this.graphQLErrors = graphQLErrors;
1306
+ if (options.fetchPolicy === "no-cache") {
1307
+ this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
1308
+ }
1309
+ else if (cacheWriteBehavior !== 0 /* CacheWriteBehavior.FORBID */) {
1310
+ if (shouldWriteResult(result, options.errorPolicy)) {
1311
+ // Using a transaction here so we have a chance to read the result
1312
+ // back from the cache before the watch callback fires as a result
1313
+ // of writeQuery, so we can store the new diff quietly and ignore
1314
+ // it when we receive it redundantly from the watch callback.
1315
+ this.cache.performTransaction(function (cache) {
1316
+ if (_this.shouldWrite(result, options.variables)) {
1317
+ cache.writeQuery({
1318
+ query: document,
1319
+ data: result.data,
1320
+ variables: options.variables,
1321
+ overwrite: cacheWriteBehavior === 1 /* CacheWriteBehavior.OVERWRITE */,
1322
+ });
1323
+ _this.lastWrite = {
1324
+ result: result,
1325
+ variables: options.variables,
1326
+ dmCount: destructiveMethodCounts.get(_this.cache),
1327
+ };
1328
+ }
1329
+ else {
1330
+ // If result is the same as the last result we received from
1331
+ // the network (and the variables match too), avoid writing
1332
+ // result into the cache again. The wisdom of skipping this
1333
+ // cache write is far from obvious, since any cache write
1334
+ // could be the one that puts the cache back into a desired
1335
+ // state, fixing corruption or missing data. However, if we
1336
+ // always write every network result into the cache, we enable
1337
+ // feuds between queries competing to update the same data in
1338
+ // incompatible ways, which can lead to an endless cycle of
1339
+ // cache broadcasts and useless network requests. As with any
1340
+ // feud, eventually one side must step back from the brink,
1341
+ // letting the other side(s) have the last word(s). There may
1342
+ // be other points where we could break this cycle, such as
1343
+ // silencing the broadcast for cache.writeQuery (not a good
1344
+ // idea, since it just delays the feud a bit) or somehow
1345
+ // avoiding the network request that just happened (also bad,
1346
+ // because the server could return useful new data). All
1347
+ // options considered, skipping this cache write seems to be
1348
+ // the least damaging place to break the cycle, because it
1349
+ // reflects the intuition that we recently wrote this exact
1350
+ // result into the cache, so the cache *should* already/still
1351
+ // contain this data. If some other query has clobbered that
1352
+ // data in the meantime, that's too bad, but there will be no
1353
+ // winners if every query blindly reverts to its own version
1354
+ // of the data. This approach also gives the network a chance
1355
+ // to return new data, which will be written into the cache as
1356
+ // usual, notifying only those queries that are directly
1357
+ // affected by the cache updates, as usual. In the future, an
1358
+ // even more sophisticated cache could perhaps prevent or
1359
+ // mitigate the clobbering somehow, but that would make this
1360
+ // particular cache write even less important, and thus
1361
+ // skipping it would be even safer than it is today.
1362
+ if (_this.lastDiff && _this.lastDiff.diff.complete) {
1363
+ // Reuse data from the last good (complete) diff that we
1364
+ // received, when possible.
1365
+ result.data = _this.lastDiff.diff.result;
1366
+ return;
1367
+ }
1368
+ // If the previous this.diff was incomplete, fall through to
1369
+ // re-reading the latest data with cache.diff, below.
1370
+ }
1371
+ var diffOptions = _this.getDiffOptions(options.variables);
1372
+ var diff = index.muteDeprecations("canonizeResults", function () {
1373
+ return cache.diff(diffOptions);
1374
+ });
1375
+ // In case the QueryManager stops this QueryInfo before its
1376
+ // results are delivered, it's important to avoid restarting the
1377
+ // cache watch when markResult is called. We also avoid updating
1378
+ // the watch if we are writing a result that doesn't match the current
1379
+ // variables to avoid race conditions from broadcasting the wrong
1380
+ // result.
1381
+ if (!_this.stopped && index.equal(_this.variables, options.variables)) {
1382
+ // Any time we're about to update this.diff, we need to make
1383
+ // sure we've started watching the cache.
1384
+ _this.updateWatch(options.variables);
1385
+ }
1386
+ // If we're allowed to write to the cache, and we can read a
1387
+ // complete result from the cache, update result.data to be the
1388
+ // result from the cache, rather than the raw network result.
1389
+ // Set without setDiff to avoid triggering a notify call, since
1390
+ // we have other ways of notifying for this result.
1391
+ _this.updateLastDiff(diff, diffOptions);
1392
+ if (diff.complete) {
1393
+ result.data = diff.result;
1394
+ }
1395
+ });
1396
+ }
1397
+ else {
1398
+ this.lastWrite = void 0;
1399
+ }
1400
+ }
1401
+ };
1402
+ QueryInfo.prototype.markReady = function () {
1403
+ this.networkError = null;
1404
+ return (this.networkStatus = NetworkStatus.ready);
1405
+ };
1406
+ QueryInfo.prototype.markError = function (error) {
1407
+ var _a;
1408
+ this.networkStatus = NetworkStatus.error;
1409
+ this.lastWrite = void 0;
1410
+ (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a["resetNotifications"]();
1411
+ if (error.graphQLErrors) {
1412
+ this.graphQLErrors = error.graphQLErrors;
1413
+ }
1414
+ if (error.networkError) {
1415
+ this.networkError = error.networkError;
1416
+ }
1417
+ return error;
1418
+ };
1419
+ return QueryInfo;
1420
+ }());
1421
+ function shouldWriteResult(result, errorPolicy) {
1422
+ if (errorPolicy === void 0) { errorPolicy = "none"; }
1423
+ var ignoreErrors = errorPolicy === "ignore" || errorPolicy === "all";
1424
+ var writeWithErrors = !index.graphQLResultHasError(result);
1425
+ if (!writeWithErrors && ignoreErrors && result.data) {
1426
+ writeWithErrors = true;
1427
+ }
1428
+ return writeWithErrors;
1429
+ }
1430
+
1431
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
1432
+ var IGNORE = Object.create(null);
1433
+ var QueryManager = /** @class */ (function () {
1434
+ function QueryManager(options) {
1435
+ var _this = this;
1436
+ this.clientAwareness = {};
1437
+ // All the queries that the QueryManager is currently managing (not
1438
+ // including mutations and subscriptions).
1439
+ this.queries = new Map();
1440
+ // Maps from queryId strings to Promise rejection functions for
1441
+ // currently active queries and fetches.
1442
+ // Use protected instead of private field so
1443
+ // @apollo/experimental-nextjs-app-support can access type info.
1444
+ this.fetchCancelFns = new Map();
1445
+ this.transformCache = new index.AutoCleanedWeakCache(index.cacheSizes["queryManager.getDocumentInfo"] ||
1446
+ 2000 /* defaultCacheSizes["queryManager.getDocumentInfo"] */);
1447
+ this.queryIdCounter = 1;
1448
+ this.requestIdCounter = 1;
1449
+ this.mutationIdCounter = 1;
1450
+ // Use protected instead of private field so
1451
+ // @apollo/experimental-nextjs-app-support can access type info.
1452
+ this.inFlightLinkObservables = new index.Trie(false);
1453
+ this.noCacheWarningsByQueryId = new Set();
1454
+ var defaultDocumentTransform = new index.DocumentTransform(function (document) { return _this.cache.transformDocument(document); },
1455
+ // Allow the apollo cache to manage its own transform caches
1456
+ { cache: false });
1457
+ this.cache = options.cache;
1458
+ this.link = options.link;
1459
+ this.defaultOptions = options.defaultOptions;
1460
+ this.queryDeduplication = options.queryDeduplication;
1461
+ this.clientAwareness = options.clientAwareness;
1462
+ this.localState = options.localState;
1463
+ this.ssrMode = options.ssrMode;
1464
+ this.assumeImmutableResults = options.assumeImmutableResults;
1465
+ this.dataMasking = options.dataMasking;
1466
+ var documentTransform = options.documentTransform;
1467
+ this.documentTransform =
1468
+ documentTransform ?
1469
+ defaultDocumentTransform
1470
+ .concat(documentTransform)
1471
+ // The custom document transform may add new fragment spreads or new
1472
+ // field selections, so we want to give the cache a chance to run
1473
+ // again. For example, the InMemoryCache adds __typename to field
1474
+ // selections and fragments from the fragment registry.
1475
+ .concat(defaultDocumentTransform)
1476
+ : defaultDocumentTransform;
1477
+ this.defaultContext = options.defaultContext || Object.create(null);
1478
+ if ((this.onBroadcast = options.onBroadcast)) {
1479
+ this.mutationStore = Object.create(null);
1480
+ }
1481
+ }
1482
+ /**
1483
+ * Call this method to terminate any active query processes, making it safe
1484
+ * to dispose of this QueryManager instance.
1485
+ */
1486
+ QueryManager.prototype.stop = function () {
1487
+ var _this = this;
1488
+ this.queries.forEach(function (_info, queryId) {
1489
+ _this.stopQueryNoBroadcast(queryId);
1490
+ });
1491
+ this.cancelPendingFetches(index.newInvariantError(35));
1492
+ };
1493
+ QueryManager.prototype.cancelPendingFetches = function (error) {
1494
+ this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
1495
+ this.fetchCancelFns.clear();
1496
+ };
1497
+ QueryManager.prototype.mutate = function (_a) {
1498
+ return index.__awaiter(this, arguments, void 0, function (_b) {
1499
+ var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;
1500
+ var _c, _d;
1501
+ var mutation = _b.mutation, variables = _b.variables, optimisticResponse = _b.optimisticResponse, updateQueries = _b.updateQueries, _e = _b.refetchQueries, refetchQueries = _e === void 0 ? [] : _e, _f = _b.awaitRefetchQueries, awaitRefetchQueries = _f === void 0 ? false : _f, updateWithProxyFn = _b.update, onQueryUpdated = _b.onQueryUpdated, _g = _b.fetchPolicy, fetchPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.fetchPolicy) || "network-only" : _g, _h = _b.errorPolicy, errorPolicy = _h === void 0 ? ((_d = this.defaultOptions.mutate) === null || _d === void 0 ? void 0 : _d.errorPolicy) || "none" : _h, keepRootFields = _b.keepRootFields, context = _b.context;
1502
+ return index.__generator(this, function (_j) {
1503
+ switch (_j.label) {
1504
+ case 0:
1505
+ index.invariant(mutation, 36);
1506
+ index.invariant(fetchPolicy === "network-only" || fetchPolicy === "no-cache", 37);
1507
+ mutationId = this.generateMutationId();
1508
+ mutation = this.cache.transformForLink(this.transform(mutation));
1509
+ hasClientExports = this.getDocumentInfo(mutation).hasClientExports;
1510
+ variables = this.getVariables(mutation, variables);
1511
+ if (!hasClientExports) return [3 /*break*/, 2];
1512
+ return [4 /*yield*/, this.localState.addExportedVariables(mutation, variables, context)];
1513
+ case 1:
1514
+ variables = (_j.sent());
1515
+ _j.label = 2;
1516
+ case 2:
1517
+ mutationStoreValue = this.mutationStore &&
1518
+ (this.mutationStore[mutationId] = {
1519
+ mutation: mutation,
1520
+ variables: variables,
1521
+ loading: true,
1522
+ error: null,
1523
+ });
1524
+ isOptimistic = optimisticResponse &&
1525
+ this.markMutationOptimistic(optimisticResponse, {
1526
+ mutationId: mutationId,
1527
+ document: mutation,
1528
+ variables: variables,
1529
+ fetchPolicy: fetchPolicy,
1530
+ errorPolicy: errorPolicy,
1531
+ context: context,
1532
+ updateQueries: updateQueries,
1533
+ update: updateWithProxyFn,
1534
+ keepRootFields: keepRootFields,
1535
+ });
1536
+ this.broadcastQueries();
1537
+ self = this;
1538
+ return [2 /*return*/, new Promise(function (resolve, reject) {
1539
+ return index.asyncMap(self.getObservableFromLink(mutation, index.__assign(index.__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, {}, false), function (result) {
1540
+ if (index.graphQLResultHasError(result) && errorPolicy === "none") {
1541
+ throw new index.ApolloError({
1542
+ graphQLErrors: index.getGraphQLErrorsFromResult(result),
1543
+ });
1544
+ }
1545
+ if (mutationStoreValue) {
1546
+ mutationStoreValue.loading = false;
1547
+ mutationStoreValue.error = null;
1548
+ }
1549
+ var storeResult = index.__assign({}, result);
1550
+ if (typeof refetchQueries === "function") {
1551
+ refetchQueries = refetchQueries(storeResult);
1552
+ }
1553
+ if (errorPolicy === "ignore" && index.graphQLResultHasError(storeResult)) {
1554
+ delete storeResult.errors;
1555
+ }
1556
+ return self.markMutationResult({
1557
+ mutationId: mutationId,
1558
+ result: storeResult,
1559
+ document: mutation,
1560
+ variables: variables,
1561
+ fetchPolicy: fetchPolicy,
1562
+ errorPolicy: errorPolicy,
1563
+ context: context,
1564
+ update: updateWithProxyFn,
1565
+ updateQueries: updateQueries,
1566
+ awaitRefetchQueries: awaitRefetchQueries,
1567
+ refetchQueries: refetchQueries,
1568
+ removeOptimistic: isOptimistic ? mutationId : void 0,
1569
+ onQueryUpdated: onQueryUpdated,
1570
+ keepRootFields: keepRootFields,
1571
+ });
1572
+ }).subscribe({
1573
+ next: function (storeResult) {
1574
+ self.broadcastQueries();
1575
+ // Since mutations might receive multiple payloads from the
1576
+ // ApolloLink chain (e.g. when used with @defer),
1577
+ // we resolve with a SingleExecutionResult or after the final
1578
+ // ExecutionPatchResult has arrived and we have assembled the
1579
+ // multipart response into a single result.
1580
+ if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
1581
+ resolve(index.__assign(index.__assign({}, storeResult), { data: self.maskOperation({
1582
+ document: mutation,
1583
+ data: storeResult.data,
1584
+ fetchPolicy: fetchPolicy,
1585
+ id: mutationId,
1586
+ }) }));
1587
+ }
1588
+ },
1589
+ error: function (err) {
1590
+ if (mutationStoreValue) {
1591
+ mutationStoreValue.loading = false;
1592
+ mutationStoreValue.error = err;
1593
+ }
1594
+ if (isOptimistic) {
1595
+ self.cache.removeOptimistic(mutationId);
1596
+ }
1597
+ self.broadcastQueries();
1598
+ reject(err instanceof index.ApolloError ? err : (new index.ApolloError({
1599
+ networkError: err,
1600
+ })));
1601
+ },
1602
+ });
1603
+ })];
1604
+ }
1605
+ });
1606
+ });
1607
+ };
1608
+ QueryManager.prototype.markMutationResult = function (mutation, cache) {
1609
+ var _this = this;
1610
+ if (cache === void 0) { cache = this.cache; }
1611
+ var result = mutation.result;
1612
+ var cacheWrites = [];
1613
+ var skipCache = mutation.fetchPolicy === "no-cache";
1614
+ if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
1615
+ if (!index.isExecutionPatchIncrementalResult(result)) {
1616
+ cacheWrites.push({
1617
+ result: result.data,
1618
+ dataId: "ROOT_MUTATION",
1619
+ query: mutation.document,
1620
+ variables: mutation.variables,
1621
+ });
1622
+ }
1623
+ if (index.isExecutionPatchIncrementalResult(result) &&
1624
+ index.isNonEmptyArray(result.incremental)) {
1625
+ var diff = cache.diff({
1626
+ id: "ROOT_MUTATION",
1627
+ // The cache complains if passed a mutation where it expects a
1628
+ // query, so we transform mutations and subscriptions to queries
1629
+ // (only once, thanks to this.transformCache).
1630
+ query: this.getDocumentInfo(mutation.document).asQuery,
1631
+ variables: mutation.variables,
1632
+ optimistic: false,
1633
+ returnPartialData: true,
1634
+ });
1635
+ var mergedData = void 0;
1636
+ if (diff.result) {
1637
+ mergedData = index.mergeIncrementalData(diff.result, result);
1638
+ }
1639
+ if (typeof mergedData !== "undefined") {
1640
+ // cast the ExecutionPatchResult to FetchResult here since
1641
+ // ExecutionPatchResult never has `data` when returned from the server
1642
+ result.data = mergedData;
1643
+ cacheWrites.push({
1644
+ result: mergedData,
1645
+ dataId: "ROOT_MUTATION",
1646
+ query: mutation.document,
1647
+ variables: mutation.variables,
1648
+ });
1649
+ }
1650
+ }
1651
+ var updateQueries_1 = mutation.updateQueries;
1652
+ if (updateQueries_1) {
1653
+ this.queries.forEach(function (_a, queryId) {
1654
+ var observableQuery = _a.observableQuery;
1655
+ var queryName = observableQuery && observableQuery.queryName;
1656
+ if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
1657
+ return;
1658
+ }
1659
+ var updater = updateQueries_1[queryName];
1660
+ var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
1661
+ // Read the current query result from the store.
1662
+ var _c = cache.diff({
1663
+ query: document,
1664
+ variables: variables,
1665
+ returnPartialData: true,
1666
+ optimistic: false,
1667
+ }), currentQueryResult = _c.result, complete = _c.complete;
1668
+ if (complete && currentQueryResult) {
1669
+ // Run our reducer using the current query result and the mutation result.
1670
+ var nextQueryResult = updater(currentQueryResult, {
1671
+ mutationResult: result,
1672
+ queryName: (document && index.getOperationName(document)) || void 0,
1673
+ queryVariables: variables,
1674
+ });
1675
+ // Write the modified result back into the store if we got a new result.
1676
+ if (nextQueryResult) {
1677
+ cacheWrites.push({
1678
+ result: nextQueryResult,
1679
+ dataId: "ROOT_QUERY",
1680
+ query: document,
1681
+ variables: variables,
1682
+ });
1683
+ }
1684
+ }
1685
+ });
1686
+ }
1687
+ }
1688
+ if (cacheWrites.length > 0 ||
1689
+ (mutation.refetchQueries || "").length > 0 ||
1690
+ mutation.update ||
1691
+ mutation.onQueryUpdated ||
1692
+ mutation.removeOptimistic) {
1693
+ var results_1 = [];
1694
+ this.refetchQueries({
1695
+ updateCache: function (cache) {
1696
+ if (!skipCache) {
1697
+ cacheWrites.forEach(function (write) { return cache.write(write); });
1698
+ }
1699
+ // If the mutation has some writes associated with it then we need to
1700
+ // apply those writes to the store by running this reducer again with
1701
+ // a write action.
1702
+ var update = mutation.update;
1703
+ // Determine whether result is a SingleExecutionResult,
1704
+ // or the final ExecutionPatchResult.
1705
+ var isFinalResult = !index.isExecutionPatchResult(result) ||
1706
+ (index.isExecutionPatchIncrementalResult(result) && !result.hasNext);
1707
+ if (update) {
1708
+ if (!skipCache) {
1709
+ // Re-read the ROOT_MUTATION data we just wrote into the cache
1710
+ // (the first cache.write call in the cacheWrites.forEach loop
1711
+ // above), so field read functions have a chance to run for
1712
+ // fields within mutation result objects.
1713
+ var diff = cache.diff({
1714
+ id: "ROOT_MUTATION",
1715
+ // The cache complains if passed a mutation where it expects a
1716
+ // query, so we transform mutations and subscriptions to queries
1717
+ // (only once, thanks to this.transformCache).
1718
+ query: _this.getDocumentInfo(mutation.document).asQuery,
1719
+ variables: mutation.variables,
1720
+ optimistic: false,
1721
+ returnPartialData: true,
1722
+ });
1723
+ if (diff.complete) {
1724
+ result = index.__assign(index.__assign({}, result), { data: diff.result });
1725
+ if ("incremental" in result) {
1726
+ delete result.incremental;
1727
+ }
1728
+ if ("hasNext" in result) {
1729
+ delete result.hasNext;
1730
+ }
1731
+ }
1732
+ }
1733
+ // If we've received the whole response,
1734
+ // either a SingleExecutionResult or the final ExecutionPatchResult,
1735
+ // call the update function.
1736
+ if (isFinalResult) {
1737
+ update(cache, result, {
1738
+ context: mutation.context,
1739
+ variables: mutation.variables,
1740
+ });
1741
+ }
1742
+ }
1743
+ // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it
1744
+ // shallow to allow rolling back optimistic evictions.
1745
+ if (!skipCache && !mutation.keepRootFields && isFinalResult) {
1746
+ cache.modify({
1747
+ id: "ROOT_MUTATION",
1748
+ fields: function (value, _a) {
1749
+ var fieldName = _a.fieldName, DELETE = _a.DELETE;
1750
+ return fieldName === "__typename" ? value : DELETE;
1751
+ },
1752
+ });
1753
+ }
1754
+ },
1755
+ include: mutation.refetchQueries,
1756
+ // Write the final mutation.result to the root layer of the cache.
1757
+ optimistic: false,
1758
+ // Remove the corresponding optimistic layer at the same time as we
1759
+ // write the final non-optimistic result.
1760
+ removeOptimistic: mutation.removeOptimistic,
1761
+ // Let the caller of client.mutate optionally determine the refetching
1762
+ // behavior for watched queries after the mutation.update function runs.
1763
+ // If no onQueryUpdated function was provided for this mutation, pass
1764
+ // null instead of undefined to disable the default refetching behavior.
1765
+ onQueryUpdated: mutation.onQueryUpdated || null,
1766
+ }).forEach(function (result) { return results_1.push(result); });
1767
+ if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
1768
+ // Returning a promise here makes the mutation await that promise, so we
1769
+ // include results in that promise's work if awaitRefetchQueries or an
1770
+ // onQueryUpdated function was specified.
1771
+ return Promise.all(results_1).then(function () { return result; });
1772
+ }
1773
+ }
1774
+ return Promise.resolve(result);
1775
+ };
1776
+ QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
1777
+ var _this = this;
1778
+ var data = typeof optimisticResponse === "function" ?
1779
+ optimisticResponse(mutation.variables, { IGNORE: IGNORE })
1780
+ : optimisticResponse;
1781
+ if (data === IGNORE) {
1782
+ return false;
1783
+ }
1784
+ this.cache.recordOptimisticTransaction(function (cache) {
1785
+ try {
1786
+ _this.markMutationResult(index.__assign(index.__assign({}, mutation), { result: { data: data } }), cache);
1787
+ }
1788
+ catch (error) {
1789
+ globalThis.__DEV__ !== false && index.invariant.error(error);
1790
+ }
1791
+ }, mutation.mutationId);
1792
+ return true;
1793
+ };
1794
+ QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
1795
+ return this.fetchConcastWithInfo(this.getOrCreateQuery(queryId), options, networkStatus).concast.promise;
1796
+ };
1797
+ QueryManager.prototype.getQueryStore = function () {
1798
+ var store = Object.create(null);
1799
+ this.queries.forEach(function (info, queryId) {
1800
+ store[queryId] = {
1801
+ variables: info.variables,
1802
+ networkStatus: info.networkStatus,
1803
+ networkError: info.networkError,
1804
+ graphQLErrors: info.graphQLErrors,
1805
+ };
1806
+ });
1807
+ return store;
1808
+ };
1809
+ QueryManager.prototype.resetErrors = function (queryId) {
1810
+ var queryInfo = this.queries.get(queryId);
1811
+ if (queryInfo) {
1812
+ queryInfo.networkError = undefined;
1813
+ queryInfo.graphQLErrors = [];
1814
+ }
1815
+ };
1816
+ QueryManager.prototype.transform = function (document) {
1817
+ return this.documentTransform.transformDocument(document);
1818
+ };
1819
+ QueryManager.prototype.getDocumentInfo = function (document) {
1820
+ var transformCache = this.transformCache;
1821
+ if (!transformCache.has(document)) {
1822
+ var cacheEntry = {
1823
+ // TODO These three calls (hasClientExports, shouldForceResolvers, and
1824
+ // usesNonreactiveDirective) are performing independent full traversals
1825
+ // of the transformed document. We should consider merging these
1826
+ // traversals into a single pass in the future, though the work is
1827
+ // cached after the first time.
1828
+ hasClientExports: index.hasClientExports(document),
1829
+ hasForcedResolvers: this.localState.shouldForceResolvers(document),
1830
+ hasNonreactiveDirective: index.hasDirectives(["nonreactive"], document),
1831
+ nonReactiveQuery: index.addNonReactiveToNamedFragments(document),
1832
+ clientQuery: this.localState.clientQuery(document),
1833
+ serverQuery: index.removeDirectivesFromDocument([
1834
+ { name: "client", remove: true },
1835
+ { name: "connection" },
1836
+ { name: "nonreactive" },
1837
+ { name: "unmask" },
1838
+ ], document),
1839
+ defaultVars: index.getDefaultValues(index.getOperationDefinition(document)),
1840
+ // Transform any mutation or subscription operations to query operations
1841
+ // so we can read/write them from/to the cache.
1842
+ asQuery: index.__assign(index.__assign({}, document), { definitions: document.definitions.map(function (def) {
1843
+ if (def.kind === "OperationDefinition" &&
1844
+ def.operation !== "query") {
1845
+ return index.__assign(index.__assign({}, def), { operation: "query" });
1846
+ }
1847
+ return def;
1848
+ }) }),
1849
+ };
1850
+ transformCache.set(document, cacheEntry);
1851
+ }
1852
+ return transformCache.get(document);
1853
+ };
1854
+ QueryManager.prototype.getVariables = function (document, variables) {
1855
+ return index.__assign(index.__assign({}, this.getDocumentInfo(document).defaultVars), variables);
1856
+ };
1857
+ QueryManager.prototype.watchQuery = function (options) {
1858
+ var query = this.transform(options.query);
1859
+ // assign variable default values if supplied
1860
+ // NOTE: We don't modify options.query here with the transformed query to
1861
+ // ensure observable.options.query is set to the raw untransformed query.
1862
+ options = index.__assign(index.__assign({}, options), { variables: this.getVariables(query, options.variables) });
1863
+ if (typeof options.notifyOnNetworkStatusChange === "undefined") {
1864
+ options.notifyOnNetworkStatusChange = false;
1865
+ }
1866
+ var queryInfo = new QueryInfo(this);
1867
+ var observable = new ObservableQuery({
1868
+ queryManager: this,
1869
+ queryInfo: queryInfo,
1870
+ options: options,
1871
+ });
1872
+ observable["lastQuery"] = query;
1873
+ if (!ObservableQuery["inactiveOnCreation"].getValue()) {
1874
+ this.queries.set(observable.queryId, queryInfo);
1875
+ }
1876
+ // We give queryInfo the transformed query to ensure the first cache diff
1877
+ // uses the transformed query instead of the raw query
1878
+ queryInfo.init({
1879
+ document: query,
1880
+ observableQuery: observable,
1881
+ variables: observable.variables,
1882
+ });
1883
+ return observable;
1884
+ };
1885
+ QueryManager.prototype.query = function (options, queryId) {
1886
+ var _this = this;
1887
+ if (queryId === void 0) { queryId = this.generateQueryId(); }
1888
+ index.invariant(options.query, 38);
1889
+ index.invariant(options.query.kind === "Document", 39);
1890
+ index.invariant(!options.returnPartialData, 40);
1891
+ index.invariant(!options.pollInterval, 41);
1892
+ var query = this.transform(options.query);
1893
+ return this.fetchQuery(queryId, index.__assign(index.__assign({}, options), { query: query }))
1894
+ .then(function (result) {
1895
+ return result && index.__assign(index.__assign({}, result), { data: _this.maskOperation({
1896
+ document: query,
1897
+ data: result.data,
1898
+ fetchPolicy: options.fetchPolicy,
1899
+ id: queryId,
1900
+ }) });
1901
+ })
1902
+ .finally(function () { return _this.stopQuery(queryId); });
1903
+ };
1904
+ QueryManager.prototype.generateQueryId = function () {
1905
+ return String(this.queryIdCounter++);
1906
+ };
1907
+ QueryManager.prototype.generateRequestId = function () {
1908
+ return this.requestIdCounter++;
1909
+ };
1910
+ QueryManager.prototype.generateMutationId = function () {
1911
+ return String(this.mutationIdCounter++);
1912
+ };
1913
+ QueryManager.prototype.stopQueryInStore = function (queryId) {
1914
+ this.stopQueryInStoreNoBroadcast(queryId);
1915
+ this.broadcastQueries();
1916
+ };
1917
+ QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
1918
+ var queryInfo = this.queries.get(queryId);
1919
+ if (queryInfo)
1920
+ queryInfo.stop();
1921
+ };
1922
+ QueryManager.prototype.clearStore = function (options) {
1923
+ if (options === void 0) { options = {
1924
+ discardWatches: true,
1925
+ }; }
1926
+ // Before we have sent the reset action to the store, we can no longer
1927
+ // rely on the results returned by in-flight requests since these may
1928
+ // depend on values that previously existed in the data portion of the
1929
+ // store. So, we cancel the promises and observers that we have issued
1930
+ // so far and not yet resolved (in the case of queries).
1931
+ this.cancelPendingFetches(index.newInvariantError(42));
1932
+ this.queries.forEach(function (queryInfo) {
1933
+ if (queryInfo.observableQuery) {
1934
+ // Set loading to true so listeners don't trigger unless they want
1935
+ // results with partial data.
1936
+ queryInfo.networkStatus = NetworkStatus.loading;
1937
+ }
1938
+ else {
1939
+ queryInfo.stop();
1940
+ }
1941
+ });
1942
+ if (this.mutationStore) {
1943
+ this.mutationStore = Object.create(null);
1944
+ }
1945
+ // begin removing data from the store
1946
+ return this.cache.reset(options);
1947
+ };
1948
+ QueryManager.prototype.getObservableQueries = function (include) {
1949
+ var _this = this;
1950
+ if (include === void 0) { include = "active"; }
1951
+ var queries = new Map();
1952
+ var queryNames = new Map();
1953
+ var queryNamesAndQueryStrings = new Map();
1954
+ var legacyQueryOptions = new Set();
1955
+ if (Array.isArray(include)) {
1956
+ include.forEach(function (desc) {
1957
+ if (typeof desc === "string") {
1958
+ queryNames.set(desc, desc);
1959
+ queryNamesAndQueryStrings.set(desc, false);
1960
+ }
1961
+ else if (index.isDocumentNode(desc)) {
1962
+ var queryString = index.print(_this.transform(desc));
1963
+ queryNames.set(queryString, index.getOperationName(desc));
1964
+ queryNamesAndQueryStrings.set(queryString, false);
1965
+ }
1966
+ else if (index.isNonNullObject(desc) && desc.query) {
1967
+ legacyQueryOptions.add(desc);
1968
+ }
1969
+ });
1970
+ }
1971
+ this.queries.forEach(function (_a, queryId) {
1972
+ var oq = _a.observableQuery, document = _a.document;
1973
+ if (oq) {
1974
+ if (include === "all") {
1975
+ queries.set(queryId, oq);
1976
+ return;
1977
+ }
1978
+ var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
1979
+ if (fetchPolicy === "standby" ||
1980
+ (include === "active" && !oq.hasObservers())) {
1981
+ return;
1982
+ }
1983
+ if (include === "active" ||
1984
+ (queryName && queryNamesAndQueryStrings.has(queryName)) ||
1985
+ (document && queryNamesAndQueryStrings.has(index.print(document)))) {
1986
+ queries.set(queryId, oq);
1987
+ if (queryName)
1988
+ queryNamesAndQueryStrings.set(queryName, true);
1989
+ if (document)
1990
+ queryNamesAndQueryStrings.set(index.print(document), true);
1991
+ }
1992
+ }
1993
+ });
1994
+ if (legacyQueryOptions.size) {
1995
+ legacyQueryOptions.forEach(function (options) {
1996
+ // We will be issuing a fresh network request for this query, so we
1997
+ // pre-allocate a new query ID here, using a special prefix to enable
1998
+ // cleaning up these temporary queries later, after fetching.
1999
+ var queryId = index.makeUniqueId("legacyOneTimeQuery");
2000
+ var queryInfo = _this.getOrCreateQuery(queryId).init({
2001
+ document: options.query,
2002
+ variables: options.variables,
2003
+ });
2004
+ var oq = new ObservableQuery({
2005
+ queryManager: _this,
2006
+ queryInfo: queryInfo,
2007
+ options: index.__assign(index.__assign({}, options), { fetchPolicy: "network-only" }),
2008
+ });
2009
+ index.invariant(oq.queryId === queryId);
2010
+ queryInfo.setObservableQuery(oq);
2011
+ queries.set(queryId, oq);
2012
+ });
2013
+ }
2014
+ if (globalThis.__DEV__ !== false && queryNamesAndQueryStrings.size) {
2015
+ queryNamesAndQueryStrings.forEach(function (included, nameOrQueryString) {
2016
+ if (!included) {
2017
+ var queryName = queryNames.get(nameOrQueryString);
2018
+ if (queryName) {
2019
+ globalThis.__DEV__ !== false && index.invariant.warn(43, queryName);
2020
+ }
2021
+ else {
2022
+ globalThis.__DEV__ !== false && index.invariant.warn(44);
2023
+ }
2024
+ }
2025
+ });
2026
+ }
2027
+ return queries;
2028
+ };
2029
+ QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
2030
+ var _this = this;
2031
+ if (includeStandby === void 0) { includeStandby = false; }
2032
+ var observableQueryPromises = [];
2033
+ this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
2034
+ var fetchPolicy = observableQuery.options.fetchPolicy;
2035
+ index.muteDeprecations("resetLastResults", function () {
2036
+ return observableQuery.resetLastResults();
2037
+ });
2038
+ if (includeStandby ||
2039
+ (fetchPolicy !== "standby" && fetchPolicy !== "cache-only")) {
2040
+ observableQueryPromises.push(observableQuery.refetch());
2041
+ }
2042
+ (_this.queries.get(queryId) || observableQuery["queryInfo"]).setDiff(null);
2043
+ });
2044
+ this.broadcastQueries();
2045
+ return Promise.all(observableQueryPromises);
2046
+ };
2047
+ QueryManager.prototype.startGraphQLSubscription = function (options) {
2048
+ var _this = this;
2049
+ var query = options.query, variables = options.variables;
2050
+ var fetchPolicy = options.fetchPolicy, _a = options.errorPolicy, errorPolicy = _a === void 0 ? "none" : _a, _b = options.context, context = _b === void 0 ? {} : _b, _c = options.extensions, extensions = _c === void 0 ? {} : _c;
2051
+ query = this.transform(query);
2052
+ variables = this.getVariables(query, variables);
2053
+ var makeObservable = function (variables) {
2054
+ return _this.getObservableFromLink(query, context, variables, extensions).map(function (result) {
2055
+ if (fetchPolicy !== "no-cache") {
2056
+ // the subscription interface should handle not sending us results we no longer subscribe to.
2057
+ // XXX I don't think we ever send in an object with errors, but we might in the future...
2058
+ if (shouldWriteResult(result, errorPolicy)) {
2059
+ _this.cache.write({
2060
+ query: query,
2061
+ result: result.data,
2062
+ dataId: "ROOT_SUBSCRIPTION",
2063
+ variables: variables,
2064
+ });
2065
+ }
2066
+ _this.broadcastQueries();
2067
+ }
2068
+ var hasErrors = index.graphQLResultHasError(result);
2069
+ var hasProtocolErrors = index.graphQLResultHasProtocolErrors(result);
2070
+ if (hasErrors || hasProtocolErrors) {
2071
+ var errors = {};
2072
+ if (hasErrors) {
2073
+ errors.graphQLErrors = result.errors;
2074
+ }
2075
+ if (hasProtocolErrors) {
2076
+ errors.protocolErrors = result.extensions[index.PROTOCOL_ERRORS_SYMBOL];
2077
+ }
2078
+ // `errorPolicy` is a mechanism for handling GraphQL errors, according
2079
+ // to our documentation, so we throw protocol errors regardless of the
2080
+ // set error policy.
2081
+ if (errorPolicy === "none" || hasProtocolErrors) {
2082
+ throw new index.ApolloError(errors);
2083
+ }
2084
+ }
2085
+ if (errorPolicy === "ignore") {
2086
+ delete result.errors;
2087
+ }
2088
+ return result;
2089
+ });
2090
+ };
2091
+ if (this.getDocumentInfo(query).hasClientExports) {
2092
+ var observablePromise_1 = this.localState
2093
+ .addExportedVariables(query, variables, context)
2094
+ .then(makeObservable);
2095
+ return new index.Observable(function (observer) {
2096
+ var sub = null;
2097
+ observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);
2098
+ return function () { return sub && sub.unsubscribe(); };
2099
+ });
2100
+ }
2101
+ return makeObservable(variables);
2102
+ };
2103
+ QueryManager.prototype.stopQuery = function (queryId) {
2104
+ this.stopQueryNoBroadcast(queryId);
2105
+ this.broadcastQueries();
2106
+ };
2107
+ QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
2108
+ this.stopQueryInStoreNoBroadcast(queryId);
2109
+ this.removeQuery(queryId);
2110
+ };
2111
+ QueryManager.prototype.removeQuery = function (queryId) {
2112
+ var _a;
2113
+ // teardown all links
2114
+ // Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises
2115
+ // that each add their reject functions to fetchCancelFns.
2116
+ // A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.
2117
+ // The same queryId could have two rejection fns for two promises
2118
+ this.fetchCancelFns.delete(queryId);
2119
+ if (this.queries.has(queryId)) {
2120
+ (_a = this.queries.get(queryId)) === null || _a === void 0 ? void 0 : _a.stop();
2121
+ this.queries.delete(queryId);
2122
+ }
2123
+ };
2124
+ QueryManager.prototype.broadcastQueries = function () {
2125
+ if (this.onBroadcast)
2126
+ this.onBroadcast();
2127
+ this.queries.forEach(function (info) { var _a; return (_a = info.observableQuery) === null || _a === void 0 ? void 0 : _a["notify"](); });
2128
+ };
2129
+ QueryManager.prototype.getLocalState = function () {
2130
+ return this.localState;
2131
+ };
2132
+ QueryManager.prototype.getObservableFromLink = function (query, context, variables, extensions,
2133
+ // Prefer context.queryDeduplication if specified.
2134
+ deduplication) {
2135
+ var _this = this;
2136
+ var _a;
2137
+ if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
2138
+ var observable;
2139
+ var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;
2140
+ if (serverQuery) {
2141
+ var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;
2142
+ var operation = {
2143
+ query: serverQuery,
2144
+ variables: variables,
2145
+ operationName: index.getOperationName(serverQuery) || void 0,
2146
+ context: this.prepareContext(index.__assign(index.__assign({}, context), { forceFetch: !deduplication })),
2147
+ extensions: extensions,
2148
+ };
2149
+ context = operation.context;
2150
+ if (deduplication) {
2151
+ var printedServerQuery_1 = index.print(serverQuery);
2152
+ var varJson_1 = index.canonicalStringify(variables);
2153
+ var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);
2154
+ observable = entry.observable;
2155
+ if (!observable) {
2156
+ var concast_1 = new index.Concast([
2157
+ index.execute(link, operation),
2158
+ ]);
2159
+ observable = entry.observable = concast_1;
2160
+ concast_1.beforeNext(function cb(method, arg) {
2161
+ if (method === "next" && "hasNext" in arg && arg.hasNext) {
2162
+ concast_1.beforeNext(cb);
2163
+ }
2164
+ else {
2165
+ inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);
2166
+ }
2167
+ });
2168
+ }
2169
+ }
2170
+ else {
2171
+ observable = new index.Concast([
2172
+ index.execute(link, operation),
2173
+ ]);
2174
+ }
2175
+ }
2176
+ else {
2177
+ observable = new index.Concast([index.Observable.of({ data: {} })]);
2178
+ context = this.prepareContext(context);
2179
+ }
2180
+ if (clientQuery) {
2181
+ observable = index.asyncMap(observable, function (result) {
2182
+ return _this.localState.runResolvers({
2183
+ document: clientQuery,
2184
+ remoteResult: result,
2185
+ context: context,
2186
+ variables: variables,
2187
+ });
2188
+ });
2189
+ }
2190
+ return observable;
2191
+ };
2192
+ QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
2193
+ var requestId = (queryInfo.lastRequestId = this.generateRequestId());
2194
+ // Performing transformForLink here gives this.cache a chance to fill in
2195
+ // missing fragment definitions (for example) before sending this document
2196
+ // through the link chain.
2197
+ var linkDocument = this.cache.transformForLink(options.query);
2198
+ return index.asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
2199
+ var graphQLErrors = index.getGraphQLErrorsFromResult(result);
2200
+ var hasErrors = graphQLErrors.length > 0;
2201
+ var errorPolicy = options.errorPolicy;
2202
+ // If we interrupted this request by calling getResultsFromLink again
2203
+ // with the same QueryInfo object, we ignore the old results.
2204
+ if (requestId >= queryInfo.lastRequestId) {
2205
+ if (hasErrors && errorPolicy === "none") {
2206
+ // Throwing here effectively calls observer.error.
2207
+ throw queryInfo.markError(new index.ApolloError({
2208
+ graphQLErrors: graphQLErrors,
2209
+ }));
2210
+ }
2211
+ // Use linkDocument rather than queryInfo.document so the
2212
+ // operation/fragments used to write the result are the same as the
2213
+ // ones used to obtain it from the link.
2214
+ queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
2215
+ queryInfo.markReady();
2216
+ }
2217
+ var aqr = {
2218
+ data: result.data,
2219
+ loading: false,
2220
+ networkStatus: NetworkStatus.ready,
2221
+ };
2222
+ // In the case we start multiple network requests simulatenously, we
2223
+ // want to ensure we properly set `data` if we're reporting on an old
2224
+ // result which will not be caught by the conditional above that ends up
2225
+ // throwing the markError result.
2226
+ if (hasErrors && errorPolicy === "none") {
2227
+ aqr.data = void 0;
2228
+ }
2229
+ if (hasErrors && errorPolicy !== "ignore") {
2230
+ aqr.errors = graphQLErrors;
2231
+ aqr.networkStatus = NetworkStatus.error;
2232
+ }
2233
+ return aqr;
2234
+ }, function (networkError) {
2235
+ var error = index.isApolloError(networkError) ? networkError : (new index.ApolloError({ networkError: networkError }));
2236
+ // Avoid storing errors from older interrupted queries.
2237
+ if (requestId >= queryInfo.lastRequestId) {
2238
+ queryInfo.markError(error);
2239
+ }
2240
+ throw error;
2241
+ });
2242
+ };
2243
+ QueryManager.prototype.fetchConcastWithInfo = function (queryInfo, options,
2244
+ // The initial networkStatus for this fetch, most often
2245
+ // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
2246
+ // or setVariables.
2247
+ networkStatus, query) {
2248
+ var _this = this;
2249
+ if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }
2250
+ if (query === void 0) { query = options.query; }
2251
+ var variables = this.getVariables(query, options.variables);
2252
+ var defaults = this.defaultOptions.watchQuery;
2253
+ var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
2254
+ var normalized = Object.assign({}, options, {
2255
+ query: query,
2256
+ variables: variables,
2257
+ fetchPolicy: fetchPolicy,
2258
+ errorPolicy: errorPolicy,
2259
+ returnPartialData: returnPartialData,
2260
+ notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
2261
+ context: context,
2262
+ });
2263
+ var fromVariables = function (variables) {
2264
+ // Since normalized is always a fresh copy of options, it's safe to
2265
+ // modify its properties here, rather than creating yet another new
2266
+ // WatchQueryOptions object.
2267
+ normalized.variables = variables;
2268
+ var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
2269
+ if (
2270
+ // If we're in standby, postpone advancing options.fetchPolicy using
2271
+ // applyNextFetchPolicy.
2272
+ normalized.fetchPolicy !== "standby" &&
2273
+ // The "standby" policy currently returns [] from fetchQueryByPolicy, so
2274
+ // this is another way to detect when nothing was done/fetched.
2275
+ sourcesWithInfo.sources.length > 0 &&
2276
+ queryInfo.observableQuery) {
2277
+ queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
2278
+ }
2279
+ return sourcesWithInfo;
2280
+ };
2281
+ // This cancel function needs to be set before the concast is created,
2282
+ // in case concast creation synchronously cancels the request.
2283
+ var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryInfo.queryId); };
2284
+ this.fetchCancelFns.set(queryInfo.queryId, function (reason) {
2285
+ cleanupCancelFn();
2286
+ // This delay ensures the concast variable has been initialized.
2287
+ setTimeout(function () { return concast.cancel(reason); });
2288
+ });
2289
+ var concast, containsDataFromLink;
2290
+ // If the query has @export(as: ...) directives, then we need to
2291
+ // process those directives asynchronously. When there are no
2292
+ // @export directives (the common case), we deliberately avoid
2293
+ // wrapping the result of this.fetchQueryByPolicy in a Promise,
2294
+ // since the timing of result delivery is (unfortunately) important
2295
+ // for backwards compatibility. TODO This code could be simpler if
2296
+ // we deprecated and removed LocalState.
2297
+ if (this.getDocumentInfo(normalized.query).hasClientExports) {
2298
+ concast = new index.Concast(this.localState
2299
+ .addExportedVariables(normalized.query, normalized.variables, normalized.context)
2300
+ .then(fromVariables)
2301
+ .then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
2302
+ // there is just no way we can synchronously get the *right* value here,
2303
+ // so we will assume `true`, which is the behaviour before the bug fix in
2304
+ // #10597. This means that bug is not fixed in that case, and is probably
2305
+ // un-fixable with reasonable effort for the edge case of @export as
2306
+ // directives.
2307
+ containsDataFromLink = true;
2308
+ }
2309
+ else {
2310
+ var sourcesWithInfo = fromVariables(normalized.variables);
2311
+ containsDataFromLink = sourcesWithInfo.fromLink;
2312
+ concast = new index.Concast(sourcesWithInfo.sources);
2313
+ }
2314
+ concast.promise.then(cleanupCancelFn, cleanupCancelFn);
2315
+ return {
2316
+ concast: concast,
2317
+ fromLink: containsDataFromLink,
2318
+ };
2319
+ };
2320
+ QueryManager.prototype.refetchQueries = function (_a) {
2321
+ var _this = this;
2322
+ var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? index.makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
2323
+ var includedQueriesById = new Map();
2324
+ if (include) {
2325
+ this.getObservableQueries(include).forEach(function (oq, queryId) {
2326
+ includedQueriesById.set(queryId, {
2327
+ oq: oq,
2328
+ lastDiff: (_this.queries.get(queryId) || oq["queryInfo"]).getDiff(),
2329
+ });
2330
+ });
2331
+ }
2332
+ var results = new Map();
2333
+ if (updateCache) {
2334
+ this.cache.batch({
2335
+ update: updateCache,
2336
+ // Since you can perform any combination of cache reads and/or writes in
2337
+ // the cache.batch update function, its optimistic option can be either
2338
+ // a boolean or a string, representing three distinct modes of
2339
+ // operation:
2340
+ //
2341
+ // * false: read/write only the root layer
2342
+ // * true: read/write the topmost layer
2343
+ // * string: read/write a fresh optimistic layer with that ID string
2344
+ //
2345
+ // When typeof optimistic === "string", a new optimistic layer will be
2346
+ // temporarily created within cache.batch with that string as its ID. If
2347
+ // we then pass that same string as the removeOptimistic option, we can
2348
+ // make cache.batch immediately remove the optimistic layer after
2349
+ // running the updateCache function, triggering only one broadcast.
2350
+ //
2351
+ // However, the refetchQueries method accepts only true or false for its
2352
+ // optimistic option (not string). We interpret true to mean a temporary
2353
+ // optimistic layer should be created, to allow efficiently rolling back
2354
+ // the effect of the updateCache function, which involves passing a
2355
+ // string instead of true as the optimistic option to cache.batch, when
2356
+ // refetchQueries receives optimistic: true.
2357
+ //
2358
+ // In other words, we are deliberately not supporting the use case of
2359
+ // writing to an *existing* optimistic layer (using the refetchQueries
2360
+ // updateCache function), since that would potentially interfere with
2361
+ // other optimistic updates in progress. Instead, you can read/write
2362
+ // only the root layer by passing optimistic: false to refetchQueries,
2363
+ // or you can read/write a brand new optimistic layer that will be
2364
+ // automatically removed by passing optimistic: true.
2365
+ optimistic: (optimistic && removeOptimistic) || false,
2366
+ // The removeOptimistic option can also be provided by itself, even if
2367
+ // optimistic === false, to remove some previously-added optimistic
2368
+ // layer safely and efficiently, like we do in markMutationResult.
2369
+ //
2370
+ // If an explicit removeOptimistic string is provided with optimistic:
2371
+ // true, the removeOptimistic string will determine the ID of the
2372
+ // temporary optimistic layer, in case that ever matters.
2373
+ removeOptimistic: removeOptimistic,
2374
+ onWatchUpdated: function (watch, diff, lastDiff) {
2375
+ var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;
2376
+ if (oq) {
2377
+ if (onQueryUpdated) {
2378
+ // Since we're about to handle this query now, remove it from
2379
+ // includedQueriesById, in case it was added earlier because of
2380
+ // options.include.
2381
+ includedQueriesById.delete(oq.queryId);
2382
+ var result = onQueryUpdated(oq, diff, lastDiff);
2383
+ if (result === true) {
2384
+ // The onQueryUpdated function requested the default refetching
2385
+ // behavior by returning true.
2386
+ result = oq.refetch();
2387
+ }
2388
+ // Record the result in the results Map, as long as onQueryUpdated
2389
+ // did not return false to skip/ignore this result.
2390
+ if (result !== false) {
2391
+ results.set(oq, result);
2392
+ }
2393
+ // Allow the default cache broadcast to happen, except when
2394
+ // onQueryUpdated returns false.
2395
+ return result;
2396
+ }
2397
+ if (onQueryUpdated !== null) {
2398
+ // If we don't have an onQueryUpdated function, and onQueryUpdated
2399
+ // was not disabled by passing null, make sure this query is
2400
+ // "included" like any other options.include-specified query.
2401
+ includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
2402
+ }
2403
+ }
2404
+ },
2405
+ });
2406
+ }
2407
+ if (includedQueriesById.size) {
2408
+ includedQueriesById.forEach(function (_a, queryId) {
2409
+ var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
2410
+ var result;
2411
+ // If onQueryUpdated is provided, we want to use it for all included
2412
+ // queries, even the QueryOptions ones.
2413
+ if (onQueryUpdated) {
2414
+ if (!diff) {
2415
+ diff = index.muteDeprecations("canonizeResults", function () {
2416
+ return _this.cache.diff(oq["queryInfo"]["getDiffOptions"]());
2417
+ });
2418
+ }
2419
+ result = onQueryUpdated(oq, diff, lastDiff);
2420
+ }
2421
+ // Otherwise, we fall back to refetching.
2422
+ if (!onQueryUpdated || result === true) {
2423
+ result = oq.refetch();
2424
+ }
2425
+ if (result !== false) {
2426
+ results.set(oq, result);
2427
+ }
2428
+ if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
2429
+ _this.stopQueryNoBroadcast(queryId);
2430
+ }
2431
+ });
2432
+ }
2433
+ if (removeOptimistic) {
2434
+ // In case no updateCache callback was provided (so cache.batch was not
2435
+ // called above, and thus did not already remove the optimistic layer),
2436
+ // remove it here. Since this is a no-op when the layer has already been
2437
+ // removed, we do it even if we called cache.batch above, since it's
2438
+ // possible this.cache is an instance of some ApolloCache subclass other
2439
+ // than InMemoryCache, and does not fully support the removeOptimistic
2440
+ // option for cache.batch.
2441
+ this.cache.removeOptimistic(removeOptimistic);
2442
+ }
2443
+ return results;
2444
+ };
2445
+ QueryManager.prototype.maskOperation = function (options) {
2446
+ var _a, _b, _c;
2447
+ var document = options.document, data = options.data;
2448
+ if (globalThis.__DEV__ !== false) {
2449
+ var fetchPolicy = options.fetchPolicy, id = options.id;
2450
+ var operationType = (_a = index.getOperationDefinition(document)) === null || _a === void 0 ? void 0 : _a.operation;
2451
+ var operationId = ((_b = operationType === null || operationType === void 0 ? void 0 : operationType[0]) !== null && _b !== void 0 ? _b : "o") + id;
2452
+ if (this.dataMasking &&
2453
+ fetchPolicy === "no-cache" &&
2454
+ !index.isFullyUnmaskedOperation(document) &&
2455
+ !this.noCacheWarningsByQueryId.has(operationId)) {
2456
+ this.noCacheWarningsByQueryId.add(operationId);
2457
+ globalThis.__DEV__ !== false && index.invariant.warn(
2458
+ 45,
2459
+ (_c = index.getOperationName(document)) !== null && _c !== void 0 ? _c : "Unnamed ".concat(operationType !== null && operationType !== void 0 ? operationType : "operation")
2460
+ );
2461
+ }
2462
+ }
2463
+ return (this.dataMasking ?
2464
+ index.maskOperation(data, document, this.cache)
2465
+ : data);
2466
+ };
2467
+ QueryManager.prototype.maskFragment = function (options) {
2468
+ var data = options.data, fragment = options.fragment, fragmentName = options.fragmentName;
2469
+ return this.dataMasking ?
2470
+ index.maskFragment(data, fragment, this.cache, fragmentName)
2471
+ : data;
2472
+ };
2473
+ QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a,
2474
+ // The initial networkStatus for this fetch, most often
2475
+ // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
2476
+ // or setVariables.
2477
+ networkStatus) {
2478
+ var _this = this;
2479
+ var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
2480
+ var oldNetworkStatus = queryInfo.networkStatus;
2481
+ queryInfo.init({
2482
+ document: query,
2483
+ variables: variables,
2484
+ networkStatus: networkStatus,
2485
+ });
2486
+ var readCache = function () { return queryInfo.getDiff(); };
2487
+ var resultsFromCache = function (diff, networkStatus) {
2488
+ if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }
2489
+ var data = diff.result;
2490
+ if (globalThis.__DEV__ !== false && !returnPartialData && !index.equal(data, {})) {
2491
+ logMissingFieldErrors(diff.missing);
2492
+ }
2493
+ var fromData = function (data) {
2494
+ return index.Observable.of(index.__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));
2495
+ };
2496
+ if (data && _this.getDocumentInfo(query).hasForcedResolvers) {
2497
+ return _this.localState
2498
+ .runResolvers({
2499
+ document: query,
2500
+ remoteResult: { data: data },
2501
+ context: context,
2502
+ variables: variables,
2503
+ onlyRunForcedResolvers: true,
2504
+ })
2505
+ .then(function (resolved) { return fromData(resolved.data || void 0); });
2506
+ }
2507
+ // Resolves https://github.com/apollographql/apollo-client/issues/10317.
2508
+ // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,
2509
+ // data was incorrectly returned from the cache on refetch:
2510
+ // if diff.missing exists, we should not return cache data.
2511
+ if (errorPolicy === "none" &&
2512
+ networkStatus === NetworkStatus.refetch &&
2513
+ Array.isArray(diff.missing)) {
2514
+ return fromData(void 0);
2515
+ }
2516
+ return fromData(data);
2517
+ };
2518
+ var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 /* CacheWriteBehavior.FORBID */
2519
+ // Watched queries must opt into overwriting existing data on refetch,
2520
+ // by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.
2521
+ : (networkStatus === NetworkStatus.refetch &&
2522
+ refetchWritePolicy !== "merge") ?
2523
+ 1 /* CacheWriteBehavior.OVERWRITE */
2524
+ : 2 /* CacheWriteBehavior.MERGE */;
2525
+ var resultsFromLink = function () {
2526
+ return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
2527
+ query: query,
2528
+ variables: variables,
2529
+ context: context,
2530
+ fetchPolicy: fetchPolicy,
2531
+ errorPolicy: errorPolicy,
2532
+ });
2533
+ };
2534
+ var shouldNotify = notifyOnNetworkStatusChange &&
2535
+ typeof oldNetworkStatus === "number" &&
2536
+ oldNetworkStatus !== networkStatus &&
2537
+ isNetworkRequestInFlight(networkStatus);
2538
+ switch (fetchPolicy) {
2539
+ default:
2540
+ case "cache-first": {
2541
+ var diff = readCache();
2542
+ if (diff.complete) {
2543
+ return {
2544
+ fromLink: false,
2545
+ sources: [resultsFromCache(diff, queryInfo.markReady())],
2546
+ };
2547
+ }
2548
+ if (returnPartialData || shouldNotify) {
2549
+ return {
2550
+ fromLink: true,
2551
+ sources: [resultsFromCache(diff), resultsFromLink()],
2552
+ };
2553
+ }
2554
+ return { fromLink: true, sources: [resultsFromLink()] };
2555
+ }
2556
+ case "cache-and-network": {
2557
+ var diff = readCache();
2558
+ if (diff.complete || returnPartialData || shouldNotify) {
2559
+ return {
2560
+ fromLink: true,
2561
+ sources: [resultsFromCache(diff), resultsFromLink()],
2562
+ };
2563
+ }
2564
+ return { fromLink: true, sources: [resultsFromLink()] };
2565
+ }
2566
+ case "cache-only":
2567
+ return {
2568
+ fromLink: false,
2569
+ sources: [resultsFromCache(readCache(), queryInfo.markReady())],
2570
+ };
2571
+ case "network-only":
2572
+ if (shouldNotify) {
2573
+ return {
2574
+ fromLink: true,
2575
+ sources: [resultsFromCache(readCache()), resultsFromLink()],
2576
+ };
2577
+ }
2578
+ return { fromLink: true, sources: [resultsFromLink()] };
2579
+ case "no-cache":
2580
+ if (shouldNotify) {
2581
+ return {
2582
+ fromLink: true,
2583
+ // Note that queryInfo.getDiff() for no-cache queries does not call
2584
+ // cache.diff, but instead returns a { complete: false } stub result
2585
+ // when there is no queryInfo.diff already defined.
2586
+ sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],
2587
+ };
2588
+ }
2589
+ return { fromLink: true, sources: [resultsFromLink()] };
2590
+ case "standby":
2591
+ return { fromLink: false, sources: [] };
2592
+ }
2593
+ };
2594
+ QueryManager.prototype.getOrCreateQuery = function (queryId) {
2595
+ if (queryId && !this.queries.has(queryId)) {
2596
+ this.queries.set(queryId, new QueryInfo(this, queryId));
2597
+ }
2598
+ return this.queries.get(queryId);
2599
+ };
2600
+ QueryManager.prototype.prepareContext = function (context) {
2601
+ if (context === void 0) { context = {}; }
2602
+ var newContext = this.localState.prepareContext(context);
2603
+ return index.__assign(index.__assign(index.__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });
2604
+ };
2605
+ return QueryManager;
2606
+ }());
2607
+
2608
+ var LocalState = /** @class */ (function () {
2609
+ function LocalState(_a) {
2610
+ var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
2611
+ this.selectionsToResolveCache = new WeakMap();
2612
+ this.cache = cache;
2613
+ if (client) {
2614
+ this.client = client;
2615
+ }
2616
+ if (resolvers) {
2617
+ this.addResolvers(resolvers);
2618
+ }
2619
+ if (fragmentMatcher) {
2620
+ this.setFragmentMatcher(fragmentMatcher);
2621
+ }
2622
+ }
2623
+ LocalState.prototype.addResolvers = function (resolvers) {
2624
+ var _this = this;
2625
+ this.resolvers = this.resolvers || {};
2626
+ if (Array.isArray(resolvers)) {
2627
+ resolvers.forEach(function (resolverGroup) {
2628
+ _this.resolvers = index.mergeDeep(_this.resolvers, resolverGroup);
2629
+ });
2630
+ }
2631
+ else {
2632
+ this.resolvers = index.mergeDeep(this.resolvers, resolvers);
2633
+ }
2634
+ };
2635
+ LocalState.prototype.setResolvers = function (resolvers) {
2636
+ this.resolvers = {};
2637
+ this.addResolvers(resolvers);
2638
+ };
2639
+ LocalState.prototype.getResolvers = function () {
2640
+ return this.resolvers || {};
2641
+ };
2642
+ // Run local client resolvers against the incoming query and remote data.
2643
+ // Locally resolved field values are merged with the incoming remote data,
2644
+ // and returned. Note that locally resolved fields will overwrite
2645
+ // remote data using the same field name.
2646
+ LocalState.prototype.runResolvers = function (_a) {
2647
+ return index.__awaiter(this, arguments, void 0, function (_b) {
2648
+ var document = _b.document, remoteResult = _b.remoteResult, context = _b.context, variables = _b.variables, _c = _b.onlyRunForcedResolvers, onlyRunForcedResolvers = _c === void 0 ? false : _c;
2649
+ return index.__generator(this, function (_d) {
2650
+ if (document) {
2651
+ return [2 /*return*/, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (index.__assign(index.__assign({}, remoteResult), { data: localResult.result })); })];
2652
+ }
2653
+ return [2 /*return*/, remoteResult];
2654
+ });
2655
+ });
2656
+ };
2657
+ LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
2658
+ this.fragmentMatcher = fragmentMatcher;
2659
+ };
2660
+ LocalState.prototype.getFragmentMatcher = function () {
2661
+ return this.fragmentMatcher;
2662
+ };
2663
+ // Client queries contain everything in the incoming document (if a @client
2664
+ // directive is found).
2665
+ LocalState.prototype.clientQuery = function (document) {
2666
+ if (index.hasDirectives(["client"], document)) {
2667
+ if (this.resolvers) {
2668
+ return document;
2669
+ }
2670
+ }
2671
+ return null;
2672
+ };
2673
+ // Server queries are stripped of all @client based selection sets.
2674
+ LocalState.prototype.serverQuery = function (document) {
2675
+ return index.removeClientSetsFromDocument(document);
2676
+ };
2677
+ LocalState.prototype.prepareContext = function (context) {
2678
+ var cache = this.cache;
2679
+ return index.__assign(index.__assign({}, context), { cache: cache,
2680
+ // Getting an entry's cache key is useful for local state resolvers.
2681
+ getCacheKey: function (obj) {
2682
+ return cache.identify(obj);
2683
+ } });
2684
+ };
2685
+ // To support `@client @export(as: "someVar")` syntax, we'll first resolve
2686
+ // @client @export fields locally, then pass the resolved values back to be
2687
+ // used alongside the original operation variables.
2688
+ LocalState.prototype.addExportedVariables = function (document_1) {
2689
+ return index.__awaiter(this, arguments, void 0, function (document, variables, context) {
2690
+ if (variables === void 0) { variables = {}; }
2691
+ if (context === void 0) { context = {}; }
2692
+ return index.__generator(this, function (_a) {
2693
+ if (document) {
2694
+ return [2 /*return*/, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (index.__assign(index.__assign({}, variables), data.exportedVariables)); })];
2695
+ }
2696
+ return [2 /*return*/, index.__assign({}, variables)];
2697
+ });
2698
+ });
2699
+ };
2700
+ LocalState.prototype.shouldForceResolvers = function (document) {
2701
+ var forceResolvers = false;
2702
+ index$1.visit(document, {
2703
+ Directive: {
2704
+ enter: function (node) {
2705
+ if (node.name.value === "client" && node.arguments) {
2706
+ forceResolvers = node.arguments.some(function (arg) {
2707
+ return arg.name.value === "always" &&
2708
+ arg.value.kind === "BooleanValue" &&
2709
+ arg.value.value === true;
2710
+ });
2711
+ if (forceResolvers) {
2712
+ return index$1.BREAK;
2713
+ }
2714
+ }
2715
+ },
2716
+ },
2717
+ });
2718
+ return forceResolvers;
2719
+ };
2720
+ // Query the cache and return matching data.
2721
+ LocalState.prototype.buildRootValueFromCache = function (document, variables) {
2722
+ return this.cache.diff({
2723
+ query: index.buildQueryFromSelectionSet(document),
2724
+ variables: variables,
2725
+ returnPartialData: true,
2726
+ optimistic: false,
2727
+ }).result;
2728
+ };
2729
+ LocalState.prototype.resolveDocument = function (document_1, rootValue_1) {
2730
+ return index.__awaiter(this, arguments, void 0, function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
2731
+ var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
2732
+ if (context === void 0) { context = {}; }
2733
+ if (variables === void 0) { variables = {}; }
2734
+ if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
2735
+ if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
2736
+ return index.__generator(this, function (_b) {
2737
+ mainDefinition = index.getMainDefinition(document);
2738
+ fragments = index.getFragmentDefinitions(document);
2739
+ fragmentMap = index.createFragmentMap(fragments);
2740
+ selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
2741
+ definitionOperation = mainDefinition.operation;
2742
+ defaultOperationType = definitionOperation ?
2743
+ definitionOperation.charAt(0).toUpperCase() +
2744
+ definitionOperation.slice(1)
2745
+ : "Query";
2746
+ _a = this, cache = _a.cache, client = _a.client;
2747
+ execContext = {
2748
+ fragmentMap: fragmentMap,
2749
+ context: index.__assign(index.__assign({}, context), { cache: cache, client: client }),
2750
+ variables: variables,
2751
+ fragmentMatcher: fragmentMatcher,
2752
+ defaultOperationType: defaultOperationType,
2753
+ exportedVariables: {},
2754
+ selectionsToResolve: selectionsToResolve,
2755
+ onlyRunForcedResolvers: onlyRunForcedResolvers,
2756
+ };
2757
+ isClientFieldDescendant = false;
2758
+ return [2 /*return*/, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
2759
+ result: result,
2760
+ exportedVariables: execContext.exportedVariables,
2761
+ }); })];
2762
+ });
2763
+ });
2764
+ };
2765
+ LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
2766
+ return index.__awaiter(this, void 0, void 0, function () {
2767
+ var fragmentMap, context, variables, resultsToMerge, execute;
2768
+ var _this = this;
2769
+ return index.__generator(this, function (_a) {
2770
+ fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
2771
+ resultsToMerge = [rootValue];
2772
+ execute = function (selection) { return index.__awaiter(_this, void 0, void 0, function () {
2773
+ var fragment, typeCondition;
2774
+ return index.__generator(this, function (_a) {
2775
+ if (!isClientFieldDescendant &&
2776
+ !execContext.selectionsToResolve.has(selection)) {
2777
+ // Skip selections without @client directives
2778
+ // (still processing if one of the ancestors or one of the child fields has @client directive)
2779
+ return [2 /*return*/];
2780
+ }
2781
+ if (!index.shouldInclude(selection, variables)) {
2782
+ // Skip this entirely.
2783
+ return [2 /*return*/];
2784
+ }
2785
+ if (index.isField(selection)) {
2786
+ return [2 /*return*/, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
2787
+ var _a;
2788
+ if (typeof fieldResult !== "undefined") {
2789
+ resultsToMerge.push((_a = {},
2790
+ _a[index.resultKeyNameFromField(selection)] = fieldResult,
2791
+ _a));
2792
+ }
2793
+ })];
2794
+ }
2795
+ if (index.isInlineFragment(selection)) {
2796
+ fragment = selection;
2797
+ }
2798
+ else {
2799
+ // This is a named fragment.
2800
+ fragment = fragmentMap[selection.name.value];
2801
+ index.invariant(fragment, 21, selection.name.value);
2802
+ }
2803
+ if (fragment && fragment.typeCondition) {
2804
+ typeCondition = fragment.typeCondition.name.value;
2805
+ if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
2806
+ return [2 /*return*/, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
2807
+ resultsToMerge.push(fragmentResult);
2808
+ })];
2809
+ }
2810
+ }
2811
+ return [2 /*return*/];
2812
+ });
2813
+ }); };
2814
+ return [2 /*return*/, Promise.all(selectionSet.selections.map(execute)).then(function () {
2815
+ return index.mergeDeepArray(resultsToMerge);
2816
+ })];
2817
+ });
2818
+ });
2819
+ };
2820
+ LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
2821
+ return index.__awaiter(this, void 0, void 0, function () {
2822
+ var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
2823
+ var _this = this;
2824
+ return index.__generator(this, function (_a) {
2825
+ if (!rootValue) {
2826
+ return [2 /*return*/, null];
2827
+ }
2828
+ variables = execContext.variables;
2829
+ fieldName = field.name.value;
2830
+ aliasedFieldName = index.resultKeyNameFromField(field);
2831
+ aliasUsed = fieldName !== aliasedFieldName;
2832
+ defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
2833
+ resultPromise = Promise.resolve(defaultResult);
2834
+ // Usually all local resolvers are run when passing through here, but
2835
+ // if we've specifically identified that we only want to run forced
2836
+ // resolvers (that is, resolvers for fields marked with
2837
+ // `@client(always: true)`), then we'll skip running non-forced resolvers.
2838
+ if (!execContext.onlyRunForcedResolvers ||
2839
+ this.shouldForceResolvers(field)) {
2840
+ resolverType = rootValue.__typename || execContext.defaultOperationType;
2841
+ resolverMap = this.resolvers && this.resolvers[resolverType];
2842
+ if (resolverMap) {
2843
+ resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
2844
+ if (resolve) {
2845
+ resultPromise = Promise.resolve(
2846
+ // In case the resolve function accesses reactive variables,
2847
+ // set cacheSlot to the current cache instance.
2848
+ index.cacheSlot.withValue(this.cache, resolve, [
2849
+ rootValue,
2850
+ index.argumentsObjectFromField(field, variables),
2851
+ execContext.context,
2852
+ { field: field, fragmentMap: execContext.fragmentMap },
2853
+ ]));
2854
+ }
2855
+ }
2856
+ }
2857
+ return [2 /*return*/, resultPromise.then(function (result) {
2858
+ var _a, _b;
2859
+ if (result === void 0) { result = defaultResult; }
2860
+ // If an @export directive is associated with the current field, store
2861
+ // the `as` export variable name and current result for later use.
2862
+ if (field.directives) {
2863
+ field.directives.forEach(function (directive) {
2864
+ if (directive.name.value === "export" && directive.arguments) {
2865
+ directive.arguments.forEach(function (arg) {
2866
+ if (arg.name.value === "as" && arg.value.kind === "StringValue") {
2867
+ execContext.exportedVariables[arg.value.value] = result;
2868
+ }
2869
+ });
2870
+ }
2871
+ });
2872
+ }
2873
+ // Handle all scalar types here.
2874
+ if (!field.selectionSet) {
2875
+ return result;
2876
+ }
2877
+ // From here down, the field has a selection set, which means it's trying
2878
+ // to query a GraphQLObjectType.
2879
+ if (result == null) {
2880
+ // Basically any field in a GraphQL response can be null, or missing
2881
+ return result;
2882
+ }
2883
+ var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === "client"; })) !== null && _b !== void 0 ? _b : false;
2884
+ if (Array.isArray(result)) {
2885
+ return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
2886
+ }
2887
+ // Returned value is an object, and the query has a sub-selection. Recurse.
2888
+ if (field.selectionSet) {
2889
+ return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
2890
+ }
2891
+ })];
2892
+ });
2893
+ });
2894
+ };
2895
+ LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
2896
+ var _this = this;
2897
+ return Promise.all(result.map(function (item) {
2898
+ if (item === null) {
2899
+ return null;
2900
+ }
2901
+ // This is a nested array, recurse.
2902
+ if (Array.isArray(item)) {
2903
+ return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
2904
+ }
2905
+ // This is an object, run the selection set on it.
2906
+ if (field.selectionSet) {
2907
+ return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
2908
+ }
2909
+ }));
2910
+ };
2911
+ // Collect selection nodes on paths from document root down to all @client directives.
2912
+ // This function takes into account transitive fragment spreads.
2913
+ // Complexity equals to a single `visit` over the full document.
2914
+ LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
2915
+ var isSingleASTNode = function (node) { return !Array.isArray(node); };
2916
+ var selectionsToResolveCache = this.selectionsToResolveCache;
2917
+ function collectByDefinition(definitionNode) {
2918
+ if (!selectionsToResolveCache.has(definitionNode)) {
2919
+ var matches_1 = new Set();
2920
+ selectionsToResolveCache.set(definitionNode, matches_1);
2921
+ index$1.visit(definitionNode, {
2922
+ Directive: function (node, _, __, ___, ancestors) {
2923
+ if (node.name.value === "client") {
2924
+ ancestors.forEach(function (node) {
2925
+ if (isSingleASTNode(node) && index.isSelectionNode(node)) {
2926
+ matches_1.add(node);
2927
+ }
2928
+ });
2929
+ }
2930
+ },
2931
+ FragmentSpread: function (spread, _, __, ___, ancestors) {
2932
+ var fragment = fragmentMap[spread.name.value];
2933
+ index.invariant(fragment, 22, spread.name.value);
2934
+ var fragmentSelections = collectByDefinition(fragment);
2935
+ if (fragmentSelections.size > 0) {
2936
+ // Fragment for this spread contains @client directive (either directly or transitively)
2937
+ // Collect selection nodes on paths from the root down to fields with the @client directive
2938
+ ancestors.forEach(function (node) {
2939
+ if (isSingleASTNode(node) && index.isSelectionNode(node)) {
2940
+ matches_1.add(node);
2941
+ }
2942
+ });
2943
+ matches_1.add(spread);
2944
+ fragmentSelections.forEach(function (selection) {
2945
+ matches_1.add(selection);
2946
+ });
2947
+ }
2948
+ },
2949
+ });
2950
+ }
2951
+ return selectionsToResolveCache.get(definitionNode);
2952
+ }
2953
+ return collectByDefinition(mainDefinition);
2954
+ };
2955
+ return LocalState;
2956
+ }());
2957
+
2958
+ var hasSuggestedDevtools = false;
2959
+ /**
2960
+ * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
2961
+ * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
2962
+ * receive results from the server and cache the results in a store. It also delivers updates
2963
+ * to GraphQL queries through `Observable` instances.
2964
+ */
2965
+ var ApolloClient = /** @class */ (function () {
2966
+ /**
2967
+ * Constructs an instance of `ApolloClient`.
2968
+ *
2969
+ * @example
2970
+ * ```js
2971
+ * import { ApolloClient, InMemoryCache } from '@apollo/client';
2972
+ *
2973
+ * const cache = new InMemoryCache();
2974
+ *
2975
+ * const client = new ApolloClient({
2976
+ * // Provide required constructor fields
2977
+ * cache: cache,
2978
+ * uri: 'http://localhost:4000/',
2979
+ *
2980
+ * // Provide some optional constructor fields
2981
+ * name: 'react-web-client',
2982
+ * version: '1.3',
2983
+ * queryDeduplication: false,
2984
+ * defaultOptions: {
2985
+ * watchQuery: {
2986
+ * fetchPolicy: 'cache-and-network',
2987
+ * },
2988
+ * },
2989
+ * });
2990
+ * ```
2991
+ */
2992
+ function ApolloClient(options) {
2993
+ var _this = this;
2994
+ var _a, _b, _c;
2995
+ this.resetStoreCallbacks = [];
2996
+ this.clearStoreCallbacks = [];
2997
+ if (!options.cache) {
2998
+ throw index.newInvariantError(16);
2999
+ }
3000
+ var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _d = options.ssrMode, ssrMode = _d === void 0 ? false : _d, _e = options.ssrForceFetchDelay, ssrForceFetchDelay = _e === void 0 ? 0 : _e,
3001
+ // Expose the client instance as window.__APOLLO_CLIENT__ and call
3002
+ // onBroadcast in queryManager.broadcastQueries to enable browser
3003
+ // devtools, but disable them by default in production.
3004
+ connectToDevTools = options.connectToDevTools, _f = options.queryDeduplication, queryDeduplication = _f === void 0 ? true : _f, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _g = options.assumeImmutableResults, assumeImmutableResults = _g === void 0 ? cache.assumeImmutableResults : _g, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwareness = options.clientAwareness, clientAwarenessName = options.name, clientAwarenessVersion = options.version, devtools = options.devtools, dataMasking = options.dataMasking;
3005
+ if (globalThis.__DEV__ !== false) {
3006
+ index.warnRemovedOption(options, "connectToDevTools", "ApolloClient", "Please use `devtools.enabled` instead.");
3007
+ index.warnRemovedOption(options, "uri", "ApolloClient", "Please initialize an instance of `HttpLink` with `uri` instead.");
3008
+ index.warnRemovedOption(options, "credentials", "ApolloClient", "Please initialize an instance of `HttpLink` with `credentials` instead.");
3009
+ index.warnRemovedOption(options, "headers", "ApolloClient", "Please initialize an instance of `HttpLink` with `headers` instead.");
3010
+ index.warnRemovedOption(options, "name", "ApolloClient", "Please use the `clientAwareness.name` option instead.");
3011
+ index.warnRemovedOption(options, "version", "ApolloClient", "Please use the `clientAwareness.version` option instead.");
3012
+ index.warnRemovedOption(options, "typeDefs", "ApolloClient");
3013
+ if (!options.link) {
3014
+ globalThis.__DEV__ !== false && index.invariant.warn(17);
3015
+ }
3016
+ }
3017
+ var link = options.link;
3018
+ if (!link) {
3019
+ link =
3020
+ uri ? new index.HttpLink({ uri: uri, credentials: credentials, headers: headers }) : index.ApolloLink.empty();
3021
+ }
3022
+ this.link = link;
3023
+ this.cache = cache;
3024
+ this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
3025
+ this.queryDeduplication = queryDeduplication;
3026
+ this.defaultOptions = defaultOptions || Object.create(null);
3027
+ this.typeDefs = typeDefs;
3028
+ this.devtoolsConfig = index.__assign(index.__assign({}, devtools), { enabled: (_a = devtools === null || devtools === void 0 ? void 0 : devtools.enabled) !== null && _a !== void 0 ? _a : connectToDevTools });
3029
+ if (this.devtoolsConfig.enabled === undefined) {
3030
+ this.devtoolsConfig.enabled = globalThis.__DEV__ !== false;
3031
+ }
3032
+ if (ssrForceFetchDelay) {
3033
+ setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
3034
+ }
3035
+ this.watchQuery = this.watchQuery.bind(this);
3036
+ this.query = this.query.bind(this);
3037
+ this.mutate = this.mutate.bind(this);
3038
+ this.watchFragment = this.watchFragment.bind(this);
3039
+ this.resetStore = this.resetStore.bind(this);
3040
+ this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
3041
+ this.version = index.version;
3042
+ this.localState = new LocalState({
3043
+ cache: cache,
3044
+ client: this,
3045
+ resolvers: resolvers,
3046
+ fragmentMatcher: fragmentMatcher,
3047
+ });
3048
+ this.queryManager = new QueryManager({
3049
+ cache: this.cache,
3050
+ link: this.link,
3051
+ defaultOptions: this.defaultOptions,
3052
+ defaultContext: defaultContext,
3053
+ documentTransform: documentTransform,
3054
+ queryDeduplication: queryDeduplication,
3055
+ ssrMode: ssrMode,
3056
+ dataMasking: !!dataMasking,
3057
+ clientAwareness: {
3058
+ name: (_b = clientAwareness === null || clientAwareness === void 0 ? void 0 : clientAwareness.name) !== null && _b !== void 0 ? _b : clientAwarenessName,
3059
+ version: (_c = clientAwareness === null || clientAwareness === void 0 ? void 0 : clientAwareness.version) !== null && _c !== void 0 ? _c : clientAwarenessVersion,
3060
+ },
3061
+ localState: this.localState,
3062
+ assumeImmutableResults: assumeImmutableResults,
3063
+ onBroadcast: this.devtoolsConfig.enabled ?
3064
+ function () {
3065
+ if (_this.devToolsHookCb) {
3066
+ _this.devToolsHookCb({
3067
+ action: {},
3068
+ state: {
3069
+ queries: _this.queryManager.getQueryStore(),
3070
+ mutations: _this.queryManager.mutationStore || {},
3071
+ },
3072
+ dataWithOptimisticResults: _this.cache.extract(true),
3073
+ });
3074
+ }
3075
+ }
3076
+ : void 0,
3077
+ });
3078
+ if (this.devtoolsConfig.enabled)
3079
+ this.connectToDevTools();
3080
+ }
3081
+ Object.defineProperty(ApolloClient.prototype, "prioritizeCacheValues", {
3082
+ /**
3083
+ * Whether to prioritize cache values over network results when `query` or `watchQuery` is called.
3084
+ * This will essentially turn a `"network-only"` or `"cache-and-network"` fetchPolicy into a `"cache-first"` fetchPolicy,
3085
+ * but without influencing the `fetchPolicy` of the created `ObservableQuery` long-term.
3086
+ *
3087
+ * This can e.g. be used to prioritize the cache during the first render after SSR.
3088
+ */
3089
+ get: function () {
3090
+ return this.disableNetworkFetches;
3091
+ },
3092
+ set: function (value) {
3093
+ this.disableNetworkFetches = value;
3094
+ },
3095
+ enumerable: false,
3096
+ configurable: true
3097
+ });
3098
+ ApolloClient.prototype.connectToDevTools = function () {
3099
+ if (typeof window === "undefined") {
3100
+ return;
3101
+ }
3102
+ var windowWithDevTools = window;
3103
+ var devtoolsSymbol = Symbol.for("apollo.devtools");
3104
+ (windowWithDevTools[devtoolsSymbol] =
3105
+ windowWithDevTools[devtoolsSymbol] || []).push(this);
3106
+ windowWithDevTools.__APOLLO_CLIENT__ = this;
3107
+ /**
3108
+ * Suggest installing the devtools for developers who don't have them
3109
+ */
3110
+ if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {
3111
+ hasSuggestedDevtools = true;
3112
+ if (window.document &&
3113
+ window.top === window.self &&
3114
+ /^(https?|file):$/.test(window.location.protocol)) {
3115
+ setTimeout(function () {
3116
+ if (!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
3117
+ var nav = window.navigator;
3118
+ var ua = nav && nav.userAgent;
3119
+ var url = void 0;
3120
+ if (typeof ua === "string") {
3121
+ if (ua.indexOf("Chrome/") > -1) {
3122
+ url =
3123
+ "https://chrome.google.com/webstore/detail/" +
3124
+ "apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
3125
+ }
3126
+ else if (ua.indexOf("Firefox/") > -1) {
3127
+ url =
3128
+ "https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
3129
+ }
3130
+ }
3131
+ if (url) {
3132
+ globalThis.__DEV__ !== false && index.invariant.log("Download the Apollo DevTools for a better development " +
3133
+ "experience: %s", url);
3134
+ }
3135
+ }
3136
+ }, 10000);
3137
+ }
3138
+ }
3139
+ };
3140
+ Object.defineProperty(ApolloClient.prototype, "documentTransform", {
3141
+ /**
3142
+ * The `DocumentTransform` used to modify GraphQL documents before a request
3143
+ * is made. If a custom `DocumentTransform` is not provided, this will be the
3144
+ * default document transform.
3145
+ */
3146
+ get: function () {
3147
+ return this.queryManager.documentTransform;
3148
+ },
3149
+ enumerable: false,
3150
+ configurable: true
3151
+ });
3152
+ /**
3153
+ * Call this method to terminate any active client processes, making it safe
3154
+ * to dispose of this `ApolloClient` instance.
3155
+ */
3156
+ ApolloClient.prototype.stop = function () {
3157
+ this.queryManager.stop();
3158
+ };
3159
+ /**
3160
+ * This watches the cache store of the query according to the options specified and
3161
+ * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
3162
+ * receive updated results through an observer when the cache store changes.
3163
+ *
3164
+ * Note that this method is not an implementation of GraphQL subscriptions. Rather,
3165
+ * it uses Apollo's store in order to reactively deliver updates to your query results.
3166
+ *
3167
+ * For example, suppose you call watchQuery on a GraphQL query that fetches a person's
3168
+ * first and last name and this person has a particular object identifier, provided by
3169
+ * dataIdFromObject. Later, a different query fetches that same person's
3170
+ * first and last name and the first name has now changed. Then, any observers associated
3171
+ * with the results of the first query will be updated with a new result object.
3172
+ *
3173
+ * Note that if the cache does not change, the subscriber will *not* be notified.
3174
+ *
3175
+ * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
3176
+ * a description of store reactivity.
3177
+ */
3178
+ ApolloClient.prototype.watchQuery = function (options) {
3179
+ if (this.defaultOptions.watchQuery) {
3180
+ options = index.mergeOptions(this.defaultOptions.watchQuery, options);
3181
+ }
3182
+ // XXX Overwriting options is probably not the best way to do this long term...
3183
+ if (this.disableNetworkFetches &&
3184
+ (options.fetchPolicy === "network-only" ||
3185
+ options.fetchPolicy === "cache-and-network")) {
3186
+ options = index.__assign(index.__assign({}, options), { fetchPolicy: "cache-first" });
3187
+ }
3188
+ if (globalThis.__DEV__ !== false) {
3189
+ index.warnRemovedOption(options, "canonizeResults", "client.watchQuery");
3190
+ index.warnRemovedOption(options, "partialRefetch", "client.watchQuery");
3191
+ }
3192
+ return this.queryManager.watchQuery(options);
3193
+ };
3194
+ /**
3195
+ * This resolves a single query according to the options specified and
3196
+ * returns a `Promise` which is either resolved with the resulting data
3197
+ * or rejected with an error.
3198
+ *
3199
+ * @param options - An object of type `QueryOptions` that allows us to
3200
+ * describe how this query should be treated e.g. whether it should hit the
3201
+ * server at all or just resolve from the cache, etc.
3202
+ */
3203
+ ApolloClient.prototype.query = function (options) {
3204
+ if (this.defaultOptions.query) {
3205
+ options = index.mergeOptions(this.defaultOptions.query, options);
3206
+ }
3207
+ index.invariant(options.fetchPolicy !== "cache-and-network", 18);
3208
+ if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
3209
+ options = index.__assign(index.__assign({}, options), { fetchPolicy: "cache-first" });
3210
+ }
3211
+ if (globalThis.__DEV__ !== false) {
3212
+ index.warnRemovedOption(options, "canonizeResults", "client.query");
3213
+ index.warnRemovedOption(options, "notifyOnNetworkStatusChange", "client.query", "This option does not affect `client.query` and can be safely removed.");
3214
+ if (options.fetchPolicy === "standby") {
3215
+ globalThis.__DEV__ !== false && index.invariant.warn(19);
3216
+ }
3217
+ }
3218
+ return this.queryManager.query(options);
3219
+ };
3220
+ /**
3221
+ * This resolves a single mutation according to the options specified and returns a
3222
+ * Promise which is either resolved with the resulting data or rejected with an
3223
+ * error. In some cases both `data` and `errors` might be undefined, for example
3224
+ * when `errorPolicy` is set to `'ignore'`.
3225
+ *
3226
+ * It takes options as an object with the following keys and values:
3227
+ */
3228
+ ApolloClient.prototype.mutate = function (options) {
3229
+ if (this.defaultOptions.mutate) {
3230
+ options = index.mergeOptions(this.defaultOptions.mutate, options);
3231
+ }
3232
+ return this.queryManager.mutate(options);
3233
+ };
3234
+ /**
3235
+ * This subscribes to a graphql subscription according to the options specified and returns an
3236
+ * `Observable` which either emits received data or an error.
3237
+ */
3238
+ ApolloClient.prototype.subscribe = function (options) {
3239
+ var _this = this;
3240
+ var id = this.queryManager.generateQueryId();
3241
+ return this.queryManager
3242
+ .startGraphQLSubscription(options)
3243
+ .map(function (result) { return (index.__assign(index.__assign({}, result), { data: _this.queryManager.maskOperation({
3244
+ document: options.query,
3245
+ data: result.data,
3246
+ fetchPolicy: options.fetchPolicy,
3247
+ id: id,
3248
+ }) })); });
3249
+ };
3250
+ /**
3251
+ * Tries to read some data from the store in the shape of the provided
3252
+ * GraphQL query without making a network request. This method will start at
3253
+ * the root query. To start at a specific id returned by `dataIdFromObject`
3254
+ * use `readFragment`.
3255
+ *
3256
+ * @param optimistic - Set to `true` to allow `readQuery` to return
3257
+ * optimistic results. Is `false` by default.
3258
+ */
3259
+ ApolloClient.prototype.readQuery = function (options, optimistic) {
3260
+ if (optimistic === void 0) { optimistic = false; }
3261
+ return this.cache.readQuery(options, optimistic);
3262
+ };
3263
+ /**
3264
+ * Watches the cache store of the fragment according to the options specified
3265
+ * and returns an `Observable`. We can subscribe to this
3266
+ * `Observable` and receive updated results through an
3267
+ * observer when the cache store changes.
3268
+ *
3269
+ * You must pass in a GraphQL document with a single fragment or a document
3270
+ * with multiple fragments that represent what you are reading. If you pass
3271
+ * in a document with multiple fragments then you must also specify a
3272
+ * `fragmentName`.
3273
+ *
3274
+ * @since 3.10.0
3275
+ * @param options - An object of type `WatchFragmentOptions` that allows
3276
+ * the cache to identify the fragment and optionally specify whether to react
3277
+ * to optimistic updates.
3278
+ */
3279
+ ApolloClient.prototype.watchFragment = function (options) {
3280
+ var _a;
3281
+ return this.cache.watchFragment(index.__assign(index.__assign({}, options), (_a = {}, _a[Symbol.for("apollo.dataMasking")] = this.queryManager.dataMasking, _a)));
3282
+ };
3283
+ /**
3284
+ * Tries to read some data from the store in the shape of the provided
3285
+ * GraphQL fragment without making a network request. This method will read a
3286
+ * GraphQL fragment from any arbitrary id that is currently cached, unlike
3287
+ * `readQuery` which will only read from the root query.
3288
+ *
3289
+ * You must pass in a GraphQL document with a single fragment or a document
3290
+ * with multiple fragments that represent what you are reading. If you pass
3291
+ * in a document with multiple fragments then you must also specify a
3292
+ * `fragmentName`.
3293
+ *
3294
+ * @param optimistic - Set to `true` to allow `readFragment` to return
3295
+ * optimistic results. Is `false` by default.
3296
+ */
3297
+ ApolloClient.prototype.readFragment = function (options, optimistic) {
3298
+ if (optimistic === void 0) { optimistic = false; }
3299
+ return this.cache.readFragment(options, optimistic);
3300
+ };
3301
+ /**
3302
+ * Writes some data in the shape of the provided GraphQL query directly to
3303
+ * the store. This method will start at the root query. To start at a
3304
+ * specific id returned by `dataIdFromObject` then use `writeFragment`.
3305
+ */
3306
+ ApolloClient.prototype.writeQuery = function (options) {
3307
+ var ref = this.cache.writeQuery(options);
3308
+ if (options.broadcast !== false) {
3309
+ this.queryManager.broadcastQueries();
3310
+ }
3311
+ return ref;
3312
+ };
3313
+ /**
3314
+ * Writes some data in the shape of the provided GraphQL fragment directly to
3315
+ * the store. This method will write to a GraphQL fragment from any arbitrary
3316
+ * id that is currently cached, unlike `writeQuery` which will only write
3317
+ * from the root query.
3318
+ *
3319
+ * You must pass in a GraphQL document with a single fragment or a document
3320
+ * with multiple fragments that represent what you are writing. If you pass
3321
+ * in a document with multiple fragments then you must also specify a
3322
+ * `fragmentName`.
3323
+ */
3324
+ ApolloClient.prototype.writeFragment = function (options) {
3325
+ var ref = this.cache.writeFragment(options);
3326
+ if (options.broadcast !== false) {
3327
+ this.queryManager.broadcastQueries();
3328
+ }
3329
+ return ref;
3330
+ };
3331
+ ApolloClient.prototype.__actionHookForDevTools = function (cb) {
3332
+ this.devToolsHookCb = cb;
3333
+ };
3334
+ ApolloClient.prototype.__requestRaw = function (payload) {
3335
+ return index.execute(this.link, payload);
3336
+ };
3337
+ /**
3338
+ * Resets your entire store by clearing out your cache and then re-executing
3339
+ * all of your active queries. This makes it so that you may guarantee that
3340
+ * there is no data left in your store from a time before you called this
3341
+ * method.
3342
+ *
3343
+ * `resetStore()` is useful when your user just logged out. You’ve removed the
3344
+ * user session, and you now want to make sure that any references to data you
3345
+ * might have fetched while the user session was active is gone.
3346
+ *
3347
+ * It is important to remember that `resetStore()` *will* refetch any active
3348
+ * queries. This means that any components that might be mounted will execute
3349
+ * their queries again using your network interface. If you do not want to
3350
+ * re-execute any queries then you should make sure to stop watching any
3351
+ * active queries.
3352
+ */
3353
+ ApolloClient.prototype.resetStore = function () {
3354
+ var _this = this;
3355
+ return Promise.resolve()
3356
+ .then(function () {
3357
+ return _this.queryManager.clearStore({
3358
+ discardWatches: false,
3359
+ });
3360
+ })
3361
+ .then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
3362
+ .then(function () { return _this.reFetchObservableQueries(); });
3363
+ };
3364
+ /**
3365
+ * Remove all data from the store. Unlike `resetStore`, `clearStore` will
3366
+ * not refetch any active queries.
3367
+ */
3368
+ ApolloClient.prototype.clearStore = function () {
3369
+ var _this = this;
3370
+ return Promise.resolve()
3371
+ .then(function () {
3372
+ return _this.queryManager.clearStore({
3373
+ discardWatches: true,
3374
+ });
3375
+ })
3376
+ .then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
3377
+ };
3378
+ /**
3379
+ * Allows callbacks to be registered that are executed when the store is
3380
+ * reset. `onResetStore` returns an unsubscribe function that can be used
3381
+ * to remove registered callbacks.
3382
+ */
3383
+ ApolloClient.prototype.onResetStore = function (cb) {
3384
+ var _this = this;
3385
+ this.resetStoreCallbacks.push(cb);
3386
+ return function () {
3387
+ _this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
3388
+ };
3389
+ };
3390
+ /**
3391
+ * Allows callbacks to be registered that are executed when the store is
3392
+ * cleared. `onClearStore` returns an unsubscribe function that can be used
3393
+ * to remove registered callbacks.
3394
+ */
3395
+ ApolloClient.prototype.onClearStore = function (cb) {
3396
+ var _this = this;
3397
+ this.clearStoreCallbacks.push(cb);
3398
+ return function () {
3399
+ _this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
3400
+ };
3401
+ };
3402
+ /**
3403
+ * Refetches all of your active queries.
3404
+ *
3405
+ * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage
3406
+ *
3407
+ * It is important to remember that `reFetchObservableQueries()` *will* refetch any active
3408
+ * queries. This means that any components that might be mounted will execute
3409
+ * their queries again using your network interface. If you do not want to
3410
+ * re-execute any queries then you should make sure to stop watching any
3411
+ * active queries.
3412
+ * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.
3413
+ */
3414
+ ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
3415
+ return this.queryManager.reFetchObservableQueries(includeStandby);
3416
+ };
3417
+ /**
3418
+ * Refetches specified active queries. Similar to "reFetchObservableQueries()" but with a specific list of queries.
3419
+ *
3420
+ * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.
3421
+ *
3422
+ * It is important to remember that `refetchQueries()` *will* refetch specified active
3423
+ * queries. This means that any components that might be mounted will execute
3424
+ * their queries again using your network interface. If you do not want to
3425
+ * re-execute any queries then you should make sure to stop watching any
3426
+ * active queries.
3427
+ */
3428
+ ApolloClient.prototype.refetchQueries = function (options) {
3429
+ var map = this.queryManager.refetchQueries(options);
3430
+ var queries = [];
3431
+ var results = [];
3432
+ map.forEach(function (result, obsQuery) {
3433
+ queries.push(obsQuery);
3434
+ results.push(result);
3435
+ });
3436
+ var result = Promise.all(results);
3437
+ // In case you need the raw results immediately, without awaiting
3438
+ // Promise.all(results):
3439
+ result.queries = queries;
3440
+ result.results = results;
3441
+ // If you decide to ignore the result Promise because you're using
3442
+ // result.queries and result.results instead, you shouldn't have to worry
3443
+ // about preventing uncaught rejections for the Promise.all result.
3444
+ result.catch(function (error) {
3445
+ globalThis.__DEV__ !== false && index.invariant.debug(20, error);
3446
+ });
3447
+ return result;
3448
+ };
3449
+ /**
3450
+ * Get all currently active `ObservableQuery` objects, in a `Map` keyed by
3451
+ * query ID strings.
3452
+ *
3453
+ * An "active" query is one that has observers and a `fetchPolicy` other than
3454
+ * "standby" or "cache-only".
3455
+ *
3456
+ * You can include all `ObservableQuery` objects (including the inactive ones)
3457
+ * by passing "all" instead of "active", or you can include just a subset of
3458
+ * active queries by passing an array of query names or DocumentNode objects.
3459
+ */
3460
+ ApolloClient.prototype.getObservableQueries = function (include) {
3461
+ if (include === void 0) { include = "active"; }
3462
+ return this.queryManager.getObservableQueries(include);
3463
+ };
3464
+ /**
3465
+ * Exposes the cache's complete state, in a serializable format for later restoration.
3466
+ */
3467
+ ApolloClient.prototype.extract = function (optimistic) {
3468
+ return this.cache.extract(optimistic);
3469
+ };
3470
+ /**
3471
+ * Replaces existing state in the cache (if any) with the values expressed by
3472
+ * `serializedState`.
3473
+ *
3474
+ * Called when hydrating a cache (server side rendering, or offline storage),
3475
+ * and also (potentially) during hot reloads.
3476
+ */
3477
+ ApolloClient.prototype.restore = function (serializedState) {
3478
+ return this.cache.restore(serializedState);
3479
+ };
3480
+ /**
3481
+ * Add additional local resolvers.
3482
+ *
3483
+ * @deprecated `addResolvers` will been removed in Apollo Client 4.0. It is
3484
+ * safe to continue using this method in Apollo Client 3.x.
3485
+ *
3486
+ * **Recommended now**
3487
+ *
3488
+ * No action needed
3489
+ *
3490
+ * **When upgrading**
3491
+ *
3492
+ * Use `client.localState.addResolvers(resolvers)`. Alternatively, store
3493
+ * the `LocalState` instance in a separate variable and call `addResolvers` on
3494
+ * that.
3495
+ */
3496
+ ApolloClient.prototype.addResolvers = function (resolvers) {
3497
+ this.localState.addResolvers(resolvers);
3498
+ };
3499
+ /**
3500
+ * Set (override existing) local resolvers.
3501
+ *
3502
+ * @deprecated `setResolvers` will been removed in Apollo Client 4.0. It is
3503
+ * safe to continue using this method in Apollo Client 3.x.
3504
+ *
3505
+ * **Recommended now**
3506
+ *
3507
+ * If possible, stop using the `setResolvers` method.
3508
+ *
3509
+ * **When upgrading**
3510
+ *
3511
+ * Remove the use of `setResolvers`.
3512
+ */
3513
+ ApolloClient.prototype.setResolvers = function (resolvers) {
3514
+ this.localState.setResolvers(resolvers);
3515
+ };
3516
+ /**
3517
+ * Get all registered local resolvers.
3518
+ *
3519
+ * @deprecated `getResolvers` will be removed in Apollo Client 4.0. It is
3520
+ * safe to continue using this method in Apollo Client 3.x.
3521
+ *
3522
+ * **Recommended now**
3523
+ *
3524
+ * If possible, stop using the `getResolvers` method.
3525
+ *
3526
+ * **When upgrading**
3527
+ *
3528
+ * Remove the use of `getResolvers`.
3529
+ */
3530
+ ApolloClient.prototype.getResolvers = function () {
3531
+ return this.localState.getResolvers();
3532
+ };
3533
+ /**
3534
+ * Set a custom local state fragment matcher.
3535
+ *
3536
+ * @deprecated Custom fragment matchers will no longer be supported in Apollo
3537
+ * Client 4.0 and has been replaced by `cache.fragmentMatches`. It is safe to
3538
+ * continue using `setLocalStateFragmentMatcher` in Apollo Client 3.x.
3539
+ *
3540
+ * **Recommended now**
3541
+ *
3542
+ * No action needed
3543
+ *
3544
+ * **When upgrading**
3545
+ *
3546
+ * Leverage `possibleTypes` with `InMemoryCache` to ensure fragments match
3547
+ * correctly. Ensure `possibleTypes` include local types if needed. If working
3548
+ * with a 3rd party cache implementation, ensure the 3rd party cache implements
3549
+ * the `cache.fragmentMatches` method. This function should no longer be used.
3550
+ */
3551
+ ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
3552
+ this.localState.setFragmentMatcher(fragmentMatcher);
3553
+ };
3554
+ /**
3555
+ * Define a new ApolloLink (or link chain) that Apollo Client will use.
3556
+ */
3557
+ ApolloClient.prototype.setLink = function (newLink) {
3558
+ this.link = this.queryManager.link = newLink;
3559
+ };
3560
+ Object.defineProperty(ApolloClient.prototype, "defaultContext", {
3561
+ get: function () {
3562
+ return this.queryManager.defaultContext;
3563
+ },
3564
+ enumerable: false,
3565
+ configurable: true
3566
+ });
3567
+ return ApolloClient;
3568
+ }());
3569
+ if (globalThis.__DEV__ !== false) {
3570
+ ApolloClient.prototype.getMemoryInternals = index.getApolloClientMemoryInternals;
3571
+ }
3572
+
3573
+ function setContext(setter) {
3574
+ return new index.ApolloLink(function (operation, forward) {
3575
+ var request = index.__rest(operation, []);
3576
+ return new index.Observable(function (observer) {
3577
+ var handle;
3578
+ var closed = false;
3579
+ Promise.resolve(request)
3580
+ .then(function (req) { return setter(req, operation.getContext()); })
3581
+ .then(operation.setContext)
3582
+ .then(function () {
3583
+ // if the observer is already closed, no need to subscribe.
3584
+ if (closed)
3585
+ return;
3586
+ handle = forward(operation).subscribe({
3587
+ next: observer.next.bind(observer),
3588
+ error: observer.error.bind(observer),
3589
+ complete: observer.complete.bind(observer),
3590
+ });
3591
+ })
3592
+ .catch(observer.error.bind(observer));
3593
+ return function () {
3594
+ closed = true;
3595
+ if (handle)
3596
+ handle.unsubscribe();
3597
+ };
3598
+ });
3599
+ });
3600
+ }
3601
+
3602
+ function onError(errorHandler) {
3603
+ return new index.ApolloLink(function (operation, forward) {
3604
+ return new index.Observable(function (observer) {
3605
+ var sub;
3606
+ var retriedSub;
3607
+ var retriedResult;
3608
+ try {
3609
+ sub = forward(operation).subscribe({
3610
+ next: function (result) {
3611
+ if (result.errors) {
3612
+ retriedResult = errorHandler({
3613
+ graphQLErrors: result.errors,
3614
+ response: result,
3615
+ operation: operation,
3616
+ forward: forward,
3617
+ });
3618
+ }
3619
+ else if (index.graphQLResultHasProtocolErrors(result)) {
3620
+ retriedResult = errorHandler({
3621
+ protocolErrors: result.extensions[index.PROTOCOL_ERRORS_SYMBOL],
3622
+ response: result,
3623
+ operation: operation,
3624
+ forward: forward,
3625
+ });
3626
+ }
3627
+ if (retriedResult) {
3628
+ retriedSub = retriedResult.subscribe({
3629
+ next: observer.next.bind(observer),
3630
+ error: observer.error.bind(observer),
3631
+ complete: observer.complete.bind(observer),
3632
+ });
3633
+ return;
3634
+ }
3635
+ observer.next(result);
3636
+ },
3637
+ error: function (networkError) {
3638
+ retriedResult = errorHandler({
3639
+ operation: operation,
3640
+ networkError: networkError,
3641
+ //Network errors can return GraphQL errors on for example a 403
3642
+ graphQLErrors: (networkError &&
3643
+ networkError.result &&
3644
+ networkError.result.errors) ||
3645
+ void 0,
3646
+ forward: forward,
3647
+ });
3648
+ if (retriedResult) {
3649
+ retriedSub = retriedResult.subscribe({
3650
+ next: observer.next.bind(observer),
3651
+ error: observer.error.bind(observer),
3652
+ complete: observer.complete.bind(observer),
3653
+ });
3654
+ return;
3655
+ }
3656
+ observer.error(networkError);
3657
+ },
3658
+ complete: function () {
3659
+ // disable the previous sub from calling complete on observable
3660
+ // if retry is in flight.
3661
+ if (!retriedResult) {
3662
+ observer.complete.bind(observer)();
3663
+ }
3664
+ },
3665
+ });
3666
+ }
3667
+ catch (e) {
3668
+ errorHandler({ networkError: e, operation: operation, forward: forward });
3669
+ observer.error(e);
3670
+ }
3671
+ return function () {
3672
+ if (sub)
3673
+ sub.unsubscribe();
3674
+ if (retriedSub)
3675
+ sub.unsubscribe();
3676
+ };
3677
+ });
3678
+ });
3679
+ }
3680
+ /** @class */ ((function (_super) {
3681
+ index.__extends(ErrorLink, _super);
3682
+ function ErrorLink(errorHandler) {
3683
+ var _this = _super.call(this) || this;
3684
+ _this.link = onError(errorHandler);
3685
+ return _this;
3686
+ }
3687
+ ErrorLink.prototype.request = function (operation, forward) {
3688
+ return this.link.request(operation, forward);
3689
+ };
3690
+ return ErrorLink;
3691
+ })(index.ApolloLink));
3692
+
3693
+ exports.ApolloError = index.ApolloError;
3694
+ exports.HttpLink = index.HttpLink;
3695
+ exports.InMemoryCache = index.InMemoryCache;
3696
+ Object.defineProperty(exports, "gql", {
3697
+ enumerable: true,
3698
+ get: function () { return index.gql; }
3699
+ });
3700
+ exports.split = index.split;
3701
+ exports.ApolloClient = ApolloClient;
3702
+ exports.onError = onError;
3703
+ exports.setContext = setContext;
3704
+ //# sourceMappingURL=apollo-client.client-DlG4HsFm.js.map