@choksheak/react-utils 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/NoSSR.cjs +5 -2
  2. package/{NoSSR.mjs → NoSSR.js} +4 -1
  3. package/NoSSR.min.cjs +14 -1
  4. package/NoSSR.min.cjs.map +1 -1
  5. package/NoSSR.min.js +15 -0
  6. package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
  7. package/chunk-4YV72T4D.min.js +105 -0
  8. package/{storage.min.mjs.map → chunk-4YV72T4D.min.js.map} +1 -1
  9. package/chunk-5PDGU37E.cjs +104 -0
  10. package/{storage.mjs → chunk-7CPBZFDV.js} +5 -3
  11. package/{stringify.mjs → chunk-7XC6EVMX.js} +2 -0
  12. package/chunk-AXDXFCZV.min.js +35 -0
  13. package/{stringify.min.mjs.map → chunk-AXDXFCZV.min.js.map} +1 -1
  14. package/chunk-C6X4GPZ4.min.cjs +596 -0
  15. package/chunk-C6X4GPZ4.min.cjs.map +1 -0
  16. package/{sharedState.mjs → chunk-CIDQGOPA.js} +23 -8
  17. package/chunk-CYTO5EZE.cjs +34 -0
  18. package/chunk-HFIQE4XZ.cjs +595 -0
  19. package/chunk-IS3BZTWE.cjs +35 -0
  20. package/chunk-JYZY2SHD.min.js +596 -0
  21. package/chunk-JYZY2SHD.min.js.map +1 -0
  22. package/chunk-K2L3OVGY.min.cjs +18 -0
  23. package/chunk-K2L3OVGY.min.cjs.map +1 -0
  24. package/chunk-KGDXU6Q2.min.cjs +222 -0
  25. package/chunk-KGDXU6Q2.min.cjs.map +1 -0
  26. package/chunk-MNWSPF5J.min.js +18 -0
  27. package/{useDeepMemo.min.mjs.map → chunk-MNWSPF5J.min.js.map} +1 -1
  28. package/chunk-P2E73RBM.min.cjs +35 -0
  29. package/chunk-P2E73RBM.min.cjs.map +1 -0
  30. package/chunk-PCGGKBOL.min.js +222 -0
  31. package/chunk-PCGGKBOL.min.js.map +1 -0
  32. package/chunk-PHITDXZT.min.js +36 -0
  33. package/chunk-PHITDXZT.min.js.map +1 -0
  34. package/{sharedQuery.mjs → chunk-RFKUMDNU.js} +17 -6
  35. package/chunk-RRQBFF4W.min.cjs +105 -0
  36. package/chunk-RRQBFF4W.min.cjs.map +1 -0
  37. package/chunk-TST6JKQ5.min.cjs +36 -0
  38. package/chunk-TST6JKQ5.min.cjs.map +1 -0
  39. package/chunk-U67V476Y.js +35 -0
  40. package/chunk-UNDIVFP5.cjs +221 -0
  41. package/chunk-WXLUEDBO.cjs +17 -0
  42. package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
  43. package/dist-4BDJ7HYS.min.js +546 -0
  44. package/dist-4BDJ7HYS.min.js.map +1 -0
  45. package/dist-HKOCAKHU.min.cjs +546 -0
  46. package/dist-HKOCAKHU.min.cjs.map +1 -0
  47. package/dist-RQU6CWRG.js +545 -0
  48. package/dist-UKP7SPWZ.cjs +545 -0
  49. package/index.cjs +43 -5
  50. package/index.d.cts +2 -2
  51. package/index.d.ts +2 -2
  52. package/index.js +43 -0
  53. package/index.min.cjs +43 -1
  54. package/index.min.cjs.map +1 -1
  55. package/index.min.js +44 -0
  56. package/index.min.js.map +1 -0
  57. package/magic-string.es-2AQNCEBL.min.js +1309 -0
  58. package/magic-string.es-2AQNCEBL.min.js.map +1 -0
  59. package/magic-string.es-HC5PDAU3.cjs +1308 -0
  60. package/magic-string.es-KDMUXKGI.js +1308 -0
  61. package/magic-string.es-XJ27RPMN.min.cjs +1309 -0
  62. package/magic-string.es-XJ27RPMN.min.cjs.map +1 -0
  63. package/package.json +48 -8
  64. package/sharedQuery.cjs +8 -575
  65. package/sharedQuery.d.cts +7 -92
  66. package/sharedQuery.d.ts +7 -92
  67. package/sharedQuery.js +17 -0
  68. package/sharedQuery.min.cjs +17 -1
  69. package/sharedQuery.min.cjs.map +1 -1
  70. package/sharedQuery.min.js +18 -0
  71. package/sharedQuery.min.js.map +1 -0
  72. package/sharedState.cjs +11 -199
  73. package/sharedState.d.cts +12 -57
  74. package/sharedState.d.ts +12 -57
  75. package/sharedState.js +18 -0
  76. package/sharedState.min.cjs +18 -1
  77. package/sharedState.min.cjs.map +1 -1
  78. package/sharedState.min.js +19 -0
  79. package/sharedState.min.js.map +1 -0
  80. package/storage.cjs +7 -98
  81. package/storage.js +11 -0
  82. package/storage.min.cjs +11 -1
  83. package/storage.min.cjs.map +1 -1
  84. package/storage.min.js +12 -0
  85. package/storage.min.js.map +1 -0
  86. package/stringify.cjs +5 -30
  87. package/stringify.js +7 -0
  88. package/stringify.min.cjs +7 -1
  89. package/stringify.min.cjs.map +1 -1
  90. package/stringify.min.js +8 -0
  91. package/stringify.min.js.map +1 -0
  92. package/useDeepMemo.cjs +5 -13
  93. package/useDeepMemo.js +7 -0
  94. package/useDeepMemo.min.cjs +7 -1
  95. package/useDeepMemo.min.cjs.map +1 -1
  96. package/useDeepMemo.min.js +8 -0
  97. package/useDeepMemo.min.js.map +1 -0
  98. package/NoSSR.min.mjs +0 -2
  99. package/index.min.mjs +0 -2
  100. package/index.min.mjs.map +0 -1
  101. package/index.mjs +0 -5
  102. package/sharedQuery.min.mjs +0 -2
  103. package/sharedQuery.min.mjs.map +0 -1
  104. package/sharedState.min.mjs +0 -2
  105. package/sharedState.min.mjs.map +0 -1
  106. package/storage.min.mjs +0 -2
  107. package/stringify.min.mjs +0 -2
  108. package/useDeepMemo.min.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.ts"],"names":["IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter"],"mappings":"AAYA,mOAAwB,4DACS,MAkC3BA,CAAAA,CAAiB,OAAO,MAAA,CAAW,GAAA,CAMlC,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CAC0B,CAC1B,KAAM,CAAE,KAAA,CAAAC,CAAM,CAAA,kBAAIF,CAAAA,SAAW,CAAC,GAAA,CAE9B,EAAA,CAAI,CAACE,CAAAA,CACH,OAAO,IAAA,CAGT,EAAA,CACE,WAAA,GAAeA,CAAAA,EACf,OAAOA,CAAAA,CAAM,SAAA,EAAc,QAAA,EAC3B,KAAA,GAASA,CAAAA,EACT,OAAOA,CAAAA,CAAM,GAAA,EAAQ,QAAA,CACrB,CACA,MAAMC,CAAAA,CAAWD,CAAAA,CAAM,QAAA,EAAYD,CAAAA,CAC7BG,CAAAA,CAAS,CAAE,GAAGF,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAA,CAEpC,MAAA,CAAQD,CAAAA,CAAM,SAAA,CAAW,CACvB,IAAK,cAAA,CACH,OAAOG,CAAAA,CAAqBD,CAAM,CAAA,CAEpC,IAAK,WAAA,CACH,OAAOE,CAAAA,CAAkBF,CAAM,CAAA,CAEjC,OAAA,CACE,MAAAF,CAAAA,CAAM,SAAA,CACA,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyBA,CAAAA,CAAM,SAAS,CAAA,CAAA","file":"/Users/choksheaklau/src/react-utils/dist/storage.min.cjs","sourcesContent":["/**\n * @packageDocumentation\n *\n * Backing storage implementation for the shared state. Note that this uses the\n * LocalStore and KvStore from package \"@choksheak/ts-utils\", but is customized\n * to be used for shared states.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\nimport { Duration } from \"@choksheak/ts-utils/duration\";\nimport { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { createLocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\n/** Options to configure a pre-built store adapter. */\nexport type StoreOptions = {\n /** Choose which pre-built store adapter to use. */\n persistTo: PersistTo;\n\n /** Storage key to act as a namespace to store the data. */\n key: string;\n\n /** How long to wait before the value is considered expired. */\n expiryMs?: number | Duration;\n\n /** Returns true if the given value supposed to be of type T is valid. */\n isValid?: (u: unknown) => boolean;\n};\n\nexport type StoreConstructorArgs = Omit<StoreOptions, \"persistTo\">;\n\n/** Either use a pre-built store, or a custom one you provide. */\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\n// In SSR (Server-Side Rendering) mode, we never want to use our storage\n// adapters for anything.\nconst IS_NOT_BROWSER = typeof window === \"undefined\";\n\n/**\n * Convert a StorageOptions<T> config object into an actual storage adapter, or\n * returns null if a storage adapter is not configured.\n */\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n const config = { ...store, expiryMs };\n\n switch (store.persistTo) {\n case \"localStorage\":\n return localStoreAdapter<T>(config);\n\n case \"indexedDb\":\n return kvStoreAdapter<T>(config);\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n\n/**\n * Create a new SSR-safe local store adapter, which allows users to reuse the\n * same adapter in multiple shared states or shared queries.\n */\nexport function localStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Put everything in the same store so that we can GC properly.\n const STORE_NAME = \"react-utils\";\n\n const adapter = createLocalStore(STORE_NAME, {\n defaultExpiryMs: expiryMs,\n });\n\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n return {\n set: (key: string, value: T): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(keyPrefix + key, value);\n },\n\n get: (key: string): T | undefined => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = adapter.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`,\n );\n adapter.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n\n delete: (key: string): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.delete(keyPrefix + key);\n },\n\n /** Note that this will clear all keys in all shared states. */\n clear: (): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.clear();\n },\n };\n}\n\n/**\n * Create a new SSR-safe indexed DB KV store adapter, which allows users to\n * reuse the same adapter in multiple shared states or shared queries.\n */\nexport function kvStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = await kvStore.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `indexedDb adapter: Auto-discard invalid value for ${key}:`,\n value,\n );\n await kvStore.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n delete: async (key: string): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.clear();\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/storage.min.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,+DAAiC;AACjC,oCAAiC;AACjC;AACE;AACA;AACA;AACF,qMAAC","file":"/Users/choksheaklau/src/react-utils/dist/storage.min.cjs"}
package/storage.min.js ADDED
@@ -0,0 +1,12 @@
1
+ import {
2
+ getStorageAdapter,
3
+ kvStoreAdapter,
4
+ localStoreAdapter
5
+ } from "./chunk-4YV72T4D.min.js";
6
+ import "./chunk-PHITDXZT.min.js";
7
+ export {
8
+ getStorageAdapter,
9
+ kvStoreAdapter,
10
+ localStoreAdapter
11
+ };
12
+ //# sourceMappingURL=storage.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/stringify.cjs CHANGED
@@ -1,32 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function stringifyDeterministicForKeys(params) {
2
- const cache = /* @__PURE__ */ new Set();
3
- return JSON.stringify(params, (_, value) => {
4
- if (typeof value === "function") {
5
- throw new Error(`Functions should not be passed into query parameters`);
6
- }
7
- if (!value || typeof value !== "object" || Array.isArray(value)) {
8
- return value;
9
- }
10
- if (cache.has(value)) {
11
- return "[Circular]";
12
- }
13
- cache.add(value);
14
- if (value !== params) {
15
- try {
16
- JSON.stringify(value);
17
- } catch (e) {
18
- return "[Unserializable]";
19
- }
20
- }
21
- return Object.keys(value).sort().reduce(
22
- (result, key) => {
23
- result[key] = value[key];
24
- return result;
25
- },
26
- {}
27
- );
28
- });
29
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
30
2
 
3
+ var _chunkCYTO5EZEcjs = require('./chunk-CYTO5EZE.cjs');
4
+ require('./chunk-IS3BZTWE.cjs');
31
5
 
32
- exports.stringifyDeterministicForKeys = stringifyDeterministicForKeys;
6
+
7
+ exports.stringifyDeterministicForKeys = _chunkCYTO5EZEcjs.stringifyDeterministicForKeys;
package/stringify.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ stringifyDeterministicForKeys
3
+ } from "./chunk-7XC6EVMX.js";
4
+ import "./chunk-U67V476Y.js";
5
+ export {
6
+ stringifyDeterministicForKeys
7
+ };
package/stringify.min.cjs CHANGED
@@ -1,2 +1,8 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});function e(n){const t=new Set;return JSON.stringify(n,(s,r)=>{if(typeof r=="function")throw new Error("Functions should not be passed into query parameters");if(!r||typeof r!="object"||Array.isArray(r))return r;if(t.has(r))return"[Circular]";if(t.add(r),r!==n)try{JSON.stringify(r)}catch (e2){return"[Unserializable]"}return Object.keys(r).sort().reduce((i,o)=>(i[o]=r[o],i),{})})}exports.stringifyDeterministicForKeys = e;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkP2E73RBMmincjs = require('./chunk-P2E73RBM.min.cjs');
4
+ require('./chunk-TST6JKQ5.min.cjs');
5
+
6
+
7
+ exports.stringifyDeterministicForKeys = _chunkP2E73RBMmincjs.stringifyDeterministicForKeys;
2
8
  //# sourceMappingURL=stringify.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stringify.ts"],"names":["stringifyDeterministicForKeys","params","cache","_","value","result","key"],"mappings":"AAmBO,kFAASA,CAAAA,CAA8BC,CAAAA,CAAyB,CACrE,MAAMC,CAAAA,CAAQ,IAAI,GAAA,CAElB,OAAO,IAAA,CAAK,SAAA,CAAUD,CAAAA,CAAQ,CAACE,CAAAA,CAAGC,CAAAA,CAAAA,EAAU,CAC1C,EAAA,CAAI,OAAOA,CAAAA,EAAU,UAAA,CACnB,MAAM,IAAI,KAAA,CAAM,sDAAsD,CAAA,CAGxE,EAAA,CAAI,CAACA,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,EAAY,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CAC5D,OAAOA,CAAAA,CAGT,EAAA,CAAIF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAEjB,MAAO,YAAA,CAOT,EAAA,CAJAF,CAAAA,CAAM,GAAA,CAAIE,CAAK,CAAA,CAIXA,CAAAA,GAAUH,CAAAA,CACZ,GAAI,CACF,IAAA,CAAK,SAAA,CAAUG,CAAK,CACtB,CAAA,UAAQ,CACN,MAAO,kBACT,CAGF,OAAO,MAAA,CAAO,IAAA,CAAKA,CAAK,CAAA,CACrB,IAAA,CAAK,CAAA,CACL,MAAA,CACC,CAACC,CAAAA,CAAiCC,CAAAA,CAAAA,EAAAA,CAChCD,CAAAA,CAAOC,CAAG,CAAA,CAAIF,CAAAA,CAAME,CAAG,CAAA,CAChBD,CAAAA,CAAAA,CAET,CAAC,CACH,CACJ,CAAC,CACH,CAAA,0CAAA","file":"/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs","sourcesContent":["/**\n * @packageDocumentation\n *\n * Implements special stringify for use in the shared queries. This will likely\n * not be reusable for your own use cases.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\n/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,+DAAiC;AACjC,oCAAiC;AACjC;AACE;AACF,2FAAC","file":"/Users/choksheaklau/src/react-utils/dist/stringify.min.cjs"}
@@ -0,0 +1,8 @@
1
+ import {
2
+ stringifyDeterministicForKeys
3
+ } from "./chunk-AXDXFCZV.min.js";
4
+ import "./chunk-PHITDXZT.min.js";
5
+ export {
6
+ stringifyDeterministicForKeys
7
+ };
8
+ //# sourceMappingURL=stringify.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/useDeepMemo.cjs CHANGED
@@ -1,15 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _lodashes = require('lodash-es');
2
- var _react = require('react');
3
- function useDeepMemo(value) {
4
- const [state, setState] = _react.useState.call(void 0, value);
5
- return _react.useMemo.call(void 0, () => {
6
- if (_lodashes.isEqual.call(void 0, state, value)) {
7
- return state;
8
- }
9
- setState(value);
10
- return value;
11
- }, [state, value]);
12
- }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
13
2
 
3
+ var _chunkWXLUEDBOcjs = require('./chunk-WXLUEDBO.cjs');
4
+ require('./chunk-IS3BZTWE.cjs');
14
5
 
15
- exports.useDeepMemo = useDeepMemo;
6
+
7
+ exports.useDeepMemo = _chunkWXLUEDBOcjs.useDeepMemo;
package/useDeepMemo.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ useDeepMemo
3
+ } from "./chunk-YTXGK6BR.js";
4
+ import "./chunk-U67V476Y.js";
5
+ export {
6
+ useDeepMemo
7
+ };
@@ -1,2 +1,8 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _lodashes = require('lodash-es');var _react = require('react');function f(t){const[e,r]=_react.useState.call(void 0, t);return _react.useMemo.call(void 0, ()=>_lodashes.isEqual.call(void 0, e,t)?e:(r(t),t),[e,t])}exports.useDeepMemo = f;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkK2L3OVGYmincjs = require('./chunk-K2L3OVGY.min.cjs');
4
+ require('./chunk-TST6JKQ5.min.cjs');
5
+
6
+
7
+ exports.useDeepMemo = _chunkK2L3OVGYmincjs.useDeepMemo;
2
8
  //# sourceMappingURL=useDeepMemo.min.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/useDeepMemo.ts"],"names":["useDeepMemo","value","state","setState","useState","useMemo","isEqual"],"mappings":"AAYA,8GAAwB,8BACU,SAMlBA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,KAAM,CAACC,CAAAA,CAAOC,CAAQ,CAAA,CAAIC,6BAAAA,CAAiB,CAAA,CAE3C,OAAOC,4BAAAA,CAAQ,CAAA,EACTC,+BAAAA,CAAQJ,CAAOD,CAAK,CAAA,CACfC,CAAAA,CAAAA,CAKTC,CAAAA,CAASF,CAAK,CAAA,CAEPA,CAAAA,CAAAA,CACN,CAACC,CAAAA,CAAOD,CAAK,CAAC,CACnB,CAAA,wBAAA","file":"/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs","sourcesContent":["/**\n * @packageDocumentation\n *\n * Provides a memoized value in React where the value is checked for deep\n * equality. If the value has changed, but is deeply equal to the previous\n * value, then useDeepMemo will return the same reference to the previous\n * value and ignore the latest value.\n *\n * This is mainly used in shared queries to check for changes in the query\n * arguments, but it might be useful for your own use cases.\n */\n\nimport { isEqual } from \"lodash-es\";\nimport { useMemo, useState } from \"react\";\n\n/**\n * Provides a stable value for T based on deep equality. The deep equality is\n * determined by the `isEqual()` function in lodash.\n */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"]}
1
+ {"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,+DAAiC;AACjC,oCAAiC;AACjC;AACE;AACF,uDAAC","file":"/Users/choksheaklau/src/react-utils/dist/useDeepMemo.min.cjs"}
@@ -0,0 +1,8 @@
1
+ import {
2
+ useDeepMemo
3
+ } from "./chunk-MNWSPF5J.min.js";
4
+ import "./chunk-PHITDXZT.min.js";
5
+ export {
6
+ useDeepMemo
7
+ };
8
+ //# sourceMappingURL=useDeepMemo.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/NoSSR.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- import{useEffect as r,useState as s}from"react";const l=({children:e,fallback:t})=>{const[o,c]=s(!1);return r(()=>{c(!0)},[]),o?e:t};export{l as NoSSR};
2
- //# sourceMappingURL=NoSSR.min.mjs.map
package/index.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- export*from"./sharedQuery";export*from"./sharedState";export*from"./storage";export*from"./useDeepMemo";export*from"./stringify";
2
- //# sourceMappingURL=index.min.mjs.map
package/index.min.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from \"./sharedQuery\";\nexport * from \"./sharedState\";\nexport * from \"./storage\";\nexport * from \"./useDeepMemo\";\nexport * from \"./stringify\";\n"],"mappings":"AAAA,WAAc,gBACd,WAAc,gBACd,WAAc,YACd,WAAc,gBACd,WAAc","names":[]}
package/index.mjs DELETED
@@ -1,5 +0,0 @@
1
- export * from "./sharedQuery";
2
- export * from "./sharedState";
3
- export * from "./storage";
4
- export * from "./useDeepMemo";
5
- export * from "./stringify";
@@ -1,2 +0,0 @@
1
- import{http as L,retries as j}from"@choksheak/ts-utils/http";import{nonNil as W}from"@choksheak/ts-utils/nonNil";import k from"object-sizeof";import{useCallback as P,useEffect as R,useMemo as v,useRef as K,useState as _}from"react";import X from"xxhashjs";import{sharedState as Y,useSharedState as H}from"./sharedState";import{stringifyDeterministicForKeys as I}from"./stringify";import{useDeepMemo as J}from"./useDeepMemo";const w={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...t)=>console.log("[sharedQuery]",...t)};function ge(t){Object.assign(w,t)}const G=new Map;function Z(){if(typeof window<"u"){const t=window.globalThis;return t.reactUtilsQueryRegistry??=new Map}return G}function q(t){const D=Z(),i=t.queryName||t.url,y=D.get(i);if(y)return y;const T=ee(t);return D.set(i,T),T}function ee(t){const D=t.url||"",i=t.queryName||D;if(!i)throw new Error("Either queryName or url must be specified.");const y=new Map,T=new Map;let S;if(t.queryFn)S=t.queryFn;else if(D){const e=L.use(j());S=async(...r)=>{let a="";const n=r?.[0];if(n){if(typeof n=="string")a=n;else if(typeof n=="object"){const f=[];for(const[Q,M]of Object.entries(n))if(M!==void 0)if(Array.isArray(M))for(const x of M)x!==void 0&&f.push([Q,String(x)]);else f.push([Q,String(M)]);a=new URLSearchParams(f).toString()}a&&(D.includes("?")?a="&"+a:a="?"+a)}return await(await e.get(D+a)).json()}}else throw new Error("Either queryFn or url must be specified");const u=t.refetchFn,p=t?.staleMs??w.staleMs,b=t?.expiryMs??w.expiryMs,U=t?.refetchOnStale??w.refetchOnStale,A=t.store;if(A){if("persistTo"in A&&A.isValid){const e=A.isValid;t={...t,store:{...A,isValid:r=>{if(!r||typeof r!="object")return!1;for(const a of Object.values(r))if(!a||typeof a!="object"||!("data"in a)||!("dataUpdatedMs"in a)||!("lastUpdatedMs"in a)||typeof a.dataUpdatedMs!="number"||typeof a.lastUpdatedMs!="number"||!e(a.data))return!1;return!0}}}}}else{const e=t.persistTo??w.persistTo;e&&(t={...t,store:{persistTo:e,key:i,expiryMs:b}})}const m=t?.maxSize??w.maxSize,o=t?.maxBytes??w.maxBytes,l=!!t?.keepLastNonEmptyData,s=t?.log??w.log,c=Y({},t);function B(e){return p===0?!0:Date.now()-e>p}function F(e){return b===0?!1:Date.now()-e>b}function O(){if(!m&&!o)return;const e=c.getSnapshot(),r=Object.keys(e).length;if(r<=1)return;const a=k(e);let n=m?r-m:0,d=o?a-o:0;if(n<=0&&d<=0){s(`No need to trim data for ${i}: size=${r} (limit=${m}), byteSize=${a.toLocaleString()} (limit=${o.toLocaleString()})`);return}s(`Need to trim ${i}: numToCut=${n}, bytesToCut=${d}`);const f={...e};let Q=!1;const M=(g,$)=>{if(T.has(g)){s(`Cannot clean up ${g} as it is mounted`);return}const N=k(g)+k(f[g]);s(`Cleaning up unmounted${$?", expired":""} ${g} (byteSize=${N.toLocaleString()})`),n--,d-=N,delete f[g],Q=!0};let x=Object.entries(f).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs);for(const[g]of x){if(!F(f[g].lastUpdatedMs))break;M(g,!0)}if(n>0||d>0){Q&&(x=Object.entries(f).sort((g,$)=>g[1].lastUpdatedMs-$[1].lastUpdatedMs));for(const[g]of x)if(M(g,!1),n<=0&&d<=0)break}if(!Q){s(`No trimmable entries found for ${i}: size=${r} (limit=${m}), byteSize=${a.toLocaleString()} (limit=${o.toLocaleString()})`);return}c.setValue(f),s(`Trimmed data for ${i}: size=[${r} -> ${Object.keys(f).length}] (limit=${m}), byteSize=[${a.toLocaleString()} -> ${k(f).toLocaleString()}] (limit=${o.toLocaleString()})`)}function V(e,r,a=Date.now()){const n={lastUpdatedMs:Date.now(),loading:!1,data:r,dataUpdatedMs:a};c.setValue(d=>({...d,[e]:n})),O()}async function E(e,r,a){s(`Start fetching ${e}, queryType=${r}`);try{const n=await(r==="refetch"&&u?u(...a):S(...a));return s(`Successfully fetched ${e}`),V(e,n,Date.now()),n}catch(n){throw s(`Failed to fetch ${e} for queryType=${r}: ${n}`),n}finally{y.delete(e)}}function C(e,r,...a){const n=y.get(e);if(n)return s(`Deduplicating inflight fetch for ${e}, queryType=${r}`),n.promise;const d=E(e,r,a),f=new AbortController;return y.set(e,{promise:d,abortController:f}),d}const h={queryName:i,queryFn:S,refetchFn:u,expiryMs:b,staleMs:p,refetchOnStale:U,maxSize:m,maxBytes:o,keepLastNonEmptyData:l,log:s,queryState:c,getQueryKey(e){let r=I(e);return r.length>30&&(r=X.h32(r,39406).toString(16).slice(2)),i+":"+r},getAbortController(e){const r=h.getQueryKey(e);return h.getAbortControllerByKey(r)},getAbortControllerByKey(e){return y.get(e)?.abortController??null},getAbortSignal(e){const r=h.getQueryKey(e);return h.getAbortSignalByKey(r)},getAbortSignalByKey(e){return h.getAbortControllerByKey(e)?.signal??null},async getCachedOrFetch(...e){const r=Date.now();await c.readyPromise;const a=Date.now()-r,n=h.getQueryKey(e),d=c.getSnapshot()?.[n];if(a&&s(`${n}: Waited for ${a}ms before data is ready`),d?.data&&!F(d.dataUpdatedMs??0))return B(d.dataUpdatedMs??0)?(U&&(s(`refetchOnStale for ${n}`),C(n,"query",...e)),s(`Returning stale data for ${n}`),d):(s(`Return fresh data ${n} from cache without fetching`),d);const f=await C(n,"query",...e),Q=Date.now();return{lastUpdatedMs:Q,loading:!1,data:f,dataUpdatedMs:Q}},getQueryValue(e){return c.getSnapshot()?.[e]},getData(e){const r=c.getSnapshot()?.[e];if(r?.lastUpdatedMs&&F(r.lastUpdatedMs)){h.deleteData(e);return}return r?.data},setData:V,async updateFromSource(...e){const r=h.getQueryKey(e);return await C(r,"query",...e)},async refetch(...e){const r=h.getQueryKey(e);return await C(r,"refetch",...e)},deleteData(e){const a={...c.getSnapshot()};delete a[e],c.setValue(a);const n=y.get(e);n&&(y.delete(e),n.abortController.abort("Deleted"))},clear(){c.delete();for(const{abortController:e}of Array.from(y.values()))e.abort("Cleared");y.clear()},mount(e){T.set(e,(T.get(e)??0)+1)},unmount(e){const r=T.get(e);r===1?T.delete(e):T.set(e,(r??0)-1)},enforceSizeLimit:O};return h}function ye(t){return q(t)}const z={lastUpdatedMs:0,loading:!0};function Te(t,...D){const i=J(D),[y,T]=H(t.queryState),S=K(!0),u=v(()=>t.getQueryKey(i),[t,i]),p=y[u]??z,b=P(o=>{T(l=>{const s={...l};return s[u]=typeof o=="function"?o(s[u]??z):o,s})},[u,T]),[U,A]=_();R(()=>{t.keepLastNonEmptyData&&p.data!==void 0&&A(p.data)},[t.keepLastNonEmptyData,p.data]);const m=P(async o=>{if(t.log(`Begin executing shared query ${u}, isRefetch=${o}`),!!S.current){b(l=>({...l,lastUpdatedMs:Date.now(),loading:!0}));try{let l;if(o){const s=await t.refetch(...i),c=Date.now();l={lastUpdatedMs:c,loading:!1,data:s,dataUpdatedMs:c}}else l=await t.getCachedOrFetch(...i);return S.current?(b({...l,loading:!1}),l.data):void 0}catch(l){if(!S.current)return;const s=Date.now();b(c=>({...c,lastUpdatedMs:s,loading:!1,error:l,errorUpdatedMs:s}))}}},[t,u,b,i]);return R(()=>(S.current=!0,t.mount(u),m(!1),()=>{S.current=!1,t.unmount(u)}),[m,t,u]),v(()=>({...p,data:p.data!==void 0?p.data:U,latestData:p.data,abortCurrentQuery:o=>{const l=t.getAbortControllerByKey(u);return l?.abort(o),!!l},getCachedOrFetch:async()=>{const o=await t.getCachedOrFetch(...i);return W(o.data,typeof o.error=="string"?o.error:JSON.stringify(o.error))},refetch:()=>m(!0),setData:(o,l)=>{t.setData(u,o,l)},deleteData:()=>{t.deleteData(u)}}),[m,U,t,u,p,i])}export{w as SharedQueryConfig,ge as configureSharedQuery,ye as sharedQuery,Te as useSharedQuery};
2
- //# sourceMappingURL=sharedQuery.min.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sharedQuery.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Think of shared queries as like the open source npm package \"react-query\",\n * but with strong type-checking and built-in support for persistence.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n * import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, userId);\n *\n * // You can check for user.loading and user.error if needed.\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { http, retries } from \"@choksheak/ts-utils/http\";\nimport { nonNil } from \"@choksheak/ts-utils/nonNil\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport XXH from \"xxhashjs\";\n\nimport { sharedState, SharedStateOptions, useSharedState } from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,\n * then this will contain the latest data (undefined when args just changed)\n * and data will contain the last non empty data.\n */\n latestData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Let the caller get the data immediately no matter what.\n */\n getCachedOrFetch: () => Promise<TData>;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => Promise<TData | undefined>;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\nexport type QueryTargetWithFn<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /** Function to fetch data. */\n queryFn: QueryFn<TArgs, TData>;\n};\n\nexport type QueryTargetWithUrl = {\n /**\n * The queryName can optionally be specified, else we will fallback to use\n * the url as the queryName.\n */\n queryName?: string;\n\n /**\n * URL to fetch data using HTTP GET. Note that using this field will cause\n * both TArgs and TData to be undefined (unknown). Therefore you can make up\n * for this by specifying types with useSharedQuery, like this:\n * ```\n * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n *\n * If `userId` were specified as [\"u1\", \"u2\"], the query url would be\n * \"/api/list-users?userId=u1&userId=u2\".\n *\n * You can also pass the params as a string like \"userId=u1&userId=u2\".\n * ```\n * const usersQuery = useSharedQuery<[string], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n */\n url: string;\n};\n\n/** Specifies how to fetch the data. */\nexport type QueryTarget<TArgs extends unknown[], TData> =\n | QueryTargetWithFn<TArgs, TData>\n | QueryTargetWithUrl;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<\n TArgs,\n TData\n> & {\n /**\n * Function to re-fetch data. Usually this would just be the `queryFn`, but\n * if you need a different behavior for refetching, then specify this.\n */\n refetchFn?: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * 86_400_000 /* MS_PER_DAY */,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Whether this is a normal query or an explicit refetch. */\ntype QueryType = \"query\" | \"refetch\";\n\nconst moduleQueryRegistry = new Map<string, unknown>();\n\n/**\n * When bundlers duplicate this module across chunks, each copy would otherwise\n * create a separate queryState (different pubSub keys in the same store).\n * Return the same SharedQuery for a given queryName app-wide.\n */\nfunction getOrCreateQueryRegistry(): Map<string, unknown> {\n if (typeof window !== \"undefined\") {\n const g = window.globalThis as {\n reactUtilsQueryRegistry?: Map<string, unknown>;\n };\n return (g.reactUtilsQueryRegistry ??= new Map());\n }\n return moduleQueryRegistry;\n}\n\n// Split out function to auto-derive the return type.\nfunction sharedQuery1<TArgs extends unknown[], TData>(\n options: SharedQueryOptions<TArgs, TData>,\n) {\n const registry = getOrCreateQueryRegistry();\n const key = options.queryName || (options as QueryTargetWithUrl).url;\n\n const existing = registry.get(key);\n if (existing) {\n return existing;\n }\n\n const obj = sharedQuery2(options);\n registry.set(key, obj);\n return obj;\n}\n\n// Split out function to auto-derive the return type.\nfunction sharedQuery2<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n // If queryName is not specified, fallback to use url as the queryName.\n const url = (options as QueryTargetWithUrl).url || \"\";\n const queryName = options.queryName || url;\n\n if (!queryName) {\n throw new Error(`Either queryName or url must be specified.`);\n }\n\n const inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n const mountedKeys = new Map<string, number>();\n\n let queryFn: QueryFn<TArgs, TData>;\n\n if ((options as QueryTargetWithFn<TArgs, TData>).queryFn) {\n queryFn = (options as QueryTargetWithFn<TArgs, TData>).queryFn;\n } else if (url) {\n const fetcher = http.use(retries());\n\n // Auto-generate the queryFn as a HTTP GET request using the url.\n queryFn = async (...args: TArgs): Promise<TData> => {\n // If args are given, treat the first argument as a search param.\n let params = \"\";\n const firstArg = args?.[0];\n\n if (firstArg) {\n if (typeof firstArg === \"string\") {\n params = firstArg;\n } else if (typeof firstArg === \"object\") {\n const entries: [string, string][] = [];\n\n for (const [k, v] of Object.entries(firstArg)) {\n if (v === undefined) continue;\n\n // Allow the same param to be specified multiple times.\n if (Array.isArray(v)) {\n for (const item of v) {\n if (item === undefined) continue;\n\n // The field values can only be primitives, not objects.\n entries.push([k, String(item)]);\n }\n } else {\n // The field values can only be primitives, not objects.\n entries.push([k, String(v)]);\n }\n }\n\n params = new URLSearchParams(entries).toString();\n }\n\n if (params) {\n if (url.includes(\"?\")) {\n // Append more search params to existing ones.\n params = \"&\" + params;\n } else {\n // Set the full search params string.\n params = \"?\" + params;\n }\n }\n }\n\n const response = await fetcher.get(url + params);\n\n return await response.json();\n };\n } else {\n throw new Error(`Either queryFn or url must be specified`);\n }\n\n const refetchFn = options.refetchFn;\n\n const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n const refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n const store = options.store;\n\n if (store) {\n // Wrap the isValid to account for the query state wrapper.\n if (\"persistTo\" in store && store.isValid) {\n const isValid = store.isValid;\n\n options = {\n ...options,\n store: {\n ...store,\n isValid: (u) => {\n // Supposed type of u: SharedQueryState<TData>\n if (!u || typeof u !== \"object\") {\n return false;\n }\n\n // Since each stored key could contain multiple values, and isValid\n // checks for each value, we need to check every value to make sure\n // they are valid.\n // Supposed type of v: QueryStateValue<TData>\n for (const v of Object.values(u)) {\n if (\n !v ||\n typeof v !== \"object\" ||\n !(\"data\" in v) ||\n !(\"dataUpdatedMs\" in v) ||\n !(\"lastUpdatedMs\" in v) ||\n typeof v.dataUpdatedMs !== \"number\" ||\n typeof v.lastUpdatedMs !== \"number\" ||\n !isValid(v.data)\n ) {\n return false;\n }\n }\n\n return true;\n },\n },\n };\n }\n } else {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options = {\n ...options,\n store: {\n persistTo,\n key: queryName,\n expiryMs,\n },\n };\n }\n }\n\n const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n const log = options?.log ?? SharedQueryConfig.log;\n\n const queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n\n function isStale(dataUpdatedMs: number): boolean {\n if (staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > staleMs;\n }\n\n function isExpired(dataUpdatedMs: number): boolean {\n if (expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > expiryMs;\n }\n\n function enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!maxSize && !maxBytes) {\n return;\n }\n\n const oldState = queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = maxSize ? oldSize - maxSize : 0;\n let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n log(\n `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n log(\n `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (mountedKeys.has(key)) {\n log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n log(\n `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n log(\n `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`,\n );\n }\n\n function setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n enforceSizeLimit();\n }\n\n async function startFetching(\n queryKey: string,\n queryType: QueryType,\n args: TArgs,\n ) {\n log(`Start fetching ${queryKey}, queryType=${queryType}`);\n\n try {\n const data = await (queryType === \"refetch\" && refetchFn\n ? refetchFn(...args)\n : queryFn(...args));\n\n log(`Successfully fetched ${queryKey}`);\n setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);\n throw e;\n } finally {\n inflightQueries.delete(queryKey);\n }\n }\n\n function dedupedFetch(\n queryKey: string,\n queryType: QueryType,\n ...args: TArgs\n ): Promise<TData> {\n const inflightQuery = inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests. Note that queries and refetches are\n // also deduped because they should technically be trying to fetch the same\n // data.\n if (inflightQuery) {\n log(\n `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`,\n );\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = startFetching(queryKey, queryType, args);\n const abortController = new AbortController();\n\n inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n const obj = {\n queryName,\n queryFn,\n refetchFn,\n expiryMs,\n staleMs,\n refetchOnStale,\n maxSize,\n maxBytes,\n keepLastNonEmptyData,\n log,\n queryState,\n\n /** Returns a key to identify requests based on the given args. */\n getQueryKey(args: TArgs): string {\n let s = stringifyDeterministicForKeys(args);\n\n // Ensure the query key is not too long.\n if (s.length > 30) {\n s = XXH.h32(s, 0x99ee).toString(16).slice(2); // remove \"0x\"\n }\n\n return queryName + \":\" + s;\n },\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n getAbortController(args: TArgs): AbortController | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortControllerByKey(queryKey);\n },\n\n getAbortControllerByKey(queryKey: string): AbortController | null {\n return inflightQueries.get(queryKey)?.abortController ?? null;\n },\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example using fetch:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n *\n * Example using `http.ts`:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await http.get(`/users/${userId}`, { signal });\n * return await response.json();\n * },\n * });\n * ```\n */\n getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortSignalByKey(queryKey);\n },\n\n getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return obj.getAbortControllerByKey(queryKey)?.signal ?? null;\n },\n\n /** For cached data, we need to return the correct timestamps as well. */\n async getCachedOrFetch(...args: TArgs): Promise<QueryStateValue<TData>> {\n // Important: wait for data to be loaded from cache first before trying to\n // fetch from server. This fixes a bad bug where the data is big, and the\n // code here starts a server fetch before the cache data loaded.\n const startMs = Date.now();\n await queryState.readyPromise;\n const waitedMs = Date.now() - startMs;\n\n const queryKey = obj.getQueryKey(args);\n const cached = queryState.getSnapshot()?.[queryKey];\n\n if (waitedMs) {\n log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);\n }\n\n if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!isStale(cached.dataUpdatedMs ?? 0)) {\n log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached;\n }\n\n // If stale, optionally update the data in the background.\n if (refetchOnStale) {\n log(`refetchOnStale for ${queryKey}`);\n void dedupedFetch(queryKey, \"query\", ...args);\n }\n\n // Still return stale data immediately.\n log(`Returning stale data for ${queryKey}`);\n return cached;\n }\n\n const data = await dedupedFetch(queryKey, \"query\", ...args);\n const now = Date.now();\n\n return {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n },\n\n /** Get the entire stored entry for a query key. */\n getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return queryState.getSnapshot()?.[queryKey];\n },\n\n /** Get the current stored data for a query key. */\n getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (isExpired(stateValue.lastUpdatedMs)) {\n obj.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n },\n\n /** Set the data directly if the user obtained it from somewhere else. */\n setData,\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n async updateFromSource(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"query\", ...args);\n },\n\n /**\n * Perform an explicit refetch. If `options.refetchFn` was not specified,\n * then this would be identical to calling `obj.updateFromSource()`.\n */\n async refetch(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"refetch\", ...args);\n },\n\n /** Delete the cached data for one set of arguments. */\n deleteData(queryKey: string): void {\n const record = queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n queryState.setValue(clone);\n\n const inflight = inflightQueries.get(queryKey);\n if (inflight) {\n inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n },\n\n /** Delete all currently cached data & all inflight promises. */\n clear(): void {\n queryState.delete();\n\n for (const { abortController } of Array.from(inflightQueries.values())) {\n abortController.abort(\"Cleared\");\n }\n\n inflightQueries.clear();\n },\n\n /** Keep track of mounted keys. */\n mount(queryKey: string): void {\n mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);\n },\n\n /** Clean up mounted keys. */\n unmount(queryKey: string): void {\n const count = mountedKeys.get(queryKey);\n if (count === 1) {\n mountedKeys.delete(queryKey);\n } else {\n mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n },\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n enforceSizeLimit,\n } as const;\n\n return obj;\n}\n\nexport type SharedQuery<TArgs extends unknown[], TData> = ReturnType<\n typeof sharedQuery2<TArgs, TData>\n>;\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is mainly used for logging and also\n * used as the storage key when you use the top-level `persistTo`.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n return sharedQuery1(options) as SharedQuery<TArgs, TData>;\n}\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const executeQuery = useCallback(\n async (isRefetch: boolean): Promise<TData | undefined> => {\n query.log(\n `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`,\n );\n\n if (!isMounted.current) return;\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n let state: QueryStateValue<TData>;\n\n if (isRefetch) {\n const data = await query.refetch(...stableArgs);\n const now = Date.now();\n\n state = {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n } else {\n state = await query.getCachedOrFetch(...stableArgs);\n }\n\n if (!isMounted.current) return;\n\n // Make sure to reset loading to false.\n setQueryStateValue({ ...state, loading: false });\n\n return state.data;\n } catch (e) {\n if (!isMounted.current) return;\n\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void executeQuery(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [executeQuery, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n\n // Fill with lastNonEmptyData when data is undefined.\n data:\n queryStateValue.data !== undefined\n ? queryStateValue.data\n : lastNonEmptyData,\n\n latestData: queryStateValue.data,\n\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown): boolean => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n getCachedOrFetch: async (): Promise<TData> => {\n const data = await query.getCachedOrFetch(...stableArgs);\n\n return nonNil(\n data.data,\n typeof data.error === \"string\"\n ? data.error\n : JSON.stringify(data.error),\n );\n },\n refetch: (): Promise<TData | undefined> => {\n return executeQuery(true);\n },\n setData: (data: TData, dataUpdatedMs?: number): void => {\n query.setData(queryKey, data, dataUpdatedMs);\n },\n deleteData: (): void => {\n query.deleteData(queryKey);\n },\n } satisfies UseQueryResult<TData>;\n }, [\n executeQuery,\n lastNonEmptyData,\n query,\n queryKey,\n queryStateValue,\n stableArgs,\n ]);\n}\n"],"mappings":"AAqFA,OAAS,QAAAA,EAAM,WAAAC,MAAe,2BAC9B,OAAS,UAAAC,MAAc,6BACvB,OAAOC,MAAiB,gBACxB,OAEE,eAAAC,EACA,aAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QACP,OAAOC,MAAS,WAEhB,OAAS,eAAAC,EAAiC,kBAAAC,MAAsB,gBAEhE,OAAS,iCAAAC,MAAqC,cAC9C,OAAS,eAAAC,MAAmB,gBAgLrB,MAAMC,EAAoB,CAE/B,QAAS,EAGT,SAAU,GAAK,MAGf,eAAgB,GAGhB,UAAW,OAGX,QAAS,IAGT,SAAU,IAGV,IAAK,IAAIC,IAAoB,QAAQ,IAAI,gBAAiB,GAAGA,CAAI,CACnE,EAKO,SAASC,GAAqBC,EAAoC,CACvE,OAAO,OAAOH,EAAmBG,CAAM,CACzC,CAKA,MAAMC,EAAsB,IAAI,IAOhC,SAASC,GAAiD,CACxD,GAAI,OAAO,OAAW,IAAa,CACjC,MAAMC,EAAI,OAAO,WAGjB,OAAQA,E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GH,KACEA,EAAgB,OAAS,OACrBA,EAAgB,KAChBG,EAEN,WAAYH,EAAgB,KAK5B,kBAAoBQ,GAA8B,CAChD,MAAMC,EAAab,EAAM,wBAAwBvB,CAAQ,EACzD,OAAAoC,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,iBAAkB,SAA4B,CAC5C,MAAMnC,EAAO,MAAMsB,EAAM,iBAAiB,GAAGC,CAAU,EAEvD,OAAO7F,EACLsE,EAAK,KACL,OAAOA,EAAK,OAAU,SAClBA,EAAK,MACL,KAAK,UAAUA,EAAK,KAAK,CAC/B,CACF,EACA,QAAS,IACA+B,EAAa,EAAI,EAE1B,QAAS,CAAC/B,EAAalB,IAAiC,CACtDwC,EAAM,QAAQvB,EAAUC,EAAMlB,CAAa,CAC7C,EACA,WAAY,IAAY,CACtBwC,EAAM,WAAWvB,CAAQ,CAC3B,CACF,GACC,CACDgC,EACAF,EACAP,EACAvB,EACA2B,EACAH,CACF,CAAC,CACH","names":["http","retries","nonNil","getByteSize","useCallback","useEffect","useMemo","useRef","useState","XXH","sharedState","useSharedState","stringifyDeterministicForKeys","useDeepMemo","SharedQueryConfig","args","configureSharedQuery","config","moduleQueryRegistry","getOrCreateQueryRegistry","g","sharedQuery1","options","registry","key","existing","obj","sharedQuery2","url","queryName","inflightQueries","mountedKeys","queryFn","fetcher","params","firstArg","entries","k","v","item","refetchFn","staleMs","expiryMs","refetchOnStale","store","isValid","u","persistTo","maxSize","maxBytes","keepLastNonEmptyData","log","queryState","isStale","dataUpdatedMs","isExpired","enforceSizeLimit","oldState","oldSize","oldByteSize","numToCut","bytesToCut","newState","needUpdate","deleteKeyIfNotMounted","expired","byteSize","entriesByTimeAscending","entry1","entry2","setData","queryKey","data","entry","prev","startFetching","queryType","e","dedupedFetch","inflightQuery","promise","abortController","s","startMs","waitedMs","cached","now","stateValue","clone","inflight","count","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","setQueryState","isMounted","queryStateValue","setQueryStateValue","next","lastNonEmptyData","setLastNonEmptyData","executeQuery","isRefetch","state","reason","controller"]}
@@ -1,2 +0,0 @@
1
- import{MS_PER_DAY as g}from"@choksheak/ts-utils/timeConstants";import{useSyncExternalStore as y}from"react";import{getStorageAdapter as v}from"./storage";const p={storeExpiryMs:30*g,lazyLoad:!1};function E(e){Object.assign(p,e)}function l(){const e=new Map,i=new Map;function S(o,n,t){const a=i.get(o);if(!a)return;const c=Array.from(a.values());for(const d of c)try{d(n,t)}catch(f){console.error("Error invoking subscriber:",f)}}return{get(o){return e.get(o)},set(o,n){const t=e.get(o);t!==n&&(e.set(o,n),S(o,n,t))},delete(o){e.delete(o)},setNoNotify(o,n){e.set(o,n)},subscribe(o,n){let t=i.get(o);return t||(t=new Set,i.set(o,t)),t.add(n),()=>{t.delete(n),t.size===0&&i.delete(o)}}}}function h(){if(typeof window<"u"){const e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=l())}return l()}const u=h(),T="state";let m=0;function P(){if(typeof window<"u"){const e=window.globalThis;return e.reactUtilsStateKey=(e.reactUtilsStateKey??0)+1,e.reactUtilsStateKey}return++m}function U(e,i){let S=()=>{};const o=new Promise(r=>{S=r}),n=S,t=String(P()),a=v(i,p.storeExpiryMs);u.setNoNotify(t,e);const c=i?.lazyLoad,d=c!==void 0?c:p.lazyLoad;function f(r){const b=r!==void 0?r:e;u.set(t,b),s.initDone=!0,n()}const s={defaultValue:e,readyPromise:o,lazy:d,initStarted:!1,initDone:!1,subscribe(r){return u.subscribe(t,()=>r())},hasStore(){return!!a},setInStore(r){return a?.set(T,r)},getFromStore(){return a?.get(T)},getSnapshot(){return u.get(t)},setValue(r){if(typeof r=="function"){const b=u.get(t);r=r(b)}u.set(t,r),s.setInStore(r)},delete(){return u.set(t,e),a?.set(T,e)},initDefaultValueOnce(){if(s.initDone||s.initStarted)return;s.initStarted=!0;const r=s.getFromStore();if(r instanceof Promise)return r.then(f);f(r)}};return d||s.initDefaultValueOnce(),s}function w(e){return e.initDefaultValueOnce(),[y(S=>e.subscribe(S),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function R(e){return w(e)[0]}function C(e){return e.initDefaultValueOnce(),e.setValue}export{p as SharedStateConfig,E as configureSharedState,U as sharedState,w as useSharedState,C as useSharedStateSetter,R as useSharedStateValue};
2
- //# sourceMappingURL=sharedState.min.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sharedState.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n function completeInit(stored: T | undefined) {\n const value = stored !== undefined ? stored : defaultValue;\n\n pubSubStore.set(pubSubKey, value);\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n }\n\n const obj = {\n defaultValue,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n lazy,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(pubSubKey, next);\n void obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n pubSubStore.set(pubSubKey, defaultValue);\n return storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const maybePromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (maybePromise instanceof Promise) {\n return maybePromise.then(completeInit);\n } else {\n const stored = maybePromise;\n completeInit(stored);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n"],"mappings":"AAwDA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QAE/D,OAAS,qBAAAC,MAAyC,YAS3C,MAAMC,EAAoB,CAK/B,cAAe,GAAKH,EAMpB,SAAU,EACZ,EAKO,SAASI,EAAqBC,EAAoC,CACvE,OAAO,OAAOF,EAAmBE,CAAM,CACzC,CAQA,SAASC,GAAoB,CAC3B,MAAMC,EAAY,IAAI,IAChBC,EAAmB,IAAI,IAE7B,SAASC,EAAUC,EAAa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UAAYA,EAAI,YAAa,OAErCA,EAAI,YAAc,GAElB,MAAMC,EAAeD,EAAI,aAAa,EAItC,GAAIC,aAAwB,QAC1B,OAAOA,EAAa,KAAKH,CAAY,EAGrCA,EADeG,CACI,CAEvB,CACF,EAEA,OAAKJ,GACHG,EAAI,qBAAqB,EAGpBA,CACT,CAYO,SAASE,EACdC,EACkC,CAClC,OAAKA,EAAM,qBAAqB,EASzB,CAPOvC,EACXwC,GAAkBD,EAAM,UAAUC,CAAa,EAChD,IAAMD,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,QAAQ,CAC/B,CAUO,SAASE,EAAuBF,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASG,EAAwBH,EAAuB,CAC7D,OAAKA,EAAM,qBAAqB,EAEzBA,EAAM,QACf","names":["MS_PER_DAY","useSyncExternalStore","getStorageAdapter","SharedStateConfig","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","getNextStateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","pubSubKey","storageAdapter","lazyLoad","lazy","completeInit","stored","obj","maybePromise","useSharedState","state","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
package/storage.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- import{kvStore as u}from"@choksheak/ts-utils/kvStore";import{createLocalStore as f}from"@choksheak/ts-utils/localStore";const n=typeof window>"u";function v(s,a){const{store:e}=s??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){const i=e.expiryMs||a,t={...e,expiryMs:i};switch(e.persistTo){case"localStorage":return c(t);case"indexedDb":return l(t);default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}function c({key:s,expiryMs:a,isValid:e}){const t=f("react-utils",{defaultExpiryMs:a}),o=s+":";return{set:(r,d)=>{n||t.set(o+r,d)},get:r=>{if(n)return;const d=o+r,p=t.get(d);if(p!==void 0&&e&&!e(p)){console.warn(`localStorage adapter: Auto-discard invalid value for ${d}: ${JSON.stringify(p)}`),t.delete(d);return}return p},delete:r=>{n||t.delete(o+r)},clear:()=>{n||t.clear()}}}function l({key:s,expiryMs:a,isValid:e}){const i=s+":";return{set:async(t,o)=>{n||await u.set(i+t,o,a)},get:async t=>{if(n)return;const o=i+t,r=await u.get(o);if(r!==void 0&&e&&!e(r)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,r),await u.delete(o);return}return r},delete:async t=>{n||await u.delete(i+t)},clear:async()=>{n||await u.clear()}}}export{v as getStorageAdapter,l as kvStoreAdapter,c as localStoreAdapter};
2
- //# sourceMappingURL=storage.min.mjs.map
package/stringify.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- function e(n){const t=new Set;return JSON.stringify(n,(s,r)=>{if(typeof r=="function")throw new Error("Functions should not be passed into query parameters");if(!r||typeof r!="object"||Array.isArray(r))return r;if(t.has(r))return"[Circular]";if(t.add(r),r!==n)try{JSON.stringify(r)}catch{return"[Unserializable]"}return Object.keys(r).sort().reduce((i,o)=>(i[o]=r[o],i),{})})}export{e as stringifyDeterministicForKeys};
2
- //# sourceMappingURL=stringify.min.mjs.map
@@ -1,2 +0,0 @@
1
- import{isEqual as o}from"lodash-es";import{useMemo as s,useState as m}from"react";function f(t){const[e,r]=m(t);return s(()=>o(e,t)?e:(r(t),t),[e,t])}export{f as useDeepMemo};
2
- //# sourceMappingURL=useDeepMemo.min.mjs.map