@choksheak/react-utils 0.3.5 → 0.3.7

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 (54) hide show
  1. package/NoSSR.cjs +37 -0
  2. package/NoSSR.d.mts +24 -0
  3. package/NoSSR.d.ts +20 -0
  4. package/NoSSR.min.cjs +2 -0
  5. package/NoSSR.min.cjs.map +1 -0
  6. package/NoSSR.min.mjs +2 -0
  7. package/NoSSR.min.mjs.map +1 -0
  8. package/NoSSR.mjs +12 -0
  9. package/README.md +10 -1
  10. package/fetcher.cjs +3 -3
  11. package/fetcher.d.mts +5 -4
  12. package/fetcher.d.ts +4 -3
  13. package/fetcher.min.cjs +1 -1
  14. package/fetcher.min.cjs.map +1 -1
  15. package/fetcher.min.mjs +1 -1
  16. package/fetcher.min.mjs.map +1 -1
  17. package/fetcher.mjs +2 -2
  18. package/package.json +21 -3
  19. package/sharedQuery.cjs +461 -471
  20. package/sharedQuery.d.mts +64 -61
  21. package/sharedQuery.d.ts +62 -59
  22. package/sharedQuery.min.cjs +1 -1
  23. package/sharedQuery.min.cjs.map +1 -1
  24. package/sharedQuery.min.mjs +1 -1
  25. package/sharedQuery.min.mjs.map +1 -1
  26. package/sharedQuery.mjs +462 -471
  27. package/sharedState.cjs +200 -189
  28. package/sharedState.d.mts +49 -37
  29. package/sharedState.d.ts +46 -35
  30. package/sharedState.min.cjs +1 -1
  31. package/sharedState.min.cjs.map +1 -1
  32. package/sharedState.min.mjs +1 -1
  33. package/sharedState.min.mjs.map +1 -1
  34. package/sharedState.mjs +201 -189
  35. package/storage.cjs +78 -65
  36. package/storage.d.mts +39 -2
  37. package/storage.d.ts +37 -1
  38. package/storage.min.cjs +1 -1
  39. package/storage.min.cjs.map +1 -1
  40. package/storage.min.mjs +1 -1
  41. package/storage.min.mjs.map +1 -1
  42. package/storage.mjs +76 -65
  43. package/stringify.d.mts +9 -0
  44. package/stringify.d.ts +9 -0
  45. package/stringify.min.cjs.map +1 -1
  46. package/stringify.min.mjs.map +1 -1
  47. package/useDeepMemo.cjs +1 -1
  48. package/useDeepMemo.d.mts +11 -0
  49. package/useDeepMemo.d.ts +11 -0
  50. package/useDeepMemo.min.cjs +1 -1
  51. package/useDeepMemo.min.cjs.map +1 -1
  52. package/useDeepMemo.min.mjs +1 -1
  53. package/useDeepMemo.min.mjs.map +1 -1
  54. package/useDeepMemo.mjs +1 -1
package/sharedQuery.cjs CHANGED
@@ -30,7 +30,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/sharedQuery.ts
31
31
  var sharedQuery_exports = {};
32
32
  __export(sharedQuery_exports, {
33
- SharedQuery: () => SharedQuery,
34
33
  SharedQueryConfig: () => SharedQueryConfig,
35
34
  configureSharedQuery: () => configureSharedQuery,
36
35
  sharedQuery: () => sharedQuery,
@@ -56,70 +55,12 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
56
55
  }
57
56
  if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
58
57
  const expiryMs = store.expiryMs || defaultStoreExpiryMs;
59
- const isValid = store.isValid;
58
+ const config = { ...store, expiryMs };
60
59
  switch (store.persistTo) {
61
- case "localStorage": {
62
- const adapter = new import_localStore.LocalStore(store.key, {
63
- defaultExpiryMs: expiryMs
64
- });
65
- return {
66
- set: (key, value) => {
67
- if (IS_NOT_BROWSER) return;
68
- adapter.set(key, value);
69
- },
70
- get: (key) => {
71
- if (IS_NOT_BROWSER) return void 0;
72
- const value = adapter.get(key);
73
- if (isValid && !isValid(value)) {
74
- console.warn(
75
- `localStorage adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
76
- );
77
- adapter.delete(key);
78
- return void 0;
79
- }
80
- return value;
81
- },
82
- delete: (key) => {
83
- if (IS_NOT_BROWSER) return;
84
- adapter.delete(key);
85
- },
86
- clear: () => {
87
- if (IS_NOT_BROWSER) return;
88
- adapter.clear();
89
- }
90
- };
91
- }
92
- case "indexedDb": {
93
- const keyPrefix = store.key + ":";
94
- const isValid2 = store.isValid;
95
- return {
96
- set: async (key, value) => {
97
- if (IS_NOT_BROWSER) return;
98
- await import_kvStore.kvStore.set(keyPrefix + key, value, expiryMs);
99
- },
100
- get: async (key) => {
101
- if (IS_NOT_BROWSER) return void 0;
102
- const fullKey = keyPrefix + key;
103
- const value = await import_kvStore.kvStore.get(fullKey);
104
- if (isValid2 && !isValid2(value)) {
105
- console.warn(
106
- `indexedDb adapter: Auto-discard invalid value for ${key}: ${JSON.stringify(value)}`
107
- );
108
- await import_kvStore.kvStore.delete(fullKey);
109
- return void 0;
110
- }
111
- return value;
112
- },
113
- delete: async (key) => {
114
- if (IS_NOT_BROWSER) return;
115
- await import_kvStore.kvStore.delete(keyPrefix + key);
116
- },
117
- clear: async () => {
118
- if (IS_NOT_BROWSER) return;
119
- await import_kvStore.kvStore.clear();
120
- }
121
- };
122
- }
60
+ case "localStorage":
61
+ return localStoreAdapter(config);
62
+ case "indexedDb":
63
+ return kvStoreAdapter(config);
123
64
  default:
124
65
  store.persistTo;
125
66
  throw new Error(`Unknown store.adapter ${store.persistTo}`);
@@ -127,6 +68,73 @@ function getStorageAdapter(options, defaultStoreExpiryMs) {
127
68
  }
128
69
  return store;
129
70
  }
71
+ function localStoreAdapter({
72
+ key,
73
+ expiryMs,
74
+ isValid
75
+ }) {
76
+ const adapter = (0, import_localStore.createLocalStore)(key, { defaultExpiryMs: expiryMs });
77
+ return {
78
+ set: (key2, value) => {
79
+ if (IS_NOT_BROWSER) return;
80
+ adapter.set(key2, value);
81
+ },
82
+ get: (key2) => {
83
+ if (IS_NOT_BROWSER) return void 0;
84
+ const value = adapter.get(key2);
85
+ if (isValid && !isValid(value)) {
86
+ console.warn(
87
+ `localStorage adapter: Auto-discard invalid value for ${key2}: ${JSON.stringify(value)}`
88
+ );
89
+ adapter.delete(key2);
90
+ return void 0;
91
+ }
92
+ return value;
93
+ },
94
+ delete: (key2) => {
95
+ if (IS_NOT_BROWSER) return;
96
+ adapter.delete(key2);
97
+ },
98
+ clear: () => {
99
+ if (IS_NOT_BROWSER) return;
100
+ adapter.clear();
101
+ }
102
+ };
103
+ }
104
+ function kvStoreAdapter({
105
+ key,
106
+ expiryMs,
107
+ isValid
108
+ }) {
109
+ const keyPrefix = key + ":";
110
+ return {
111
+ set: async (key2, value) => {
112
+ if (IS_NOT_BROWSER) return;
113
+ await import_kvStore.kvStore.set(keyPrefix + key2, value, expiryMs);
114
+ },
115
+ get: async (key2) => {
116
+ if (IS_NOT_BROWSER) return void 0;
117
+ const fullKey = keyPrefix + key2;
118
+ const value = await import_kvStore.kvStore.get(fullKey);
119
+ if (isValid && !isValid(value)) {
120
+ console.warn(
121
+ `indexedDb adapter: Auto-discard invalid value for ${key2}: ${JSON.stringify(value)}`
122
+ );
123
+ await import_kvStore.kvStore.delete(fullKey);
124
+ return void 0;
125
+ }
126
+ return value;
127
+ },
128
+ delete: async (key2) => {
129
+ if (IS_NOT_BROWSER) return;
130
+ await import_kvStore.kvStore.delete(keyPrefix + key2);
131
+ },
132
+ clear: async () => {
133
+ if (IS_NOT_BROWSER) return;
134
+ await import_kvStore.kvStore.clear();
135
+ }
136
+ };
137
+ }
130
138
 
131
139
  // src/sharedState.ts
132
140
  var SharedStateConfig = {
@@ -141,41 +149,11 @@ var SharedStateConfig = {
141
149
  */
142
150
  lazyLoad: false
143
151
  };
144
- var PubSubStore = class {
145
- dataByKey = /* @__PURE__ */ new Map();
146
- subscribersByKey = /* @__PURE__ */ new Map();
147
- // This could be undefined if T includes undefined, else it should never
148
- // return undefined because the user has to always specify the default value.
149
- get(key) {
150
- return this.dataByKey.get(key);
151
- }
152
- set(key, value) {
153
- const prev = this.dataByKey.get(key);
154
- if (prev === value) return;
155
- this.dataByKey.set(key, value);
156
- this.notify(key, value, prev);
157
- }
158
- delete(key) {
159
- this.dataByKey.delete(key);
160
- }
161
- setNoNotify(key, value) {
162
- this.dataByKey.set(key, value);
163
- }
164
- // Subscribe to changes of a specific key
165
- subscribe(key, subscriber) {
166
- let subscribers = this.subscribersByKey.get(key);
167
- if (!subscribers) {
168
- subscribers = /* @__PURE__ */ new Set();
169
- this.subscribersByKey.set(key, subscribers);
170
- }
171
- subscribers.add(subscriber);
172
- return () => {
173
- subscribers.delete(subscriber);
174
- if (subscribers.size === 0) this.subscribersByKey.delete(key);
175
- };
176
- }
177
- notify(key, next, prev) {
178
- const subscribers = this.subscribersByKey.get(key);
152
+ function createPubSubStore() {
153
+ const dataByKey = /* @__PURE__ */ new Map();
154
+ const subscribersByKey = /* @__PURE__ */ new Map();
155
+ function notify(key, next, prev) {
156
+ const subscribers = subscribersByKey.get(key);
179
157
  if (!subscribers) return;
180
158
  const copy = Array.from(subscribers.values());
181
159
  for (const subscriber of copy) {
@@ -186,106 +164,139 @@ var PubSubStore = class {
186
164
  }
187
165
  }
188
166
  }
189
- };
190
- var pubSubStore = new PubSubStore();
167
+ return {
168
+ // This could be undefined if T includes undefined, else it should never
169
+ // return undefined because the user has to always specify the default value.
170
+ get(key) {
171
+ return dataByKey.get(key);
172
+ },
173
+ set(key, value) {
174
+ const prev = dataByKey.get(key);
175
+ if (prev === value) return;
176
+ dataByKey.set(key, value);
177
+ notify(key, value, prev);
178
+ },
179
+ delete(key) {
180
+ dataByKey.delete(key);
181
+ },
182
+ setNoNotify(key, value) {
183
+ dataByKey.set(key, value);
184
+ },
185
+ // Subscribe to changes of a specific key
186
+ subscribe(key, subscriber) {
187
+ let subscribers = subscribersByKey.get(key);
188
+ if (!subscribers) {
189
+ subscribers = /* @__PURE__ */ new Set();
190
+ subscribersByKey.set(key, subscribers);
191
+ }
192
+ subscribers.add(subscriber);
193
+ return () => {
194
+ subscribers.delete(subscriber);
195
+ if (subscribers.size === 0) subscribersByKey.delete(key);
196
+ };
197
+ }
198
+ };
199
+ }
200
+ var pubSubStore = createPubSubStore();
191
201
  var STORAGE_KEY = "state";
192
202
  var stateKey = 0;
193
- var SharedState = class {
194
- constructor(defaultValue, options) {
195
- this.defaultValue = defaultValue;
196
- this.pubSubKey = String(stateKey++);
197
- this.storageAdapter = getStorageAdapter(
198
- options,
199
- SharedStateConfig.storeExpiryMs
200
- );
201
- this.setValueBounded = (next) => {
202
- this.setValue(next);
203
- };
204
- pubSubStore.setNoNotify(this.pubSubKey, defaultValue);
205
- const lazyLoad = options?.lazyLoad;
206
- const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
207
- if (!lazy) {
208
- void this.initDefaultValueOnce();
209
- }
210
- }
211
- pubSubKey;
212
- storageAdapter;
213
- setValueBounded;
214
- initStarted = false;
215
- initDone = false;
216
- /** `subscribe` function required by useSyncExternalStore. */
217
- subscribe(subscriber) {
218
- return pubSubStore.subscribe(this.pubSubKey, () => subscriber());
219
- }
220
- /** Returns true if there is a backing store. */
221
- hasStore() {
222
- return Boolean(this.storageAdapter);
223
- }
224
- /**
225
- * Set a value directly into the store. Does nothing if there is no
226
- * backing store.
227
- *
228
- * Warning: If you want to set the value properly, you should use
229
- * `setValue()` instead which also updates the in-memory copy.
230
- */
231
- async setInStore(value) {
232
- return await this.storageAdapter?.set(STORAGE_KEY, value);
233
- }
234
- /**
235
- * Get a value directly from the store. Returns undefined if there is no
236
- * backing store.
237
- */
238
- async getFromStore() {
239
- return await this.storageAdapter?.get(STORAGE_KEY);
240
- }
241
- /**
242
- * Get the value of the shared state.
243
- * `getSnapshot` function — must return same ref if value unchanged.
244
- * Note that this would return the default value if data init from store is
245
- * not completed yet.
246
- */
247
- getSnapshot() {
248
- return pubSubStore.get(this.pubSubKey);
249
- }
250
- /** Set the value of the shared state. */
251
- setValue(next) {
252
- if (typeof next === "function") {
253
- const prev = pubSubStore.get(this.pubSubKey);
254
- next = next(prev);
203
+ function sharedState(defaultValue, options) {
204
+ let readyResolve = () => {
205
+ };
206
+ const readyPromise = new Promise((resolve) => {
207
+ readyResolve = resolve;
208
+ });
209
+ const resolveReadyPromise = readyResolve;
210
+ const pubSubKey = String(stateKey++);
211
+ const storageAdapter = getStorageAdapter(
212
+ options,
213
+ SharedStateConfig.storeExpiryMs
214
+ );
215
+ pubSubStore.setNoNotify(pubSubKey, defaultValue);
216
+ const lazyLoad = options?.lazyLoad;
217
+ const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
218
+ const obj = {
219
+ /** Allow users to await for the completion of data init. */
220
+ readyPromise,
221
+ lazy,
222
+ initStarted: false,
223
+ initDone: false,
224
+ /** `subscribe` function required by useSyncExternalStore. */
225
+ subscribe(subscriber) {
226
+ return pubSubStore.subscribe(pubSubKey, () => subscriber());
227
+ },
228
+ /** Returns true if there is a backing store. */
229
+ hasStore() {
230
+ return Boolean(storageAdapter);
231
+ },
232
+ /**
233
+ * Set a value directly into the store. Does nothing if there is no
234
+ * backing store.
235
+ *
236
+ * Warning: If you want to set the value properly, you should use
237
+ * `setValue()` instead which also updates the in-memory copy.
238
+ */
239
+ async setInStore(value) {
240
+ return await storageAdapter?.set(STORAGE_KEY, value);
241
+ },
242
+ /**
243
+ * Get a value directly from the store. Returns undefined if there is no
244
+ * backing store.
245
+ */
246
+ async getFromStore() {
247
+ return await storageAdapter?.get(STORAGE_KEY);
248
+ },
249
+ /**
250
+ * Get the value of the shared state.
251
+ * `getSnapshot` function — must return same ref if value unchanged.
252
+ * Note that this would return the default value if data init from store is
253
+ * not completed yet.
254
+ */
255
+ getSnapshot() {
256
+ return pubSubStore.get(pubSubKey);
257
+ },
258
+ /** Set the value of the shared state. */
259
+ setValue(next) {
260
+ if (typeof next === "function") {
261
+ const prev = pubSubStore.get(pubSubKey);
262
+ next = next(prev);
263
+ }
264
+ pubSubStore.set(pubSubKey, next);
265
+ void obj.setInStore(next);
266
+ },
267
+ /**
268
+ * Remove the value of the shared state. Actually this just sets the value
269
+ * back to the given default value.
270
+ */
271
+ delete() {
272
+ pubSubStore.set(pubSubKey, defaultValue);
273
+ void storageAdapter?.set(STORAGE_KEY, defaultValue);
274
+ },
275
+ /** Initial default handling. */
276
+ async initDefaultValueOnce() {
277
+ if (obj.initDone || obj.initStarted) return;
278
+ obj.initStarted = true;
279
+ const stored = await obj.getFromStore();
280
+ const value = stored !== void 0 ? stored : defaultValue;
281
+ pubSubStore.set(pubSubKey, value);
282
+ obj.initDone = true;
283
+ resolveReadyPromise();
255
284
  }
256
- pubSubStore.set(this.pubSubKey, next);
257
- void this.setInStore(next);
258
- }
259
- /**
260
- * Remove the value of the shared state. Actually this just sets the value
261
- * back to the given default value.
262
- */
263
- delete() {
264
- pubSubStore.set(this.pubSubKey, this.defaultValue);
265
- void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);
266
- }
267
- /** Initial default handling. */
268
- async initDefaultValueOnce() {
269
- if (this.initDone || this.initStarted) return;
270
- this.initStarted = true;
271
- const stored = await this.getFromStore();
272
- const value = stored !== void 0 ? stored : this.defaultValue;
273
- pubSubStore.set(this.pubSubKey, value);
274
- this.initDone = true;
285
+ };
286
+ if (!lazy) {
287
+ void obj.initDefaultValueOnce();
275
288
  }
276
- };
277
- function sharedState(defaultValue, options) {
278
- return new SharedState(defaultValue, options);
289
+ return obj;
279
290
  }
280
291
  function useSharedState(state) {
281
- state.initDefaultValueOnce();
292
+ void state.initDefaultValueOnce();
282
293
  const value = (0, import_react.useSyncExternalStore)(
283
294
  (onStoreChange) => state.subscribe(onStoreChange),
284
295
  () => state.getSnapshot(),
285
296
  // getServerSnapshot is needed to prevent SSR dev errors in nextjs.
286
297
  () => state.getSnapshot()
287
298
  );
288
- return [value, state.setValueBounded];
299
+ return [value, state.setValue];
289
300
  }
290
301
 
291
302
  // src/stringify.ts
@@ -325,7 +336,7 @@ var import_react2 = require("react");
325
336
  function useDeepMemo(value) {
326
337
  const [state, setState] = (0, import_react2.useState)(value);
327
338
  return (0, import_react2.useMemo)(() => {
328
- if (state === value || (0, import_isEqual.default)(state, value)) {
339
+ if ((0, import_isEqual.default)(state, value)) {
329
340
  return state;
330
341
  }
331
342
  setState(value);
@@ -353,276 +364,79 @@ var SharedQueryConfig = {
353
364
  function configureSharedQuery(config) {
354
365
  Object.assign(SharedQueryConfig, config);
355
366
  }
356
- var SharedQuery = class {
357
- inflightQueries = /* @__PURE__ */ new Map();
358
- queryState;
359
- /**
360
- * Keep track of the mounted query keys. This handles the case where an
361
- * earlier-started query returns later, and when it returns, it was already
362
- * unmounted, thus making it eligible for clean up right after fetch.
363
- */
364
- mountedKeys = /* @__PURE__ */ new Map();
365
- queryName;
366
- queryFn;
367
- refetchFn;
368
- expiryMs;
369
- staleMs;
370
- refetchOnStale;
371
- maxSize;
372
- maxBytes;
373
- keepLastNonEmptyData;
374
- log;
375
- constructor(options) {
376
- this.queryName = options.queryName;
377
- this.queryFn = options.queryFn;
378
- this.refetchFn = options.refetchFn;
379
- this.staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
380
- this.expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
381
- this.refetchOnStale = options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;
382
- if (!options.store) {
383
- const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
384
- if (persistTo) {
385
- options.store = {
386
- persistTo,
387
- key: options.queryName,
388
- expiryMs: this.expiryMs
389
- };
390
- }
391
- }
392
- this.maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
393
- this.maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
394
- this.keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
395
- this.log = options?.log ?? SharedQueryConfig.log;
396
- this.queryState = sharedState(
397
- {},
398
- // defaultValue
399
- options
400
- );
401
- }
402
- /** Returns a key to identify requests based on the given args. */
403
- getQueryKey(args) {
404
- return this.queryName + ":" + stringifyDeterministicForKeys(args);
405
- }
406
- /**
407
- * Get the AbortController to abort the inflight query (if any).
408
- *
409
- * Note that once you get the controller, you can also get the signal easily
410
- * using `controller.signal`. So if you need both the controller and the
411
- * signal, just use this function.
412
- */
413
- getAbortController(args) {
414
- const queryKey = this.getQueryKey(args);
415
- return this.getAbortControllerByKey(queryKey);
416
- }
417
- getAbortControllerByKey(queryKey) {
418
- return this.inflightQueries.get(queryKey)?.abortController ?? null;
419
- }
420
- /**
421
- * Get the AbortSignal to check for query abortions.
422
- *
423
- * Example:
424
- * ```
425
- * const getUserQuery = sharedQuery({
426
- * queryName: "getUser",
427
- * queryFn: (userId: string) => {
428
- * // Get the signal for this current execution.
429
- * const signal = getUserQuery.getAbortSignal([userId]);
430
- *
431
- * // Pass the signal to fetch so that it can be aborted.
432
- * const response = await fetch(`/users/${userId}`, { signal });
433
- *
434
- * // Check for errors.
435
- * if (!response.ok) {
436
- * throw new Error(response.statusText);
437
- * }
438
- *
439
- * // Return the data.
440
- * return await response.json();
441
- * },
442
- * });
443
- * ```
444
- */
445
- getAbortSignal(args) {
446
- const queryKey = this.getQueryKey(args);
447
- return this.getAbortSignalByKey(queryKey);
367
+ var seenQueryNames = /* @__PURE__ */ new Set();
368
+ function sharedQuery(options) {
369
+ if (seenQueryNames.has(options.queryName)) {
370
+ throw new Error(`Duplicate shared query name "${options.queryName}"`);
448
371
  }
449
- getAbortSignalByKey(queryKey) {
450
- return this.getAbortControllerByKey(queryKey)?.signal ?? null;
372
+ seenQueryNames.add(options.queryName);
373
+ const inflightQueries = /* @__PURE__ */ new Map();
374
+ const mountedKeys = /* @__PURE__ */ new Map();
375
+ const queryName = options.queryName;
376
+ const queryFn = options.queryFn;
377
+ const refetchFn = options.refetchFn;
378
+ const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;
379
+ const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;
380
+ const refetchOnStale = options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;
381
+ if (!options.store) {
382
+ const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;
383
+ if (persistTo) {
384
+ options.store = {
385
+ persistTo,
386
+ key: queryName,
387
+ expiryMs
388
+ };
389
+ }
451
390
  }
452
- isStale(dataUpdatedMs) {
453
- if (this.staleMs === 0) return true;
391
+ const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;
392
+ const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
393
+ const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
394
+ const log = options?.log ?? SharedQueryConfig.log;
395
+ const queryState = sharedState(
396
+ {},
397
+ // defaultValue
398
+ options
399
+ );
400
+ function isStale(dataUpdatedMs) {
401
+ if (staleMs === 0) return true;
454
402
  const ageMs = Date.now() - dataUpdatedMs;
455
- return ageMs > this.staleMs;
403
+ return ageMs > staleMs;
456
404
  }
457
- isExpired(dataUpdatedMs) {
458
- if (this.expiryMs === 0) return false;
405
+ function isExpired(dataUpdatedMs) {
406
+ if (expiryMs === 0) return false;
459
407
  const ageMs = Date.now() - dataUpdatedMs;
460
- return ageMs > this.expiryMs;
461
- }
462
- /** For cached data, we need to return the correct timestamps as well. */
463
- async getCachedOrFetch(...args) {
464
- const queryKey = this.getQueryKey(args);
465
- const cached = this.queryState.getSnapshot()?.[queryKey];
466
- if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {
467
- if (!this.isStale(cached.dataUpdatedMs ?? 0)) {
468
- this.log(`Return fresh data ${queryKey} from cache without fetching`);
469
- return cached;
470
- }
471
- if (this.refetchOnStale) {
472
- this.log(`refetchOnStale for ${queryKey}`);
473
- void this.dedupedFetch(queryKey, "query", ...args);
474
- }
475
- this.log(`Returning stale data for ${queryKey}`);
476
- return cached;
477
- }
478
- const data = await this.dedupedFetch(queryKey, "query", ...args);
479
- const now = Date.now();
480
- return {
481
- // Don't keep old error.
482
- lastUpdatedMs: now,
483
- loading: false,
484
- data,
485
- dataUpdatedMs: now
486
- };
408
+ return ageMs > expiryMs;
487
409
  }
488
- dedupedFetch(queryKey, queryType, ...args) {
489
- const inflightQuery = this.inflightQueries.get(queryKey);
490
- if (inflightQuery) {
491
- this.log(
492
- `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
493
- );
494
- return inflightQuery.promise;
495
- }
496
- const promise = this.startFetching(queryKey, queryType, args);
497
- const abortController = new AbortController();
498
- this.inflightQueries.set(queryKey, { promise, abortController });
499
- return promise;
500
- }
501
- async startFetching(queryKey, queryType, args) {
502
- this.log(`Start fetching ${queryKey}, queryType=${queryType}`);
503
- try {
504
- const data = await (queryType === "refetch" && this.refetchFn ? this.refetchFn(...args) : this.queryFn(...args));
505
- this.log(`Successfully fetched ${queryKey}`);
506
- this.setData(queryKey, data, Date.now());
507
- return data;
508
- } catch (e) {
509
- this.log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
510
- throw e;
511
- } finally {
512
- this.inflightQueries.delete(queryKey);
513
- }
514
- }
515
- /** Get the entire stored entry for a query key. */
516
- getQueryValue(queryKey) {
517
- return this.queryState.getSnapshot()?.[queryKey];
518
- }
519
- /** Get the current stored data for a query key. */
520
- getData(queryKey) {
521
- const stateValue = this.queryState.getSnapshot()?.[queryKey];
522
- if (stateValue?.lastUpdatedMs) {
523
- if (this.isExpired(stateValue.lastUpdatedMs)) {
524
- this.deleteData(queryKey);
525
- return void 0;
526
- }
527
- }
528
- return stateValue?.data;
529
- }
530
- /** Set the data directly if the user obtained it from somewhere else. */
531
- setData(queryKey, data, dataUpdatedMs = Date.now()) {
532
- const entry = {
533
- lastUpdatedMs: Date.now(),
534
- loading: false,
535
- data,
536
- dataUpdatedMs
537
- };
538
- this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
539
- this.enforceSizeLimit();
540
- }
541
- /**
542
- * Do a new fetch even when the data is already cached, but don't fetch if
543
- * another fetch is already inflight.
544
- */
545
- async updateFromSource(...args) {
546
- const key = this.getQueryKey(args);
547
- return await this.dedupedFetch(key, "query", ...args);
548
- }
549
- /**
550
- * Perform an explicit refetch. If `options.refetchFn` was not specified,
551
- * then this would be identical to calling `this.updateFromSource()`.
552
- */
553
- async refetch(...args) {
554
- const key = this.getQueryKey(args);
555
- return await this.dedupedFetch(key, "refetch", ...args);
556
- }
557
- /** Delete the cached data for one set of arguments. */
558
- deleteData(queryKey) {
559
- const record = this.queryState.getSnapshot();
560
- const clone = { ...record };
561
- delete clone[queryKey];
562
- this.queryState.setValue(clone);
563
- const inflight = this.inflightQueries.get(queryKey);
564
- if (inflight) {
565
- this.inflightQueries.delete(queryKey);
566
- inflight.abortController.abort("Deleted");
567
- }
568
- }
569
- /** Delete all currently cached data & all inflight promises. */
570
- clear() {
571
- this.queryState.delete();
572
- for (const { abortController } of Array.from(
573
- this.inflightQueries.values()
574
- )) {
575
- abortController.abort("Cleared");
576
- }
577
- this.inflightQueries.clear();
578
- }
579
- /** Keep track of mounted keys. */
580
- mount(queryKey) {
581
- this.mountedKeys.set(queryKey, (this.mountedKeys.get(queryKey) ?? 0) + 1);
582
- }
583
- /** Clean up mounted keys. */
584
- unmount(queryKey) {
585
- const count = this.mountedKeys.get(queryKey);
586
- if (count === 1) {
587
- this.mountedKeys.delete(queryKey);
588
- } else {
589
- this.mountedKeys.set(queryKey, (count ?? 0) - 1);
590
- }
591
- }
592
- /**
593
- * Discard the oldest entries if the size exceeds the limit. The last
594
- * remaining record cannot be deleted no matter what the limit is.
595
- */
596
- enforceSizeLimit() {
597
- if (!this.maxSize && !this.maxBytes) {
410
+ function enforceSizeLimit() {
411
+ if (!maxSize && !maxBytes) {
598
412
  return;
599
413
  }
600
- const oldState = this.queryState.getSnapshot();
414
+ const oldState = queryState.getSnapshot();
601
415
  const oldSize = Object.keys(oldState).length;
602
416
  if (oldSize <= 1) {
603
417
  return;
604
418
  }
605
419
  const oldByteSize = (0, import_object_sizeof.default)(oldState);
606
- let numToCut = this.maxSize ? oldSize - this.maxSize : 0;
607
- let bytesToCut = this.maxBytes ? oldByteSize - this.maxBytes : 0;
420
+ let numToCut = maxSize ? oldSize - maxSize : 0;
421
+ let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
608
422
  if (numToCut <= 0 && bytesToCut <= 0) {
609
- this.log(
610
- `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`
423
+ log(
424
+ `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
611
425
  );
612
426
  return;
613
427
  }
614
- this.log(
615
- `Need to trim ${this.queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
428
+ log(
429
+ `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
616
430
  );
617
431
  const newState = { ...oldState };
618
432
  let needUpdate = false;
619
433
  const deleteKeyIfNotMounted = (key, expired) => {
620
- if (this.mountedKeys.has(key)) {
621
- this.log(`Cannot clean up ${key} as it is mounted`);
434
+ if (mountedKeys.has(key)) {
435
+ log(`Cannot clean up ${key} as it is mounted`);
622
436
  return;
623
437
  }
624
438
  const byteSize = (0, import_object_sizeof.default)(key) + (0, import_object_sizeof.default)(newState[key]);
625
- this.log(
439
+ log(
626
440
  `Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
627
441
  );
628
442
  numToCut--;
@@ -634,7 +448,7 @@ var SharedQuery = class {
634
448
  (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
635
449
  );
636
450
  for (const [key] of entriesByTimeAscending) {
637
- if (!this.isExpired(newState[key].lastUpdatedMs)) {
451
+ if (!isExpired(newState[key].lastUpdatedMs)) {
638
452
  break;
639
453
  }
640
454
  deleteKeyIfNotMounted(key, true);
@@ -653,24 +467,220 @@ var SharedQuery = class {
653
467
  }
654
468
  }
655
469
  if (!needUpdate) {
656
- this.log(
657
- `No trimmable entries found for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`
470
+ log(
471
+ `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
658
472
  );
659
473
  return;
660
474
  }
661
- this.queryState.setValue(newState);
662
- this.log(
663
- `Trimmed data for ${this.queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${this.maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${(0, import_object_sizeof.default)(newState).toLocaleString()}] (limit=${this.maxBytes.toLocaleString()})`
475
+ queryState.setValue(newState);
476
+ log(
477
+ `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${(0, import_object_sizeof.default)(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
664
478
  );
665
479
  }
666
- };
667
- var seenQueryNames = /* @__PURE__ */ new Set();
668
- function sharedQuery(options) {
669
- if (seenQueryNames.has(options.queryName)) {
670
- throw new Error(`Duplicate shared query "${options.queryName}"`);
480
+ function setData(queryKey, data, dataUpdatedMs = Date.now()) {
481
+ const entry = {
482
+ lastUpdatedMs: Date.now(),
483
+ loading: false,
484
+ data,
485
+ dataUpdatedMs
486
+ };
487
+ queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
488
+ enforceSizeLimit();
671
489
  }
672
- seenQueryNames.add(options.queryName);
673
- return new SharedQuery(options);
490
+ async function startFetching(queryKey, queryType, args) {
491
+ log(`Start fetching ${queryKey}, queryType=${queryType}`);
492
+ try {
493
+ const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
494
+ log(`Successfully fetched ${queryKey}`);
495
+ setData(queryKey, data, Date.now());
496
+ return data;
497
+ } catch (e) {
498
+ log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
499
+ throw e;
500
+ } finally {
501
+ inflightQueries.delete(queryKey);
502
+ }
503
+ }
504
+ function dedupedFetch(queryKey, queryType, ...args) {
505
+ const inflightQuery = inflightQueries.get(queryKey);
506
+ if (inflightQuery) {
507
+ log(
508
+ `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
509
+ );
510
+ return inflightQuery.promise;
511
+ }
512
+ const promise = startFetching(queryKey, queryType, args);
513
+ const abortController = new AbortController();
514
+ inflightQueries.set(queryKey, { promise, abortController });
515
+ return promise;
516
+ }
517
+ const obj = {
518
+ queryName,
519
+ queryFn,
520
+ refetchFn,
521
+ expiryMs,
522
+ staleMs,
523
+ refetchOnStale,
524
+ maxSize,
525
+ maxBytes,
526
+ keepLastNonEmptyData,
527
+ log,
528
+ queryState,
529
+ /** Returns a key to identify requests based on the given args. */
530
+ getQueryKey(args) {
531
+ return queryName + ":" + stringifyDeterministicForKeys(args);
532
+ },
533
+ /**
534
+ * Get the AbortController to abort the inflight query (if any).
535
+ *
536
+ * Note that once you get the controller, you can also get the signal easily
537
+ * using `controller.signal`. So if you need both the controller and the
538
+ * signal, just use this function.
539
+ */
540
+ getAbortController(args) {
541
+ const queryKey = obj.getQueryKey(args);
542
+ return obj.getAbortControllerByKey(queryKey);
543
+ },
544
+ getAbortControllerByKey(queryKey) {
545
+ return inflightQueries.get(queryKey)?.abortController ?? null;
546
+ },
547
+ /**
548
+ * Get the AbortSignal to check for query abortions.
549
+ *
550
+ * Example:
551
+ * ```
552
+ * const getUserQuery = sharedQuery({
553
+ * queryName: "getUser",
554
+ * queryFn: (userId: string) => {
555
+ * // Get the signal for this current execution.
556
+ * const signal = getUserQuery.getAbortSignal([userId]);
557
+ *
558
+ * // Pass the signal to fetch so that it can be aborted.
559
+ * const response = await fetch(`/users/${userId}`, { signal });
560
+ *
561
+ * // Check for errors.
562
+ * if (!response.ok) {
563
+ * throw new Error(response.statusText);
564
+ * }
565
+ *
566
+ * // Return the data.
567
+ * return await response.json();
568
+ * },
569
+ * });
570
+ * ```
571
+ */
572
+ getAbortSignal(args) {
573
+ const queryKey = obj.getQueryKey(args);
574
+ return obj.getAbortSignalByKey(queryKey);
575
+ },
576
+ getAbortSignalByKey(queryKey) {
577
+ return obj.getAbortControllerByKey(queryKey)?.signal ?? null;
578
+ },
579
+ /** For cached data, we need to return the correct timestamps as well. */
580
+ async getCachedOrFetch(...args) {
581
+ const startMs = Date.now();
582
+ await queryState.readyPromise;
583
+ const waitedMs = Date.now() - startMs;
584
+ const queryKey = obj.getQueryKey(args);
585
+ const cached = queryState.getSnapshot()?.[queryKey];
586
+ if (waitedMs) {
587
+ log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
588
+ }
589
+ if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {
590
+ if (!isStale(cached.dataUpdatedMs ?? 0)) {
591
+ log(`Return fresh data ${queryKey} from cache without fetching`);
592
+ return cached;
593
+ }
594
+ if (refetchOnStale) {
595
+ log(`refetchOnStale for ${queryKey}`);
596
+ void dedupedFetch(queryKey, "query", ...args);
597
+ }
598
+ log(`Returning stale data for ${queryKey}`);
599
+ return cached;
600
+ }
601
+ const data = await dedupedFetch(queryKey, "query", ...args);
602
+ const now = Date.now();
603
+ return {
604
+ // Don't keep old error.
605
+ lastUpdatedMs: now,
606
+ loading: false,
607
+ data,
608
+ dataUpdatedMs: now
609
+ };
610
+ },
611
+ /** Get the entire stored entry for a query key. */
612
+ getQueryValue(queryKey) {
613
+ return queryState.getSnapshot()?.[queryKey];
614
+ },
615
+ /** Get the current stored data for a query key. */
616
+ getData(queryKey) {
617
+ const stateValue = queryState.getSnapshot()?.[queryKey];
618
+ if (stateValue?.lastUpdatedMs) {
619
+ if (isExpired(stateValue.lastUpdatedMs)) {
620
+ obj.deleteData(queryKey);
621
+ return void 0;
622
+ }
623
+ }
624
+ return stateValue?.data;
625
+ },
626
+ /** Set the data directly if the user obtained it from somewhere else. */
627
+ setData,
628
+ /**
629
+ * Do a new fetch even when the data is already cached, but don't fetch if
630
+ * another fetch is already inflight.
631
+ */
632
+ async updateFromSource(...args) {
633
+ const key = obj.getQueryKey(args);
634
+ return await dedupedFetch(key, "query", ...args);
635
+ },
636
+ /**
637
+ * Perform an explicit refetch. If `options.refetchFn` was not specified,
638
+ * then this would be identical to calling `obj.updateFromSource()`.
639
+ */
640
+ async refetch(...args) {
641
+ const key = obj.getQueryKey(args);
642
+ return await dedupedFetch(key, "refetch", ...args);
643
+ },
644
+ /** Delete the cached data for one set of arguments. */
645
+ deleteData(queryKey) {
646
+ const record = queryState.getSnapshot();
647
+ const clone = { ...record };
648
+ delete clone[queryKey];
649
+ queryState.setValue(clone);
650
+ const inflight = inflightQueries.get(queryKey);
651
+ if (inflight) {
652
+ inflightQueries.delete(queryKey);
653
+ inflight.abortController.abort("Deleted");
654
+ }
655
+ },
656
+ /** Delete all currently cached data & all inflight promises. */
657
+ clear() {
658
+ queryState.delete();
659
+ for (const { abortController } of Array.from(inflightQueries.values())) {
660
+ abortController.abort("Cleared");
661
+ }
662
+ inflightQueries.clear();
663
+ },
664
+ /** Keep track of mounted keys. */
665
+ mount(queryKey) {
666
+ mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);
667
+ },
668
+ /** Clean up mounted keys. */
669
+ unmount(queryKey) {
670
+ const count = mountedKeys.get(queryKey);
671
+ if (count === 1) {
672
+ mountedKeys.delete(queryKey);
673
+ } else {
674
+ mountedKeys.set(queryKey, (count ?? 0) - 1);
675
+ }
676
+ },
677
+ /**
678
+ * Discard the oldest entries if the size exceeds the limit. The last
679
+ * remaining record cannot be deleted no matter what the limit is.
680
+ */
681
+ enforceSizeLimit
682
+ };
683
+ return obj;
674
684
  }
675
685
  var DEFAULT_QUERY_STATE_ENTRY = {
676
686
  lastUpdatedMs: 0,
@@ -767,39 +777,19 @@ function useSharedQuery(query, ...args) {
767
777
  return Boolean(controller);
768
778
  },
769
779
  refetch: () => {
770
- void execute(true);
780
+ return execute(true);
771
781
  },
772
782
  setData: (data, dataUpdatedMs) => {
773
- const now = Date.now();
774
- setQueryStateValue((prev) => ({
775
- ...prev,
776
- data,
777
- dataUpdatedMs: dataUpdatedMs ?? now,
778
- lastUpdatedMs: now,
779
- loading: false
780
- }));
783
+ query.setData(queryKey, data, dataUpdatedMs);
781
784
  },
782
785
  deleteData: () => {
783
- setQueryState((prev) => {
784
- const clone = { ...prev };
785
- delete clone[queryKey];
786
- return clone;
787
- });
786
+ query.deleteData(queryKey);
788
787
  }
789
788
  };
790
- }, [
791
- execute,
792
- lastNonEmptyData,
793
- query,
794
- queryKey,
795
- queryStateValue,
796
- setQueryState,
797
- setQueryStateValue
798
- ]);
789
+ }, [execute, lastNonEmptyData, query, queryKey, queryStateValue]);
799
790
  }
800
791
  // Annotate the CommonJS export names for ESM import in node:
801
792
  0 && (module.exports = {
802
- SharedQuery,
803
793
  SharedQueryConfig,
804
794
  configureSharedQuery,
805
795
  sharedQuery,