@choksheak/react-utils 0.4.8 → 0.4.9

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 (94) hide show
  1. package/LICENSE +2 -0
  2. package/NoSSR.min.cjs +1 -14
  3. package/NoSSR.min.cjs.map +1 -1
  4. package/NoSSR.min.js +1 -14
  5. package/NoSSR.min.js.map +1 -1
  6. package/{chunk-HFIQE4XZ.cjs → chunk-2VVAT5AA.cjs} +9 -5
  7. package/chunk-CW3XVEI4.min.cjs +2 -0
  8. package/chunk-CW3XVEI4.min.cjs.map +1 -0
  9. package/chunk-GV7KUTU2.min.js +2 -0
  10. package/chunk-GV7KUTU2.min.js.map +1 -0
  11. package/{chunk-CIDQGOPA.js → chunk-H4OYYPJV.js} +7 -3
  12. package/chunk-JOHZV3FD.min.cjs +2 -0
  13. package/chunk-JOHZV3FD.min.cjs.map +1 -0
  14. package/chunk-KGN4HQPP.min.cjs +2 -0
  15. package/chunk-KGN4HQPP.min.cjs.map +1 -0
  16. package/{chunk-UNDIVFP5.cjs → chunk-KXFV42DP.cjs} +7 -3
  17. package/chunk-MBPSSROD.min.js +2 -0
  18. package/{chunk-MNWSPF5J.min.js.map → chunk-MBPSSROD.min.js.map} +1 -1
  19. package/chunk-QASRLGQX.min.js +2 -0
  20. package/{chunk-4YV72T4D.min.js.map → chunk-QASRLGQX.min.js.map} +1 -1
  21. package/chunk-SQX7XDQJ.min.cjs +2 -0
  22. package/chunk-SQX7XDQJ.min.cjs.map +1 -0
  23. package/chunk-TDP547RX.min.js +2 -0
  24. package/{chunk-AXDXFCZV.min.js.map → chunk-TDP547RX.min.js.map} +1 -1
  25. package/{chunk-RFKUMDNU.js → chunk-TSVUVVWZ.js} +7 -3
  26. package/chunk-UFJQLQFI.min.cjs +2 -0
  27. package/chunk-UFJQLQFI.min.cjs.map +1 -0
  28. package/chunk-UNSZMVZB.min.js +2 -0
  29. package/chunk-ZCDXPV3A.min.cjs +2 -0
  30. package/chunk-ZCDXPV3A.min.cjs.map +1 -0
  31. package/chunk-ZCVFQ4FC.min.js +2 -0
  32. package/chunk-ZCVFQ4FC.min.js.map +1 -0
  33. package/dist-6EWLBMVU.min.js +2 -0
  34. package/{dist-4BDJ7HYS.min.js.map → dist-6EWLBMVU.min.js.map} +1 -1
  35. package/dist-SEGTJ72R.min.cjs +2 -0
  36. package/dist-SEGTJ72R.min.cjs.map +1 -0
  37. package/index.cjs +3 -3
  38. package/index.d.cts +2 -2
  39. package/index.d.ts +2 -2
  40. package/index.js +2 -2
  41. package/index.min.cjs +1 -43
  42. package/index.min.cjs.map +1 -1
  43. package/index.min.js +1 -43
  44. package/magic-string.es-FXUUD55Y.min.cjs +14 -0
  45. package/magic-string.es-FXUUD55Y.min.cjs.map +1 -0
  46. package/magic-string.es-W5QTEOCE.min.js +14 -0
  47. package/{magic-string.es-2AQNCEBL.min.js.map → magic-string.es-W5QTEOCE.min.js.map} +1 -1
  48. package/package.json +10 -10
  49. package/sharedQuery.cjs +3 -3
  50. package/sharedQuery.js +2 -2
  51. package/sharedQuery.min.cjs +1 -17
  52. package/sharedQuery.min.cjs.map +1 -1
  53. package/sharedQuery.min.js +1 -17
  54. package/sharedState.cjs +2 -2
  55. package/sharedState.js +1 -1
  56. package/sharedState.min.cjs +1 -18
  57. package/sharedState.min.cjs.map +1 -1
  58. package/sharedState.min.js +1 -18
  59. package/storage.min.cjs +1 -11
  60. package/storage.min.cjs.map +1 -1
  61. package/storage.min.js +1 -11
  62. package/stringify.min.cjs +1 -7
  63. package/stringify.min.cjs.map +1 -1
  64. package/stringify.min.js +1 -7
  65. package/useDeepMemo.min.cjs +1 -7
  66. package/useDeepMemo.min.cjs.map +1 -1
  67. package/useDeepMemo.min.js +1 -7
  68. package/chunk-4YV72T4D.min.js +0 -105
  69. package/chunk-AXDXFCZV.min.js +0 -35
  70. package/chunk-C6X4GPZ4.min.cjs +0 -596
  71. package/chunk-C6X4GPZ4.min.cjs.map +0 -1
  72. package/chunk-JYZY2SHD.min.js +0 -596
  73. package/chunk-JYZY2SHD.min.js.map +0 -1
  74. package/chunk-K2L3OVGY.min.cjs +0 -18
  75. package/chunk-K2L3OVGY.min.cjs.map +0 -1
  76. package/chunk-KGDXU6Q2.min.cjs +0 -222
  77. package/chunk-KGDXU6Q2.min.cjs.map +0 -1
  78. package/chunk-MNWSPF5J.min.js +0 -18
  79. package/chunk-P2E73RBM.min.cjs +0 -35
  80. package/chunk-P2E73RBM.min.cjs.map +0 -1
  81. package/chunk-PCGGKBOL.min.js +0 -222
  82. package/chunk-PCGGKBOL.min.js.map +0 -1
  83. package/chunk-PHITDXZT.min.js +0 -36
  84. package/chunk-RRQBFF4W.min.cjs +0 -105
  85. package/chunk-RRQBFF4W.min.cjs.map +0 -1
  86. package/chunk-TST6JKQ5.min.cjs +0 -36
  87. package/chunk-TST6JKQ5.min.cjs.map +0 -1
  88. package/dist-4BDJ7HYS.min.js +0 -546
  89. package/dist-HKOCAKHU.min.cjs +0 -546
  90. package/dist-HKOCAKHU.min.cjs.map +0 -1
  91. package/magic-string.es-2AQNCEBL.min.js +0 -1309
  92. package/magic-string.es-XJ27RPMN.min.cjs +0 -1309
  93. package/magic-string.es-XJ27RPMN.min.cjs.map +0 -1
  94. /package/{chunk-PHITDXZT.min.js.map → chunk-UNSZMVZB.min.js.map} +0 -0
@@ -1,596 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
- var _chunkKGDXU6Q2mincjs = require('./chunk-KGDXU6Q2.min.cjs');
5
-
6
-
7
- var _chunkP2E73RBMmincjs = require('./chunk-P2E73RBM.min.cjs');
8
-
9
-
10
- var _chunkK2L3OVGYmincjs = require('./chunk-K2L3OVGY.min.cjs');
11
-
12
- // src/sharedQuery.ts
13
- var _http = require('@choksheak/ts-utils/http');
14
- var _nonNil = require('@choksheak/ts-utils/nonNil');
15
- var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);
16
-
17
-
18
-
19
-
20
-
21
-
22
- var _react = require('react');
23
- var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);
24
- var SharedQueryConfig = {
25
- /** Refetch on every page load. */
26
- staleMs: 0,
27
- /** Keep in cache for a long time. */
28
- expiryMs: 30 * 864e5,
29
- /** Always refetch automatically if the data is stale. */
30
- refetchOnStale: true,
31
- /** No default persistence configured. */
32
- persistTo: void 0,
33
- /** 100 is not too large, but please tweak accordingly. */
34
- maxSize: 100,
35
- /** 100kb limit before discarding old records. */
36
- maxBytes: 1e5,
37
- /** Default to log to console. */
38
- log: (...args) => console.log("[sharedQuery]", ...args)
39
- };
40
- function configureSharedQuery(config) {
41
- Object.assign(SharedQueryConfig, config);
42
- }
43
- var moduleQueryRegistry = /* @__PURE__ */ new Map();
44
- function getOrCreateQueryRegistry() {
45
- if (typeof window !== "undefined") {
46
- const g = window.globalThis;
47
- return g.reactUtilsQueryRegistry ??= /* @__PURE__ */ new Map();
48
- }
49
- return moduleQueryRegistry;
50
- }
51
- function sharedQuery1(options) {
52
- const registry = getOrCreateQueryRegistry();
53
- const key = options.queryName || options.url;
54
- const existing = registry.get(key);
55
- if (existing) {
56
- return existing;
57
- }
58
- const obj = sharedQuery2(options);
59
- registry.set(key, obj);
60
- return obj;
61
- }
62
- function sharedQuery2(options) {
63
- const url = options.url || "";
64
- const queryName = options.queryName || url;
65
- if (!queryName) {
66
- throw new Error(`Either queryName or url must be specified.`);
67
- }
68
- const inflightQueries = /* @__PURE__ */ new Map();
69
- const mountedKeys = /* @__PURE__ */ new Map();
70
- let queryFn;
71
- if (options.queryFn) {
72
- queryFn = options.queryFn;
73
- } else if (url) {
74
- const fetcher = _http.http.use(_http.retries.call(void 0, ));
75
- queryFn = async (...args) => {
76
- let params = "";
77
- const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
78
- if (firstArg) {
79
- if (typeof firstArg === "string") {
80
- params = firstArg;
81
- } else if (typeof firstArg === "object") {
82
- const entries = [];
83
- for (const [k, v] of Object.entries(firstArg)) {
84
- if (v === void 0) continue;
85
- if (Array.isArray(v)) {
86
- for (const item of v) {
87
- if (item === void 0) continue;
88
- entries.push([k, String(item)]);
89
- }
90
- } else {
91
- entries.push([k, String(v)]);
92
- }
93
- }
94
- params = new URLSearchParams(entries).toString();
95
- }
96
- if (params) {
97
- if (url.includes("?")) {
98
- params = "&" + params;
99
- } else {
100
- params = "?" + params;
101
- }
102
- }
103
- }
104
- const response = await fetcher.get(url + params);
105
- return await response.json();
106
- };
107
- } else {
108
- throw new Error(`Either queryFn or url must be specified`);
109
- }
110
- const refetchFn = options.refetchFn;
111
- const staleMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.staleMs]), () => ( SharedQueryConfig.staleMs));
112
- const expiryMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.expiryMs]), () => ( SharedQueryConfig.expiryMs));
113
- const refetchOnStale = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.refetchOnStale]), () => ( SharedQueryConfig.refetchOnStale));
114
- const store = options.store;
115
- if (store) {
116
- if ("persistTo" in store && store.isValid) {
117
- const isValid = store.isValid;
118
- options = {
119
- ...options,
120
- store: {
121
- ...store,
122
- isValid: (u) => {
123
- if (!u || typeof u !== "object") {
124
- return false;
125
- }
126
- for (const v of Object.values(u)) {
127
- if (!v || typeof v !== "object" || !("data" in v) || !("dataUpdatedMs" in v) || !("lastUpdatedMs" in v) || typeof v.dataUpdatedMs !== "number" || typeof v.lastUpdatedMs !== "number" || !isValid(v.data)) {
128
- return false;
129
- }
130
- }
131
- return true;
132
- }
133
- }
134
- };
135
- }
136
- } else {
137
- const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
138
- if (persistTo) {
139
- options = {
140
- ...options,
141
- store: {
142
- persistTo,
143
- key: queryName,
144
- expiryMs
145
- }
146
- };
147
- }
148
- }
149
- const maxSize = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.maxSize]), () => ( SharedQueryConfig.maxSize));
150
- const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _6 => _6.maxBytes]), () => ( SharedQueryConfig.maxBytes));
151
- const keepLastNonEmptyData = Boolean(_optionalChain([options, 'optionalAccess', _7 => _7.keepLastNonEmptyData]));
152
- const log = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.log]), () => ( SharedQueryConfig.log));
153
- options.name = queryName;
154
- const queryState = _chunkKGDXU6Q2mincjs.sharedState.call(void 0,
155
- {},
156
- // defaultValue
157
- options
158
- );
159
- function isStale(dataUpdatedMs) {
160
- if (staleMs === 0) return true;
161
- const ageMs = Date.now() - dataUpdatedMs;
162
- return ageMs > staleMs;
163
- }
164
- function isExpired(dataUpdatedMs) {
165
- if (expiryMs === 0) return false;
166
- const ageMs = Date.now() - dataUpdatedMs;
167
- return ageMs > expiryMs;
168
- }
169
- function enforceSizeLimit() {
170
- if (!maxSize && !maxBytes) {
171
- return;
172
- }
173
- const oldState = queryState.getSnapshot();
174
- const oldSize = Object.keys(oldState).length;
175
- if (oldSize <= 1) {
176
- return;
177
- }
178
- const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
179
- let numToCut = maxSize ? oldSize - maxSize : 0;
180
- let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
181
- if (numToCut <= 0 && bytesToCut <= 0) {
182
- log(
183
- `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
184
- );
185
- return;
186
- }
187
- log(
188
- `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
189
- );
190
- const newState = { ...oldState };
191
- let needUpdate = false;
192
- const deleteKeyIfNotMounted = (key, expired) => {
193
- if (mountedKeys.has(key)) {
194
- log(`Cannot clean up ${key} as it is mounted`);
195
- return;
196
- }
197
- const byteSize = _objectsizeof2.default.call(void 0, key) + _objectsizeof2.default.call(void 0, newState[key]);
198
- log(
199
- `Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
200
- );
201
- numToCut--;
202
- bytesToCut -= byteSize;
203
- delete newState[key];
204
- needUpdate = true;
205
- };
206
- let entriesByTimeAscending = Object.entries(newState).sort(
207
- (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
208
- );
209
- for (const [key] of entriesByTimeAscending) {
210
- if (!isExpired(newState[key].lastUpdatedMs)) {
211
- break;
212
- }
213
- deleteKeyIfNotMounted(key, true);
214
- }
215
- if (numToCut > 0 || bytesToCut > 0) {
216
- if (needUpdate) {
217
- entriesByTimeAscending = Object.entries(newState).sort(
218
- (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
219
- );
220
- }
221
- for (const [key] of entriesByTimeAscending) {
222
- deleteKeyIfNotMounted(key, false);
223
- if (numToCut <= 0 && bytesToCut <= 0) {
224
- break;
225
- }
226
- }
227
- }
228
- if (!needUpdate) {
229
- log(
230
- `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
231
- );
232
- return;
233
- }
234
- queryState.setValue(newState);
235
- log(
236
- `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
237
- );
238
- }
239
- function setData(queryKey, data, dataUpdatedMs = Date.now()) {
240
- const entry = {
241
- lastUpdatedMs: Date.now(),
242
- loading: false,
243
- data,
244
- dataUpdatedMs
245
- };
246
- queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
247
- enforceSizeLimit();
248
- }
249
- async function startFetching(queryKey, queryType, args) {
250
- log(`Start fetching ${queryKey}, queryType=${queryType}`);
251
- try {
252
- const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
253
- log(`Successfully fetched ${queryKey}`);
254
- setData(queryKey, data, Date.now());
255
- return data;
256
- } catch (e) {
257
- log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
258
- throw e;
259
- } finally {
260
- inflightQueries.delete(queryKey);
261
- }
262
- }
263
- function dedupedFetch(queryKey, queryType, ...args) {
264
- const inflightQuery = inflightQueries.get(queryKey);
265
- if (inflightQuery) {
266
- log(
267
- `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
268
- );
269
- return inflightQuery.promise;
270
- }
271
- const promise = startFetching(queryKey, queryType, args);
272
- const abortController = new AbortController();
273
- inflightQueries.set(queryKey, { promise, abortController });
274
- return promise;
275
- }
276
- const obj = {
277
- queryName,
278
- queryFn,
279
- refetchFn,
280
- expiryMs,
281
- staleMs,
282
- refetchOnStale,
283
- maxSize,
284
- maxBytes,
285
- keepLastNonEmptyData,
286
- log,
287
- queryState,
288
- /** Returns a key to identify requests based on the given args. */
289
- getQueryKey(args) {
290
- let s = _chunkP2E73RBMmincjs.stringifyDeterministicForKeys.call(void 0, args);
291
- if (s.length > 30) {
292
- s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
293
- }
294
- return queryName + ":" + s;
295
- },
296
- /**
297
- * Get the AbortController to abort the inflight query (if any).
298
- *
299
- * Note that once you get the controller, you can also get the signal easily
300
- * using `controller.signal`. So if you need both the controller and the
301
- * signal, just use this function.
302
- */
303
- getAbortController(args) {
304
- const queryKey = obj.getQueryKey(args);
305
- return obj.getAbortControllerByKey(queryKey);
306
- },
307
- getAbortControllerByKey(queryKey) {
308
- return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
309
- },
310
- /**
311
- * Get the AbortSignal to check for query abortions.
312
- *
313
- * Example using fetch:
314
- * ```
315
- * const getUserQuery = sharedQuery({
316
- * queryName: "getUser",
317
- * queryFn: (userId: string) => {
318
- * // Get the signal for this current execution.
319
- * const signal = getUserQuery.getAbortSignal([userId]);
320
- *
321
- * // Pass the signal to fetch so that it can be aborted.
322
- * const response = await fetch(`/users/${userId}`, { signal });
323
- *
324
- * // Check for errors.
325
- * if (!response.ok) {
326
- * throw new Error(response.statusText);
327
- * }
328
- *
329
- * // Return the data.
330
- * return await response.json();
331
- * },
332
- * });
333
- * ```
334
- *
335
- * Example using `http.ts`:
336
- * ```
337
- * const getUserQuery = sharedQuery({
338
- * queryName: "getUser",
339
- * queryFn: (userId: string) => {
340
- * // Get the signal for this current execution.
341
- * const signal = getUserQuery.getAbortSignal([userId]);
342
- *
343
- * // Pass the signal to fetch so that it can be aborted.
344
- * const response = await http.get(`/users/${userId}`, { signal });
345
- * return await response.json();
346
- * },
347
- * });
348
- * ```
349
- */
350
- getAbortSignal(args) {
351
- const queryKey = obj.getQueryKey(args);
352
- return obj.getAbortSignalByKey(queryKey);
353
- },
354
- getAbortSignalByKey(queryKey) {
355
- return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
356
- },
357
- /** For cached data, we need to return the correct timestamps as well. */
358
- async getCachedOrFetch(...args) {
359
- const startMs = Date.now();
360
- await queryState.readyPromise;
361
- const waitedMs = Date.now() - startMs;
362
- const queryKey = obj.getQueryKey(args);
363
- const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
364
- if (waitedMs) {
365
- log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
366
- }
367
- if (_optionalChain([cached, 'optionalAccess', _18 => _18.data]) && !isExpired(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
368
- if (!isStale(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
369
- log(`Return fresh data ${queryKey} from cache without fetching`);
370
- return cached;
371
- }
372
- if (refetchOnStale) {
373
- log(`refetchOnStale for ${queryKey}`);
374
- void dedupedFetch(queryKey, "query", ...args);
375
- }
376
- log(`Returning stale data for ${queryKey}`);
377
- return cached;
378
- }
379
- const data = await dedupedFetch(queryKey, "query", ...args);
380
- const now = Date.now();
381
- return {
382
- // Don't keep old error.
383
- lastUpdatedMs: now,
384
- loading: false,
385
- data,
386
- dataUpdatedMs: now
387
- };
388
- },
389
- /** Get the entire stored entry for a query key. */
390
- getQueryValue(queryKey) {
391
- return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
392
- },
393
- /** Get the current stored data for a query key. */
394
- getData(queryKey) {
395
- const stateValue = _optionalChain([queryState, 'access', _22 => _22.getSnapshot, 'call', _23 => _23(), 'optionalAccess', _24 => _24[queryKey]]);
396
- if (_optionalChain([stateValue, 'optionalAccess', _25 => _25.lastUpdatedMs])) {
397
- if (isExpired(stateValue.lastUpdatedMs)) {
398
- obj.deleteData(queryKey);
399
- return void 0;
400
- }
401
- }
402
- return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
403
- },
404
- /** Set the data directly if the user obtained it from somewhere else. */
405
- setData,
406
- /**
407
- * Do a new fetch even when the data is already cached, but don't fetch if
408
- * another fetch is already inflight.
409
- */
410
- async updateFromSource(...args) {
411
- const key = obj.getQueryKey(args);
412
- return await dedupedFetch(key, "query", ...args);
413
- },
414
- /**
415
- * Perform an explicit refetch. If `options.refetchFn` was not specified,
416
- * then this would be identical to calling `obj.updateFromSource()`.
417
- */
418
- async refetch(...args) {
419
- const key = obj.getQueryKey(args);
420
- return await dedupedFetch(key, "refetch", ...args);
421
- },
422
- /** Delete the cached data for one set of arguments. */
423
- deleteData(queryKey) {
424
- const record = queryState.getSnapshot();
425
- const clone = { ...record };
426
- delete clone[queryKey];
427
- queryState.setValue(clone);
428
- const inflight = inflightQueries.get(queryKey);
429
- if (inflight) {
430
- inflightQueries.delete(queryKey);
431
- inflight.abortController.abort("Deleted");
432
- }
433
- },
434
- /** Delete all currently cached data & all inflight promises. */
435
- clear() {
436
- queryState.delete();
437
- for (const { abortController } of Array.from(inflightQueries.values())) {
438
- abortController.abort("Cleared");
439
- }
440
- inflightQueries.clear();
441
- },
442
- /** Keep track of mounted keys. */
443
- mount(queryKey) {
444
- mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
445
- },
446
- /** Clean up mounted keys. */
447
- unmount(queryKey) {
448
- const count = mountedKeys.get(queryKey);
449
- if (count === 1) {
450
- mountedKeys.delete(queryKey);
451
- } else {
452
- mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
453
- }
454
- },
455
- /**
456
- * Discard the oldest entries if the size exceeds the limit. The last
457
- * remaining record cannot be deleted no matter what the limit is.
458
- */
459
- enforceSizeLimit
460
- };
461
- return obj;
462
- }
463
- function sharedQuery(options) {
464
- return sharedQuery1(options);
465
- }
466
- var DEFAULT_QUERY_STATE_ENTRY = {
467
- lastUpdatedMs: 0,
468
- loading: true
469
- };
470
- function useSharedQuery(query, ...args) {
471
- const stableArgs = _chunkK2L3OVGYmincjs.useDeepMemo.call(void 0, args);
472
- const [queryState, setQueryState] = _chunkKGDXU6Q2mincjs.useSharedState.call(void 0, query.queryState);
473
- const isMounted = _react.useRef.call(void 0, true);
474
- const queryKey = _react.useMemo.call(void 0,
475
- () => query.getQueryKey(stableArgs),
476
- [query, stableArgs]
477
- );
478
- const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
479
- const setQueryStateValue = _react.useCallback.call(void 0,
480
- (next) => {
481
- setQueryState((prev) => {
482
- const clone = { ...prev };
483
- clone[queryKey] = typeof next === "function" ? next(_nullishCoalesce(clone[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY))) : next;
484
- return clone;
485
- });
486
- },
487
- [queryKey, setQueryState]
488
- );
489
- const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
490
- _react.useEffect.call(void 0, () => {
491
- if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
492
- setLastNonEmptyData(queryStateValue.data);
493
- }
494
- }, [query.keepLastNonEmptyData, queryStateValue.data]);
495
- const executeQuery = _react.useCallback.call(void 0,
496
- async (isRefetch) => {
497
- query.log(
498
- `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
499
- );
500
- if (!isMounted.current) return;
501
- setQueryStateValue((prev) => ({
502
- // Keep old data and error.
503
- ...prev,
504
- lastUpdatedMs: Date.now(),
505
- loading: true
506
- }));
507
- try {
508
- let state;
509
- if (isRefetch) {
510
- const data = await query.refetch(...stableArgs);
511
- const now = Date.now();
512
- state = {
513
- // Don't keep old error.
514
- lastUpdatedMs: now,
515
- loading: false,
516
- data,
517
- dataUpdatedMs: now
518
- };
519
- } else {
520
- state = await query.getCachedOrFetch(...stableArgs);
521
- }
522
- if (!isMounted.current) return;
523
- setQueryStateValue({ ...state, loading: false });
524
- return state.data;
525
- } catch (e) {
526
- if (!isMounted.current) return;
527
- const now = Date.now();
528
- setQueryStateValue((prev) => ({
529
- // Keep old data.
530
- ...prev,
531
- lastUpdatedMs: now,
532
- loading: false,
533
- error: e,
534
- errorUpdatedMs: now
535
- }));
536
- }
537
- },
538
- [query, queryKey, setQueryStateValue, stableArgs]
539
- );
540
- _react.useEffect.call(void 0, () => {
541
- isMounted.current = true;
542
- query.mount(queryKey);
543
- void executeQuery(false);
544
- return () => {
545
- isMounted.current = false;
546
- query.unmount(queryKey);
547
- };
548
- }, [executeQuery, query, queryKey]);
549
- return _react.useMemo.call(void 0, () => {
550
- return {
551
- ...queryStateValue,
552
- // Fill with lastNonEmptyData when data is undefined.
553
- data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
554
- latestData: queryStateValue.data,
555
- // This works only if the user-given queryFn supports abort. If not,
556
- // this function doesn't do anything, since we don't have any means to
557
- // abort the running queryFn.
558
- abortCurrentQuery: (reason) => {
559
- const controller = query.getAbortControllerByKey(queryKey);
560
- _optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
561
- return Boolean(controller);
562
- },
563
- getCachedOrFetch: async () => {
564
- const data = await query.getCachedOrFetch(...stableArgs);
565
- return _nonNil.nonNil.call(void 0,
566
- data.data,
567
- typeof data.error === "string" ? data.error : JSON.stringify(data.error)
568
- );
569
- },
570
- refetch: () => {
571
- return executeQuery(true);
572
- },
573
- setData: (data, dataUpdatedMs) => {
574
- query.setData(queryKey, data, dataUpdatedMs);
575
- },
576
- deleteData: () => {
577
- query.deleteData(queryKey);
578
- }
579
- };
580
- }, [
581
- executeQuery,
582
- lastNonEmptyData,
583
- query,
584
- queryKey,
585
- queryStateValue,
586
- stableArgs
587
- ]);
588
- }
589
-
590
-
591
-
592
-
593
-
594
-
595
- exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;
596
- //# sourceMappingURL=chunk-C6X4GPZ4.min.cjs.map