@khanacademy/wonder-blocks-data 7.0.0 → 8.0.1

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 (53) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/es/index.js +321 -759
  3. package/dist/index.js +1188 -802
  4. package/package.json +3 -3
  5. package/src/__docs__/_overview_ssr_.stories.mdx +13 -13
  6. package/src/__docs__/exports.abort-inflight-requests.stories.mdx +20 -0
  7. package/src/__docs__/exports.data.stories.mdx +3 -3
  8. package/src/__docs__/{exports.fulfill-all-data-requests.stories.mdx → exports.fetch-tracked-requests.stories.mdx} +5 -5
  9. package/src/__docs__/exports.get-gql-request-id.stories.mdx +24 -0
  10. package/src/__docs__/{exports.has-unfulfilled-requests.stories.mdx → exports.has-tracked-requests-to-be-fetched.stories.mdx} +4 -4
  11. package/src/__docs__/exports.intialize-hydration-cache.stories.mdx +29 -0
  12. package/src/__docs__/exports.purge-caches.stories.mdx +23 -0
  13. package/src/__docs__/{exports.remove-all-from-cache.stories.mdx → exports.purge-hydration-cache.stories.mdx} +4 -4
  14. package/src/__docs__/{exports.clear-shared-cache.stories.mdx → exports.purge-shared-cache.stories.mdx} +4 -4
  15. package/src/__docs__/exports.track-data.stories.mdx +4 -4
  16. package/src/__docs__/exports.use-cached-effect.stories.mdx +7 -4
  17. package/src/__docs__/exports.use-gql.stories.mdx +1 -33
  18. package/src/__docs__/exports.use-server-effect.stories.mdx +1 -1
  19. package/src/__docs__/exports.use-shared-cache.stories.mdx +2 -2
  20. package/src/__docs__/types.fetch-policy.stories.mdx +44 -0
  21. package/src/__docs__/types.response-cache.stories.mdx +1 -1
  22. package/src/__tests__/generated-snapshot.test.js +5 -5
  23. package/src/components/__tests__/data.test.js +2 -6
  24. package/src/hooks/__tests__/use-cached-effect.test.js +341 -100
  25. package/src/hooks/__tests__/use-hydratable-effect.test.js +15 -9
  26. package/src/hooks/__tests__/use-shared-cache.test.js +6 -6
  27. package/src/hooks/use-cached-effect.js +169 -93
  28. package/src/hooks/use-hydratable-effect.js +8 -1
  29. package/src/hooks/use-shared-cache.js +2 -2
  30. package/src/index.js +14 -78
  31. package/src/util/__tests__/get-gql-request-id.test.js +74 -0
  32. package/src/util/__tests__/graphql-document-node-parser.test.js +542 -0
  33. package/src/util/__tests__/hydration-cache-api.test.js +35 -0
  34. package/src/util/__tests__/purge-caches.test.js +29 -0
  35. package/src/util/__tests__/request-api.test.js +188 -0
  36. package/src/util/__tests__/request-fulfillment.test.js +42 -0
  37. package/src/util/__tests__/ssr-cache.test.js +68 -60
  38. package/src/util/__tests__/to-gql-operation.test.js +42 -0
  39. package/src/util/data-error.js +6 -0
  40. package/src/util/get-gql-request-id.js +50 -0
  41. package/src/util/graphql-document-node-parser.js +133 -0
  42. package/src/util/graphql-types.js +30 -0
  43. package/src/util/hydration-cache-api.js +28 -0
  44. package/src/util/purge-caches.js +15 -0
  45. package/src/util/request-api.js +66 -0
  46. package/src/util/request-fulfillment.js +32 -12
  47. package/src/util/request-tracking.js +1 -1
  48. package/src/util/ssr-cache.js +11 -24
  49. package/src/util/to-gql-operation.js +44 -0
  50. package/src/util/types.js +31 -0
  51. package/src/__docs__/exports.intialize-cache.stories.mdx +0 -29
  52. package/src/__docs__/exports.remove-from-cache.stories.mdx +0 -25
  53. package/src/__docs__/exports.request-fulfillment.stories.mdx +0 -36
package/dist/es/index.js CHANGED
@@ -4,47 +4,17 @@ import _extends from '@babel/runtime/helpers/extends';
4
4
  import * as React from 'react';
5
5
  import { useContext, useRef, useMemo, useCallback } from 'react';
6
6
 
7
- /**
8
- * Error kinds for DataError.
9
- */
7
+ const FetchPolicy = require("flow-enums-runtime").Mirrored(["CacheBeforeNetwork", "CacheAndNetwork", "CacheOnly", "NetworkOnly"]);
8
+
10
9
  const DataErrors = Object.freeze({
11
- /**
12
- * The kind of error is not known.
13
- */
14
10
  Unknown: "Unknown",
15
-
16
- /**
17
- * The error is internal to the executing code.
18
- */
19
11
  Internal: "Internal",
20
-
21
- /**
22
- * There was a problem with the provided input.
23
- */
24
12
  InvalidInput: "InvalidInput",
25
-
26
- /**
27
- * A network error occurred.
28
- */
29
13
  Network: "Network",
30
-
31
- /**
32
- * Response could not be parsed.
33
- */
14
+ NotAllowed: "NotAllowed",
34
15
  Parse: "Parse",
35
-
36
- /**
37
- * An error that occurred during SSR and was hydrated from cache
38
- */
39
16
  Hydrated: "Hydrated"
40
17
  });
41
- /**
42
- * An error from the Wonder Blocks Data API.
43
- *
44
- * Errors of this type will have names of the format:
45
- * `${kind}DataError`
46
- */
47
-
48
18
  class DataError extends KindError {
49
19
  constructor(message, kind, {
50
20
  metadata,
@@ -59,27 +29,14 @@ class DataError extends KindError {
59
29
 
60
30
  }
61
31
 
62
- /**
63
- * Describe an in-memory cache.
64
- */
65
32
  class ScopedInMemoryCache {
66
33
  constructor(initialCache = {}) {
67
34
  this._cache = initialCache;
68
35
  }
69
- /**
70
- * Indicate if this cache is being used or not.
71
- *
72
- * When the cache has entries, returns `true`; otherwise, returns `false`.
73
- */
74
-
75
36
 
76
37
  get inUse() {
77
38
  return Object.keys(this._cache).length > 0;
78
39
  }
79
- /**
80
- * Set a value in the cache.
81
- */
82
-
83
40
 
84
41
  set(scope, id, value) {
85
42
  var _this$_cache$scope;
@@ -99,20 +56,12 @@ class ScopedInMemoryCache {
99
56
  this._cache[scope] = (_this$_cache$scope = this._cache[scope]) != null ? _this$_cache$scope : {};
100
57
  this._cache[scope][id] = value;
101
58
  }
102
- /**
103
- * Retrieve a value from the cache.
104
- */
105
-
106
59
 
107
60
  get(scope, id) {
108
61
  var _this$_cache$scope$id, _this$_cache$scope2;
109
62
 
110
63
  return (_this$_cache$scope$id = (_this$_cache$scope2 = this._cache[scope]) == null ? void 0 : _this$_cache$scope2[id]) != null ? _this$_cache$scope$id : null;
111
64
  }
112
- /**
113
- * Purge an item from the cache.
114
- */
115
-
116
65
 
117
66
  purge(scope, id) {
118
67
  var _this$_cache$scope3;
@@ -127,12 +76,6 @@ class ScopedInMemoryCache {
127
76
  delete this._cache[scope];
128
77
  }
129
78
  }
130
- /**
131
- * Purge a scope of items that match the given predicate.
132
- *
133
- * If the predicate is omitted, then all items in the scope are purged.
134
- */
135
-
136
79
 
137
80
  purgeScope(scope, predicate) {
138
81
  if (!this._cache[scope]) {
@@ -154,12 +97,6 @@ class ScopedInMemoryCache {
154
97
  delete this._cache[scope];
155
98
  }
156
99
  }
157
- /**
158
- * Purge all items from the cache that match the given predicate.
159
- *
160
- * If the predicate is omitted, then all items in the cache are purged.
161
- */
162
-
163
100
 
164
101
  purgeAll(predicate) {
165
102
  if (predicate == null) {
@@ -174,9 +111,6 @@ class ScopedInMemoryCache {
174
111
 
175
112
  }
176
113
 
177
- /**
178
- * Describe a serializable in-memory cache.
179
- */
180
114
  class SerializableInMemoryCache extends ScopedInMemoryCache {
181
115
  constructor(initialCache = {}) {
182
116
  try {
@@ -185,18 +119,10 @@ class SerializableInMemoryCache extends ScopedInMemoryCache {
185
119
  throw new DataError(`An error occurred trying to initialize from a response cache snapshot: ${e}`, DataErrors.InvalidInput);
186
120
  }
187
121
  }
188
- /**
189
- * Set a value in the cache.
190
- */
191
-
192
122
 
193
123
  set(scope, id, value) {
194
124
  super.set(scope, id, Object.freeze(clone(value)));
195
125
  }
196
- /**
197
- * Clone the cache.
198
- */
199
-
200
126
 
201
127
  clone() {
202
128
  try {
@@ -211,18 +137,8 @@ class SerializableInMemoryCache extends ScopedInMemoryCache {
211
137
  }
212
138
 
213
139
  const DefaultScope$2 = "default";
214
- /**
215
- * The default instance is stored here.
216
- * It's created below in the Default() static property.
217
- */
218
140
 
219
141
  let _default$2;
220
- /**
221
- * Implements the response cache.
222
- *
223
- * INTERNAL USE ONLY
224
- */
225
-
226
142
 
227
143
  class SsrCache {
228
144
  static get Default() {
@@ -240,7 +156,6 @@ class SsrCache {
240
156
  }
241
157
 
242
158
  this._hydrationCache = new SerializableInMemoryCache({
243
- // $FlowIgnore[incompatible-call]
244
159
  [DefaultScope$2]: source
245
160
  });
246
161
  };
@@ -259,65 +174,34 @@ class SsrCache {
259
174
  this.getEntry = id => {
260
175
  var _this$_ssrOnlyCache$g, _this$_ssrOnlyCache;
261
176
 
262
- // Get the cached entry for this value.
263
- // We first look in the ssr cache and then the hydration cache.
264
- const internalEntry = (_this$_ssrOnlyCache$g = (_this$_ssrOnlyCache = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache.get(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$g : this._hydrationCache.get(DefaultScope$2, id); // If we are not server-side and we hydrated something, let's clear
265
- // that from the hydration cache to save memory.
177
+ const internalEntry = (_this$_ssrOnlyCache$g = (_this$_ssrOnlyCache = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache.get(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$g : this._hydrationCache.get(DefaultScope$2, id);
266
178
 
267
179
  if (this._ssrOnlyCache == null && internalEntry != null) {
268
- // We now delete this from our hydration cache as we don't need it.
269
- // This does mean that if another handler of the same type but
270
- // without some sort of linked cache won't get the value, but
271
- // that's not an expected use-case. If two different places use the
272
- // same handler and options (i.e. the same request), then the
273
- // handler should cater to that to ensure they share the result.
274
180
  this._hydrationCache.purge(DefaultScope$2, id);
275
- } // Getting the typing right between the in-memory cache and this
276
- // is hard. Just telling flow it's OK.
277
- // $FlowIgnore[incompatible-return]
278
-
181
+ }
279
182
 
280
183
  return internalEntry;
281
184
  };
282
185
 
283
- this.remove = id => {
284
- var _this$_ssrOnlyCache$p, _this$_ssrOnlyCache2;
285
-
286
- // NOTE(somewhatabstract): We could invoke removeAll with a predicate
287
- // to match the key of the entry we're removing, but that's an
288
- // inefficient way to remove a single item, so let's not do that.
289
- // Delete the entry from the appropriate cache.
290
- return this._hydrationCache.purge(DefaultScope$2, id) || ((_this$_ssrOnlyCache$p = (_this$_ssrOnlyCache2 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache2.purge(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$p : false);
291
- };
292
-
293
- this.removeAll = predicate => {
294
- var _this$_ssrOnlyCache3;
186
+ this.purgeData = predicate => {
187
+ var _this$_ssrOnlyCache2;
295
188
 
296
- const realPredicate = predicate ? // We know what we're putting into the cache so let's assume it
297
- // conforms.
298
- // $FlowIgnore[incompatible-call]
299
- (_, key, cachedEntry) => predicate(key, cachedEntry) : undefined; // Apply the predicate to what we have in our caches.
189
+ const realPredicate = predicate ? (_, key, cachedEntry) => predicate(key, cachedEntry) : undefined;
300
190
 
301
191
  this._hydrationCache.purgeAll(realPredicate);
302
192
 
303
- (_this$_ssrOnlyCache3 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache3.purgeAll(realPredicate);
193
+ (_this$_ssrOnlyCache2 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache2.purgeAll(realPredicate);
304
194
  };
305
195
 
306
196
  this.cloneHydratableData = () => {
307
197
  var _cache$DefaultScope;
308
198
 
309
- // We return our hydration cache only.
310
- const cache = this._hydrationCache.clone(); // If we're empty, we still want to return an object, so we default
311
- // to an empty object.
312
- // We only need the default scope out of our scoped in-memory cache.
313
- // We know that it conforms to our expectations.
314
- // $FlowIgnore[incompatible-return]
315
-
199
+ const cache = this._hydrationCache.clone();
316
200
 
317
201
  return (_cache$DefaultScope = cache[DefaultScope$2]) != null ? _cache$DefaultScope : {};
318
202
  };
319
203
 
320
- this._ssrOnlyCache = Server.isServerSide() ? ssrOnlyCache || new SerializableInMemoryCache() : undefined;
204
+ this._ssrOnlyCache = process.env.NODE_ENV === "test" || Server.isServerSide() ? ssrOnlyCache || new SerializableInMemoryCache() : undefined;
321
205
  this._hydrationCache = hydrationCache || new SerializableInMemoryCache();
322
206
  }
323
207
 
@@ -325,36 +209,24 @@ class SsrCache {
325
209
  const frozenEntry = Object.freeze(entry);
326
210
 
327
211
  if (Server.isServerSide()) {
328
- // We are server-side.
329
- // We need to store this value.
330
212
  if (hydrate) {
331
213
  this._hydrationCache.set(DefaultScope$2, id, frozenEntry);
332
214
  } else {
333
- var _this$_ssrOnlyCache4;
215
+ var _this$_ssrOnlyCache3;
334
216
 
335
- // Usually, when server-side, this cache will always be present.
336
- // We do fake server-side in our doc example though, when it
337
- // won't be.
338
- (_this$_ssrOnlyCache4 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache4.set(DefaultScope$2, id, frozenEntry);
217
+ (_this$_ssrOnlyCache3 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache3.set(DefaultScope$2, id, frozenEntry);
339
218
  }
340
219
  }
341
220
 
342
221
  return frozenEntry;
343
222
  }
344
- /**
345
- * Initialize the cache from a given cache state.
346
- *
347
- * This can only be called if the cache is not already in use.
348
- */
349
-
350
223
 
351
224
  }
352
225
 
353
- let _default$1;
354
- /**
355
- * This fulfills a request, making sure that in-flight requests are shared.
356
- */
226
+ const initializeHydrationCache = source => SsrCache.Default.initialize(source);
227
+ const purgeHydrationCache = predicate => SsrCache.Default.purgeData(predicate);
357
228
 
229
+ let _default$1;
358
230
 
359
231
  class RequestFulfillment {
360
232
  constructor() {
@@ -364,18 +236,11 @@ class RequestFulfillment {
364
236
  handler,
365
237
  hydrate: _hydrate = true
366
238
  }) => {
367
- /**
368
- * If we have an inflight request, we'll provide that.
369
- */
370
239
  const inflight = this._requests[id];
371
240
 
372
241
  if (inflight) {
373
242
  return inflight;
374
243
  }
375
- /**
376
- * We don't have an inflight request, so let's set one up.
377
- */
378
-
379
244
 
380
245
  const request = handler().then(data => ({
381
246
  status: "success",
@@ -385,13 +250,7 @@ class RequestFulfillment {
385
250
  metadata: {
386
251
  unexpectedError: error
387
252
  }
388
- }) : error; // Return aborted result if the request was aborted.
389
- // The only way to detect this reliably, it seems, is to
390
- // check the error name and see if it's "AbortError" (this
391
- // is also what Apollo does).
392
- // Even then, it's reliant on the handler supporting aborts.
393
- // TODO(somewhatabstract, FEI-4276): Add first class abort
394
- // support to the handler API.
253
+ }) : error;
395
254
 
396
255
  if (actualError.name === "AbortError") {
397
256
  return {
@@ -405,11 +264,18 @@ class RequestFulfillment {
405
264
  };
406
265
  }).finally(() => {
407
266
  delete this._requests[id];
408
- }); // Store the request in our cache.
409
-
267
+ });
410
268
  this._requests[id] = request;
411
269
  return request;
412
270
  };
271
+
272
+ this.abort = id => {
273
+ delete this._requests[id];
274
+ };
275
+
276
+ this.abortAll = () => {
277
+ Object.keys(this._requests).forEach(id => this.abort(id));
278
+ };
413
279
  }
414
280
 
415
281
  static get Default() {
@@ -422,24 +288,9 @@ class RequestFulfillment {
422
288
 
423
289
  }
424
290
 
425
- /**
426
- * Used to inject our tracking function into the render framework.
427
- *
428
- * INTERNAL USE ONLY
429
- */
430
- const TrackerContext = new React.createContext(null);
431
- /**
432
- * The default instance is stored here.
433
- * It's created below in the Default() static property.
434
- */
291
+ const TrackerContext = React.createContext(null);
435
292
 
436
293
  let _default;
437
- /**
438
- * Implements request tracking and fulfillment.
439
- *
440
- * INTERNAL USE ONLY
441
- */
442
-
443
294
 
444
295
  class RequestTracker {
445
296
  static get Default() {
@@ -449,18 +300,11 @@ class RequestTracker {
449
300
 
450
301
  return _default;
451
302
  }
452
- /**
453
- * These are the caches for tracked requests, their handlers, and responses.
454
- */
455
-
456
303
 
457
304
  constructor(responseCache = undefined) {
458
305
  this._trackedRequests = {};
459
306
 
460
307
  this.trackDataRequest = (id, handler, hydrate) => {
461
- /**
462
- * If we don't already have this tracked, then let's track it.
463
- */
464
308
  if (this._trackedRequests[id] == null) {
465
309
  this._trackedRequests[id] = {
466
310
  handler,
@@ -487,113 +331,113 @@ class RequestTracker {
487
331
  promises.push(this._requestFulfillment.fulfill(requestKey, _extends({}, options)).then(result => {
488
332
  switch (result.status) {
489
333
  case "success":
490
- /**
491
- * Let's cache the data!
492
- *
493
- * NOTE: This only caches when we're
494
- * server side.
495
- */
496
334
  cacheData(requestKey, result.data, options.hydrate);
497
335
  break;
498
336
 
499
337
  case "error":
500
- /**
501
- * Let's cache the error!
502
- *
503
- * NOTE: This only caches when we're
504
- * server side.
505
- */
506
338
  cacheError(requestKey, result.error, options.hydrate);
507
339
  break;
508
- } // For status === "loading":
509
- // Could never get here unless we wrote
510
- // the code wrong. Rather than bloat
511
- // code with useless error, just ignore.
512
- // For status === "aborted":
513
- // We won't cache this.
514
- // We don't hydrate aborted requests,
515
- // so the client would just see them
516
- // as unfulfilled data.
517
-
340
+ }
518
341
 
519
342
  return;
520
343
  }));
521
344
  } catch (e) {
522
- // This captures if there are problems in the code that
523
- // begins the requests.
524
345
  promises.push(Promise.resolve(cacheError(requestKey, e, options.hydrate)));
525
346
  }
526
347
  }
527
- /**
528
- * Clear out our tracked info.
529
- *
530
- * We call this now for a simpler API.
531
- *
532
- * If we reset the tracked calls after all promises resolve, any
533
- * request tracking done while promises are in flight would be lost.
534
- *
535
- * If we don't reset at all, then we have to expose the `reset` call
536
- * for consumers to use, or they'll only ever be able to accumulate
537
- * more and more tracked requests, having to fulfill them all every
538
- * time.
539
- *
540
- * Calling it here means we can have multiple "track -> request"
541
- * cycles in a row and in an easy to reason about manner.
542
- */
543
-
544
348
 
545
349
  this.reset();
546
- /**
547
- * Let's wait for everything to fulfill, and then clone the cached data.
548
- */
549
-
550
350
  return Promise.all(promises).then(() => this._responseCache.cloneHydratableData());
551
351
  };
552
352
 
553
353
  this._responseCache = responseCache || SsrCache.Default;
554
354
  this._requestFulfillment = new RequestFulfillment();
555
355
  }
556
- /**
557
- * Track a request.
558
- *
559
- * This method caches a request and its handler for use during server-side
560
- * rendering to allow us to fulfill requests before producing a final render.
561
- */
562
356
 
563
-
564
- /**
565
- * Indicates if we have requests waiting to be fulfilled.
566
- */
567
357
  get hasUnfulfilledRequests() {
568
358
  return Object.keys(this._trackedRequests).length > 0;
569
359
  }
570
- /**
571
- * Initiate fulfillment of all tracked requests.
572
- *
573
- * This loops over the requests that were tracked using TrackData, and asks
574
- * the respective handlers to fulfill those requests in the order they were
575
- * tracked.
576
- *
577
- * Calling this method marks tracked requests as fulfilled; requests are
578
- * removed from the list of tracked requests by calling this method.
579
- *
580
- * @returns {Promise<ResponseCache>} The promise of the data that was
581
- * cached as a result of fulfilling the tracked requests.
582
- */
583
-
584
360
 
585
361
  }
586
362
 
587
- /**
588
- * Component to enable data request tracking when server-side rendering.
589
- */
363
+ const SSRCheck = () => {
364
+ if (Server.isServerSide()) {
365
+ return null;
366
+ }
367
+
368
+ if (process.env.NODE_ENV === "production") {
369
+ return new DataError("No CSR tracking", DataErrors.NotAllowed);
370
+ } else {
371
+ return new DataError("Data requests are not tracked for fulfillment when when client-side", DataErrors.NotAllowed);
372
+ }
373
+ };
374
+
375
+ const fetchTrackedRequests = () => {
376
+ const ssrCheck = SSRCheck();
377
+
378
+ if (ssrCheck != null) {
379
+ return Promise.reject(ssrCheck);
380
+ }
381
+
382
+ return RequestTracker.Default.fulfillTrackedRequests();
383
+ };
384
+ const hasTrackedRequestsToBeFetched = () => {
385
+ const ssrCheck = SSRCheck();
386
+
387
+ if (ssrCheck != null) {
388
+ throw ssrCheck;
389
+ }
390
+
391
+ return RequestTracker.Default.hasUnfulfilledRequests;
392
+ };
393
+ const abortInflightRequests = () => {
394
+ RequestFulfillment.Default.abortAll();
395
+ };
396
+
397
+ const cache$1 = new ScopedInMemoryCache();
398
+ const purgeSharedCache = (scope = "") => {
399
+ if (scope && typeof scope === "string") {
400
+ cache$1.purgeScope(scope);
401
+ } else {
402
+ cache$1.purgeAll();
403
+ }
404
+ };
405
+ const useSharedCache = (id, scope, initialValue) => {
406
+ if (!id || typeof id !== "string") {
407
+ throw new DataError("id must be a non-empty string", DataErrors.InvalidInput);
408
+ }
409
+
410
+ if (!scope || typeof scope !== "string") {
411
+ throw new DataError("scope must be a non-empty string", DataErrors.InvalidInput);
412
+ }
413
+
414
+ const cacheValue = React.useCallback(value => value == null ? cache$1.purge(scope, id) : cache$1.set(scope, id, value), [id, scope]);
415
+ let currentValue = cache$1.get(scope, id);
416
+
417
+ if (currentValue == null && initialValue !== undefined) {
418
+ const value = typeof initialValue === "function" ? initialValue() : initialValue;
419
+
420
+ if (value != null) {
421
+ cacheValue(value);
422
+ currentValue = value;
423
+ }
424
+ }
425
+
426
+ return [currentValue, cacheValue];
427
+ };
428
+
429
+ const purgeCaches = () => {
430
+ purgeSharedCache();
431
+ purgeHydrationCache();
432
+ };
433
+
590
434
  class TrackData extends React.Component {
591
435
  render() {
592
436
  if (!Server.isServerSide()) {
593
437
  throw new Error("This component is not for use during client-side rendering");
594
438
  }
595
439
 
596
- return /*#__PURE__*/React.createElement(TrackerContext.Provider, {
440
+ return React.createElement(TrackerContext.Provider, {
597
441
  value: RequestTracker.Default.trackDataRequest
598
442
  }, this.props.children);
599
443
  }
@@ -606,10 +450,6 @@ const loadingStatus = Object.freeze({
606
450
  const abortedStatus = Object.freeze({
607
451
  status: "aborted"
608
452
  });
609
- /**
610
- * Create Result<TData> instances with specific statuses.
611
- */
612
-
613
453
  const Status = Object.freeze({
614
454
  loading: () => loadingStatus,
615
455
  aborted: () => abortedStatus,
@@ -623,11 +463,7 @@ const Status = Object.freeze({
623
463
  })
624
464
  });
625
465
 
626
- /**
627
- * Turns a cache entry into a stateful result.
628
- */
629
466
  const resultFromCachedResponse = cacheEntry => {
630
- // No cache entry means no result to be hydrated.
631
467
  if (cacheEntry == null) {
632
468
  return null;
633
469
  }
@@ -638,338 +474,163 @@ const resultFromCachedResponse = cacheEntry => {
638
474
  } = cacheEntry;
639
475
 
640
476
  if (error != null) {
641
- // Let's hydrate the error. We don't persist everything about the
642
- // original error on the server, hence why we only superficially
643
- // hydrate it to a GqlHydratedError.
644
477
  return Status.error(new DataError(error, DataErrors.Hydrated));
645
478
  }
646
479
 
647
480
  if (data != null) {
648
481
  return Status.success(data);
649
- } // We shouldn't get here since we don't actually cache null data.
650
-
482
+ }
651
483
 
652
484
  return Status.aborted();
653
485
  };
654
486
 
655
- /**
656
- * InterceptContext defines a map from request ID to interception methods.
657
- *
658
- * INTERNAL USE ONLY
659
- */
660
- const InterceptContext = /*#__PURE__*/React.createContext([]);
661
-
662
- /**
663
- * Allow request handling to be intercepted.
664
- *
665
- * Hook to take a uniquely identified request handler and return a
666
- * method that will support request interception from the InterceptRequest
667
- * component.
668
- *
669
- * If you want request interception to be supported with `useServerEffect` or
670
- * any client-side effect that uses the handler, call this first to generate
671
- * an intercepted handler, and then invoke `useServerEffect` (or other things)
672
- * with that intercepted handler.
673
- */
674
- const useRequestInterception = (requestId, handler) => {
675
- // Get the interceptors that have been registered.
676
- const interceptors = React.useContext(InterceptContext); // Now, we need to create a new handler that will check if the
677
- // request is intercepted before ultimately calling the original handler
678
- // if nothing intercepted it.
679
- // We memoize this so that it only changes if something related to it
680
- // changes.
487
+ const InterceptContext = React.createContext([]);
681
488
 
489
+ const useRequestInterception = (requestId, handler) => {
490
+ const interceptors = React.useContext(InterceptContext);
682
491
  const interceptedHandler = React.useCallback(() => {
683
- // Call the interceptors from closest to furthest.
684
- // If one returns a non-null result, then we keep that.
685
492
  const interceptResponse = interceptors.reduceRight((prev, interceptor) => {
686
493
  if (prev != null) {
687
494
  return prev;
688
495
  }
689
496
 
690
497
  return interceptor(requestId);
691
- }, null); // If nothing intercepted this request, invoke the original handler.
692
- // NOTE: We can't guarantee all interceptors return the same type
693
- // as our handler, so how can flow know? Let's just suppress that.
694
- // $FlowFixMe[incompatible-return]
695
-
498
+ }, null);
696
499
  return interceptResponse != null ? interceptResponse : handler();
697
500
  }, [handler, interceptors, requestId]);
698
501
  return interceptedHandler;
699
502
  };
700
503
 
701
- /**
702
- * Hook to perform an asynchronous action during server-side rendering.
703
- *
704
- * This hook registers an asynchronous action to be performed during
705
- * server-side rendering. The action is performed only once, and the result
706
- * is cached against the given identifier so that subsequent calls return that
707
- * cached result allowing components to render more of the component.
708
- *
709
- * This hook requires the Wonder Blocks Data functionality for resolving
710
- * pending requests, as well as support for the hydration cache to be
711
- * embedded into a page so that the result can by hydrated (if that is a
712
- * requirement).
713
- *
714
- * The asynchronous action is never invoked on the client-side.
715
- */
716
504
  const useServerEffect = (requestId, handler, options = {}) => {
717
505
  const {
718
506
  hydrate = true,
719
507
  skip = false
720
- } = options; // Plug in to the request interception framework for code that wants
721
- // to use that.
722
-
723
- const interceptedHandler = useRequestInterception(requestId, handler); // If we're server-side or hydrating, we'll have a cached entry to use.
724
- // So we get that and use it to initialize our state.
725
- // This works in both hydration and SSR because the very first call to
726
- // this will have cached data in those cases as it will be present on the
727
- // initial render - and subsequent renders on the client it will be null.
728
-
729
- const cachedResult = SsrCache.Default.getEntry(requestId); // We only track data requests when we are server-side, we are not skipping
730
- // the request, and we don't already have a result, as given by the
731
- // cachedData (which is also the initial value for the result state).
732
-
508
+ } = options;
509
+ const interceptedHandler = useRequestInterception(requestId, handler);
510
+ const cachedResult = SsrCache.Default.getEntry(requestId);
733
511
  const maybeTrack = useContext(TrackerContext);
734
512
 
735
513
  if (!skip && cachedResult == null && Server.isServerSide()) {
736
514
  maybeTrack == null ? void 0 : maybeTrack(requestId, interceptedHandler, hydrate);
737
- } // A null result means there was no result to hydrate.
738
-
515
+ }
739
516
 
740
517
  return cachedResult == null ? null : resultFromCachedResponse(cachedResult);
741
518
  };
742
519
 
743
- /**
744
- * This is the cache.
745
- * It's incredibly complex.
746
- * Very in-memory. So cache. Such complex. Wow.
747
- */
748
- const cache = new ScopedInMemoryCache();
749
- /**
750
- * Clear the in-memory cache or a single scope within it.
751
- */
752
-
753
- const clearSharedCache = (scope = "") => {
754
- // If we have a valid scope (empty string is falsy), then clear that scope.
755
- if (scope && typeof scope === "string") {
756
- cache.purgeScope(scope);
757
- } else {
758
- // Just reset the object. This should be sufficient.
759
- cache.purgeAll();
760
- }
761
- };
762
- /**
763
- * Hook to retrieve data from and store data in an in-memory cache.
764
- *
765
- * @returns {[?ReadOnlyCacheValue, CacheValueFn]}
766
- * Returns an array containing the current cache entry (or undefined), a
767
- * function to set the cache entry (passing null or undefined to this function
768
- * will delete the entry).
769
- *
770
- * To clear a single scope within the cache or the entire cache,
771
- * the `clearScopedCache` export is available.
772
- *
773
- * NOTE: Unlike useState or useReducer, we don't automatically update folks
774
- * if the value they reference changes. We might add it later (if we need to),
775
- * but the likelihood here is that things won't be changing in this cache in a
776
- * way where we would need that. If we do (and likely only in specific
777
- * circumstances), we should consider adding a simple boolean useState that can
778
- * be toggled to cause a rerender whenever the referenced cached data changes
779
- * so that callers can re-render on cache changes. However, we should make
780
- * sure this toggling is optional - or we could use a callback argument, to
781
- * achieve this on an as-needed basis.
782
- */
783
-
784
- const useSharedCache = (id, scope, initialValue) => {
785
- // Verify arguments.
786
- if (!id || typeof id !== "string") {
787
- throw new DataError("id must be a non-empty string", DataErrors.InvalidInput);
788
- }
789
-
790
- if (!scope || typeof scope !== "string") {
791
- throw new DataError("scope must be a non-empty string", DataErrors.InvalidInput);
792
- } // Memoize our APIs.
793
- // This one allows callers to set or replace the cached value.
520
+ const DefaultScope$1 = "useCachedEffect";
521
+ const useCachedEffect = (requestId, handler, options = {}) => {
522
+ var _ref;
794
523
 
524
+ const {
525
+ fetchPolicy = FetchPolicy.CacheBeforeNetwork,
526
+ skip: hardSkip = false,
527
+ retainResultOnChange = false,
528
+ onResultChanged,
529
+ scope = DefaultScope$1
530
+ } = options;
531
+ const interceptedHandler = useRequestInterception(requestId, handler);
532
+ const [mostRecentResult, setMostRecentResult] = useSharedCache(requestId, scope);
533
+ const forceUpdate = useForceUpdate();
534
+ const networkResultRef = React.useRef();
535
+ const currentRequestRef = React.useRef();
536
+ const fetchRequest = React.useMemo(() => {
537
+ var _currentRequestRef$cu;
795
538
 
796
- const cacheValue = React.useCallback(value => value == null ? cache.purge(scope, id) : cache.set(scope, id, value), [id, scope]); // We don't memo-ize the current value, just in case the cache was updated
797
- // since our last run through. Also, our cache does not know what type it
798
- // stores, so we have to cast it to the type we're exporting. This is a
799
- // dev time courtesy, rather than a runtime thing.
800
- // $FlowIgnore[incompatible-type]
539
+ (_currentRequestRef$cu = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu.cancel();
540
+ currentRequestRef.current = null;
541
+ networkResultRef.current = null;
801
542
 
802
- let currentValue = cache.get(scope, id); // If we have an initial value, we need to add it to the cache
803
- // and use it as our current value.
543
+ const fetchFn = () => {
544
+ var _currentRequestRef$cu2, _currentRequestRef$cu3;
804
545
 
805
- if (currentValue == null && initialValue !== undefined) {
806
- // Get the initial value.
807
- const value = typeof initialValue === "function" ? initialValue() : initialValue;
546
+ if (fetchPolicy === FetchPolicy.CacheOnly) {
547
+ throw new DataError("Cannot fetch with CacheOnly policy", DataErrors.NotAllowed);
548
+ }
808
549
 
809
- if (value != null) {
810
- // Update the cache.
811
- cacheValue(value); // Make sure we return this value as our current value.
550
+ const request = RequestFulfillment.Default.fulfill(`${requestId}|${scope}`, {
551
+ handler: interceptedHandler
552
+ });
812
553
 
813
- currentValue = value;
814
- }
815
- } // Now we have everything, let's return it.
554
+ if (request === ((_currentRequestRef$cu2 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu2.request)) {
555
+ return;
556
+ }
816
557
 
558
+ networkResultRef.current = null;
559
+ (_currentRequestRef$cu3 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu3.cancel();
560
+ let cancel = false;
561
+ request.then(result => {
562
+ currentRequestRef.current = null;
817
563
 
818
- return [currentValue, cacheValue];
819
- };
564
+ if (cancel) {
565
+ return;
566
+ }
820
567
 
821
- const DefaultScope$1 = "useCachedEffect";
822
- /**
823
- * Hook to execute and cache an async operation on the client.
824
- *
825
- * This hook executes the given handler on the client if there is no
826
- * cached result to use.
827
- *
828
- * Results are cached so they can be shared between equivalent invocations.
829
- * In-flight requests are also shared, so that concurrent calls will
830
- * behave as one might exect. Cache updates invoked by one hook instance
831
- * do not trigger renders in components that use the same requestID; however,
832
- * that should not matter since concurrent requests will share the same
833
- * in-flight request, and subsequent renders will grab from the cache.
834
- *
835
- * Once the request has been tried once and a non-loading response has been
836
- * cached, the request will not executed made again.
837
- */
568
+ setMostRecentResult(result);
569
+ networkResultRef.current = result;
838
570
 
839
- const useCachedEffect = (requestId, handler, options = {}) => {
840
- const {
841
- skip: hardSkip = false,
842
- retainResultOnChange = false,
843
- onResultChanged,
844
- scope = DefaultScope$1
845
- } = options; // Plug in to the request interception framework for code that wants
846
- // to use that.
571
+ if (onResultChanged != null) {
572
+ onResultChanged(result);
573
+ } else {
574
+ forceUpdate();
575
+ }
847
576
 
848
- const interceptedHandler = useRequestInterception(requestId, handler); // Instead of using state, which would be local to just this hook instance,
849
- // we use a shared in-memory cache.
577
+ return;
578
+ });
579
+ currentRequestRef.current = {
580
+ requestId,
581
+ request,
850
582
 
851
- const [mostRecentResult, setMostRecentResult] = useSharedCache(requestId, // The key of the cached item
852
- scope // The scope of the cached items
853
- // No default value. We don't want the loading status there; to ensure
854
- // that all calls when the request is in-flight will update once that
855
- // request is done, we want the cache to be empty until that point.
856
- ); // Build a function that will update the cache and either invoke the
857
- // callback provided in options, or force an update.
583
+ cancel() {
584
+ cancel = true;
585
+ RequestFulfillment.Default.abort(requestId);
586
+ }
858
587
 
859
- const forceUpdate = useForceUpdate();
860
- const setCacheAndNotify = React.useCallback(value => {
861
- setMostRecentResult(value); // If our caller provided a cacheUpdated callback, we use that.
862
- // Otherwise, we toggle our little state update.
588
+ };
589
+ };
863
590
 
864
- if (onResultChanged != null) {
865
- onResultChanged(value);
866
- } else {
867
- forceUpdate();
868
- }
869
- }, [setMostRecentResult, onResultChanged, forceUpdate]); // We need to trigger a re-render when the request ID changes as that
870
- // indicates its a different request. We don't default the current id as
871
- // this is a proxy for the first render, where we will make the request
872
- // if we don't already have a cached value.
873
-
874
- const requestIdRef = React.useRef();
875
- const previousRequestId = requestIdRef.current; // Calculate our soft skip state.
876
- // Soft skip changes are things that should skip the effect if something
877
- // else triggers the effect to run, but should not itself trigger the effect
878
- // (which would cancel a previous invocation).
879
-
880
- const softSkip = React.useMemo(() => {
881
- if (requestId === previousRequestId) {
882
- // If the requestId is unchanged, it means we already rendered at
883
- // least once and so we already made the request at least once. So
884
- // we can bail out right here.
885
- return true;
886
- } // If we already have a cached value, we're going to skip.
887
-
888
-
889
- if (mostRecentResult != null) {
890
- return true;
591
+ return fetchFn;
592
+ }, [requestId, onResultChanged, forceUpdate, setMostRecentResult, fetchPolicy]);
593
+ const requestIdRef = React.useRef(requestId);
594
+ const shouldFetch = React.useMemo(() => {
595
+ if (hardSkip) {
596
+ return false;
891
597
  }
892
598
 
893
- return false;
894
- }, [requestId, previousRequestId, mostRecentResult]); // So now we make sure the client-side request happens per our various
895
- // options.
599
+ switch (fetchPolicy) {
600
+ case FetchPolicy.CacheOnly:
601
+ return false;
602
+
603
+ case FetchPolicy.CacheBeforeNetwork:
604
+ return mostRecentResult == null || requestId !== requestIdRef.current;
896
605
 
606
+ case FetchPolicy.CacheAndNetwork:
607
+ case FetchPolicy.NetworkOnly:
608
+ return networkResultRef.current == null;
609
+ }
610
+ }, [requestId, mostRecentResult, fetchPolicy, hardSkip]);
611
+ requestIdRef.current = requestId;
897
612
  React.useEffect(() => {
898
- let cancel = false; // We don't do anything if we've been told to hard skip (a hard skip
899
- // means we should cancel the previous request and is therefore a
900
- // dependency on that), or we have determined we have already done
901
- // enough and can soft skip (a soft skip doesn't trigger the request
902
- // to re-run; we don't want to cancel the in progress effect if we're
903
- // soft skipping.
904
-
905
- if (hardSkip || softSkip) {
613
+ if (!shouldFetch) {
906
614
  return;
907
- } // If we got here, we're going to perform the request.
908
- // Let's make sure our ref is set to the most recent requestId.
909
-
910
-
911
- requestIdRef.current = requestId; // OK, we've done all our checks and things. It's time to make the
912
- // request. We use our request fulfillment here so that in-flight
913
- // requests are shared.
914
- // NOTE: Our request fulfillment handles the error cases here.
915
- // Catching shouldn't serve a purpose.
916
- // eslint-disable-next-line promise/catch-or-return
917
-
918
- RequestFulfillment.Default.fulfill(requestId, {
919
- handler: interceptedHandler
920
- }).then(result => {
921
- if (cancel) {
922
- // We don't modify our result if an earlier effect was
923
- // cancelled as it means that this hook no longer cares about
924
- // that old request.
925
- return;
926
- }
615
+ }
927
616
 
928
- setCacheAndNotify(result);
929
- return; // Shut up eslint always-return rule.
930
- });
617
+ fetchRequest();
931
618
  return () => {
932
- // TODO(somewhatabstract, FEI-4276): Eventually, we will want to be
933
- // able abort in-flight requests, but for now, we don't have that.
934
- // (Of course, we will only want to abort them if no one is waiting
935
- // on them)
936
- // For now, we just block cancelled requests from changing our
937
- // cache.
938
- cancel = true;
939
- }; // We only want to run this effect if the requestId, or skip values
940
- // change. These are the only two things that should affect the
941
- // cancellation of a pending request. We do not update if the handler
942
- // changes, in order to simplify the API - otherwise, callers would
943
- // not be able to use inline functions with this hook.
944
- // eslint-disable-next-line react-hooks/exhaustive-deps
945
- }, [hardSkip, requestId]); // We track the last result we returned in order to support the
946
- // "retainResultOnChange" option.
619
+ var _currentRequestRef$cu4;
947
620
 
621
+ (_currentRequestRef$cu4 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu4.cancel();
622
+ currentRequestRef.current = null;
623
+ };
624
+ }, [shouldFetch, fetchRequest]);
948
625
  const lastResultAgnosticOfIdRef = React.useRef(Status.loading());
949
- const loadingResult = retainResultOnChange ? lastResultAgnosticOfIdRef.current : Status.loading(); // Loading is a transient state, so we only use it here; it's not something
950
- // we cache.
951
-
952
- const result = React.useMemo(() => mostRecentResult != null ? mostRecentResult : loadingResult, [mostRecentResult, loadingResult]);
626
+ const loadingResult = retainResultOnChange ? lastResultAgnosticOfIdRef.current : Status.loading();
627
+ const result = (_ref = fetchPolicy === FetchPolicy.NetworkOnly ? networkResultRef.current : mostRecentResult) != null ? _ref : loadingResult;
953
628
  lastResultAgnosticOfIdRef.current = result;
954
- return result;
629
+ return [result, fetchRequest];
955
630
  };
956
631
 
957
- /**
958
- * Policies to define how a hydratable effect should behave client-side.
959
- */
960
632
  const WhenClientSide = require("flow-enums-runtime").Mirrored(["DoNotHydrate", "ExecuteWhenNoResult", "ExecuteWhenNoSuccessResult", "AlwaysExecute"]);
961
633
  const DefaultScope = "useHydratableEffect";
962
- /**
963
- * Hook to execute an async operation on server and client.
964
- *
965
- * This hook executes the given handler on the server and on the client,
966
- * and, depending on the given options, can hydrate the server-side result.
967
- *
968
- * Results are cached on the client so they can be shared between equivalent
969
- * invocations. Cache changes from one hook instance do not trigger renders
970
- * in components that use the same requestID.
971
- */
972
-
973
634
  const useHydratableEffect = (requestId, handler, options = {}) => {
974
635
  const {
975
636
  clientBehavior = WhenClientSide.ExecuteWhenNoSuccessResult,
@@ -977,76 +638,39 @@ const useHydratableEffect = (requestId, handler, options = {}) => {
977
638
  retainResultOnChange = false,
978
639
  onResultChanged,
979
640
  scope = DefaultScope
980
- } = options; // Now we instruct the server to perform the operation.
981
- // When client-side, this will look up any response for hydration; it does
982
- // not invoke the handler.
983
-
641
+ } = options;
984
642
  const serverResult = useServerEffect(requestId, handler, {
985
- // Only hydrate if our behavior isn't telling us not to.
986
643
  hydrate: clientBehavior !== WhenClientSide.DoNotHydrate,
987
644
  skip
988
645
  });
989
646
  const getDefaultCacheValue = React.useCallback(() => {
990
- // If we don't have a requestId, it's our first render, the one
991
- // where we hydrated. So defer to our clientBehavior value.
992
647
  switch (clientBehavior) {
993
648
  case WhenClientSide.DoNotHydrate:
994
649
  case WhenClientSide.AlwaysExecute:
995
- // Either we weren't hydrating at all, or we don't care
996
- // if we hydrated something or not, either way, we're
997
- // doing a request.
998
650
  return null;
999
651
 
1000
652
  case WhenClientSide.ExecuteWhenNoResult:
1001
- // We only execute if we didn't hydrate something.
1002
- // So, returning the hydration result as default for our
1003
- // cache, will then prevent the cached effect running.
1004
653
  return serverResult;
1005
654
 
1006
655
  case WhenClientSide.ExecuteWhenNoSuccessResult:
1007
- // We only execute if we didn't hydrate a success result.
1008
656
  if ((serverResult == null ? void 0 : serverResult.status) === "success") {
1009
- // So, returning the hydration result as default for our
1010
- // cache, will then prevent the cached effect running.
1011
657
  return serverResult;
1012
658
  }
1013
659
 
1014
660
  return null;
1015
- } // There is no reason for this to change after the first render,
1016
- // you might think, but the function closes around serverResult and if
1017
- // the requestId changes, it still returns the hydrate result of the
1018
- // first render of the previous requestId. This then means that the
1019
- // hydrate result is still the same, and the effect is not re-executed
1020
- // because the cache gets incorrectly defaulted.
1021
- // However, we don't want to bother doing anything with this on
1022
- // client behavior changing since that truly is irrelevant.
1023
- // eslint-disable-next-line react-hooks/exhaustive-deps
1024
-
1025
- }, [serverResult]); // Instead of using state, which would be local to just this hook instance,
1026
- // we use a shared in-memory cache.
1027
-
1028
- useSharedCache(requestId, // The key of the cached item
1029
- scope, // The scope of the cached items
1030
- getDefaultCacheValue); // When we're client-side, we ultimately want the result from this call.
1031
-
1032
- const clientResult = useCachedEffect(requestId, handler, {
661
+ }
662
+ }, [serverResult]);
663
+ useSharedCache(requestId, scope, getDefaultCacheValue);
664
+ const [clientResult] = useCachedEffect(requestId, handler, {
1033
665
  skip,
1034
666
  onResultChanged,
1035
667
  retainResultOnChange,
1036
- scope
1037
- }); // OK, now which result do we return.
1038
- // Well, we return the serverResult on our very first call and then
1039
- // the clientResult thereafter. The great thing is that after the very
1040
- // first call, the serverResult is going to be `null` anyway.
1041
-
668
+ scope,
669
+ fetchPolicy: FetchPolicy.CacheBeforeNetwork
670
+ });
1042
671
  return serverResult != null ? serverResult : clientResult;
1043
672
  };
1044
673
 
1045
- /**
1046
- * This component is the main component of Wonder Blocks Data. With this, data
1047
- * requirements can be placed in a React application in a manner that will
1048
- * support server-side rendering and efficient caching.
1049
- */
1050
674
  const Data = ({
1051
675
  requestId,
1052
676
  handler,
@@ -1061,87 +685,143 @@ const Data = ({
1061
685
  return children(result);
1062
686
  };
1063
687
 
1064
- /**
1065
- * This component provides a mechanism to intercept data requests.
1066
- * This is for use in testing.
1067
- *
1068
- * This component is not recommended for use in production code as it
1069
- * can prevent predictable functioning of the Wonder Blocks Data framework.
1070
- * One possible side-effect is that inflight requests from the interceptor could
1071
- * be picked up by `Data` component requests from outside the children of this
1072
- * component.
1073
- *
1074
- * Interceptions within the same component tree are chained such that the
1075
- * interceptor closest to the intercepted request is called first, and the
1076
- * furthest interceptor is called last.
1077
- */
1078
688
  const InterceptRequests = ({
1079
689
  interceptor,
1080
690
  children
1081
691
  }) => {
1082
692
  const interceptors = React.useContext(InterceptContext);
1083
- const updatedInterceptors = React.useMemo( // We could build this in reverse order so that our hook that does
1084
- // the interception didn't have to use reduceRight, but I think it
1085
- // is easier to think about if we do this in component tree order.
1086
- () => [].concat(interceptors, [interceptor]), [interceptors, interceptor]);
1087
- return /*#__PURE__*/React.createElement(InterceptContext.Provider, {
693
+ const updatedInterceptors = React.useMemo(() => [].concat(interceptors, [interceptor]), [interceptors, interceptor]);
694
+ return React.createElement(InterceptContext.Provider, {
1088
695
  value: updatedInterceptors
1089
696
  }, children);
1090
697
  };
1091
698
 
1092
- const GqlRouterContext = /*#__PURE__*/React.createContext(null);
699
+ const toString = valid => {
700
+ var _JSON$stringify;
701
+
702
+ if (typeof valid === "string") {
703
+ return valid;
704
+ }
705
+
706
+ return (_JSON$stringify = JSON.stringify(valid)) != null ? _JSON$stringify : "";
707
+ };
708
+
709
+ const getGqlRequestId = (operation, variables, context) => {
710
+ const parts = [];
711
+ const sortableContext = new URLSearchParams(context);
712
+ sortableContext.sort();
713
+ parts.push(sortableContext.toString());
714
+ parts.push(operation.id);
715
+
716
+ if (variables != null) {
717
+ const stringifiedVariables = Object.keys(variables).reduce((acc, key) => {
718
+ acc[key] = toString(variables[key]);
719
+ return acc;
720
+ }, {});
721
+ const sortableVariables = new URLSearchParams(stringifiedVariables);
722
+ sortableVariables.sort();
723
+ parts.push(sortableVariables.toString());
724
+ }
725
+
726
+ return parts.join("|");
727
+ };
728
+
729
+ const DocumentTypes = Object.freeze({
730
+ query: "query",
731
+ mutation: "mutation"
732
+ });
733
+ const cache = new Map();
734
+ function graphQLDocumentNodeParser(document) {
735
+ var _definition$name;
736
+
737
+ const cached = cache.get(document);
738
+
739
+ if (cached) {
740
+ return cached;
741
+ }
742
+
743
+ if (!(document != null && document.kind)) {
744
+ if (process.env.NODE_ENV === "production") {
745
+ throw new DataError("Bad DocumentNode", DataErrors.InvalidInput);
746
+ } else {
747
+ throw new DataError(`Argument of ${JSON.stringify(document)} passed to parser was not a valid GraphQL ` + `DocumentNode. You may need to use 'graphql-tag' or another method ` + `to convert your operation into a document`, DataErrors.InvalidInput);
748
+ }
749
+ }
750
+
751
+ const fragments = document.definitions.filter(x => x.kind === "FragmentDefinition");
752
+ const queries = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "query");
753
+ const mutations = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "mutation");
754
+ const subscriptions = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "subscription");
755
+
756
+ if (fragments.length && !queries.length && !mutations.length) {
757
+ if (process.env.NODE_ENV === "production") {
758
+ throw new DataError("Fragment only", DataErrors.InvalidInput);
759
+ } else {
760
+ throw new DataError(`Passing only a fragment to 'graphql' is not supported. ` + `You must include a query or mutation as well`, DataErrors.InvalidInput);
761
+ }
762
+ }
763
+
764
+ if (subscriptions.length) {
765
+ if (process.env.NODE_ENV === "production") {
766
+ throw new DataError("No subscriptions", DataErrors.InvalidInput);
767
+ } else {
768
+ throw new DataError(`We do not support subscriptions. ` + `${JSON.stringify(document)} had ${subscriptions.length} subscriptions`, DataErrors.InvalidInput);
769
+ }
770
+ }
771
+
772
+ if (queries.length + mutations.length > 1) {
773
+ if (process.env.NODE_ENV === "production") {
774
+ throw new DataError("Too many ops", DataErrors.InvalidInput);
775
+ } else {
776
+ throw new DataError(`We only support one query or mutation per component. ` + `${JSON.stringify(document)} had ${queries.length} queries and ` + `${mutations.length} mutations. `, DataErrors.InvalidInput);
777
+ }
778
+ }
779
+
780
+ const type = queries.length ? DocumentTypes.query : DocumentTypes.mutation;
781
+ const definitions = queries.length ? queries : mutations;
782
+ const definition = definitions[0];
783
+ const variables = definition.variableDefinitions || [];
784
+ const name = ((_definition$name = definition.name) == null ? void 0 : _definition$name.kind) === "Name" ? definition.name.value : "data";
785
+ const payload = {
786
+ name,
787
+ type,
788
+ variables
789
+ };
790
+ cache.set(document, payload);
791
+ return payload;
792
+ }
793
+
794
+ const toGqlOperation = documentNode => {
795
+ const definition = graphQLDocumentNodeParser(documentNode);
796
+ const wbDataOperation = {
797
+ id: definition.name,
798
+ type: definition.type
799
+ };
800
+ return wbDataOperation;
801
+ };
802
+
803
+ const GqlRouterContext = React.createContext(null);
1093
804
 
1094
- /**
1095
- * Configure GraphQL routing for GraphQL hooks and components.
1096
- *
1097
- * These can be nested. Components and hooks relying on the GraphQL routing
1098
- * will use the configuration from their closest ancestral GqlRouter.
1099
- */
1100
805
  const GqlRouter = ({
1101
806
  defaultContext: thisDefaultContext,
1102
807
  fetch: thisFetch,
1103
808
  children
1104
809
  }) => {
1105
- // We don't care if we're nested. We always force our callers to define
1106
- // everything. It makes for a clearer API and requires less error checking
1107
- // code (assuming our flow types are correct). We also don't default fetch
1108
- // to anything - our callers can tell us what function to use quite easily.
1109
- // If code that consumes this wants more nuanced nesting, it can implement
1110
- // it within its own GqlRouter than then defers to this one.
1111
- // We want to always use the same object if things haven't changed to avoid
1112
- // over-rendering consumers of our context, let's memoize the configuration.
1113
- // By doing this, if a component under children that uses this context
1114
- // uses React.memo, we won't force it to re-render every time we render
1115
- // because we'll only change the context value if something has actually
1116
- // changed.
1117
810
  const configuration = React.useMemo(() => ({
1118
811
  fetch: thisFetch,
1119
812
  defaultContext: thisDefaultContext
1120
813
  }), [thisDefaultContext, thisFetch]);
1121
- return /*#__PURE__*/React.createElement(GqlRouterContext.Provider, {
814
+ return React.createElement(GqlRouterContext.Provider, {
1122
815
  value: configuration
1123
816
  }, children);
1124
817
  };
1125
818
 
1126
- /**
1127
- * Construct a complete GqlContext from current defaults and a partial context.
1128
- *
1129
- * Values in the partial context that are `undefined` will be ignored.
1130
- * Values in the partial context that are `null` will be deleted.
1131
- */
1132
819
  const mergeGqlContext = (defaultContext, overrides) => {
1133
- // Let's merge the partial context default context. We deliberately
1134
- // don't spread because spreading would overwrite default context
1135
- // values with undefined or null if the partial context includes a value
1136
- // explicitly set to undefined or null.
1137
820
  return Object.keys(overrides).reduce((acc, key) => {
1138
- // Undefined values are ignored.
1139
821
  if (overrides[key] !== undefined) {
1140
822
  if (overrides[key] === null) {
1141
- // Null indicates we delete this context value.
1142
823
  delete acc[key];
1143
824
  } else {
1144
- // Otherwise, we set it.
1145
825
  acc[key] = overrides[key];
1146
826
  }
1147
827
  }
@@ -1150,32 +830,11 @@ const mergeGqlContext = (defaultContext, overrides) => {
1150
830
  }, _extends({}, defaultContext));
1151
831
  };
1152
832
 
1153
- /**
1154
- * Error kinds for GqlError.
1155
- */
1156
833
  const GqlErrors = Object.freeze({
1157
- /**
1158
- * An internal framework error.
1159
- */
1160
834
  Internal: "Internal",
1161
-
1162
- /**
1163
- * Response does not have the correct structure for a GraphQL response.
1164
- */
1165
835
  BadResponse: "BadResponse",
1166
-
1167
- /**
1168
- * A valid GraphQL result with errors field in the payload.
1169
- */
1170
836
  ErrorResult: "ErrorResult"
1171
837
  });
1172
- /**
1173
- * An error from the GQL API.
1174
- *
1175
- * Errors of this type will have names of the format:
1176
- * `${kind}GqlError`
1177
- */
1178
-
1179
838
  class GqlError extends KindError {
1180
839
  constructor(message, kind, {
1181
840
  metadata,
@@ -1190,11 +849,7 @@ class GqlError extends KindError {
1190
849
 
1191
850
  }
1192
851
 
1193
- /**
1194
- * Construct a GqlRouterContext from the current one and partial context.
1195
- */
1196
852
  const useGqlRouterContext = (contextOverrides = {}) => {
1197
- // This hook only works if the `GqlRouter` has been used to setup context.
1198
853
  const gqlRouterContext = useContext(GqlRouterContext);
1199
854
 
1200
855
  if (gqlRouterContext == null) {
@@ -1206,17 +861,14 @@ const useGqlRouterContext = (contextOverrides = {}) => {
1206
861
  defaultContext
1207
862
  } = gqlRouterContext;
1208
863
  const contextRef = useRef(defaultContext);
1209
- const mergedContext = mergeGqlContext(defaultContext, contextOverrides); // Now, we can see if this represents a new context and if so,
1210
- // update our ref and return the merged value.
1211
-
864
+ const mergedContext = mergeGqlContext(defaultContext, contextOverrides);
1212
865
  const refKeys = Object.keys(contextRef.current);
1213
866
  const mergedKeys = Object.keys(mergedContext);
1214
867
  const shouldWeUpdateRef = refKeys.length !== mergedKeys.length || mergedKeys.every(key => contextRef.current[key] !== mergedContext[key]);
1215
868
 
1216
869
  if (shouldWeUpdateRef) {
1217
870
  contextRef.current = mergedContext;
1218
- } // OK, now we're up-to-date, let's memoize our final result.
1219
-
871
+ }
1220
872
 
1221
873
  const finalContext = contextRef.current;
1222
874
  const finalRouterContext = useMemo(() => ({
@@ -1226,13 +878,7 @@ const useGqlRouterContext = (contextOverrides = {}) => {
1226
878
  return finalRouterContext;
1227
879
  };
1228
880
 
1229
- /**
1230
- * Validate a GQL operation response and extract the data.
1231
- */
1232
-
1233
881
  const getGqlDataFromResponse = async response => {
1234
- // Get the response as text, that way we can use the text in error
1235
- // messaging, should our parsing fail.
1236
882
  const bodyText = await response.text();
1237
883
  let result;
1238
884
 
@@ -1246,8 +892,7 @@ const getGqlDataFromResponse = async response => {
1246
892
  },
1247
893
  cause: e
1248
894
  });
1249
- } // Check for a bad status code.
1250
-
895
+ }
1251
896
 
1252
897
  if (response.status >= 300) {
1253
898
  throw new DataError("Response unsuccessful", DataErrors.Network, {
@@ -1256,22 +901,16 @@ const getGqlDataFromResponse = async response => {
1256
901
  result
1257
902
  }
1258
903
  });
1259
- } // Check that we have a valid result payload.
1260
-
904
+ }
1261
905
 
1262
- if ( // Flow shouldn't be warning about this.
1263
- // $FlowIgnore[method-unbinding]
1264
- !Object.prototype.hasOwnProperty.call(result, "data") && // Flow shouldn't be warning about this.
1265
- // $FlowIgnore[method-unbinding]
1266
- !Object.prototype.hasOwnProperty.call(result, "errors")) {
906
+ if (!Object.prototype.hasOwnProperty.call(result, "data") && !Object.prototype.hasOwnProperty.call(result, "errors")) {
1267
907
  throw new GqlError("Server response missing", GqlErrors.BadResponse, {
1268
908
  metadata: {
1269
909
  statusCode: response.status,
1270
910
  result
1271
911
  }
1272
912
  });
1273
- } // If the response payload has errors, throw an error.
1274
-
913
+ }
1275
914
 
1276
915
  if (result.errors != null && Array.isArray(result.errors) && result.errors.length > 0) {
1277
916
  throw new GqlError("GraphQL errors", GqlErrors.ErrorResult, {
@@ -1280,30 +919,13 @@ const getGqlDataFromResponse = async response => {
1280
919
  result
1281
920
  }
1282
921
  });
1283
- } // We got here, so return the data.
1284
-
922
+ }
1285
923
 
1286
924
  return result.data;
1287
925
  };
1288
926
 
1289
- /**
1290
- * Hook to obtain a gqlFetch function for performing GraphQL requests.
1291
- *
1292
- * The fetch function will resolve null if the request was aborted, otherwise
1293
- * it will resolve the data returned by the GraphQL server.
1294
- *
1295
- * Context is merged with the default context provided to the GqlRouter.
1296
- * Values in the partial context given to the returned fetch function will
1297
- * only be included if they have a value other than undefined.
1298
- */
1299
927
  const useGql = (context = {}) => {
1300
- // This hook only works if the `GqlRouter` has been used to setup context.
1301
- const gqlRouterContext = useGqlRouterContext(context); // Let's memoize the gqlFetch function we create based off our context.
1302
- // That way, even if the context happens to change, if its values don't
1303
- // we give the same function instance back to our callers instead of
1304
- // making a new one. That then means they can safely use the return value
1305
- // in hooks deps without fear of it triggering extra renders.
1306
-
928
+ const gqlRouterContext = useGqlRouterContext(context);
1307
929
  const gqlFetch = useCallback((operation, options = Object.freeze({})) => {
1308
930
  const {
1309
931
  fetch,
@@ -1313,70 +935,10 @@ const useGql = (context = {}) => {
1313
935
  variables,
1314
936
  context = {}
1315
937
  } = options;
1316
- const finalContext = mergeGqlContext(defaultContext, context); // Invoke the fetch and extract the data.
1317
-
938
+ const finalContext = mergeGqlContext(defaultContext, context);
1318
939
  return fetch(operation, variables, finalContext).then(getGqlDataFromResponse);
1319
940
  }, [gqlRouterContext]);
1320
941
  return gqlFetch;
1321
942
  };
1322
943
 
1323
- /**
1324
- * Initialize the hydration cache.
1325
- *
1326
- * @param {ResponseCache} source The cache content to use for initializing the
1327
- * cache.
1328
- * @throws {Error} If the cache is already initialized.
1329
- */
1330
- const initializeCache = source => SsrCache.Default.initialize(source);
1331
- /**
1332
- * Fulfill all tracked data requests.
1333
- *
1334
- * This is for use with the `TrackData` component during server-side rendering.
1335
- *
1336
- * @throws {Error} If executed outside of server-side rendering.
1337
- * @returns {Promise<void>} A promise that resolves when all tracked requests
1338
- * have been fulfilled.
1339
- */
1340
-
1341
- const fulfillAllDataRequests = () => {
1342
- if (!Server.isServerSide()) {
1343
- return Promise.reject(new Error("Data requests are not tracked when client-side"));
1344
- }
1345
-
1346
- return RequestTracker.Default.fulfillTrackedRequests();
1347
- };
1348
- /**
1349
- * Indicate if there are unfulfilled tracked requests.
1350
- *
1351
- * This is used in conjunction with `TrackData`.
1352
- *
1353
- * @throws {Error} If executed outside of server-side rendering.
1354
- * @returns {boolean} `true` if there are unfulfilled tracked requests;
1355
- * otherwise, `false`.
1356
- */
1357
-
1358
- const hasUnfulfilledRequests = () => {
1359
- if (!Server.isServerSide()) {
1360
- throw new Error("Data requests are not tracked when client-side");
1361
- }
1362
-
1363
- return RequestTracker.Default.hasUnfulfilledRequests;
1364
- };
1365
- /**
1366
- * Remove the request identified from the cached hydration responses.
1367
- *
1368
- * @param {string} id The request ID of the response to remove from the cache.
1369
- */
1370
-
1371
- const removeFromCache = id => SsrCache.Default.remove(id);
1372
- /**
1373
- * Remove all cached hydration responses that match the given predicate.
1374
- *
1375
- * @param {(id: string) => boolean} [predicate] The predicate to match against
1376
- * the cached hydration responses. If no predicate is provided, all cached
1377
- * hydration responses will be removed.
1378
- */
1379
-
1380
- const removeAllFromCache = predicate => SsrCache.Default.removeAll(predicate);
1381
-
1382
- export { Data, DataError, DataErrors, GqlError, GqlErrors, GqlRouter, InterceptRequests, RequestFulfillment, ScopedInMemoryCache, SerializableInMemoryCache, Status, TrackData, WhenClientSide, clearSharedCache, fulfillAllDataRequests, hasUnfulfilledRequests, initializeCache, removeAllFromCache, removeFromCache, useCachedEffect, useGql, useHydratableEffect, useServerEffect, useSharedCache };
944
+ export { Data, DataError, DataErrors, FetchPolicy, GqlError, GqlErrors, GqlRouter, InterceptRequests, ScopedInMemoryCache, SerializableInMemoryCache, Status, TrackData, WhenClientSide, abortInflightRequests, fetchTrackedRequests, getGqlRequestId, graphQLDocumentNodeParser, hasTrackedRequestsToBeFetched, initializeHydrationCache, purgeCaches, purgeHydrationCache, purgeSharedCache, toGqlOperation, useCachedEffect, useGql, useHydratableEffect, useServerEffect, useSharedCache };