@khanacademy/wonder-blocks-data 10.0.2 → 10.0.4

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @khanacademy/wonder-blocks-data
2
2
 
3
+ ## 10.0.4
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [496119f2]
8
+ - @khanacademy/wonder-blocks-core@4.6.2
9
+
10
+ ## 10.0.3
11
+
12
+ ### Patch Changes
13
+
14
+ - @khanacademy/wonder-blocks-core@4.6.1
15
+
3
16
  ## 10.0.2
4
17
 
5
18
  ### Patch Changes
package/dist/index.js ADDED
@@ -0,0 +1,1009 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var wonderBlocksCore = require('@khanacademy/wonder-blocks-core');
6
+ var wonderStuffCore = require('@khanacademy/wonder-stuff-core');
7
+ var _extends = require('@babel/runtime/helpers/extends');
8
+ var React = require('react');
9
+
10
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
+
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n["default"] = e;
27
+ return Object.freeze(n);
28
+ }
29
+
30
+ var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);
31
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
32
+
33
+ const FetchPolicy = require("flow-enums-runtime").Mirrored(["CacheBeforeNetwork", "CacheAndNetwork", "CacheOnly", "NetworkOnly"]);
34
+
35
+ const DataErrors = Object.freeze({
36
+ Unknown: "Unknown",
37
+ Internal: "Internal",
38
+ InvalidInput: "InvalidInput",
39
+ Network: "Network",
40
+ NotAllowed: "NotAllowed",
41
+ Parse: "Parse",
42
+ Hydrated: "Hydrated"
43
+ });
44
+ class DataError extends wonderStuffCore.KindError {
45
+ constructor(message, kind, {
46
+ metadata,
47
+ cause
48
+ } = {}) {
49
+ super(message, kind, {
50
+ metadata,
51
+ cause,
52
+ name: "Data"
53
+ });
54
+ }
55
+
56
+ }
57
+
58
+ class ScopedInMemoryCache {
59
+ constructor(initialCache = {}) {
60
+ this._cache = initialCache;
61
+ }
62
+
63
+ get inUse() {
64
+ return Object.keys(this._cache).length > 0;
65
+ }
66
+
67
+ set(scope, id, value) {
68
+ var _this$_cache$scope;
69
+
70
+ if (!id || typeof id !== "string") {
71
+ throw new DataError("id must be non-empty string", DataErrors.InvalidInput);
72
+ }
73
+
74
+ if (!scope || typeof scope !== "string") {
75
+ throw new DataError("scope must be non-empty string", DataErrors.InvalidInput);
76
+ }
77
+
78
+ if (typeof value === "function") {
79
+ throw new DataError("value must be a non-function value", DataErrors.InvalidInput);
80
+ }
81
+
82
+ this._cache[scope] = (_this$_cache$scope = this._cache[scope]) != null ? _this$_cache$scope : {};
83
+ this._cache[scope][id] = value;
84
+ }
85
+
86
+ get(scope, id) {
87
+ var _this$_cache$scope$id, _this$_cache$scope2;
88
+
89
+ return (_this$_cache$scope$id = (_this$_cache$scope2 = this._cache[scope]) == null ? void 0 : _this$_cache$scope2[id]) != null ? _this$_cache$scope$id : null;
90
+ }
91
+
92
+ purge(scope, id) {
93
+ var _this$_cache$scope3;
94
+
95
+ if (!((_this$_cache$scope3 = this._cache[scope]) != null && _this$_cache$scope3[id])) {
96
+ return;
97
+ }
98
+
99
+ delete this._cache[scope][id];
100
+
101
+ if (Object.keys(this._cache[scope]).length === 0) {
102
+ delete this._cache[scope];
103
+ }
104
+ }
105
+
106
+ purgeScope(scope, predicate) {
107
+ if (!this._cache[scope]) {
108
+ return;
109
+ }
110
+
111
+ if (predicate == null) {
112
+ delete this._cache[scope];
113
+ return;
114
+ }
115
+
116
+ for (const key of Object.keys(this._cache[scope])) {
117
+ if (predicate(key, this._cache[scope][key])) {
118
+ delete this._cache[scope][key];
119
+ }
120
+ }
121
+
122
+ if (Object.keys(this._cache[scope]).length === 0) {
123
+ delete this._cache[scope];
124
+ }
125
+ }
126
+
127
+ purgeAll(predicate) {
128
+ if (predicate == null) {
129
+ this._cache = {};
130
+ return;
131
+ }
132
+
133
+ for (const scope of Object.keys(this._cache)) {
134
+ this.purgeScope(scope, (id, value) => predicate(scope, id, value));
135
+ }
136
+ }
137
+
138
+ }
139
+
140
+ class SerializableInMemoryCache extends ScopedInMemoryCache {
141
+ constructor(initialCache = {}) {
142
+ try {
143
+ super(wonderStuffCore.clone(initialCache));
144
+ } catch (e) {
145
+ throw new DataError(`An error occurred trying to initialize from a response cache snapshot: ${e}`, DataErrors.InvalidInput);
146
+ }
147
+ }
148
+
149
+ set(scope, id, value) {
150
+ super.set(scope, id, Object.freeze(wonderStuffCore.clone(value)));
151
+ }
152
+
153
+ clone() {
154
+ try {
155
+ return wonderStuffCore.clone(this._cache);
156
+ } catch (e) {
157
+ throw new DataError("An error occurred while trying to clone the cache", DataErrors.Internal, {
158
+ cause: e
159
+ });
160
+ }
161
+ }
162
+
163
+ }
164
+
165
+ const DefaultScope$2 = "default";
166
+
167
+ let _default$2;
168
+
169
+ class SsrCache {
170
+ static get Default() {
171
+ if (!_default$2) {
172
+ _default$2 = new SsrCache();
173
+ }
174
+
175
+ return _default$2;
176
+ }
177
+
178
+ constructor(hydrationCache = null, ssrOnlyCache = null) {
179
+ this.initialize = source => {
180
+ if (this._hydrationCache.inUse) {
181
+ throw new Error("Cannot initialize data response cache more than once");
182
+ }
183
+
184
+ this._hydrationCache = new SerializableInMemoryCache({
185
+ [DefaultScope$2]: source
186
+ });
187
+ };
188
+
189
+ this.cacheData = (id, data, hydrate) => this._setCachedResponse(id, {
190
+ data
191
+ }, hydrate);
192
+
193
+ this.cacheError = (id, error, hydrate) => {
194
+ const errorMessage = typeof error === "string" ? error : error.message;
195
+ return this._setCachedResponse(id, {
196
+ error: errorMessage
197
+ }, hydrate);
198
+ };
199
+
200
+ this.getEntry = id => {
201
+ const ssrEntry = wonderBlocksCore.Server.isServerSide() ? this._ssrOnlyCache.get(DefaultScope$2, id) : null;
202
+ const internalEntry = ssrEntry != null ? ssrEntry : this._hydrationCache.get(DefaultScope$2, id);
203
+
204
+ if (!wonderBlocksCore.Server.isServerSide() && internalEntry != null) {
205
+ this._hydrationCache.purge(DefaultScope$2, id);
206
+ }
207
+
208
+ return internalEntry;
209
+ };
210
+
211
+ this.purgeData = predicate => {
212
+ const realPredicate = predicate ? (_, key, cachedEntry) => predicate(key, cachedEntry) : undefined;
213
+
214
+ this._hydrationCache.purgeAll(realPredicate);
215
+
216
+ this._ssrOnlyCache.purgeAll(realPredicate);
217
+ };
218
+
219
+ this.cloneHydratableData = () => {
220
+ var _cache$DefaultScope;
221
+
222
+ const cache = this._hydrationCache.clone();
223
+
224
+ return (_cache$DefaultScope = cache[DefaultScope$2]) != null ? _cache$DefaultScope : {};
225
+ };
226
+
227
+ this._ssrOnlyCache = ssrOnlyCache || new SerializableInMemoryCache();
228
+ this._hydrationCache = hydrationCache || new SerializableInMemoryCache();
229
+ }
230
+
231
+ _setCachedResponse(id, entry, hydrate) {
232
+ const frozenEntry = Object.freeze(entry);
233
+
234
+ if (wonderBlocksCore.Server.isServerSide()) {
235
+ if (hydrate) {
236
+ this._hydrationCache.set(DefaultScope$2, id, frozenEntry);
237
+ } else {
238
+ this._ssrOnlyCache.set(DefaultScope$2, id, frozenEntry);
239
+ }
240
+ }
241
+
242
+ return frozenEntry;
243
+ }
244
+
245
+ }
246
+
247
+ const initializeHydrationCache = source => SsrCache.Default.initialize(source);
248
+ const purgeHydrationCache = predicate => SsrCache.Default.purgeData(predicate);
249
+
250
+ let _default$1;
251
+
252
+ class RequestFulfillment {
253
+ constructor() {
254
+ this._requests = {};
255
+
256
+ this.fulfill = (id, {
257
+ handler,
258
+ hydrate: _hydrate = true
259
+ }) => {
260
+ const inflight = this._requests[id];
261
+
262
+ if (inflight) {
263
+ return inflight;
264
+ }
265
+
266
+ const request = handler().then(data => ({
267
+ status: "success",
268
+ data
269
+ })).catch(error => {
270
+ const actualError = typeof error === "string" ? new DataError("Request failed", DataErrors.Unknown, {
271
+ metadata: {
272
+ unexpectedError: error
273
+ }
274
+ }) : error;
275
+
276
+ if (actualError.name === "AbortError") {
277
+ return {
278
+ status: "aborted"
279
+ };
280
+ }
281
+
282
+ return {
283
+ status: "error",
284
+ error: actualError
285
+ };
286
+ }).finally(() => {
287
+ delete this._requests[id];
288
+ });
289
+ this._requests[id] = request;
290
+ return request;
291
+ };
292
+
293
+ this.abort = id => {
294
+ delete this._requests[id];
295
+ };
296
+
297
+ this.abortAll = () => {
298
+ Object.keys(this._requests).forEach(id => this.abort(id));
299
+ };
300
+ }
301
+
302
+ static get Default() {
303
+ if (!_default$1) {
304
+ _default$1 = new RequestFulfillment();
305
+ }
306
+
307
+ return _default$1;
308
+ }
309
+
310
+ }
311
+
312
+ const TrackerContext = React__namespace.createContext(null);
313
+
314
+ let _default;
315
+
316
+ class RequestTracker {
317
+ static get Default() {
318
+ if (!_default) {
319
+ _default = new RequestTracker();
320
+ }
321
+
322
+ return _default;
323
+ }
324
+
325
+ constructor(responseCache = undefined) {
326
+ this._trackedRequests = {};
327
+
328
+ this.trackDataRequest = (id, handler, hydrate) => {
329
+ if (this._trackedRequests[id] == null) {
330
+ this._trackedRequests[id] = {
331
+ handler,
332
+ hydrate
333
+ };
334
+ }
335
+ };
336
+
337
+ this.reset = () => {
338
+ this._trackedRequests = {};
339
+ };
340
+
341
+ this.fulfillTrackedRequests = () => {
342
+ const promises = [];
343
+ const {
344
+ cacheData,
345
+ cacheError
346
+ } = this._responseCache;
347
+
348
+ for (const requestKey of Object.keys(this._trackedRequests)) {
349
+ const options = this._trackedRequests[requestKey];
350
+
351
+ try {
352
+ promises.push(this._requestFulfillment.fulfill(requestKey, _extends__default["default"]({}, options)).then(result => {
353
+ switch (result.status) {
354
+ case "success":
355
+ cacheData(requestKey, result.data, options.hydrate);
356
+ break;
357
+
358
+ case "error":
359
+ cacheError(requestKey, result.error, options.hydrate);
360
+ break;
361
+ }
362
+
363
+ return;
364
+ }));
365
+ } catch (e) {
366
+ promises.push(Promise.resolve(cacheError(requestKey, e, options.hydrate)));
367
+ }
368
+ }
369
+
370
+ this.reset();
371
+ return Promise.all(promises).then(() => this._responseCache.cloneHydratableData());
372
+ };
373
+
374
+ this._responseCache = responseCache || SsrCache.Default;
375
+ this._requestFulfillment = new RequestFulfillment();
376
+ }
377
+
378
+ get hasUnfulfilledRequests() {
379
+ return Object.keys(this._trackedRequests).length > 0;
380
+ }
381
+
382
+ }
383
+
384
+ const SSRCheck = () => {
385
+ if (wonderBlocksCore.Server.isServerSide()) {
386
+ return null;
387
+ }
388
+
389
+ if (process.env.NODE_ENV === "production") {
390
+ return new DataError("No CSR tracking", DataErrors.NotAllowed);
391
+ } else {
392
+ return new DataError("Data requests are not tracked for fulfillment when when client-side", DataErrors.NotAllowed);
393
+ }
394
+ };
395
+
396
+ const fetchTrackedRequests = () => {
397
+ const ssrCheck = SSRCheck();
398
+
399
+ if (ssrCheck != null) {
400
+ return Promise.reject(ssrCheck);
401
+ }
402
+
403
+ return RequestTracker.Default.fulfillTrackedRequests();
404
+ };
405
+ const hasTrackedRequestsToBeFetched = () => {
406
+ const ssrCheck = SSRCheck();
407
+
408
+ if (ssrCheck != null) {
409
+ throw ssrCheck;
410
+ }
411
+
412
+ return RequestTracker.Default.hasUnfulfilledRequests;
413
+ };
414
+ const abortInflightRequests = () => {
415
+ RequestFulfillment.Default.abortAll();
416
+ };
417
+
418
+ const cache$1 = new ScopedInMemoryCache();
419
+ const SharedCache = cache$1;
420
+ const useSharedCache = (id, scope, initialValue) => {
421
+ if (!id || typeof id !== "string") {
422
+ throw new DataError("id must be a non-empty string", DataErrors.InvalidInput);
423
+ }
424
+
425
+ if (!scope || typeof scope !== "string") {
426
+ throw new DataError("scope must be a non-empty string", DataErrors.InvalidInput);
427
+ }
428
+
429
+ const cacheValue = React__namespace.useCallback(value => value == null ? cache$1.purge(scope, id) : cache$1.set(scope, id, value), [id, scope]);
430
+ let currentValue = cache$1.get(scope, id);
431
+
432
+ if (currentValue == null && initialValue !== undefined) {
433
+ const value = typeof initialValue === "function" ? initialValue() : initialValue;
434
+
435
+ if (value != null) {
436
+ cacheValue(value);
437
+ currentValue = value;
438
+ }
439
+ }
440
+
441
+ return [currentValue, cacheValue];
442
+ };
443
+
444
+ const purgeCaches = () => {
445
+ SharedCache.purgeAll();
446
+ purgeHydrationCache();
447
+ };
448
+
449
+ class TrackData extends React__namespace.Component {
450
+ render() {
451
+ if (!wonderBlocksCore.Server.isServerSide()) {
452
+ throw new Error("This component is not for use during client-side rendering");
453
+ }
454
+
455
+ return React__namespace.createElement(TrackerContext.Provider, {
456
+ value: RequestTracker.Default.trackDataRequest
457
+ }, this.props.children);
458
+ }
459
+
460
+ }
461
+
462
+ const loadingStatus = Object.freeze({
463
+ status: "loading"
464
+ });
465
+ const abortedStatus = Object.freeze({
466
+ status: "aborted"
467
+ });
468
+ const Status = Object.freeze({
469
+ loading: () => loadingStatus,
470
+ aborted: () => abortedStatus,
471
+ success: data => ({
472
+ status: "success",
473
+ data
474
+ }),
475
+ error: error => ({
476
+ status: "error",
477
+ error
478
+ })
479
+ });
480
+
481
+ const resultFromCachedResponse = cacheEntry => {
482
+ if (cacheEntry == null) {
483
+ return null;
484
+ }
485
+
486
+ const {
487
+ data,
488
+ error
489
+ } = cacheEntry;
490
+
491
+ if (error != null) {
492
+ return Status.error(new DataError(error, DataErrors.Hydrated));
493
+ }
494
+
495
+ if (data != null) {
496
+ return Status.success(data);
497
+ }
498
+
499
+ return Status.aborted();
500
+ };
501
+
502
+ const InterceptContext = React__namespace.createContext([]);
503
+
504
+ const useRequestInterception = (requestId, handler) => {
505
+ const interceptors = React__namespace.useContext(InterceptContext);
506
+ const interceptedHandler = React__namespace.useCallback(() => {
507
+ const interceptResponse = interceptors.reduceRight((prev, interceptor) => {
508
+ if (prev != null) {
509
+ return prev;
510
+ }
511
+
512
+ return interceptor(requestId);
513
+ }, null);
514
+ return interceptResponse != null ? interceptResponse : handler();
515
+ }, [handler, interceptors, requestId]);
516
+ return interceptedHandler;
517
+ };
518
+
519
+ const useServerEffect = (requestId, handler, options = {}) => {
520
+ const {
521
+ hydrate = true,
522
+ skip = false
523
+ } = options;
524
+ const interceptedHandler = useRequestInterception(requestId, handler);
525
+ const cachedResult = SsrCache.Default.getEntry(requestId);
526
+ const maybeTrack = React.useContext(TrackerContext);
527
+
528
+ if (!skip && cachedResult == null && wonderBlocksCore.Server.isServerSide()) {
529
+ maybeTrack == null ? void 0 : maybeTrack(requestId, interceptedHandler, hydrate);
530
+ }
531
+
532
+ return cachedResult == null ? null : resultFromCachedResponse(cachedResult);
533
+ };
534
+
535
+ const DefaultScope$1 = "useCachedEffect";
536
+ const useCachedEffect = (requestId, handler, options = {}) => {
537
+ var _ref;
538
+
539
+ const {
540
+ fetchPolicy = FetchPolicy.CacheBeforeNetwork,
541
+ skip: hardSkip = false,
542
+ retainResultOnChange = false,
543
+ onResultChanged,
544
+ scope = DefaultScope$1
545
+ } = options;
546
+ const interceptedHandler = useRequestInterception(requestId, handler);
547
+ const [mostRecentResult, setMostRecentResult] = useSharedCache(requestId, scope);
548
+ const forceUpdate = wonderBlocksCore.useForceUpdate();
549
+ const networkResultRef = React__namespace.useRef();
550
+ const currentRequestRef = React__namespace.useRef();
551
+ const fetchRequest = React__namespace.useMemo(() => {
552
+ var _currentRequestRef$cu;
553
+
554
+ (_currentRequestRef$cu = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu.cancel();
555
+ currentRequestRef.current = null;
556
+ networkResultRef.current = null;
557
+
558
+ const fetchFn = () => {
559
+ var _currentRequestRef$cu2, _currentRequestRef$cu3;
560
+
561
+ if (fetchPolicy === FetchPolicy.CacheOnly) {
562
+ throw new DataError("Cannot fetch with CacheOnly policy", DataErrors.NotAllowed);
563
+ }
564
+
565
+ const request = RequestFulfillment.Default.fulfill(`${requestId}|${scope}`, {
566
+ handler: interceptedHandler
567
+ });
568
+
569
+ if (request === ((_currentRequestRef$cu2 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu2.request)) {
570
+ return;
571
+ }
572
+
573
+ networkResultRef.current = null;
574
+ (_currentRequestRef$cu3 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu3.cancel();
575
+ let cancel = false;
576
+ request.then(result => {
577
+ currentRequestRef.current = null;
578
+
579
+ if (cancel) {
580
+ return;
581
+ }
582
+
583
+ setMostRecentResult(result);
584
+ networkResultRef.current = result;
585
+
586
+ if (onResultChanged != null) {
587
+ onResultChanged(result);
588
+ } else {
589
+ forceUpdate();
590
+ }
591
+
592
+ return;
593
+ });
594
+ currentRequestRef.current = {
595
+ requestId,
596
+ request,
597
+
598
+ cancel() {
599
+ cancel = true;
600
+ RequestFulfillment.Default.abort(requestId);
601
+ }
602
+
603
+ };
604
+ };
605
+
606
+ return fetchFn;
607
+ }, [requestId, onResultChanged, forceUpdate, setMostRecentResult, fetchPolicy]);
608
+ const shouldFetch = React__namespace.useMemo(() => {
609
+ if (hardSkip) {
610
+ return false;
611
+ }
612
+
613
+ switch (fetchPolicy) {
614
+ case FetchPolicy.CacheOnly:
615
+ return false;
616
+
617
+ case FetchPolicy.CacheBeforeNetwork:
618
+ return mostRecentResult == null;
619
+
620
+ case FetchPolicy.CacheAndNetwork:
621
+ case FetchPolicy.NetworkOnly:
622
+ return networkResultRef.current == null;
623
+ }
624
+ }, [mostRecentResult, fetchPolicy, hardSkip]);
625
+ React__namespace.useEffect(() => {
626
+ if (!shouldFetch) {
627
+ return;
628
+ }
629
+
630
+ fetchRequest();
631
+ return () => {
632
+ var _currentRequestRef$cu4;
633
+
634
+ (_currentRequestRef$cu4 = currentRequestRef.current) == null ? void 0 : _currentRequestRef$cu4.cancel();
635
+ currentRequestRef.current = null;
636
+ };
637
+ }, [shouldFetch, fetchRequest]);
638
+ const lastResultAgnosticOfIdRef = React__namespace.useRef(Status.loading());
639
+ const loadingResult = retainResultOnChange ? lastResultAgnosticOfIdRef.current : Status.loading();
640
+ const result = (_ref = fetchPolicy === FetchPolicy.NetworkOnly ? networkResultRef.current : mostRecentResult) != null ? _ref : loadingResult;
641
+ lastResultAgnosticOfIdRef.current = result;
642
+ return [result, fetchRequest];
643
+ };
644
+
645
+ const WhenClientSide = require("flow-enums-runtime").Mirrored(["DoNotHydrate", "ExecuteWhenNoResult", "ExecuteWhenNoSuccessResult", "AlwaysExecute"]);
646
+ const DefaultScope = "useHydratableEffect";
647
+ const useHydratableEffect = (requestId, handler, options = {}) => {
648
+ const {
649
+ clientBehavior = WhenClientSide.ExecuteWhenNoSuccessResult,
650
+ skip = false,
651
+ retainResultOnChange = false,
652
+ onResultChanged,
653
+ scope = DefaultScope
654
+ } = options;
655
+ const serverResult = useServerEffect(requestId, handler, {
656
+ hydrate: clientBehavior !== WhenClientSide.DoNotHydrate,
657
+ skip
658
+ });
659
+ const getDefaultCacheValue = React__namespace.useCallback(() => {
660
+ switch (clientBehavior) {
661
+ case WhenClientSide.DoNotHydrate:
662
+ case WhenClientSide.AlwaysExecute:
663
+ return null;
664
+
665
+ case WhenClientSide.ExecuteWhenNoResult:
666
+ return serverResult;
667
+
668
+ case WhenClientSide.ExecuteWhenNoSuccessResult:
669
+ if ((serverResult == null ? void 0 : serverResult.status) === "success") {
670
+ return serverResult;
671
+ }
672
+
673
+ return null;
674
+ }
675
+ }, [serverResult]);
676
+ useSharedCache(requestId, scope, getDefaultCacheValue);
677
+ const [clientResult] = useCachedEffect(requestId, handler, {
678
+ skip,
679
+ onResultChanged,
680
+ retainResultOnChange,
681
+ scope,
682
+ fetchPolicy: FetchPolicy.CacheBeforeNetwork
683
+ });
684
+ return serverResult != null ? serverResult : clientResult;
685
+ };
686
+
687
+ const Data = ({
688
+ requestId,
689
+ handler,
690
+ children,
691
+ retainResultOnChange: _retainResultOnChange = false,
692
+ clientBehavior: _clientBehavior = WhenClientSide.ExecuteWhenNoSuccessResult
693
+ }) => {
694
+ const result = useHydratableEffect(requestId, handler, {
695
+ retainResultOnChange: _retainResultOnChange,
696
+ clientBehavior: _clientBehavior
697
+ });
698
+ return children(result);
699
+ };
700
+
701
+ const InterceptRequests = ({
702
+ interceptor,
703
+ children
704
+ }) => {
705
+ const interceptors = React__namespace.useContext(InterceptContext);
706
+ const updatedInterceptors = React__namespace.useMemo(() => [].concat(interceptors, [interceptor]), [interceptors, interceptor]);
707
+ return React__namespace.createElement(InterceptContext.Provider, {
708
+ value: updatedInterceptors
709
+ }, children);
710
+ };
711
+
712
+ const toString = value => {
713
+ var _JSON$stringify;
714
+
715
+ if (typeof value === "string") {
716
+ return value;
717
+ }
718
+
719
+ if (typeof value === "object" && value != null) {
720
+ if (value instanceof Date) {
721
+ return value.toISOString();
722
+ } else if (typeof value.toString === "function") {
723
+ return value.toString();
724
+ }
725
+ }
726
+
727
+ return (_JSON$stringify = JSON.stringify(value)) != null ? _JSON$stringify : "";
728
+ };
729
+
730
+ const toStringifiedVariables = (acc, key, value) => {
731
+ if (typeof value === "object" && value !== null) {
732
+ const subValues = wonderStuffCore.entries(value);
733
+
734
+ if (subValues.length !== 0) {
735
+ return subValues.reduce((innerAcc, [i, v]) => {
736
+ const subKey = `${key}.${i}`;
737
+ return toStringifiedVariables(innerAcc, subKey, v);
738
+ }, acc);
739
+ }
740
+ }
741
+
742
+ acc[key] = toString(value);
743
+ return acc;
744
+ };
745
+
746
+ const getGqlRequestId = (operation, variables, context) => {
747
+ const parts = [];
748
+ const sortableContext = new URLSearchParams(context);
749
+ sortableContext.sort();
750
+ parts.push(sortableContext.toString());
751
+ parts.push(operation.id);
752
+
753
+ if (variables != null) {
754
+ const stringifiedVariables = Object.keys(variables).reduce((acc, key) => {
755
+ const value = variables[key];
756
+ return toStringifiedVariables(acc, key, value);
757
+ }, {});
758
+ const sortableVariables = new URLSearchParams(stringifiedVariables);
759
+ sortableVariables.sort();
760
+ parts.push(sortableVariables.toString());
761
+ }
762
+
763
+ return parts.join("|");
764
+ };
765
+
766
+ const GqlErrors = Object.freeze({
767
+ Internal: "Internal",
768
+ BadResponse: "BadResponse",
769
+ ErrorResult: "ErrorResult"
770
+ });
771
+ class GqlError extends wonderStuffCore.KindError {
772
+ constructor(message, kind, {
773
+ metadata,
774
+ cause
775
+ } = {}) {
776
+ super(message, kind, {
777
+ metadata,
778
+ cause,
779
+ name: "Gql"
780
+ });
781
+ }
782
+
783
+ }
784
+
785
+ const getGqlDataFromResponse = async response => {
786
+ const bodyText = await response.text();
787
+ let result;
788
+
789
+ try {
790
+ result = JSON.parse(bodyText);
791
+ } catch (e) {
792
+ throw new DataError("Failed to parse response", DataErrors.Parse, {
793
+ metadata: {
794
+ statusCode: response.status,
795
+ bodyText
796
+ },
797
+ cause: e
798
+ });
799
+ }
800
+
801
+ if (response.status >= 300) {
802
+ throw new DataError("Response unsuccessful", DataErrors.Network, {
803
+ metadata: {
804
+ statusCode: response.status,
805
+ result
806
+ }
807
+ });
808
+ }
809
+
810
+ if (!Object.prototype.hasOwnProperty.call(result, "data") && !Object.prototype.hasOwnProperty.call(result, "errors")) {
811
+ throw new GqlError("Server response missing", GqlErrors.BadResponse, {
812
+ metadata: {
813
+ statusCode: response.status,
814
+ result
815
+ }
816
+ });
817
+ }
818
+
819
+ if (result.errors != null && Array.isArray(result.errors) && result.errors.length > 0) {
820
+ throw new GqlError("GraphQL errors", GqlErrors.ErrorResult, {
821
+ metadata: {
822
+ statusCode: response.status,
823
+ result
824
+ }
825
+ });
826
+ }
827
+
828
+ return result.data;
829
+ };
830
+
831
+ const DocumentTypes = Object.freeze({
832
+ query: "query",
833
+ mutation: "mutation"
834
+ });
835
+ const cache = new Map();
836
+ function graphQLDocumentNodeParser(document) {
837
+ var _definition$name;
838
+
839
+ const cached = cache.get(document);
840
+
841
+ if (cached) {
842
+ return cached;
843
+ }
844
+
845
+ if (!(document != null && document.kind)) {
846
+ if (process.env.NODE_ENV === "production") {
847
+ throw new DataError("Bad DocumentNode", DataErrors.InvalidInput);
848
+ } else {
849
+ 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);
850
+ }
851
+ }
852
+
853
+ const fragments = document.definitions.filter(x => x.kind === "FragmentDefinition");
854
+ const queries = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "query");
855
+ const mutations = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "mutation");
856
+ const subscriptions = document.definitions.filter(x => x.kind === "OperationDefinition" && x.operation === "subscription");
857
+
858
+ if (fragments.length && !queries.length && !mutations.length) {
859
+ if (process.env.NODE_ENV === "production") {
860
+ throw new DataError("Fragment only", DataErrors.InvalidInput);
861
+ } else {
862
+ throw new DataError(`Passing only a fragment to 'graphql' is not supported. ` + `You must include a query or mutation as well`, DataErrors.InvalidInput);
863
+ }
864
+ }
865
+
866
+ if (subscriptions.length) {
867
+ if (process.env.NODE_ENV === "production") {
868
+ throw new DataError("No subscriptions", DataErrors.InvalidInput);
869
+ } else {
870
+ throw new DataError(`We do not support subscriptions. ` + `${JSON.stringify(document)} had ${subscriptions.length} subscriptions`, DataErrors.InvalidInput);
871
+ }
872
+ }
873
+
874
+ if (queries.length + mutations.length > 1) {
875
+ if (process.env.NODE_ENV === "production") {
876
+ throw new DataError("Too many ops", DataErrors.InvalidInput);
877
+ } else {
878
+ 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);
879
+ }
880
+ }
881
+
882
+ const type = queries.length ? DocumentTypes.query : DocumentTypes.mutation;
883
+ const definitions = queries.length ? queries : mutations;
884
+ const definition = definitions[0];
885
+ const variables = definition.variableDefinitions || [];
886
+ const name = ((_definition$name = definition.name) == null ? void 0 : _definition$name.kind) === "Name" ? definition.name.value : "data";
887
+ const payload = {
888
+ name,
889
+ type,
890
+ variables
891
+ };
892
+ cache.set(document, payload);
893
+ return payload;
894
+ }
895
+
896
+ const toGqlOperation = documentNode => {
897
+ const definition = graphQLDocumentNodeParser(documentNode);
898
+ const wbDataOperation = {
899
+ id: definition.name,
900
+ type: definition.type
901
+ };
902
+ return wbDataOperation;
903
+ };
904
+
905
+ const GqlRouterContext = React__namespace.createContext(null);
906
+
907
+ const GqlRouter = ({
908
+ defaultContext: thisDefaultContext,
909
+ fetch: thisFetch,
910
+ children
911
+ }) => {
912
+ const configuration = React__namespace.useMemo(() => ({
913
+ fetch: thisFetch,
914
+ defaultContext: thisDefaultContext
915
+ }), [thisDefaultContext, thisFetch]);
916
+ return React__namespace.createElement(GqlRouterContext.Provider, {
917
+ value: configuration
918
+ }, children);
919
+ };
920
+
921
+ const mergeGqlContext = (defaultContext, overrides) => {
922
+ return Object.keys(overrides).reduce((acc, key) => {
923
+ if (overrides[key] !== undefined) {
924
+ if (overrides[key] === null) {
925
+ delete acc[key];
926
+ } else {
927
+ acc[key] = overrides[key];
928
+ }
929
+ }
930
+
931
+ return acc;
932
+ }, _extends__default["default"]({}, defaultContext));
933
+ };
934
+
935
+ const useGqlRouterContext = (contextOverrides = {}) => {
936
+ const gqlRouterContext = React.useContext(GqlRouterContext);
937
+
938
+ if (gqlRouterContext == null) {
939
+ throw new GqlError("No GqlRouter", GqlErrors.Internal);
940
+ }
941
+
942
+ const {
943
+ fetch,
944
+ defaultContext
945
+ } = gqlRouterContext;
946
+ const contextRef = React.useRef(defaultContext);
947
+ const mergedContext = mergeGqlContext(defaultContext, contextOverrides);
948
+ const refKeys = Object.keys(contextRef.current);
949
+ const mergedKeys = Object.keys(mergedContext);
950
+ const shouldWeUpdateRef = refKeys.length !== mergedKeys.length || mergedKeys.every(key => contextRef.current[key] !== mergedContext[key]);
951
+
952
+ if (shouldWeUpdateRef) {
953
+ contextRef.current = mergedContext;
954
+ }
955
+
956
+ const finalContext = contextRef.current;
957
+ const finalRouterContext = React.useMemo(() => ({
958
+ fetch,
959
+ defaultContext: finalContext
960
+ }), [fetch, finalContext]);
961
+ return finalRouterContext;
962
+ };
963
+
964
+ const useGql = (context = {}) => {
965
+ const gqlRouterContext = useGqlRouterContext(context);
966
+ const gqlFetch = React.useCallback((operation, options = Object.freeze({})) => {
967
+ const {
968
+ fetch,
969
+ defaultContext
970
+ } = gqlRouterContext;
971
+ const {
972
+ variables,
973
+ context = {}
974
+ } = options;
975
+ const finalContext = mergeGqlContext(defaultContext, context);
976
+ return fetch(operation, variables, finalContext).then(getGqlDataFromResponse);
977
+ }, [gqlRouterContext]);
978
+ return gqlFetch;
979
+ };
980
+
981
+ exports.Data = Data;
982
+ exports.DataError = DataError;
983
+ exports.DataErrors = DataErrors;
984
+ exports.FetchPolicy = FetchPolicy;
985
+ exports.GqlError = GqlError;
986
+ exports.GqlErrors = GqlErrors;
987
+ exports.GqlRouter = GqlRouter;
988
+ exports.InterceptRequests = InterceptRequests;
989
+ exports.ScopedInMemoryCache = ScopedInMemoryCache;
990
+ exports.SerializableInMemoryCache = SerializableInMemoryCache;
991
+ exports.SharedCache = SharedCache;
992
+ exports.Status = Status;
993
+ exports.TrackData = TrackData;
994
+ exports.WhenClientSide = WhenClientSide;
995
+ exports.abortInflightRequests = abortInflightRequests;
996
+ exports.fetchTrackedRequests = fetchTrackedRequests;
997
+ exports.getGqlDataFromResponse = getGqlDataFromResponse;
998
+ exports.getGqlRequestId = getGqlRequestId;
999
+ exports.graphQLDocumentNodeParser = graphQLDocumentNodeParser;
1000
+ exports.hasTrackedRequestsToBeFetched = hasTrackedRequestsToBeFetched;
1001
+ exports.initializeHydrationCache = initializeHydrationCache;
1002
+ exports.purgeCaches = purgeCaches;
1003
+ exports.purgeHydrationCache = purgeHydrationCache;
1004
+ exports.toGqlOperation = toGqlOperation;
1005
+ exports.useCachedEffect = useCachedEffect;
1006
+ exports.useGql = useGql;
1007
+ exports.useHydratableEffect = useHydratableEffect;
1008
+ exports.useServerEffect = useServerEffect;
1009
+ exports.useSharedCache = useSharedCache;
@@ -0,0 +1,2 @@
1
+ // @flow
2
+ export * from "../src/index.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanacademy/wonder-blocks-data",
3
- "version": "10.0.2",
3
+ "version": "10.0.4",
4
4
  "design": "v1",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@babel/runtime": "^7.18.6",
17
- "@khanacademy/wonder-blocks-core": "^4.6.0"
17
+ "@khanacademy/wonder-blocks-core": "^4.6.2"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "@khanacademy/wonder-stuff-core": "^1.0.1",
@@ -22,7 +22,7 @@
22
22
  "react": "16.14.0"
23
23
  },
24
24
  "devDependencies": {
25
- "wb-dev-build-settings": "^0.5.0"
25
+ "wb-dev-build-settings": "^0.7.0"
26
26
  },
27
27
  "author": "",
28
28
  "license": "MIT"